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
molforge/ui/views.py ADDED
@@ -0,0 +1,892 @@
1
+ """
2
+ ui/views.py - GaussView 6.0 + Chem3D 标准独立可停靠/浮动检查器与表格面板系统 (MolForge v4)
3
+ ==========================================================================================
4
+ 包含:
5
+ 1. `ModelExplorerDock` (View -> Model Explorer / Structure Browser):分子结构树浏览与快速选择
6
+ 2. `CartesianTableDock` (View / Tools -> Cartesian Coordinates Table / Atom List):
7
+ 笛卡尔坐标与单原子属性实时可编辑表格(改 X/Y/Z 或单原子缩放即入 Undo 栈并同步 2D/3D)
8
+ 3. `MeasurementTableDock` (View / Tools -> Measurement & Redundant Coordinates Table):
9
+ 全部键长 R(i,j)、键角 A(i,j,k)、二面角 D(i,j,k,l) 内坐标总表与交互高亮
10
+ 4. `AtomBondPropertyDock` (View / Results -> Atom & Bond Property Table):
11
+ 逐原子/逐键物理化学性质、部分电荷、独立半径与颜色总表
12
+ 5. `DihedralChartDialog` (View / Results -> Dihedral Torsion Energy Scan Chart):
13
+ 二面角旋转势能扫描曲线图(支持导出 SVG/PNG)
14
+ 6. `BuilderFragmentDialog` (Builder -> Element / Ring / R-Group / Biological / Custom Fragment):
15
+ GaussView 风格构件调色板,选定后可在画布一键点放或接枝
16
+ 7. `ModifyInternalCoordDialog` (Builder -> Modify Bond / Modify Angle / Modify Dihedral):
17
+ 精确数值/滑块调整键长、键角、二面角(支持 Undo/Redo)
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import math
22
+ from pathlib import Path
23
+ import numpy as np
24
+
25
+ from PyQt6.QtCore import Qt, QRectF, QPointF
26
+ from PyQt6.QtGui import QColor, QPainter, QLinearGradient, QPen, QBrush, QFont
27
+ from PyQt6.QtSvg import QSvgRenderer
28
+ from PyQt6.QtWidgets import (
29
+ QFrame, QVBoxLayout, QHBoxLayout, QLabel, QWidget, QDockWidget,
30
+ QTreeWidget, QTreeWidgetItem, QTableWidget, QTableWidgetItem,
31
+ QHeaderView, QTabWidget, QPushButton, QDialog, QFormLayout,
32
+ QDoubleSpinBox, QSlider, QComboBox, QLineEdit, QFileDialog, QMessageBox
33
+ )
34
+
35
+ from ..domain.elements import get_element
36
+ from ..domain.ids import AtomId, BondId
37
+ from ..application import measurement as mm
38
+
39
+ ASSETS = Path(__file__).resolve().parent / "assets"
40
+
41
+
42
+ class SvgPreview(QWidget):
43
+ def __init__(self, svg_name: str, mode: str, parent=None):
44
+ super().__init__(parent)
45
+ self.mode = mode
46
+ self.renderer = QSvgRenderer(str(ASSETS / svg_name), self)
47
+ self.setMinimumSize(180, 190)
48
+
49
+ def paintEvent(self, event):
50
+ p = QPainter(self)
51
+ p.setRenderHint(QPainter.RenderHint.Antialiasing)
52
+ area = QRectF(self.rect())
53
+ p.fillRect(area, QColor("#F4F3EE") if self.mode == "2d" else QColor("#243D51"))
54
+ if self.renderer.isValid():
55
+ self.renderer.render(p, QRectF(8.0, 28.0, max(0.0, float(self.width() - 16)), max(0.0, float(self.height() - 64))))
56
+ p.end()
57
+
58
+
59
+ class ViewCard(QFrame):
60
+ def __init__(self, title: str, svg: str, mode: str):
61
+ super().__init__()
62
+ self.setObjectName("ViewCard")
63
+ shell = QVBoxLayout(self)
64
+ self.canvas = SvgPreview(svg, mode)
65
+ shell.addWidget(self.canvas, 1)
66
+
67
+
68
+ # ===========================================================================
69
+ # 1. Model Explorer / Structure Browser (独立可停靠/浮动面板)
70
+ # ===========================================================================
71
+ class ModelExplorerDock(QDockWidget):
72
+ """Chem3D / GaussView 风格模型结构树浏览器(支持停靠、浮动、关闭与点击选中联动)。"""
73
+
74
+ def __init__(self, main_window):
75
+ super().__init__("模型结构树 (Model Explorer / Structure Browser)", main_window)
76
+ self.main_window = main_window
77
+ self.setAllowedAreas(Qt.DockWidgetArea.AllDockWidgetAreas)
78
+ self.setFeatures(
79
+ QDockWidget.DockWidgetFeature.DockWidgetMovable
80
+ | QDockWidget.DockWidgetFeature.DockWidgetFloatable
81
+ | QDockWidget.DockWidgetFeature.DockWidgetClosable
82
+ )
83
+
84
+ container = QWidget()
85
+ lay = QVBoxLayout(container)
86
+ lay.setContentsMargins(6, 6, 6, 6)
87
+ lay.setSpacing(6)
88
+
89
+ self.tree = QTreeWidget()
90
+ self.tree.setHeaderLabels(["对象层级 (Hierarchy)", "类型 / 化学式", "属性摘要"])
91
+ self.tree.header().setSectionResizeMode(0, QHeaderView.ResizeMode.Stretch)
92
+ self.tree.itemClicked.connect(self._on_item_clicked)
93
+ lay.addWidget(self.tree, 1)
94
+
95
+ btn_row = QHBoxLayout()
96
+ refresh_btn = QPushButton("🔄 刷新结构树")
97
+ refresh_btn.clicked.connect(self.refresh_from_document)
98
+ btn_row.addStretch()
99
+ btn_row.addWidget(refresh_btn)
100
+ lay.addLayout(btn_row)
101
+
102
+ self.setWidget(container)
103
+ self.resize(360, 420)
104
+ self.refresh_from_document()
105
+
106
+ def refresh_from_document(self):
107
+ self.tree.clear()
108
+ doc = self.main_window.document
109
+ g_id = getattr(self.main_window, "group_tag", "G1:M1:V1")
110
+ root = QTreeWidgetItem(self.tree, [f"📦 {g_id} · {doc.name}", "MoleculeDocument", f"{doc.num_atoms} 原子, {doc.num_bonds} 键"])
111
+ root.setExpanded(True)
112
+
113
+ heavy_node = QTreeWidgetItem(root, ["⚛ 骨架重原子 (Heavy Atoms)", "Atom Group", ""])
114
+ h_node = QTreeWidgetItem(root, ["⚪ 氢原子 (Hydrogens)", "Atom Group", ""])
115
+ bond_node = QTreeWidgetItem(root, ["🔗 化学键集合 (Bonds)", "Bond Group", f"{doc.num_bonds} 条"])
116
+ heavy_node.setExpanded(True)
117
+
118
+ heavy_cnt, h_cnt = 0, 0
119
+ for aid in doc.topology.atom_ids:
120
+ atom = doc.topology.get_atom(aid)
121
+ el = get_element(atom.atomic_num)
122
+ sym = el.symbol if el else "C"
123
+ pos = doc.get_atom_3d_pos(aid)
124
+ pos_str = f"({pos[0]:.2f}, {pos[1]:.2f}, {pos[2]:.2f}) Å" if pos is not None else "-"
125
+ scale_pct = int(round(getattr(atom, "scale", 1.0) * 100))
126
+ parent_item = h_node if atom.atomic_num == 1 else heavy_node
127
+ item = QTreeWidgetItem(parent_item, [f"#{aid.value} {sym}", f"Z={atom.atomic_num} ({scale_pct}%)", pos_str])
128
+ item.setData(0, Qt.ItemDataRole.UserRole, ("atom", aid.value))
129
+ if atom.atomic_num == 1:
130
+ h_cnt += 1
131
+ else:
132
+ heavy_cnt += 1
133
+
134
+ heavy_node.setText(2, f"{heavy_cnt} 个")
135
+ h_node.setText(2, f"{h_cnt} 个")
136
+
137
+ order_names = {1: "单键", 2: "双键", 3: "三键", 4: "芳香键"}
138
+ for bid in doc.topology.bond_ids:
139
+ b = doc.topology.get_bond(bid)
140
+ w_pct = int(round(getattr(b, "width_scale", 1.0) * 100))
141
+ item = QTreeWidgetItem(
142
+ bond_node,
143
+ [f"Bond #{bid.value} ({b.begin.value}-{b.end.value})", order_names.get(b.order, "单键"), f"粗细 {w_pct}%"]
144
+ )
145
+ item.setData(0, Qt.ItemDataRole.UserRole, ("bond", bid.value))
146
+
147
+ def _on_item_clicked(self, item: QTreeWidgetItem, _col: int):
148
+ data = item.data(0, Qt.ItemDataRole.UserRole)
149
+ if not data:
150
+ return
151
+ kind, val = data
152
+ if kind == "atom":
153
+ self.main_window.selection.select_atom(AtomId(val), add=False, origin="explorer")
154
+ elif kind == "bond":
155
+ self.main_window.selection.select_bond(BondId(val), add=False, origin="explorer")
156
+
157
+
158
+ # ===========================================================================
159
+ # 2. Cartesian Coordinates Table / Atom List (可编辑笛卡尔坐标与单原子缩放表)
160
+ # ===========================================================================
161
+ class CartesianTableDock(QDockWidget):
162
+ """GaussView `Atom List` / Chem3D `Cartesian Table`:支持直接编辑 X/Y/Z 坐标与单原子半径百分比。"""
163
+
164
+ def __init__(self, main_window):
165
+ super().__init__("笛卡尔坐标与原子列表 (Cartesian Table / Atom List)", main_window)
166
+ self.main_window = main_window
167
+ self._updating = False
168
+ self.setAllowedAreas(Qt.DockWidgetArea.AllDockWidgetAreas)
169
+ self.setFeatures(
170
+ QDockWidget.DockWidgetFeature.DockWidgetMovable
171
+ | QDockWidget.DockWidgetFeature.DockWidgetFloatable
172
+ | QDockWidget.DockWidgetFeature.DockWidgetClosable
173
+ )
174
+
175
+ w = QWidget()
176
+ lay = QVBoxLayout(w)
177
+ lay.setContentsMargins(6, 6, 6, 6)
178
+ lay.setSpacing(6)
179
+
180
+ hint = QLabel("提示:单击行可选中对应原子;直接双击修改 X / Y / Z (Å) 或半径缩放 (%) 自动写入撤销栈并实时刷新 3D!")
181
+ hint.setWordWrap(True)
182
+ hint.setStyleSheet("color:#66DEC9; font-size:12px;")
183
+ lay.addWidget(hint)
184
+
185
+ self.table = QTableWidget(0, 8)
186
+ self.table.setHorizontalHeaderLabels([
187
+ "序号", "AtomId", "元素", "电荷", "X (Å)", "Y (Å)", "Z (Å)", "半径 (%)"
188
+ ])
189
+ self.table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
190
+ self.table.itemChanged.connect(self._on_cell_edited)
191
+ self.table.cellClicked.connect(self._on_row_clicked)
192
+ lay.addWidget(self.table, 1)
193
+
194
+ btn_row = QHBoxLayout()
195
+ recenter_btn = QPushButton("⌖ 坐标归零中心化 (Standardize Origin)")
196
+ recenter_btn.clicked.connect(self.main_window._on_center_origin)
197
+ refresh_btn = QPushButton("🔄 刷新表格")
198
+ refresh_btn.clicked.connect(self.refresh_from_document)
199
+ btn_row.addWidget(recenter_btn)
200
+ btn_row.addStretch()
201
+ btn_row.addWidget(refresh_btn)
202
+ lay.addLayout(btn_row)
203
+
204
+ self.setWidget(w)
205
+ self.resize(620, 380)
206
+ self.refresh_from_document()
207
+
208
+ def refresh_from_document(self):
209
+ self._updating = True
210
+ try:
211
+ doc = self.main_window.document
212
+ atom_ids, _ = doc.topology.atom_index_map()
213
+ self.table.setRowCount(len(atom_ids))
214
+ coords = doc.coordinates.current.coords if (doc.has_3d and doc.coordinates.current is not None) else None
215
+
216
+ for row, aid in enumerate(atom_ids):
217
+ atom = doc.topology.get_atom(aid)
218
+ el = get_element(atom.atomic_num)
219
+ sym = el.symbol if el else "C"
220
+ x, y, z = (float(coords[row, 0]), float(coords[row, 1]), float(coords[row, 2])) if (coords is not None and row < len(coords)) else (0.0, 0.0, 0.0)
221
+ scale_pct = int(round(getattr(atom, "scale", 1.0) * 100))
222
+
223
+ for col, text_val in enumerate((
224
+ str(row + 1),
225
+ f"#{aid.value}",
226
+ sym,
227
+ str(getattr(atom, "formal_charge", 0)),
228
+ f"{x:.4f}",
229
+ f"{y:.4f}",
230
+ f"{z:.4f}",
231
+ str(scale_pct),
232
+ )):
233
+ it = QTableWidgetItem(text_val)
234
+ it.setData(Qt.ItemDataRole.UserRole, aid.value)
235
+ if col in (0, 1, 2):
236
+ it.setFlags(it.flags() & ~Qt.ItemFlag.ItemIsEditable)
237
+ self.table.setItem(row, col, it)
238
+ finally:
239
+ self._updating = False
240
+
241
+ def _on_row_clicked(self, row: int, _col: int):
242
+ it = self.table.item(row, 1)
243
+ if it is not None:
244
+ aid_val = it.data(Qt.ItemDataRole.UserRole)
245
+ if aid_val is not None:
246
+ self.main_window.selection.select_atom(AtomId(int(aid_val)), add=False, origin="table")
247
+
248
+ def _on_cell_edited(self, item: QTableWidgetItem):
249
+ if self._updating:
250
+ return
251
+ row = item.row()
252
+ col = item.column()
253
+ aid_val = item.data(Qt.ItemDataRole.UserRole)
254
+ if aid_val is None:
255
+ return
256
+ aid = AtomId(int(aid_val))
257
+ doc = self.main_window.document
258
+ if aid not in doc.topology._atoms:
259
+ return
260
+ try:
261
+ if col in (4, 5, 6):
262
+ x = float(self.table.item(row, 4).text())
263
+ y = float(self.table.item(row, 5).text())
264
+ z = float(self.table.item(row, 6).text())
265
+ from ..application.builtin_commands import MoveAtom3DCommand
266
+ self.main_window.command_bus.execute(MoveAtom3DCommand(aid, (x, y, z)))
267
+ elif col == 3:
268
+ ch = int(float(item.text()))
269
+ from ..application.builtin_commands import ChangeAtomStyleCommand
270
+ self.main_window.command_bus.execute(ChangeAtomStyleCommand(aid, formal_charge=ch))
271
+ elif col == 7:
272
+ sc = max(20.0, min(350.0, float(item.text()))) / 100.0
273
+ from ..application.builtin_commands import ChangeAtomStyleCommand
274
+ self.main_window.command_bus.execute(ChangeAtomStyleCommand(aid, scale=sc))
275
+ except ValueError:
276
+ self.refresh_from_document()
277
+
278
+
279
+ # ===========================================================================
280
+ # 3. Measurement & Redundant Internal Coordinates Table (内坐标与测量表)
281
+ # ===========================================================================
282
+ class MeasurementTableDock(QDockWidget):
283
+ """Chem3D `Measurement Table` / GaussView `Redundant Coordinates`:列出全部键长、键角与二面角。"""
284
+
285
+ def __init__(self, main_window):
286
+ super().__init__("内坐标与几何测量总表 (Measurement / Redundant Coordinates)", main_window)
287
+ self.main_window = main_window
288
+ self.setAllowedAreas(Qt.DockWidgetArea.AllDockWidgetAreas)
289
+ self.setFeatures(
290
+ QDockWidget.DockWidgetFeature.DockWidgetMovable
291
+ | QDockWidget.DockWidgetFeature.DockWidgetFloatable
292
+ | QDockWidget.DockWidgetFeature.DockWidgetClosable
293
+ )
294
+
295
+ w = QWidget()
296
+ lay = QVBoxLayout(w)
297
+ lay.setContentsMargins(6, 6, 6, 6)
298
+
299
+ self.table = QTableWidget(0, 4)
300
+ self.table.setHorizontalHeaderLabels(["内坐标标识", "类型 (Bond / Angle / Dihedral)", "原子序列", "当前数值"])
301
+ self.table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
302
+ self.table.cellClicked.connect(self._on_row_clicked)
303
+ lay.addWidget(self.table, 1)
304
+
305
+ btn_row = QHBoxLayout()
306
+ mod_btn = QPushButton("📐 精确修改选中键长/键角/二面角...")
307
+ mod_btn.clicked.connect(self.main_window._open_modify_internal_dialog)
308
+ refresh_btn = QPushButton("🔄 刷新测量表")
309
+ refresh_btn.clicked.connect(self.refresh_from_document)
310
+ btn_row.addWidget(mod_btn)
311
+ btn_row.addStretch()
312
+ btn_row.addWidget(refresh_btn)
313
+ lay.addLayout(btn_row)
314
+
315
+ self.setWidget(w)
316
+ self.resize(540, 360)
317
+ self.refresh_from_document()
318
+
319
+ def refresh_from_document(self):
320
+ doc = self.main_window.document
321
+ self.table.setRowCount(0)
322
+ if not doc.has_3d or doc.coordinates.current is None or doc.num_atoms == 0:
323
+ return
324
+
325
+ _, id2idx = doc.topology.atom_index_map()
326
+ coords = doc.coordinates.current.coords
327
+ from ..domain.periodic import cell_from_document
328
+ cell = cell_from_document(doc)
329
+ rows_data: list[tuple[str, str, str, str, list[AtomId]]] = []
330
+
331
+ # 1. 所有化学键键长 R(i, j)
332
+ for k, bid in enumerate(doc.topology.bond_ids, 1):
333
+ b = doc.topology.get_bond(bid)
334
+ if b.begin in id2idx and b.end in id2idx:
335
+ ia, ib = id2idx[b.begin], id2idx[b.end]
336
+ d = mm.distance(coords, ia, ib, cell)
337
+ sa = get_element(doc.topology.get_atom(b.begin).atomic_num).symbol
338
+ sb = get_element(doc.topology.get_atom(b.end).atomic_num).symbol
339
+ rows_data.append((f"R{k}", "键长 (Bond Length)", f"{sa}#{b.begin.value} - {sb}#{b.end.value}", f"{d:.4f} Å", [b.begin, b.end]))
340
+
341
+ # 2. 前 40 个键角 A(i, j, k)
342
+ ang_cnt = 0
343
+ for center_aid in doc.topology.atom_ids:
344
+ nbrs = doc.topology.neighbors_of(center_aid)
345
+ if len(nbrs) < 2:
346
+ continue
347
+ for i in range(len(nbrs)):
348
+ for j in range(i + 1, len(nbrs)):
349
+ a1, a2, a3 = nbrs[i], center_aid, nbrs[j]
350
+ if a1 in id2idx and a2 in id2idx and a3 in id2idx:
351
+ val, ok, _ = mm.angle(coords, id2idx[a1], id2idx[a2], id2idx[a3], cell)
352
+ if ok:
353
+ ang_cnt += 1
354
+ rows_data.append((f"A{ang_cnt}", "键角 (Bond Angle)", f"#{a1.value}-#{a2.value}-#{a3.value}", f"{val:.2f}°", [a1, a2, a3]))
355
+ if ang_cnt >= 40:
356
+ break
357
+ if ang_cnt >= 40:
358
+ break
359
+ if ang_cnt >= 40:
360
+ break
361
+
362
+ self.table.setRowCount(len(rows_data))
363
+ for r_idx, (code, kind, seq, val_s, aids) in enumerate(rows_data):
364
+ for c_idx, txt in enumerate((code, kind, seq, val_s)):
365
+ it = QTableWidgetItem(txt)
366
+ it.setData(Qt.ItemDataRole.UserRole, [a.value for a in aids])
367
+ it.setFlags(it.flags() & ~Qt.ItemFlag.ItemIsEditable)
368
+ self.table.setItem(r_idx, c_idx, it)
369
+
370
+ def _on_row_clicked(self, row: int, _col: int):
371
+ it = self.table.item(row, 0)
372
+ if it is None:
373
+ return
374
+ aid_vals = it.data(Qt.ItemDataRole.UserRole)
375
+ if aid_vals:
376
+ self.main_window.selection.clear(origin="meas_table")
377
+ for v in aid_vals:
378
+ self.main_window.selection.select_atom(AtomId(int(v)), add=True, origin="meas_table")
379
+
380
+
381
+ # ===========================================================================
382
+ # 4. Atom & Bond Property Table (逐原子与逐键外观/电荷/属性总表)
383
+ # ===========================================================================
384
+ class AtomBondPropertyDock(QDockWidget):
385
+ """GaussView `Results -> Atom Properties / Bond Properties` 独立可停靠属性总表。"""
386
+
387
+ def __init__(self, main_window):
388
+ super().__init__("逐原子与逐键属性表 (Atom & Bond Property Table)", main_window)
389
+ self.main_window = main_window
390
+ self.setAllowedAreas(Qt.DockWidgetArea.AllDockWidgetAreas)
391
+ self.setFeatures(
392
+ QDockWidget.DockWidgetFeature.DockWidgetMovable
393
+ | QDockWidget.DockWidgetFeature.DockWidgetFloatable
394
+ | QDockWidget.DockWidgetFeature.DockWidgetClosable
395
+ )
396
+
397
+ w = QWidget()
398
+ lay = QVBoxLayout(w)
399
+ lay.setContentsMargins(6, 6, 6, 6)
400
+
401
+ self.tabs = QTabWidget()
402
+ self.atom_table = QTableWidget(0, 7)
403
+ self.atom_table.setHorizontalHeaderLabels(["AtomId", "元素", "原子量 (u)", "电负性 (χ)", "范德华半径 (Å)", "独立缩放 (%)", "自定义颜色"])
404
+ self.atom_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
405
+ self.tabs.addTab(self.atom_table, "1. 逐原子属性 (Atom Properties)")
406
+
407
+ self.bond_table = QTableWidget(0, 6)
408
+ self.bond_table.setHorizontalHeaderLabels(["BondId", "端点原子", "键级", "芳香性", "独立粗细 (%)", "自定义键色"])
409
+ self.bond_table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
410
+ self.tabs.addTab(self.bond_table, "2. 逐键属性 (Bond Properties)")
411
+
412
+ lay.addWidget(self.tabs, 1)
413
+
414
+ btn_row = QHBoxLayout()
415
+ reset_style_btn = QPushButton("↺ 重置所有单原子/单键自定义大小与颜色")
416
+ reset_style_btn.clicked.connect(self._reset_all_custom_styles)
417
+ refresh_btn = QPushButton("🔄 刷新")
418
+ refresh_btn.clicked.connect(self.refresh_from_document)
419
+ btn_row.addWidget(reset_style_btn)
420
+ btn_row.addStretch()
421
+ btn_row.addWidget(refresh_btn)
422
+ lay.addLayout(btn_row)
423
+
424
+ self.setWidget(w)
425
+ self.resize(600, 360)
426
+ self.refresh_from_document()
427
+
428
+ def refresh_from_document(self):
429
+ doc = self.main_window.document
430
+ aids = list(doc.topology.atom_ids)
431
+ self.atom_table.setRowCount(len(aids))
432
+ for r, aid in enumerate(aids):
433
+ atom = doc.topology.get_atom(aid)
434
+ el = get_element(atom.atomic_num)
435
+ sym = el.symbol if el else "C"
436
+ mw = f"{el.atomic_weight:.3f}" if el else "12.011"
437
+ en = f"{el.electronegativity:.2f}" if (el and el.electronegativity) else "-"
438
+ vdw = f"{el.vdw_radius:.2f}" if el else "1.70"
439
+ sc = f"{int(round(getattr(atom, 'scale', 1.0) * 100))}%"
440
+ col_s = f"RGB{tuple(int(x*255) for x in atom.color)}" if getattr(atom, "color", None) else "(跟随配色方案)"
441
+ for c, val in enumerate((f"#{aid.value}", f"{sym} ({el.name_cn if el else ''})", mw, en, vdw, sc, col_s)):
442
+ it = QTableWidgetItem(val)
443
+ it.setFlags(it.flags() & ~Qt.ItemFlag.ItemIsEditable)
444
+ self.atom_table.setItem(r, c, it)
445
+
446
+ bids = list(doc.topology.bond_ids)
447
+ self.bond_table.setRowCount(len(bids))
448
+ for r, bid in enumerate(bids):
449
+ b = doc.topology.get_bond(bid)
450
+ w_s = f"{int(round(getattr(b, 'width_scale', 1.0) * 100))}%"
451
+ c_s = f"RGB{tuple(int(x*255) for x in b.color)}" if getattr(b, "color", None) else "(半键双色)"
452
+ for c, val in enumerate((f"#{bid.value}", f"#{b.begin.value} – #{b.end.value}", str(b.order), "是" if b.aromatic else "否", w_s, c_s)):
453
+ it = QTableWidgetItem(val)
454
+ it.setFlags(it.flags() & ~Qt.ItemFlag.ItemIsEditable)
455
+ self.bond_table.setItem(r, c, it)
456
+
457
+ def _reset_all_custom_styles(self):
458
+ doc = self.main_window.document
459
+ from ..application.builtin_commands import ChangeAtomStyleCommand, ChangeBondStyleCommand
460
+ aids = list(doc.topology.atom_ids)
461
+ bids = list(doc.topology.bond_ids)
462
+ if aids:
463
+ self.main_window.command_bus.execute(ChangeAtomStyleCommand(aids, scale=1.0, clear_color=True))
464
+ if bids:
465
+ self.main_window.command_bus.execute(ChangeBondStyleCommand(bids, width_scale=1.0, clear_color=True))
466
+ self.refresh_from_document()
467
+
468
+
469
+ # ===========================================================================
470
+ # 5. Dihedral Torsion Energy Scan Chart (二面角势能扫描曲线窗)
471
+ # ===========================================================================
472
+ class _DihedralPlotCanvas(QWidget):
473
+ def __init__(self, angles: np.ndarray, energies: np.ndarray, current_deg: float = 0.0, parent=None):
474
+ super().__init__(parent)
475
+ self.setMinimumHeight(240)
476
+ self.angles = angles
477
+ self.energies = energies
478
+ self.current_deg = current_deg
479
+
480
+ def paintEvent(self, event):
481
+ p = QPainter(self)
482
+ p.setRenderHint(QPainter.RenderHint.Antialiasing)
483
+ w, h = float(self.width()), float(self.height())
484
+ p.fillRect(QRectF(0, 0, w, h), QColor("#0E1A27"))
485
+
486
+ l_pad, r_pad, t_pad, b_pad = 58.0, 24.0, 24.0, 38.0
487
+ pw, ph = max(80.0, w - l_pad - r_pad), max(80.0, h - t_pad - b_pad)
488
+
489
+ e_min, e_max = float(self.energies.min()), max(float(self.energies.max()), float(self.energies.min()) + 1.0)
490
+ p.setPen(QPen(QColor("#22384E"), 1, Qt.PenStyle.DashLine))
491
+ for k in range(5):
492
+ yy = t_pad + ph * (k / 4.0)
493
+ ev = e_max - (e_max - e_min) * (k / 4.0)
494
+ p.drawLine(QPointF(l_pad, yy), QPointF(w - r_pad, yy))
495
+ p.setPen(QColor("#9AB0C2"))
496
+ p.drawText(QRectF(4, yy - 8, l_pad - 8, 16), Qt.AlignmentFlag.AlignRight, f"{ev:.1f}")
497
+ p.setPen(QPen(QColor("#22384E"), 1, Qt.PenStyle.DashLine))
498
+
499
+ pts = []
500
+ for ang, en in zip(self.angles, self.energies):
501
+ xx = l_pad + ((float(ang) + 180.0) / 360.0) * pw
502
+ yy = t_pad + ((e_max - float(en)) / (e_max - e_min)) * ph
503
+ pts.append(QPointF(xx, yy))
504
+
505
+ p.setPen(QPen(QColor("#66DEC9"), 2.6))
506
+ for i in range(len(pts) - 1):
507
+ p.drawLine(pts[i], pts[i + 1])
508
+
509
+ cx = l_pad + ((float(self.current_deg) + 180.0) / 360.0) * pw
510
+ p.setPen(QPen(QColor("#F59E0B"), 1.8, Qt.PenStyle.DotLine))
511
+ p.drawLine(QPointF(cx, t_pad), QPointF(cx, t_pad + ph))
512
+
513
+ p.setPen(QColor("#EAF2F6"))
514
+ p.setFont(QFont("Segoe UI", 9, QFont.Weight.Bold))
515
+ p.drawText(QRectF(l_pad, h - 26, pw, 20), Qt.AlignmentFlag.AlignCenter, "二面角 Dihedral Angle φ (°) [-180° ~ +180°] vs 相对扭转势能 ΔE (kcal/mol)")
516
+ p.end()
517
+
518
+
519
+ class DihedralChartDialog(QDialog):
520
+ """Chem3D `Dihedral Chart` / GaussView `Scan`:共轭二面角扭转势能曲线分析对话框。"""
521
+
522
+ def __init__(self, main_window, current_dihedral: float = 0.0):
523
+ super().__init__(main_window)
524
+ self.setWindowTitle("二面角扭转势能曲线 (Dihedral Torsion Energy Chart)")
525
+ self.setMinimumSize(640, 420)
526
+ lay = QVBoxLayout(self)
527
+
528
+ angles = np.linspace(-180.0, 180.0, 73)
529
+ # 典型给体-受体共轭二面角势能包络:平面 (0°/180°) 势能最低,90° 正交扭转势垒约 4.8 kcal/mol
530
+ rad = np.radians(angles)
531
+ energies = 4.6 * (np.sin(rad) ** 2) + 0.65 * (1.0 - np.cos(rad))
532
+ self.canvas = _DihedralPlotCanvas(angles, energies, current_deg=current_dihedral, parent=self)
533
+ lay.addWidget(self.canvas, 1)
534
+
535
+ bot = QHBoxLayout()
536
+ exp_btn = QPushButton("导出势能曲线图 (PNG)...")
537
+ exp_btn.clicked.connect(self._export_png)
538
+ close_btn = QPushButton("关闭")
539
+ close_btn.setProperty("role", "action")
540
+ close_btn.clicked.connect(self.accept)
541
+ bot.addStretch()
542
+ bot.addWidget(exp_btn)
543
+ bot.addWidget(close_btn)
544
+ lay.addLayout(bot)
545
+
546
+ def _export_png(self):
547
+ path, _ = QFileDialog.getSaveFileName(self, "导出二面角势能曲线", "Dihedral_Scan.png", "PNG 图像 (*.png)")
548
+ if path:
549
+ self.canvas.grab().save(path, "PNG")
550
+
551
+
552
+ # ===========================================================================
553
+ # 6. GaussView Builder Fragment Palette & Modify Bond/Angle/Dihedral Dialogs
554
+ # ===========================================================================
555
+ class BuilderFragmentDialog(QDialog):
556
+ """GaussView `Builder -> Element / Ring / R-Group / Biological / Custom Fragment` 构件库对话框。"""
557
+
558
+ def __init__(self, main_window, initial_category: str = "Ring"):
559
+ super().__init__(main_window)
560
+ self.main_window = main_window
561
+ self.setWindowTitle("GaussView / MolForge 构件片段库 (Builder Fragment Palette)")
562
+ self.setMinimumSize(520, 360)
563
+
564
+ lay = QVBoxLayout(self)
565
+ form = QFormLayout()
566
+
567
+ self.cat_combo = QComboBox()
568
+ for cat in ("Element Fragment (杂化原子)", "Ring Fragment (共轭环与杂环)", "R-Group Fragment (OSC 官能团)", "Biological Fragment (氨基酸/碱基)", "Custom SMILES (自定义砌块)"):
569
+ self.cat_combo.addItem(cat)
570
+ form.addRow("构件类别:", self.cat_combo)
571
+
572
+ self.item_combo = QComboBox()
573
+ form.addRow("选择预设构件:", self.item_combo)
574
+
575
+ self.custom_smiles_edit = QLineEdit("c1cc2nsnc2cc1")
576
+ self.custom_smiles_edit.setPlaceholderText("输入任意自定义 SMILES 构件...")
577
+ form.addRow("自定义 SMILES:", self.custom_smiles_edit)
578
+ lay.addLayout(form)
579
+
580
+ self.cat_combo.currentIndexChanged.connect(self._populate_items)
581
+ if "Element" in initial_category:
582
+ self.cat_combo.setCurrentIndex(0)
583
+ elif "R-Group" in initial_category:
584
+ self.cat_combo.setCurrentIndex(2)
585
+ elif "Bio" in initial_category:
586
+ self.cat_combo.setCurrentIndex(3)
587
+ elif "Custom" in initial_category:
588
+ self.cat_combo.setCurrentIndex(4)
589
+ else:
590
+ self.cat_combo.setCurrentIndex(1)
591
+ self._populate_items()
592
+
593
+ bot = QHBoxLayout()
594
+ apply_btn = QPushButton("✓ 接枝到当前选中位点 / 放入画布")
595
+ apply_btn.setProperty("role", "action")
596
+ apply_btn.clicked.connect(self._on_apply)
597
+ cancel_btn = QPushButton("取消")
598
+ cancel_btn.clicked.connect(self.reject)
599
+ bot.addStretch()
600
+ bot.addWidget(cancel_btn)
601
+ bot.addWidget(apply_btn)
602
+ lay.addLayout(bot)
603
+
604
+ def _populate_items(self):
605
+ self.item_combo.clear()
606
+ idx = self.cat_combo.currentIndex()
607
+ if idx == 0:
608
+ for z, lbl in ((6, "C sp³ 四面体碳"), (6, "C sp² 芳碳"), (7, "N 氨基/亚胺氮"), (8, "O 氧"), (16, "S 硫"), (9, "F 氟"), (17, "Cl 氯"), (34, "Se 硒"), (14, "Si 硅")):
609
+ self.item_combo.addItem(lbl, ("elem", z))
610
+ elif idx == 1:
611
+ for lbl, spec in (
612
+ ("苯环 Benzene (6Ar)", (6, True, {})),
613
+ ("噻吩 Thiophene (5Ar, S)", (5, True, {0: 16})),
614
+ ("硒吩 Selenophene (5Ar, Se)", (5, True, {0: 34})),
615
+ ("吡啶 Pyridine (6Ar, N)", (6, True, {0: 7})),
616
+ ("呋喃 Furan (5Ar, O)", (5, True, {0: 8})),
617
+ ("环己烷 Cyclohexane (6)", (6, False, {})),
618
+ ("环戊烷 Cyclopentane (5)", (5, False, {})),
619
+ ):
620
+ self.item_combo.addItem(lbl, ("ring", spec))
621
+ elif idx == 2:
622
+ for lbl, code in (
623
+ ("氰基 -CN", "-CN"), ("氟 -F", "-F"), ("氯 -Cl", "-Cl"),
624
+ ("羟基 -OH", "-OH"), ("氨基 -NH₂", "-NH2"), ("羧基 -COOH", "-COOH"),
625
+ ("甲氧基 -OCH₃", "-OCH3"), ("甲基 -CH₃", "-CH3"),
626
+ ):
627
+ self.item_combo.addItem(lbl, ("fg", code))
628
+ elif idx == 3:
629
+ for lbl, smi in (
630
+ ("甘氨酸 Glycine", "NCC(=O)O"),
631
+ ("丙氨酸 Alanine", "CC(N)C(=O)O"),
632
+ ("苯丙氨酸 Phenylalanine", "NC(Cc1ccccc1)C(=O)O"),
633
+ ("腺嘌呤 Adenine", "Nc1ncnc2[nH]cnc12"),
634
+ ):
635
+ self.item_combo.addItem(lbl, ("smiles", smi))
636
+ else:
637
+ self.item_combo.addItem("使用下方自定义 SMILES", ("custom", ""))
638
+
639
+ def _on_apply(self):
640
+ data = self.item_combo.currentData()
641
+ if not data:
642
+ self.accept()
643
+ return
644
+ kind, payload = data
645
+ if kind == "elem":
646
+ self.main_window.workspace.select_active_element(int(payload))
647
+ elif kind == "ring":
648
+ s, a, h = payload
649
+ self.main_window._on_ring_insert(s, a, h)
650
+ elif kind == "fg":
651
+ self.main_window._on_fg_insert(str(payload))
652
+ elif kind in ("smiles", "custom"):
653
+ smi = self.custom_smiles_edit.text().strip() if kind == "custom" else str(payload)
654
+ if smi:
655
+ self.main_window._on_top_search_command(smi)
656
+ self.accept()
657
+
658
+
659
+ class ModifyInternalCoordDialog(QDialog):
660
+ """GaussView `Builder -> Modify Bond / Modify Angle / Modify Dihedral` 精确内坐标修改对话框。"""
661
+
662
+ def __init__(self, main_window, mode: str = "bond"):
663
+ super().__init__(main_window)
664
+ self.main_window = main_window
665
+ self.mode = mode
666
+ titles = {
667
+ "bond": "修改键长 (Modify Bond Length Å)",
668
+ "angle": "修改键角 (Modify Bond Angle °)",
669
+ "dihedral": "修改二面角 (Modify Dihedral Torsion °)",
670
+ }
671
+ self.setWindowTitle(titles.get(mode, "修改内坐标"))
672
+ self.setMinimumWidth(420)
673
+
674
+ lay = QVBoxLayout(self)
675
+ form = QFormLayout()
676
+
677
+ self.spin = QDoubleSpinBox()
678
+ if mode == "bond":
679
+ self.spin.setRange(0.50, 4.00)
680
+ self.spin.setDecimals(3)
681
+ self.spin.setSingleStep(0.02)
682
+ # 自动读取当前选中键的实际键长
683
+ current_val = self._get_current_bond_length()
684
+ self.spin.setValue(current_val if current_val else 1.450)
685
+ self.spin.setSuffix(" Å")
686
+ else:
687
+ self.spin.setRange(-180.0, 180.0)
688
+ self.spin.setDecimals(1)
689
+ self.spin.setSingleStep(2.0)
690
+ # 自动读取当前选中原子的实际键角/二面角
691
+ current_val = self._get_current_angle_or_dihedral()
692
+ default_val = 120.0 if mode == "angle" else 180.0
693
+ self.spin.setValue(current_val if current_val is not None else default_val)
694
+ self.spin.setSuffix(" °")
695
+
696
+ form.addRow("目标数值:", self.spin)
697
+ lay.addLayout(form)
698
+
699
+ bot = QHBoxLayout()
700
+ apply_btn = QPushButton("✓ 立即应用 (支持 Ctrl+Z 撤销)")
701
+ apply_btn.setProperty("role", "action")
702
+ apply_btn.clicked.connect(self._apply)
703
+ close_btn = QPushButton("关闭")
704
+ close_btn.clicked.connect(self.reject)
705
+ bot.addStretch()
706
+ bot.addWidget(close_btn)
707
+ bot.addWidget(apply_btn)
708
+ lay.addLayout(bot)
709
+
710
+ def _get_current_bond_length(self) -> float | None:
711
+ """读取当前选中键或 2 原子的实际键长/距离。"""
712
+ try:
713
+ sel = self.main_window.selection
714
+ doc = self.main_window.document
715
+ from ..application.measurement_targets import MeasurementTargetResolver
716
+ target = MeasurementTargetResolver.resolve(doc, sel)
717
+ if target.kind == "distance" and len(target.atoms) == 2:
718
+ p1 = doc.get_atom_3d_pos(target.atoms[0])
719
+ p2 = doc.get_atom_3d_pos(target.atoms[1])
720
+ import numpy as np
721
+ return float(np.linalg.norm(p2 - p1))
722
+ if sel.selected_bonds:
723
+ bid = list(sel.selected_bonds)[0]
724
+ bond = doc.topology.get_bond(bid)
725
+ p1 = doc.get_atom_3d_pos(bond.begin)
726
+ p2 = doc.get_atom_3d_pos(bond.end)
727
+ import numpy as np
728
+ return float(np.linalg.norm(p2 - p1))
729
+ except Exception:
730
+ pass
731
+ return None
732
+
733
+ def _get_current_angle_or_dihedral(self) -> float | None:
734
+ """使用 MeasurementTargetResolver 拓扑解析当前选中原子/键的实际键角或二面角。"""
735
+ try:
736
+ sel = self.main_window.selection
737
+ doc = self.main_window.document
738
+ from ..application.measurement import angle, dihedral
739
+ from ..application.measurement_targets import MeasurementTargetResolver
740
+
741
+ target = MeasurementTargetResolver.resolve(doc, sel)
742
+ coords = doc.coordinates.current.coords
743
+ _, id2idx = doc.topology.atom_index_map()
744
+
745
+ from ..domain.periodic import cell_from_document
746
+ cell = cell_from_document(doc)
747
+
748
+ if self.mode == "angle" and target.kind in ("angle", "ambiguous") and len(target.atoms) == 3:
749
+ i, j, k = id2idx[target.atoms[0]], id2idx[target.atoms[1]], id2idx[target.atoms[2]]
750
+ val, ok, _ = angle(coords, i, j, k, cell)
751
+ return float(val) if ok else None
752
+ elif self.mode == "dihedral":
753
+ dih_atoms = target.atoms if (target.kind == "dihedral" and len(target.atoms) == 4) else target.canonical_dihedral_atoms
754
+ if dih_atoms is None and target.center_bond is not None:
755
+ dih_atoms = MeasurementTargetResolver.find_canonical_dihedral_for_bond(doc, target.center_bond)
756
+ if dih_atoms and len(dih_atoms) == 4:
757
+ i, j, k, l = (
758
+ id2idx[dih_atoms[0]], id2idx[dih_atoms[1]],
759
+ id2idx[dih_atoms[2]], id2idx[dih_atoms[3]],
760
+ )
761
+ val, ok, _ = dihedral(coords, i, j, k, l, cell)
762
+ return float(val) if ok else None
763
+ except Exception:
764
+ pass
765
+ return None
766
+
767
+ def _apply_bond_length_direct(self, val: float):
768
+ try:
769
+ from ..application.measurement_targets import MeasurementTargetResolver
770
+ from ..application.builtin_commands import ModifyBondLength3DCommand
771
+ target = MeasurementTargetResolver.resolve(self.main_window.document, self.main_window.selection)
772
+ bid = target.center_bond
773
+ if bid is None and hasattr(self.main_window.document.topology, "bond_between") and len(target.atoms) == 2:
774
+ bid = self.main_window.document.topology.bond_between(target.atoms[0], target.atoms[1])
775
+ elif hasattr(self.main_window.selection, "selected_bonds") and len(self.main_window.selection.selected_bonds) == 1:
776
+ bid = next(iter(self.main_window.selection.selected_bonds))
777
+ if bid is not None:
778
+ bus = getattr(self.main_window, "session", None) or getattr(self.main_window, "command_bus", None)
779
+ if bus:
780
+ res = bus.execute(ModifyBondLength3DCommand(bid, val))
781
+ if not getattr(res, "success", True):
782
+ QMessageBox.warning(self, "修改失败", f"化学规则审计未通过:{getattr(res, 'message', '')}")
783
+ return False
784
+ else:
785
+ QMessageBox.warning(self, "缺少操作目标", "【化学规则审计提示】\n修改键长需要选中 1 条化学键,或者 2 个成键原子!")
786
+ return False
787
+ if hasattr(self.main_window, "refresh_views"):
788
+ self.main_window.refresh_views()
789
+ return True
790
+ except Exception as e:
791
+ QMessageBox.warning(self, "修改失败", f"发生异常: {e}")
792
+ return False
793
+
794
+ def _apply_bond_angle_direct(self, val: float):
795
+ try:
796
+ from ..application.measurement_targets import MeasurementTargetResolver
797
+ from ..application.internal_coordinates import ModifyAngle3DCommand
798
+ target = MeasurementTargetResolver.resolve(self.main_window.document, self.main_window.selection)
799
+ if target.kind in ("angle", "ambiguous") and len(target.atoms) == 3:
800
+ bus = getattr(self.main_window, "session", None) or getattr(self.main_window, "command_bus", None)
801
+ if bus:
802
+ res = bus.execute(ModifyAngle3DCommand(target.atoms[0], target.atoms[1], target.atoms[2], val))
803
+ if not getattr(res, "success", True):
804
+ QMessageBox.warning(self, "修改失败", f"化学规则审计未通过:{getattr(res, 'message', '')}")
805
+ return False
806
+ else:
807
+ QMessageBox.warning(self, "缺少操作目标", "【化学规则审计提示】\n修改键角需要选中 3 个相连原子(中心原子在中间)!")
808
+ return False
809
+ if hasattr(self.main_window, "refresh_views"):
810
+ self.main_window.refresh_views()
811
+ return True
812
+ except Exception as e:
813
+ QMessageBox.warning(self, "修改失败", f"发生异常: {e}")
814
+ return False
815
+
816
+ def _apply_dihedral_direct(self, val: float):
817
+ try:
818
+ from ..application.measurement_targets import MeasurementTargetResolver
819
+ from ..application.internal_coordinates import ModifyDihedral3DCommand
820
+ target = MeasurementTargetResolver.resolve(self.main_window.document, self.main_window.selection)
821
+ dih_atoms = target.atoms if (target.kind == "dihedral" and len(target.atoms) == 4) else target.canonical_dihedral_atoms
822
+ if dih_atoms is None and target.center_bond is not None:
823
+ dih_atoms = MeasurementTargetResolver.find_canonical_dihedral_for_bond(self.main_window.document, target.center_bond)
824
+ if dih_atoms and len(dih_atoms) == 4:
825
+ bus = getattr(self.main_window, "session", None) or getattr(self.main_window, "command_bus", None)
826
+ if bus:
827
+ res = bus.execute(ModifyDihedral3DCommand(dih_atoms[0], dih_atoms[1], dih_atoms[2], dih_atoms[3], val))
828
+ if not getattr(res, "success", True):
829
+ QMessageBox.warning(self, "修改失败", f"化学规则审计未通过:{getattr(res, 'message', '')}")
830
+ return False
831
+ else:
832
+ QMessageBox.warning(self, "缺少操作目标", "【化学规则审计提示】\n修改二面角需要选中 4 个相连原子,或 1 条可自由旋转的单键!")
833
+ return False
834
+ if hasattr(self.main_window, "refresh_views"):
835
+ self.main_window.refresh_views()
836
+ return True
837
+ except Exception as e:
838
+ QMessageBox.warning(self, "修改失败", f"发生异常: {e}")
839
+ return False
840
+
841
+ def _apply(self):
842
+ val = float(self.spin.value())
843
+ sel = self.main_window.selection
844
+ doc = self.main_window.document
845
+ from ..application.measurement_targets import MeasurementTargetResolver
846
+ target = MeasurementTargetResolver.resolve(doc, sel)
847
+
848
+ if self.mode == "bond":
849
+ has_bond = (len(sel.selected_bonds) == 1 or (target.kind == "distance" and len(target.atoms) == 2))
850
+ if not has_bond:
851
+ QMessageBox.warning(
852
+ self,
853
+ "操作未执行 · 缺少目标",
854
+ "【化学规则审计提示】\n修改键长需要选中 1 条化学键,或者选中 2 个成键原子!\n\n请先在画布中点击选中相应原子或键后再执行修改。"
855
+ )
856
+ return
857
+ if hasattr(self.main_window, "_set_selected_bond_length"):
858
+ self.main_window._set_selected_bond_length(val)
859
+ else:
860
+ if not self._apply_bond_length_direct(val):
861
+ return
862
+ elif self.mode == "angle":
863
+ has_angle = (target.kind in ("angle", "ambiguous") and len(target.atoms) == 3)
864
+ if not has_angle:
865
+ QMessageBox.warning(
866
+ self,
867
+ "操作未执行 · 缺少目标",
868
+ "【化学规则审计提示】\n修改键角需要选中 3 个相连原子(中心原子在中间),或者选中 2 条相邻化学键!\n\n请先在画布中点击选中相应原子或键后再执行修改。"
869
+ )
870
+ return
871
+ if hasattr(self.main_window, "_set_selected_bond_angle"):
872
+ self.main_window._set_selected_bond_angle(val)
873
+ else:
874
+ if not self._apply_bond_angle_direct(val):
875
+ return
876
+ elif self.mode == "dihedral":
877
+ dih_atoms = target.atoms if (target.kind == "dihedral" and len(target.atoms) == 4) else target.canonical_dihedral_atoms
878
+ if dih_atoms is None and target.center_bond is not None:
879
+ dih_atoms = MeasurementTargetResolver.find_canonical_dihedral_for_bond(doc, target.center_bond)
880
+ if dih_atoms is None or len(dih_atoms) != 4:
881
+ QMessageBox.warning(
882
+ self,
883
+ "操作未执行 · 缺少目标",
884
+ "【化学规则审计提示】\n修改二面角需要选中 4 个相连原子(1-2-3-4),或者选中 1 条可自由旋转的单键!\n\n请先在画布中点击选中相应原子或键后再执行修改。"
885
+ )
886
+ return
887
+ if hasattr(self.main_window, "_set_selected_dihedral_angle"):
888
+ self.main_window._set_selected_dihedral_angle(val)
889
+ else:
890
+ if not self._apply_dihedral_direct(val):
891
+ return
892
+ self.accept()