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,614 @@
1
+ """Multiwfn headless automation driver.
2
+
3
+ Provides non-blocking, automated integration with Multiwfn (Tian Lu, Beijing Kein Research Center):
4
+ 1. QTAIM (Quantum Theory of Atoms in Molecules):
5
+ - Topology critical points: (3,-3) attractors, (3,-1) bond critical points (BCPs),
6
+ (3,+1) ring critical points (RCPs), (3,+3) cage critical points (CCPs).
7
+ - Real-space properties at CPs: rho, Laplacian, energy density H(r), G(r), V(r), ellipticity.
8
+ - 3D gradient bond paths connecting attractors through BCPs.
9
+ 2. NCI / RDG (Non-Covalent Interactions / Reduced Density Gradient):
10
+ - Ab initio NCI (from .wfn/.fchk) or Promolecular NCI (from .xyz/.pdb/MoleculeDocument).
11
+ - Produces sign(lambda2)*rho and RDG volumetric cube grids + scatter data.
12
+ 3. ELF / LOL / ESP 3D spatial grids:
13
+ - Electron Localization Function, Localized Orbital Locator, Electrostatic Potential.
14
+ 4. Population Analysis & Atomic Charges:
15
+ - ADCH (Atomic Dipole Corrected Hirshfeld), Hirshfeld, CM5, RESP charges + dipole.
16
+ 5. Bond Order Analysis:
17
+ - Mayer bond order matrix and total atomic valences.
18
+
19
+ All coordinates are strictly converted from Bohr to Angstrom upon import.
20
+ Subprocess execution is strictly protected with timeouts and redirected stdin ending with 'q'.
21
+ """
22
+ from __future__ import annotations
23
+
24
+ import os
25
+ import re
26
+ import shutil
27
+ import subprocess
28
+ import tempfile
29
+ from dataclasses import dataclass, field
30
+ from pathlib import Path
31
+ from typing import Optional, List, Dict, Tuple, Any
32
+
33
+ import numpy as np
34
+
35
+ from molforge.io.cube_reader import CubeData, read_cube
36
+
37
+ BOHR_TO_ANGSTROM = 0.529177210903
38
+
39
+
40
+ @dataclass
41
+ class CriticalPoint:
42
+ """QTAIM 拓扑临界点。"""
43
+ index: int
44
+ cp_type: str # "(3,-3)", "(3,-1)", "(3,+1)", "(3,+3)"
45
+ type_name: str # "Nuclear Attractor", "Bond Critical Point", etc.
46
+ coords_angstrom: np.ndarray # (3,) Å
47
+ coords_bohr: np.ndarray # (3,) Bohr
48
+ nucleus: Optional[str] = None # e.g. "1(O )"
49
+ rho: float = 0.0 # 电子密度
50
+ laplacian: float = 0.0 # 电子密度拉普拉斯量 ∇²ρ
51
+ energy_density_H: float = 0.0 # 总能量密度 H(r)
52
+ potential_energy_V: float = 0.0 # 势能密度 V(r)
53
+ lagrangian_kinetic_G: float = 0.0 # 动能密度 G(r)
54
+ elf: float = 0.0 # 电子定域化函数 ELF
55
+ lol: float = 0.0 # 局域轨道定位器 LOL
56
+ rdg: float = 0.0 # 约化密度梯度 RDG
57
+ sign_lambda2_rho: float = 0.0 # sign(λ₂)ρ
58
+ ellipticity: float = 0.0 # 键椭圆度 ε = λ₁/λ₂ - 1
59
+
60
+
61
+ @dataclass
62
+ class BondPath:
63
+ """QTAIM 3D 梯度键径 (从核到 BCP 的梯度矢量积分路径)。"""
64
+ path_index: int
65
+ points_angstrom: np.ndarray # (N, 3) Å
66
+ points_bohr: np.ndarray # (N, 3) Bohr
67
+ bcp_index: Optional[int] = None
68
+ connected_nuclei: Tuple[str, str] = ("", "")
69
+
70
+
71
+ @dataclass
72
+ class QTAIMResult:
73
+ """QTAIM 拓扑分析完整结果。"""
74
+ critical_points: List[CriticalPoint] = field(default_factory=list)
75
+ paths: List[BondPath] = field(default_factory=list)
76
+ raw_summary: str = ""
77
+
78
+ @property
79
+ def bcps(self) -> List[CriticalPoint]:
80
+ return [cp for cp in self.critical_points if cp.cp_type == "(3,-1)"]
81
+
82
+ @property
83
+ def attractors(self) -> List[CriticalPoint]:
84
+ return [cp for cp in self.critical_points if cp.cp_type == "(3,-3)"]
85
+
86
+ @property
87
+ def ring_cps(self) -> List[CriticalPoint]:
88
+ return [cp for cp in self.critical_points if cp.cp_type == "(3,+1)"]
89
+
90
+ @property
91
+ def cage_cps(self) -> List[CriticalPoint]:
92
+ return [cp for cp in self.critical_points if cp.cp_type == "(3,+3)"]
93
+
94
+
95
+ @dataclass
96
+ class NCIResult:
97
+ """弱相互作用 NCI / RDG 分析结果。"""
98
+ sign_lambda2_rho_cube: Optional[CubeData] = None
99
+ rdg_cube: Optional[CubeData] = None
100
+ scatter_points: Optional[np.ndarray] = None # (M, 2) [sign(λ₂)ρ, RDG]
101
+ is_promolecular: bool = False
102
+ cube_files: List[Path] = field(default_factory=list)
103
+
104
+
105
+ @dataclass
106
+ class PopulationResult:
107
+ """原子电荷与布居分析结果。"""
108
+ method: str
109
+ charges: Dict[int, float] = field(default_factory=dict) # atom_index (1-based) -> charge
110
+ atom_labels: Dict[int, str] = field(default_factory=dict)
111
+ dipole_au: Optional[np.ndarray] = None
112
+ dipole_debye: Optional[np.ndarray] = None
113
+
114
+
115
+ @dataclass
116
+ class MayerBondOrderResult:
117
+ """Mayer 键级分析结果。"""
118
+ bond_orders: Dict[Tuple[int, int], float] = field(default_factory=dict) # (a1, a2) -> BO
119
+ total_valences: Dict[int, float] = field(default_factory=dict) # atom_idx -> valence
120
+ free_valences: Dict[int, float] = field(default_factory=dict) # atom_idx -> free valence
121
+ atom_labels: Dict[int, str] = field(default_factory=dict)
122
+
123
+
124
+ class MultiwfnDriver:
125
+ """Multiwfn 官方命令行无头执行器。"""
126
+
127
+ DEFAULT_PATHS = [
128
+ Path(r"D:\Multiwfn\Multiwfn_3.8_bin_Win64\Multiwfn.exe"),
129
+ Path(r"C:\Multiwfn\Multiwfn.exe"),
130
+ Path(r"E:\Multiwfn\Multiwfn.exe"),
131
+ ]
132
+
133
+ def __init__(self, executable_path: Optional[str | Path] = None, work_dir: Optional[str | Path] = None):
134
+ self._executable = self._resolve_executable(executable_path)
135
+ self.work_dir = Path(work_dir) if work_dir else Path(r"E:\temp")
136
+ self.work_dir.mkdir(parents=True, exist_ok=True)
137
+
138
+ def _resolve_executable(self, custom_path: Optional[str | Path]) -> Optional[Path]:
139
+ if custom_path:
140
+ p = Path(custom_path)
141
+ if p.is_file():
142
+ return p
143
+ which = shutil.which("Multiwfn") or shutil.which("Multiwfn.exe")
144
+ if which:
145
+ return Path(which)
146
+ for cand in self.DEFAULT_PATHS:
147
+ if cand.is_file():
148
+ return cand
149
+ return None
150
+
151
+ @property
152
+ def is_available(self) -> bool:
153
+ return self._executable is not None and self._executable.is_file()
154
+
155
+ @property
156
+ def executable_path(self) -> Optional[Path]:
157
+ return self._executable
158
+
159
+ def _run_commands(self, input_file: str | Path, command_script: str, timeout: int = 120) -> subprocess.CompletedProcess[str]:
160
+ """安全执行 Multiwfn,严格重定向 stdin 并在结尾添加安全退出指令。"""
161
+ if not self.is_available:
162
+ raise RuntimeError(f"未检测到 Multiwfn 可执行程序,请检查路径配置。")
163
+
164
+ inp = Path(input_file).resolve()
165
+ if not inp.is_file():
166
+ raise FileNotFoundError(f"输入文件不存在: {inp}")
167
+
168
+ # 确保以 q 退出
169
+ full_script = command_script.strip()
170
+ if not full_script.endswith("q"):
171
+ full_script += "\nq\nq\n"
172
+ else:
173
+ full_script += "\nq\n"
174
+
175
+ proc = subprocess.run(
176
+ [str(self._executable), str(inp)],
177
+ input=full_script,
178
+ text=True,
179
+ capture_output=True,
180
+ cwd=str(self.work_dir),
181
+ timeout=timeout,
182
+ encoding="utf-8",
183
+ errors="replace",
184
+ )
185
+ return proc
186
+
187
+ # =========================================================================
188
+ # 1. QTAIM 拓扑临界点与键径分析 (Menu 2)
189
+ # =========================================================================
190
+
191
+ def run_qtaim_analysis(self, wfn_path: str | Path, timeout: int = 90) -> QTAIMResult:
192
+ """执行 Bader QTAIM 拓扑分析:搜索 CPs,生成键径,提取完整实空间性质。"""
193
+ # Multiwfn 指令流:
194
+ # 2: Topology analysis
195
+ # 2: Search CPs from nuclear positions
196
+ # 3: Search CPs from midpoint of atomic pairs
197
+ # 8: Generating the paths connecting (3,-3) and (3,-1) CPs
198
+ # -5 -> 4 -> 0: Save points of all paths to paths.txt, return
199
+ # 7 -> -1: Show and output properties of all CPs to CPprop.txt
200
+ # q -> q: Exit
201
+ script = "\n".join([
202
+ "2",
203
+ "2",
204
+ "3",
205
+ "8",
206
+ "-5",
207
+ "4",
208
+ "0",
209
+ "7",
210
+ "-1",
211
+ "q",
212
+ "q",
213
+ ])
214
+
215
+ proc = self._run_commands(wfn_path, script, timeout=timeout)
216
+ stem = Path(wfn_path).stem
217
+
218
+ # 查找输出文件: Multiwfn 自动生成 <stem>_CPprop.txt 或 CPprop.txt
219
+ cpprop_candidates = [
220
+ self.work_dir / f"{stem}_CPprop.txt",
221
+ self.work_dir / "CPprop.txt",
222
+ ]
223
+ cpprop_path = next((p for p in cpprop_candidates if p.is_file()), None)
224
+
225
+ paths_candidates = [
226
+ self.work_dir / "paths.txt",
227
+ self.work_dir / f"{stem}_paths.txt",
228
+ ]
229
+ paths_path = next((p for p in paths_candidates if p.is_file()), None)
230
+
231
+ cps: List[CriticalPoint] = []
232
+ if cpprop_path and cpprop_path.exists():
233
+ cps = self._parse_cpprop(cpprop_path.read_text(encoding="utf-8", errors="replace"))
234
+
235
+ bond_paths: List[BondPath] = []
236
+ if paths_path and paths_path.exists():
237
+ bond_paths = self._parse_paths(paths_path.read_text(encoding="utf-8", errors="replace"))
238
+
239
+ return QTAIMResult(
240
+ critical_points=cps,
241
+ paths=bond_paths,
242
+ raw_summary=proc.stdout,
243
+ )
244
+
245
+ def _parse_cpprop(self, text: str) -> List[CriticalPoint]:
246
+ cps: List[CriticalPoint] = []
247
+ blocks = re.split(r"-{4,}\s+CP\s+(\d+),\s+Type\s+(\([3\+\-1\,]+\))\s+-{4,}", text)
248
+ i = 1
249
+ type_names = {
250
+ "(3,-3)": "核引力中心 Nuclear Attractor (3,-3)",
251
+ "(3,-1)": "键临界点 Bond Critical Point (3,-1)",
252
+ "(3,+1)": "环临界点 Ring Critical Point (3,+1)",
253
+ "(3,+3)": "笼临界点 Cage Critical Point (3,+3)",
254
+ }
255
+
256
+ while i < len(blocks) - 2:
257
+ cp_idx = int(blocks[i])
258
+ cp_type = blocks[i+1].strip()
259
+ body = blocks[i+2]
260
+ i += 3
261
+
262
+ type_name = type_names.get(cp_type, f"临界点 {cp_type}")
263
+ m_nuc = re.search(r"Corresponding nucleus:\s*(.+)", body)
264
+ nucleus = m_nuc.group(1).strip() if m_nuc else None
265
+
266
+ pos_bohr = np.zeros(3)
267
+ pos_ang = np.zeros(3)
268
+ m_bohr = re.search(r"Position \(Bohr\):\s+([-\d\.\+Eed]+)\s+([-\d\.\+Eed]+)\s+([-\d\.\+Eed]+)", body)
269
+ if m_bohr:
270
+ pos_bohr = np.array([float(m_bohr.group(1)), float(m_bohr.group(2)), float(m_bohr.group(3))])
271
+ m_ang = re.search(r"Position \(Angstrom\):\s+([-\d\.\+Eed]+)\s+([-\d\.\+Eed]+)\s+([-\d\.\+Eed]+)", body)
272
+ if m_ang:
273
+ pos_ang = np.array([float(m_ang.group(1)), float(m_ang.group(2)), float(m_ang.group(3))])
274
+ elif m_bohr:
275
+ pos_ang = pos_bohr * BOHR_TO_ANGSTROM
276
+
277
+ def _val(pat: str) -> float:
278
+ m = re.search(pat, body)
279
+ if m:
280
+ try:
281
+ return float(m.group(1))
282
+ except ValueError:
283
+ return 0.0
284
+ return 0.0
285
+
286
+ cps.append(CriticalPoint(
287
+ index=cp_idx,
288
+ cp_type=cp_type,
289
+ type_name=type_name,
290
+ coords_angstrom=pos_ang,
291
+ coords_bohr=pos_bohr,
292
+ nucleus=nucleus,
293
+ rho=_val(r"Density of all electrons:\s+([-\d\.\+Eed]+)"),
294
+ laplacian=_val(r"Laplacian of electron density:\s+([-\d\.\+Eed]+)"),
295
+ energy_density_H=_val(r"Energy density E\(r\) or H\(r\):\s+([-\d\.\+Eed]+)"),
296
+ potential_energy_V=_val(r"Potential energy density V\(r\):\s+([-\d\.\+Eed]+)"),
297
+ lagrangian_kinetic_G=_val(r"Lagrangian kinetic energy G\(r\):\s+([-\d\.\+Eed]+)"),
298
+ elf=_val(r"Electron localization function \(ELF\):\s+([-\d\.\+Eed]+)"),
299
+ lol=_val(r"Localized orbital locator \(LOL\):\s+([-\d\.\+Eed]+)"),
300
+ rdg=_val(r"Reduced density gradient \(RDG\):\s+([-\d\.\+Eed]+)"),
301
+ sign_lambda2_rho=_val(r"Sign\(lambda2\)\*rho:\s+([-\d\.\+Eed]+)"),
302
+ ellipticity=_val(r"Ellipticity of electron density:\s+([-\d\.\+Eed]+)"),
303
+ ))
304
+ return cps
305
+
306
+ def _parse_paths(self, text: str) -> List[BondPath]:
307
+ paths: List[BondPath] = []
308
+ lines = text.splitlines()
309
+ i = 0
310
+ while i < len(lines):
311
+ line = lines[i].strip()
312
+ if line.startswith("Path index:"):
313
+ parts = line.split(":")
314
+ path_idx = int(parts[1].strip())
315
+ i += 1
316
+ if i >= len(lines):
317
+ break
318
+ try:
319
+ n_pts = int(lines[i].strip())
320
+ except ValueError:
321
+ i += 1
322
+ continue
323
+ pts_bohr = []
324
+ i += 1
325
+ for _ in range(n_pts):
326
+ if i < len(lines):
327
+ pt_parts = lines[i].split()
328
+ if len(pt_parts) >= 3:
329
+ try:
330
+ pts_bohr.append([float(pt_parts[0]), float(pt_parts[1]), float(pt_parts[2])])
331
+ except ValueError:
332
+ pass
333
+ i += 1
334
+ if pts_bohr:
335
+ arr_bohr = np.array(pts_bohr, dtype=float)
336
+ arr_ang = arr_bohr * BOHR_TO_ANGSTROM
337
+ paths.append(BondPath(
338
+ path_index=path_idx,
339
+ points_angstrom=arr_ang,
340
+ points_bohr=arr_bohr,
341
+ ))
342
+ else:
343
+ i += 1
344
+ return paths
345
+
346
+ # =========================================================================
347
+ # 2. NCI / RDG 弱相互作用分析 (Menu 20)
348
+ # =========================================================================
349
+
350
+ def run_nci_analysis(
351
+ self,
352
+ input_file: str | Path,
353
+ grid_quality: int = 1, # 1: low (fast), 2: medium, 3: high
354
+ is_promolecular: Optional[bool] = None,
355
+ timeout: int = 120,
356
+ ) -> NCIResult:
357
+ """执行 NCI / RDG 分析,生成 sign(λ₂)ρ 与 RDG 3D Cube 网格及散点。"""
358
+ inp = Path(input_file).resolve()
359
+ if is_promolecular is None:
360
+ # 自动识别:若为 xyz / pdb 则使用分子原初密度近似
361
+ is_promolecular = inp.suffix.lower() in [".xyz", ".pdb", ".gro"]
362
+
363
+ mode = "2" if is_promolecular else "1"
364
+ # 指令流:
365
+ # 20: Visual study of weak interaction
366
+ # 1 or 2: NCI analysis (ab initio or promolecular)
367
+ # grid_quality: 1 (fast/low) or 2 (medium)
368
+ # 3: Output cube files to func1.cub (sign(λ₂)ρ) and func2.cub (RDG)
369
+ # 2: Output scatter points to output.txt
370
+ # q -> q: Exit
371
+ script = "\n".join([
372
+ "20",
373
+ mode,
374
+ str(grid_quality),
375
+ "3",
376
+ "2",
377
+ "q",
378
+ "q",
379
+ ])
380
+
381
+ self._run_commands(inp, script, timeout=timeout)
382
+
383
+ f1 = self.work_dir / "func1.cub"
384
+ f2 = self.work_dir / "func2.cub"
385
+ scatter_file = self.work_dir / "output.txt"
386
+
387
+ s_rho_cube = read_cube(f1, convert_bohr=True) if f1.is_file() else None
388
+ rdg_cube = read_cube(f2, convert_bohr=True) if f2.is_file() else None
389
+
390
+ scatter_data = None
391
+ if scatter_file.is_file():
392
+ try:
393
+ raw = np.loadtxt(str(scatter_file), comments="#")
394
+ if raw.ndim == 2 and raw.shape[1] >= 2:
395
+ scatter_data = raw[:, :2] # col 0: sign(λ₂)ρ, col 1: RDG
396
+ except Exception:
397
+ pass
398
+
399
+ return NCIResult(
400
+ sign_lambda2_rho_cube=s_rho_cube,
401
+ rdg_cube=rdg_cube,
402
+ scatter_points=scatter_data,
403
+ is_promolecular=is_promolecular,
404
+ cube_files=[p for p in (f1, f2) if p.is_file()],
405
+ )
406
+
407
+ # =========================================================================
408
+ # 3. ELF / LOL / ESP 空间三维网格 (Menu 5)
409
+ # =========================================================================
410
+
411
+ def run_grid_calculation(
412
+ self,
413
+ wfn_path: str | Path,
414
+ func_type: int = 9, # 9: ELF, 10: LOL, 12: ESP, 1: Rho, 3: Laplacian
415
+ grid_quality: int = 1,
416
+ timeout: int = 120,
417
+ ) -> Optional[CubeData]:
418
+ """计算空间网格属性 (ELF/LOL/ESP) 并导出为 CubeData。"""
419
+ # 指令流:
420
+ # 5: Output and plot specific property in spatial region
421
+ # <func_type>: 9 (ELF) / 10 (LOL) / 12 (ESP)
422
+ # <grid_quality>: 1 (low) / 2 (medium)
423
+ # 2: Export data to a Gaussian cube file in current folder
424
+ # 0: Return
425
+ # q: Exit
426
+ script = "\n".join([
427
+ "5",
428
+ str(func_type),
429
+ str(grid_quality),
430
+ "2",
431
+ "0",
432
+ "q",
433
+ ])
434
+
435
+ self._run_commands(wfn_path, script, timeout=timeout)
436
+ stem = Path(wfn_path).stem
437
+
438
+ type_suffixes = {
439
+ 9: "ELF",
440
+ 10: "LOL",
441
+ 12: "ESP",
442
+ 1: "density",
443
+ 3: "laplacian",
444
+ }
445
+ suf = type_suffixes.get(func_type, f"func{func_type}")
446
+
447
+ # Multiwfn 自动生成 <stem>_<suf>.cub
448
+ cub_candidates = [
449
+ self.work_dir / f"{stem}_{suf}.cub",
450
+ self.work_dir / f"{stem}_{suf.lower()}.cub",
451
+ self.work_dir / f"{stem}_{suf.upper()}.cub",
452
+ self.work_dir / "density.cub",
453
+ ]
454
+ target = next((p for p in cub_candidates if p.is_file()), None)
455
+ if target:
456
+ return read_cube(target, convert_bohr=True)
457
+ return None
458
+
459
+ # =========================================================================
460
+ # 4. ADCH / Hirshfeld 原子电荷与偶极 (Menu 7)
461
+ # =========================================================================
462
+
463
+ def run_population_analysis(
464
+ self,
465
+ wfn_path: str | Path,
466
+ method: str = "ADCH", # "ADCH", "Hirshfeld", "CM5", "RESP"
467
+ grid_quality: int = 1,
468
+ timeout: int = 90,
469
+ ) -> PopulationResult:
470
+ """执行布居分析计算原子净电荷。推荐 ADCH(校正原子偶极的赫氏电荷)。"""
471
+ method_map = {
472
+ "HIRSHFELD": "1",
473
+ "ADCH": "11",
474
+ "CM5": "16",
475
+ "RESP": "18",
476
+ }
477
+ opt = method_map.get(method.upper(), "11")
478
+
479
+ script = "\n".join([
480
+ "7",
481
+ opt,
482
+ str(grid_quality),
483
+ "n", # Don't output .chg file, we parse stdout directly
484
+ "0",
485
+ "q",
486
+ ])
487
+
488
+ proc = self._run_commands(wfn_path, script, timeout=timeout)
489
+ return self._parse_population_output(proc.stdout, method)
490
+
491
+ def _parse_population_output(self, text: str, method: str) -> PopulationResult:
492
+ charges: Dict[int, float] = {}
493
+ labels: Dict[int, str] = {}
494
+ dipole_au = None
495
+
496
+ m_dip = re.search(r"X/Y/Z of dipole moment from the charge \(a\.u\.\)\s+([-\d\.\+Eed]+)\s+([-\d\.\+Eed]+)\s+([-\d\.\+Eed]+)", text)
497
+ if m_dip:
498
+ dipole_au = np.array([float(m_dip.group(1)), float(m_dip.group(2)), float(m_dip.group(3))])
499
+
500
+ # Atom 1(O ): -0.36728452
501
+ for line in text.splitlines():
502
+ m = re.match(r"\s*Atom\s+(\d+)\((.+?)\)\s*:\s*([-\d\.\+Eed]+)", line)
503
+ if m:
504
+ idx = int(m.group(1))
505
+ sym = m.group(2).strip()
506
+ val = float(m.group(3))
507
+ charges[idx] = val
508
+ labels[idx] = sym
509
+
510
+ dipole_debye = dipole_au * 2.5417464519 if dipole_au is not None else None
511
+
512
+ return PopulationResult(
513
+ method=method,
514
+ charges=charges,
515
+ atom_labels=labels,
516
+ dipole_au=dipole_au,
517
+ dipole_debye=dipole_debye,
518
+ )
519
+
520
+ # =========================================================================
521
+ # 5. Mayer 键级分析 (Menu 9)
522
+ # =========================================================================
523
+
524
+ def run_mayer_bond_order(
525
+ self,
526
+ fchk_path: str | Path,
527
+ threshold: float = 0.05,
528
+ timeout: int = 90,
529
+ ) -> MayerBondOrderResult:
530
+ """从 Gaussian .fchk 计算 Mayer 键级与原子总价。"""
531
+ script = "\n".join([
532
+ "9",
533
+ "1", # Mayer bond order
534
+ "n", # Don't output bndmat.txt
535
+ "0",
536
+ "q",
537
+ ])
538
+
539
+ proc = self._run_commands(fchk_path, script, timeout=timeout)
540
+ return self._parse_mayer_output(proc.stdout)
541
+
542
+ def _parse_mayer_output(self, text: str) -> MayerBondOrderResult:
543
+ bos: Dict[Tuple[int, int], float] = {}
544
+ valences: Dict[int, float] = {}
545
+ free_vals: Dict[int, float] = {}
546
+ labels: Dict[int, str] = {}
547
+
548
+ lines = text.splitlines()
549
+ in_bo = False
550
+ in_val = False
551
+
552
+ for line in lines:
553
+ if "Bond orders with absolute value >=" in line:
554
+ in_bo = True
555
+ in_val = False
556
+ continue
557
+ elif "Total valences and free valences defined by Mayer:" in line:
558
+ in_bo = False
559
+ in_val = True
560
+ continue
561
+ elif "If outputting bond order matrix" in line or "================" in line:
562
+ in_bo = False
563
+ in_val = False
564
+
565
+ if in_bo:
566
+ # # 1: 1(C ) 2(H ) 0.93327430
567
+ m = re.search(r"#\s*\d+:\s+(\d+)\((.+?)\)\s+(\d+)\((.+?)\)\s+([-\d\.\+Eed]+)", line)
568
+ if m:
569
+ a1 = int(m.group(1))
570
+ sym1 = m.group(2).strip()
571
+ a2 = int(m.group(3))
572
+ sym2 = m.group(4).strip()
573
+ bo = float(m.group(5))
574
+ bos[(a1, a2)] = bo
575
+ labels[a1] = sym1
576
+ labels[a2] = sym2
577
+
578
+ elif in_val:
579
+ # Atom 1(C ) : 3.78818001 0.00000000
580
+ m = re.search(r"Atom\s+(\d+)\((.+?)\)\s*:\s+([-\d\.\+Eed]+)\s+([-\d\.\+Eed]+)", line)
581
+ if m:
582
+ a_idx = int(m.group(1))
583
+ sym = m.group(2).strip()
584
+ t_val = float(m.group(3))
585
+ f_val = float(m.group(4))
586
+ valences[a_idx] = t_val
587
+ free_vals[a_idx] = f_val
588
+ labels[a_idx] = sym
589
+
590
+ return MayerBondOrderResult(
591
+ bond_orders=bos,
592
+ total_valences=valences,
593
+ free_valences=free_vals,
594
+ atom_labels=labels,
595
+ )
596
+
597
+ # =========================================================================
598
+ # 6. 从当前 MoleculeDocument 导出临时 XYZ 用于 Multiwfn
599
+ # =========================================================================
600
+
601
+ def export_document_xyz(self, doc: Any, output_name: str = "current_mol.xyz") -> Path:
602
+ """将当前 MolForge MoleculeDocument 导出为标准 XYZ 文件 (用于 Promolecular NCI 等)。"""
603
+ out_path = self.work_dir / output_name
604
+ coords = doc.coordinates.get_3d_coords()
605
+ atoms = doc.topology.atoms
606
+
607
+ lines = [str(len(atoms)), "Generated by MolForge for Multiwfn Analysis"]
608
+ for i, atom in enumerate(atoms):
609
+ sym = getattr(atom, "symbol", None) or getattr(atom, "element", "C")
610
+ pos = coords[i]
611
+ lines.append(f"{sym:<2} {pos[0]:14.8f} {pos[1]:14.8f} {pos[2]:14.8f}")
612
+
613
+ out_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
614
+ return out_path