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,650 @@
1
+ """Input-validated OSC workflow helpers.
2
+
3
+ All external engines run serially, in a fresh output directory, with captured logs.
4
+ The pure parsers and geometry routines do not require Gaussian, Multiwfn, or VMD.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import csv
9
+ import json
10
+ import math
11
+ import re
12
+ import shutil
13
+ import subprocess
14
+ import time
15
+ from dataclasses import asdict, dataclass
16
+ from pathlib import Path
17
+ from typing import Iterable
18
+
19
+ import numpy as np
20
+
21
+ HARTREE_TO_EV = 27.211386245988
22
+ BOHR_TO_ANGSTROM = 0.529177210903
23
+ ASSET_DIR = Path(__file__).resolve().parent / "assets"
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class FrontierLevels:
28
+ source: str
29
+ homo_orbital: int
30
+ homo_ev: float
31
+ lumo_ev: float
32
+ gap_ev: float
33
+ validation: str
34
+
35
+
36
+ def _fchk_field(path: str | Path, label: str) -> tuple[int, list[str]]:
37
+ """Read one fixed-width Gaussian formatted-checkpoint array without loading the file."""
38
+ p = Path(path)
39
+ with p.open("r", encoding="ascii", errors="replace") as fh:
40
+ for line in fh:
41
+ if line.startswith(label):
42
+ m = re.search(r"\bN=\s*(\d+)", line)
43
+ if not m:
44
+ raise ValueError(f"字段 {label} 不包含数组长度")
45
+ n = int(m.group(1))
46
+ vals: list[str] = []
47
+ while len(vals) < n:
48
+ block = fh.readline()
49
+ if not block:
50
+ break
51
+ vals.extend(block.split())
52
+ if len(vals) < n:
53
+ raise ValueError(f"{label} 数据不完整:需要 {n} 项,读到 {len(vals)} 项")
54
+ return n, vals[:n]
55
+ raise ValueError(f"fchk 中找不到字段:{label}")
56
+
57
+
58
+ def read_fchk_orbitals(path: str | Path) -> tuple[int, np.ndarray]:
59
+ """Return alpha-electron count and alpha orbital energies in eV."""
60
+ p = Path(path)
61
+ alpha = None
62
+ with p.open("r", encoding="ascii", errors="replace") as fh:
63
+ for line in fh:
64
+ if line.startswith("Number of alpha electrons"):
65
+ try:
66
+ alpha = int(line.split()[-1])
67
+ except (ValueError, IndexError):
68
+ pass
69
+
70
+ if alpha is None:
71
+ raise ValueError("fchk 缺少 Number of alpha electrons,无法确定 HOMO 轨道号")
72
+ _, vals = _fchk_field(p, "Alpha Orbital Energies")
73
+ energies = np.asarray([float(x.replace("D", "E")) for x in vals], dtype=float) * HARTREE_TO_EV
74
+ if alpha < 1 or alpha >= len(energies):
75
+ raise ValueError(f"alpha 电子数 {alpha} 与轨道数组长度 {len(energies)} 不匹配")
76
+ return alpha, energies
77
+
78
+
79
+ def parse_log_frontier(path: str | Path) -> tuple[float, float]:
80
+ """Return HOMO/LUMO from the last Gaussian alpha occupied/virtual eigenvalue blocks."""
81
+ occ: list[float] = []
82
+ virt: list[float] = []
83
+ occ_re = re.compile(r"Alpha\s+occ\.\s+eigenvalues\s*--\s*(.*)", re.I)
84
+ virt_re = re.compile(r"Alpha\s+virt\.\s+eigenvalues\s*--\s*(.*)", re.I)
85
+ number_re = re.compile(r"[-+]?(?:\d+\.\d*|\.\d+|\d+)(?:[DEde][-+]?\d+)?")
86
+ with Path(path).open("r", encoding="utf-8", errors="replace") as fh:
87
+ for line in fh:
88
+ om = occ_re.search(line)
89
+ vm = virt_re.search(line)
90
+ if om:
91
+ if virt:
92
+ occ, virt = [], []
93
+ occ += [float(x.replace("D", "E").replace("d", "e")) for x in number_re.findall(om.group(1))]
94
+ elif vm:
95
+ virt += [float(x.replace("D", "E").replace("d", "e")) for x in number_re.findall(vm.group(1))]
96
+ if not occ or not virt:
97
+ raise ValueError("Gaussian log 中没有完整的 Alpha occupied/virtual eigenvalues")
98
+ return occ[-1] * HARTREE_TO_EV, virt[0] * HARTREE_TO_EV
99
+
100
+
101
+ def extract_frontier(fchk_path: str | Path, log_path: str | Path | None = None,
102
+ tolerance_ev: float = 0.05) -> FrontierLevels:
103
+ alpha, energies = read_fchk_orbitals(fchk_path)
104
+ homo, lumo = float(energies[alpha - 1]), float(energies[alpha])
105
+ status = "fchk"
106
+ if log_path:
107
+ log_h, log_l = parse_log_frontier(log_path)
108
+ dh, dl = abs(homo - log_h), abs(lumo - log_l)
109
+ if max(dh, dl) > tolerance_ev:
110
+ raise ValueError(f"fchk/log 能级差异超过 {tolerance_ev:.2f} eV(HOMO {dh:.3f}, LUMO {dl:.3f});请确认两个文件属于同一次计算")
111
+ status = f"fchk/log 一致(最大差异 {max(dh, dl):.4f} eV)"
112
+ return FrontierLevels(Path(fchk_path).stem, alpha, homo, lumo, lumo - homo, status)
113
+
114
+
115
+ def read_fchk_geometry(path: str | Path) -> tuple[np.ndarray, np.ndarray]:
116
+ """Return atomic numbers and Cartesian coordinates in Angstrom."""
117
+ _, zs = _fchk_field(path, "Atomic numbers")
118
+ _, xyz = _fchk_field(path, "Current cartesian coordinates")
119
+ z = np.asarray([int(x) for x in zs], dtype=int)
120
+ coords = np.asarray([float(x.replace("D", "E")) for x in xyz], dtype=float).reshape(-1, 3)
121
+ if len(z) != len(coords) or not len(z):
122
+ raise ValueError("fchk 原子序数与坐标数不一致或分子为空")
123
+ return z, coords * BOHR_TO_ANGSTROM
124
+
125
+
126
+ def planarity_from_coordinates(atomic_numbers: Iterable[int], coords: Iterable[Iterable[float]]) -> dict:
127
+ z = np.asarray(list(atomic_numbers), dtype=int)
128
+ xyz = np.asarray(list(coords), dtype=float).reshape(-1, 3)
129
+ if len(z) != len(xyz):
130
+ raise ValueError("原子序数和坐标数量不同")
131
+ keep = z != 1
132
+ pts = xyz[keep]
133
+ if len(pts) < 3:
134
+ raise ValueError("平面性分析至少需要 3 个重原子")
135
+ center = pts.mean(axis=0)
136
+ _u, _s, vt = np.linalg.svd(pts - center, full_matrices=False)
137
+ normal = vt[-1]
138
+ signed = (pts - center) @ normal
139
+ abs_dev = np.abs(signed)
140
+ return {
141
+ "heavy_atom_count": int(len(pts)),
142
+ "rmsd_angstrom": float(np.sqrt(np.mean(signed**2))),
143
+ "max_deviation_angstrom": float(abs_dev.max()),
144
+ "span_angstrom": float(signed.max() - signed.min()),
145
+ "normal": [float(x) for x in normal],
146
+ "center_angstrom": [float(x) for x in center],
147
+ }
148
+
149
+
150
+ def new_output_dir(base: str | Path, prefix: str) -> Path:
151
+ base = Path(base).expanduser().resolve()
152
+ base.mkdir(parents=True, exist_ok=True)
153
+ stem = f"{prefix}_{time.strftime('%Y%m%d_%H%M%S')}"
154
+ out = base / stem
155
+ i = 2
156
+ while out.exists():
157
+ out = base / f"{stem}_{i}"
158
+ i += 1
159
+ out.mkdir()
160
+ return out
161
+
162
+
163
+ def _engine(tool_id: str) -> str:
164
+ from ..io.calculators import EngineToolRegistry
165
+ status = EngineToolRegistry.detect_tool(tool_id)
166
+ if not status.available or not status.executable_path:
167
+ raise RuntimeError(status.diagnostic)
168
+ return status.executable_path
169
+
170
+
171
+ def _run(argv: list[str], cwd: Path, stdin: str = "", timeout: int = 3600,
172
+ allow_nonzero: bool = False) -> str:
173
+ proc = subprocess.run(argv, input=stdin, cwd=cwd, capture_output=True,
174
+ text=True, encoding="utf-8", errors="replace",
175
+ timeout=timeout, shell=False)
176
+ log = proc.stdout + ("\n[stderr]\n" + proc.stderr if proc.stderr else "")
177
+ (cwd / f"{Path(argv[0]).stem}_last.log").write_text(log, encoding="utf-8")
178
+ if proc.returncode and not allow_nonzero:
179
+ raise RuntimeError(f"外部程序退出码 {proc.returncode};查看 {Path(argv[0]).stem}_last.log")
180
+ return log
181
+
182
+
183
+ def _patched_vmd_script(source: Path, destination: Path, tachyon: str | None = None) -> Path:
184
+ text = source.read_text(encoding="utf-8", errors="replace")
185
+ # These user scripts pin Tachyon to a previous workstation; resolve beside the detected VMD.
186
+ text = re.sub(r'"D:/VMD/tachyon_WIN64\.exe"', lambda _m: f'"{(Path(tachyon).as_posix() if tachyon else "tachyon_WIN64.exe")}"', text)
187
+ destination.write_text(text, encoding="utf-8")
188
+ return destination
189
+
190
+
191
+ def run_esp_surface(fchk: str | Path, output_parent: str | Path, isovalue: float = 0.001) -> Path:
192
+ fchk = Path(fchk).resolve()
193
+ if not fchk.is_file() or fchk.suffix.lower() != ".fchk":
194
+ raise ValueError("ESP 表面分析需要存在的 Gaussian .fchk 文件")
195
+ mwfn, vmd = _engine("multiwfn"), _engine("vmd")
196
+ out = new_output_dir(output_parent, f"ESP_{fchk.stem}")
197
+ assets = ASSET_DIR / "esp-surface-analysis" / "scripts"
198
+ (out / "ESPiso_input.txt").write_text((assets / "ESPiso_input.txt").read_text(encoding="utf-8"), encoding="utf-8")
199
+ # Workflow specifies separate commands because ESPrhoiso creates cubes while menu 12 exports surface PDBs.
200
+ log1 = _run([mwfn, str(fchk), "-ESPrhoiso", str(isovalue)], out,
201
+ stdin=(out / "ESPiso_input.txt").read_text(encoding="utf-8"), timeout=3600, allow_nonzero=True)
202
+ esp_menu = "12\n3\n0.15\n0\n5\nmol.pdb\n6\n2\nq\n"
203
+ log2 = _run([mwfn, str(fchk)], out, stdin=esp_menu, timeout=3600, allow_nonzero=True)
204
+ (out / "multiwfn_esp.log").write_text(log1 + "\n--- surface analysis ---\n" + log2, encoding="utf-8")
205
+ for target, patterns in (("density.cub", ["*_density.cub", "density.cub"]),
206
+ ("totesp.cub", ["*_totesp.cub", "totesp.cub"])):
207
+ dest=out/target
208
+ if not dest.exists():
209
+ candidate=next((q for pattern in patterns for q in out.glob(pattern) if q.is_file()),None)
210
+ if candidate is not None and candidate != dest: candidate.replace(dest)
211
+ needed = ["density.cub", "totesp.cub", "mol.pdb", "surfanalysis.pdb", "vtx.pdb"]
212
+ missing = [n for n in needed if not (out / n).is_file()]
213
+ if missing:
214
+ raise RuntimeError("Multiwfn 未生成所需文件:" + ", ".join(missing) + f"。输出保留在 {out}")
215
+ from ..io.calculators import EngineToolRegistry, MultiwfnAdapter
216
+ metrics=MultiwfnAdapter.parse_esp_summary_text(log1+"\n"+log2)
217
+ (out/"esp_descriptors.json").write_text(json.dumps(metrics,indent=2,ensure_ascii=False),encoding="utf-8")
218
+ if not metrics:
219
+ (out/"esp_descriptor_status.txt").write_text("没有从本次 Multiwfn 文本中识别到描述符字段;请核对 Multiwfn 日志与版本。\n",encoding="utf-8")
220
+ vmd_status = EngineToolRegistry.detect_tool("vmd")
221
+ tachyon = str(Path(vmd_status.executable_path).parent / "tachyon_WIN64.exe")
222
+ tcl = _patched_vmd_script(assets / "draw_ESP.tcl", out / "draw_ESP.tcl", tachyon)
223
+ vsurf = _read_extrema(out / "surfanalysis.pdb")
224
+ low, high = vsurf if vsurf else (-35.0, 35.0)
225
+ # Skill requires per-molecule extrema with a 20% margin; do not reuse fixed ranges.
226
+ margin = max(abs(low), abs(high)) * 0.2
227
+ colorlow, colorhigh = (low - margin) / 627.51, (high + margin) / 627.51
228
+ bmp = out / f"{fchk.stem}_esp.bmp"
229
+ _run([vmd, "-dispdev", "text", "-e", str(tcl), "-args",
230
+ "mol.pdb", "surfanalysis.pdb", "density.cub", "totesp.cub", str(bmp),
231
+ str(isovalue), f"{colorlow:.6f}", f"{colorhigh:.6f}"], out, timeout=3600)
232
+ if not bmp.is_file():
233
+ raise RuntimeError(f"VMD 未生成 ESP 图像:{bmp};请查看 VMD 日志")
234
+ return out
235
+
236
+
237
+ def _read_extrema(path: Path) -> tuple[float, float] | None:
238
+ maxima, minima = [], []
239
+ for line in path.read_text(encoding="utf-8", errors="replace").splitlines():
240
+ if not line.startswith("HETATM"):
241
+ continue
242
+ try:
243
+ atom = line[12:16].strip()
244
+ value = float(line[60:66])
245
+ if atom == "C": maxima.append(value)
246
+ elif atom == "O": minima.append(value)
247
+ except (ValueError, IndexError):
248
+ continue
249
+ if not maxima or not minima:
250
+ return None
251
+ return min(minima), max(maxima)
252
+
253
+
254
+ def export_osc_levels(inputs: Iterable[tuple[str | Path, str | Path | None]], output_parent: str | Path) -> Path:
255
+ records = [asdict(extract_frontier(fchk, log)) for fchk, log in inputs]
256
+ if len(records) < 2:
257
+ raise ValueError("OSC 能级比较至少需要两个分子")
258
+ out = new_output_dir(output_parent, "OSC_energy")
259
+ (out / "levels.json").write_text(json.dumps(records, indent=2, ensure_ascii=False), encoding="utf-8")
260
+ with (out / "levels.csv").open("w", newline="", encoding="utf-8-sig") as fh:
261
+ w = csv.DictWriter(fh, fieldnames=list(records[0]))
262
+ w.writeheader(); w.writerows(records)
263
+ write_levels_svg(records, out / "osc_energy_levels.svg")
264
+ _write_rectangle_svg(records, out / "osc_rectangle_levels.svg")
265
+ _write_grid_svg(records, out / "osc_2xN_levels.svg")
266
+ _write_energy_workbook(records, out / "osc_energy_levels.xlsx")
267
+ _write_editable_pptx(records, out / "osc_energy_levels.pptx")
268
+ return out
269
+
270
+
271
+ def write_levels_svg(records: list[dict], output: str | Path) -> None:
272
+ width, height = 1000, 620
273
+ left, right, top, bottom = 100, 35, 45, 95
274
+ emin = min(-6.5, min(x["homo_ev"] for x in records) - .4)
275
+ emax = max(-2.2, max(x["lumo_ev"] for x in records) + .4)
276
+ def y(e): return top + (emax - e) / (emax - emin) * (height - top - bottom)
277
+ step = (width-left-right) / len(records)
278
+ parts = [f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" viewBox="0 0 {width} {height}">',
279
+ '<rect width="100%" height="100%" fill="white"/>', '<g font-family="Arial,sans-serif" fill="#263746">']
280
+ for tick_i in range(math.ceil(emin*2), math.floor(emax*2)+1):
281
+ e=tick_i/2; yy=y(e)
282
+ parts += [f'<path d="M{left} {yy:.1f}H{width-right}" stroke="#e3e9ee"/>',
283
+ f'<text x="{left-12}" y="{yy+5:.1f}" text-anchor="end" font-size="14">{e:.1f} eV</text>']
284
+ parts.append(f'<path d="M{left} {top}V{height-bottom}" stroke="#314555" stroke-width="2"/>')
285
+ colors=['#198c8c','#dd7a35','#5679bb','#6a9b65','#aa6594','#bc9b36']
286
+ for i, rec in enumerate(records):
287
+ cx=left+(i+.5)*step; col=colors[i%len(colors)]
288
+ yh, yl=y(rec['homo_ev']), y(rec['lumo_ev'])
289
+ parts += [f'<path d="M{cx-35} {yh:.1f}H{cx+35}" stroke="#163246" stroke-width="4"/>',
290
+ f'<path d="M{cx-35} {yl:.1f}H{cx+35}" stroke="{col}" stroke-width="4"/>',
291
+ f'<text x="{cx}" y="{yh+20:.1f}" text-anchor="middle" font-size="13">{rec["homo_ev"]:.2f}</text>',
292
+ f'<text x="{cx}" y="{yl-9:.1f}" text-anchor="middle" font-size="13">{rec["lumo_ev"]:.2f}</text>',
293
+ f'<text x="{cx}" y="{height-bottom+25}" text-anchor="middle" font-size="13">{_xml(rec["source"])}</text>',
294
+ f'<text x="{cx}" y="{height-bottom+47}" text-anchor="middle" font-size="12" fill="#697987">Gap {rec["gap_ev"]:.2f} eV</text>']
295
+ parts += ['</g></svg>']
296
+ Path(output).write_text('\n'.join(parts), encoding='utf-8')
297
+
298
+
299
+ def _xml(text: str) -> str:
300
+ return str(text).replace('&','&amp;').replace('<','&lt;').replace('>','&gt;').replace('"','&quot;')
301
+
302
+
303
+ def analyze_fchk_planarity(fchk: str | Path, output_parent: str | Path) -> Path:
304
+ fchk = Path(fchk).resolve()
305
+ result = planarity_from_coordinates(*read_fchk_geometry(fchk))
306
+ result.update(source=str(fchk), metric="重原子最佳拟合平面 RMSD")
307
+ out = new_output_dir(output_parent, f"Planarity_{fchk.stem}")
308
+ (out / "planarity.json").write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding="utf-8")
309
+ with (out / "planarity.csv").open("w", newline="", encoding="utf-8-sig") as fh:
310
+ w=csv.writer(fh); w.writerow(["metric","value","unit"])
311
+ for k,v in result.items():
312
+ if isinstance(v,(int,float)): w.writerow([k,v,"Å" if "angstrom" in k else ""])
313
+ return out
314
+
315
+
316
+ def analyze_fchk_dipole(fchk: str | Path, output_parent: str | Path) -> Path:
317
+ fchk = Path(fchk).resolve()
318
+ _, values = _fchk_field(fchk, "Dipole Moment")
319
+ vec = np.asarray([float(x.replace("D","E")) for x in values[:3]], dtype=float)
320
+ if vec.size != 3:
321
+ raise ValueError("fchk 偶极矩字段不是三维向量")
322
+ result = {"source": str(fchk), "dipole_au": vec.tolist(),
323
+ "dipole_debye": float(np.linalg.norm(vec) * 2.541746473),
324
+ "note": "总偶极矩取自 fchk;分片段偶极需要用户定义片段并另行运行 Multiwfn。"}
325
+ out = new_output_dir(output_parent, f"Dipole_{fchk.stem}")
326
+ (out / "dipole.json").write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding="utf-8")
327
+ try:
328
+ image=_render_total_dipole(fchk, vec, out)
329
+ result["rendered_image"]=str(image)
330
+ (out/"dipole.json").write_text(json.dumps(result,indent=2,ensure_ascii=False),encoding="utf-8")
331
+ except Exception as exc:
332
+ (out/"dipole_render_status.txt").write_text(f"总偶极矩数值已导出;3D 箭头未生成:{exc}\n",encoding="utf-8")
333
+ return out
334
+
335
+
336
+
337
+ def _render_total_dipole(fchk, dipole, out):
338
+ vmd=_engine("vmd")
339
+ from ..io.calculators import EngineToolRegistry
340
+ status=EngineToolRegistry.detect_tool("vmd")
341
+ tachyon=Path(status.executable_path).parent/"tachyon_WIN64.exe"
342
+ if not tachyon.is_file():raise RuntimeError("VMD 目录中找不到 tachyon_WIN64.exe")
343
+ z,coords=read_fchk_geometry(fchk)
344
+ symbols={1:"H",6:"C",7:"N",8:"O",9:"F",15:"P",16:"S",17:"Cl",35:"Br",53:"I"}
345
+ xyz=out/(Path(fchk).stem+".xyz")
346
+ with xyz.open("w",encoding="utf-8") as fh:
347
+ fh.write(f"{len(z)}\n{Path(fchk).stem}\n")
348
+ for atom,point in zip(z,coords):fh.write(f"{symbols.get(int(atom), 'C')} {point[0]:.8f} {point[1]:.8f} {point[2]:.8f}\n")
349
+ center=coords.mean(axis=0);vector=np.asarray(dipole,dtype=float)*1.2
350
+ start=center-vector*.5;mid=center+vector*.25;end=center+vector*.5
351
+ image=out/(Path(fchk).stem+"_dipole.bmp");base=out/(Path(fchk).stem+"_dipole.tga")
352
+ def fmt(v):return " ".join(f"{float(x):.8f}" for x in v)
353
+ lines=[f"mol new {{{xyz.as_posix()}}} type xyz waitfor all",
354
+ "mol modstyle 0 top CPK 1.0 0.3 22.0 22.0","color Display Background white",
355
+ "axes location Off","display projection Orthographic",f'set beg "{fmt(start)}"',
356
+ f'set mid "{fmt(mid)}"',f'set end "{fmt(end)}"',"draw color blue",
357
+ "draw cylinder $beg $mid radius 0.12 filled yes resolution 20",
358
+ "draw cone $mid $end radius 0.30 resolution 20","display resetview","scale by 1.15",
359
+ f"render Tachyon {{{base.as_posix()}}} {{{tachyon.as_posix()}}} -aasamples 12 -format BMP -o {{{image.as_posix()}}}","quit"]
360
+ tcl=out/"render_total_dipole.tcl";tcl.write_text("\n".join(lines)+"\n",encoding="utf-8")
361
+ _run([vmd,"-dispdev","text","-e",str(tcl)],out,timeout=1800)
362
+ if not image.is_file():raise RuntimeError("VMD 未生成偶极矩图像")
363
+ return image
364
+
365
+ def run_homo_lumo(fchks: Iterable[str | Path], output_parent: str | Path,
366
+ log_by_stem: dict[str, str | Path] | None = None) -> Path:
367
+ files = [Path(p).resolve() for p in fchks]
368
+ if not files or any(not p.is_file() or p.suffix.lower() != ".fchk" for p in files):
369
+ raise ValueError("HOMO/LUMO 流程需要一个或多个有效 .fchk 文件")
370
+ mwfn, vmd = _engine("multiwfn"), _engine("vmd")
371
+ out = new_output_dir(output_parent, "HOMO_LUMO")
372
+ log_by_stem = log_by_stem or {}
373
+ records=[]
374
+ script = ASSET_DIR / "homo-lumo-plot" / "render_one.tcl"
375
+ from ..io.calculators import EngineToolRegistry
376
+ vmd_status=EngineToolRegistry.detect_tool("vmd")
377
+ tcl=_patched_vmd_script(script, out / "render_one.tcl", str(Path(vmd_status.executable_path).parent / "tachyon_WIN64.exe"))
378
+ for fchk in files:
379
+ log = log_by_stem.get(fchk.stem)
380
+ rec=asdict(extract_frontier(fchk, log))
381
+ records.append(rec)
382
+ mol_dir=out / fchk.stem; mol_dir.mkdir()
383
+ for orbital,label in ((rec["homo_orbital"],"HOMO"),(rec["homo_orbital"]+1,"LUMO")):
384
+ _run([mwfn,str(fchk)],mol_dir,stdin=f"200\n3\n{orbital}\n3\n1\n",timeout=1800,allow_nonzero=True)
385
+ cub=mol_dir / f"orb{orbital:07d}.cub"
386
+ if not cub.is_file():
387
+ # Some Multiwfn builds emit a variant with an unpadded orbital number.
388
+ candidates=list(mol_dir.glob("orb*.cub"))
389
+ if len(candidates)==1: cub=candidates[0]
390
+ else: raise RuntimeError(f"Multiwfn 没有生成第 {orbital} 轨道 cube;查看 {mol_dir}")
391
+ base=mol_dir / f"{fchk.stem}_{label}"
392
+ _run([vmd,"-dispdev","text","-e",str(tcl),"-args",str(cub),str(base),"0.005"],mol_dir,timeout=1800)
393
+ if not Path(str(base)+".bmp").is_file():
394
+ raise RuntimeError(f"VMD 未生成 {label} 图;输出保留在 {mol_dir}")
395
+ cub.rename(mol_dir / f"{fchk.stem}_{label}.cub")
396
+ (out/"levels.json").write_text(json.dumps(records,indent=2,ensure_ascii=False),encoding="utf-8")
397
+ if len(records)>=2: write_levels_svg(records,out/"homo_lumo_levels.svg")
398
+ with (out/"levels.csv").open("w",newline="",encoding="utf-8-sig") as fh:
399
+ w=csv.DictWriter(fh,fieldnames=list(records[0]));w.writeheader();w.writerows(records)
400
+ return out
401
+
402
+
403
+ def _structure_arrays(doc):
404
+ z=np.asarray([doc.topology.get_atom(a).atomic_num for a in doc.topology.atom_ids],dtype=int)
405
+ if not doc.has_3d or doc.coordinates.current is None:
406
+ raise ValueError(f"{doc.name} 没有 3D 坐标")
407
+ xyz=np.asarray(doc.coordinates.current.coords,dtype=float)
408
+ return z,xyz
409
+
410
+
411
+ def detect_pair_interactions(doc_a, doc_b, output_parent: str | Path) -> Path:
412
+ """Report cross-molecule heavy-atom contacts and geometry-qualified N/O/S hydrogen bonds."""
413
+ za,xa=_structure_arrays(doc_a); zb,xb=_structure_arrays(doc_b)
414
+ symbols={1:'H',6:'C',7:'N',8:'O',9:'F',15:'P',16:'S',17:'Cl',35:'Br',53:'I'}
415
+ radii={1:1.2,6:1.7,7:1.55,8:1.52,9:1.47,15:1.8,16:1.8,17:1.75,35:1.85,53:1.98}
416
+ heavy_a=np.where(za!=1)[0];heavy_b=np.where(zb!=1)[0]
417
+ contacts=[];hbonds=[]
418
+ for i in heavy_a:
419
+ for j in heavy_b:
420
+ d=float(np.linalg.norm(xa[i]-xb[j]))
421
+ cutoff=radii.get(int(za[i]),1.8)+radii.get(int(zb[j]),1.8)+0.5
422
+ if d <= cutoff:
423
+ contacts.append({'atom_a':int(i+1),'element_a':symbols.get(int(za[i]),str(int(za[i]))),
424
+ 'atom_b':int(j+1),'element_b':symbols.get(int(zb[j]),str(int(zb[j]))),
425
+ 'distance_angstrom':d,'vdw_overlap_angstrom':cutoff-d})
426
+ # Explicit-H D-H...A test. Donors are N/O/S; acceptors are N/O/S.
427
+ if int(zb[j]) in (7,8,16):
428
+ _check_hbond(doc_a,doc_b,xa,xb,za,zb,i,j,True,hbonds)
429
+ if int(za[i]) in (7,8,16):
430
+ _check_hbond(doc_b,doc_a,xb,xa,zb,za,j,i,False,hbonds)
431
+ result={'molecule_a':doc_a.name,'molecule_b':doc_b.name,
432
+ 'contact_count':len(contacts),'hydrogen_bond_count':len(hbonds),
433
+ 'contacts':contacts,'hydrogen_bonds':hbonds,
434
+ 'pi_stacking':_pi_stack_pairs(doc_a,doc_b,xa,xb),
435
+ 'limitations':'范德华接触阈值为元素半径筛查近似;氢键角度和距离采用几何判据,不替代能量分析。'}
436
+ out=new_output_dir(output_parent,'Interactions')
437
+ (out/'interactions.json').write_text(json.dumps(result,indent=2,ensure_ascii=False),encoding='utf-8')
438
+ with (out/'contacts.csv').open('w',newline='',encoding='utf-8-sig') as f:
439
+ keys=['atom_a','element_a','atom_b','element_b','distance_angstrom','vdw_overlap_angstrom']
440
+ w=csv.DictWriter(f,fieldnames=keys);w.writeheader();w.writerows(contacts)
441
+ return out
442
+
443
+
444
+ def _check_hbond(donor_doc,acceptor_doc,xd,xa,zd,za,donor_idx,acceptor_idx,acceptor_is_b,out):
445
+ acc=int(za[acceptor_idx])
446
+ if int(zd[donor_idx]) not in (7,8,16): return
447
+ for hidx in np.where(zd==1)[0]:
448
+ if np.linalg.norm(xd[hidx]-xd[donor_idx])>1.25: continue
449
+ da=float(np.linalg.norm(xd[donor_idx]-xa[acceptor_idx]))
450
+ ha=float(np.linalg.norm(xd[hidx]-xa[acceptor_idx]))
451
+ if da>3.6 or ha>2.6: continue
452
+ v1=xd[donor_idx]-xd[hidx];v2=xa[acceptor_idx]-xd[hidx]
453
+ den=float(np.linalg.norm(v1)*np.linalg.norm(v2))
454
+ angle=math.degrees(math.acos(float(np.clip(np.dot(v1,v2)/den,-1,1)))) if den else 0
455
+ if angle>=120:
456
+ out.append({'donor':donor_doc.name,'donor_atom':int(donor_idx+1),'hydrogen_atom':int(hidx+1),
457
+ 'acceptor':acceptor_doc.name,'acceptor_atom':int(acceptor_idx+1),
458
+ 'D_A_angstrom':da,'H_A_angstrom':ha,'D_H_A_degree':angle})
459
+
460
+
461
+
462
+ def _pi_stack_pairs(doc_a,doc_b,xa,xb):
463
+ try:
464
+ from ..io.rdkit_adapter import doc_to_rdkit
465
+ ma=doc_to_rdkit(doc_a,sanitize=True)[0]; mb=doc_to_rdkit(doc_b,sanitize=True)[0]
466
+ except Exception:
467
+ return []
468
+ def rings(m,xyz):
469
+ out=[]
470
+ for ids in m.GetRingInfo().AtomRings():
471
+ if len(ids)<5 or not all(m.GetAtomWithIdx(i).GetIsAromatic() for i in ids):continue
472
+ pts=xyz[list(ids)];center=pts.mean(axis=0)
473
+ _u,_s,vt=np.linalg.svd(pts-center,full_matrices=False)
474
+ out.append((tuple(int(i+1) for i in ids),center,vt[-1]))
475
+ return out
476
+ result=[]
477
+ for ia,ca,na in rings(ma,xa):
478
+ for ib,cb,nb in rings(mb,xb):
479
+ delta=cb-ca;dist=float(np.linalg.norm(delta))
480
+ if not 3.0<=dist<=6.0:continue
481
+ angle=math.degrees(math.acos(float(np.clip(abs(np.dot(na,nb)),-1,1))))
482
+ vertical=abs(float(np.dot(delta,na)))
483
+ lateral=math.sqrt(max(0.,dist*dist-vertical*vertical))
484
+ geometry=('parallel' if angle<=30 and vertical<=4.0 and lateral<=4.5
485
+ else 'T-shaped' if angle>=60 and 3.0<=vertical<=5.0 else None)
486
+ if geometry:
487
+ result.append({'ring_a_atoms':ia,'ring_b_atoms':ib,'centroid_distance_angstrom':dist,
488
+ 'plane_angle_degree':angle,'geometry':geometry})
489
+ return result
490
+
491
+ def _kabsch_rmsd(reference: np.ndarray, mobile: np.ndarray) -> float:
492
+ a=reference-reference.mean(axis=0);b=mobile-mobile.mean(axis=0)
493
+ u,_s,vt=np.linalg.svd(b.T@a);d=np.linalg.det(u@vt)
494
+ rot=u@np.diag([1.,1.,d])@vt
495
+ delta=b@rot-a
496
+ return float(np.sqrt(np.mean(np.sum(delta*delta,axis=1))))
497
+
498
+
499
+ def run_md_postprocess(topology: str | Path, trajectory: str | Path, output_parent: str | Path) -> Path:
500
+ """Use MDAnalysis to calculate aligned RMSD and radius of gyration per frame."""
501
+ try: import MDAnalysis as mda
502
+ except ImportError as exc: raise RuntimeError('MD 轨迹分析需要安装 MDAnalysis(requirements-md.txt)。') from exc
503
+ top,traj=Path(topology).resolve(),Path(trajectory).resolve()
504
+ if not top.is_file() or not traj.is_file(): raise ValueError('拓扑或轨迹文件不存在')
505
+ universe=mda.Universe(str(top),str(traj))
506
+ if len(universe.atoms)==0: raise ValueError('轨迹中没有原子')
507
+ frames=[];reference=None
508
+ for ts in universe.trajectory:
509
+ coords=np.asarray(universe.atoms.positions,dtype=float).copy()
510
+ if reference is None: reference=coords.copy()
511
+ rg=float(universe.atoms.radius_of_gyration())
512
+ frames.append({'frame':int(ts.frame),'time_ps':float(getattr(ts,'time',ts.frame)),
513
+ 'rmsd_angstrom':_kabsch_rmsd(reference,coords),'rg_angstrom':rg})
514
+ if not frames: raise ValueError('轨迹中没有帧')
515
+ # Deterministic coarse clustering by aligned RMSD and Rg features.
516
+ values=np.asarray([[x['rmsd_angstrom'],x['rg_angstrom']] for x in frames],dtype=float)
517
+ scale=values.std(axis=0);scale[scale<1e-12]=1.0
518
+ feat=(values-values.mean(axis=0))/scale;k=min(3,len(feat))
519
+ centers=feat[np.linspace(0,len(feat)-1,k,dtype=int)].copy()
520
+ for _ in range(40):
521
+ labels=np.argmin(((feat[:,None,:]-centers[None,:,:])**2).sum(axis=2),axis=1)
522
+ updated=np.asarray([feat[labels==j].mean(axis=0) if np.any(labels==j) else centers[j] for j in range(k)])
523
+ if np.allclose(updated,centers):break
524
+ centers=updated
525
+ for row,cluster in zip(frames,labels):row['cluster_id']=int(cluster+1)
526
+ hbonds={'status':'not_run','count':0,'occupancy':[]}
527
+ try:
528
+ from MDAnalysis.analysis.hydrogenbonds import HydrogenBondAnalysis
529
+ hba=HydrogenBondAnalysis(universe,d_a_cutoff=3.5,d_h_a_angle_cutoff=150.0)
530
+ hba.run()
531
+ data=np.asarray(hba.results.hbonds)
532
+ hbonds['status']='ok'
533
+ hbonds['count']=int(len(data))
534
+ if data.size:
535
+ pairs={}
536
+ for record in data:
537
+ key=(int(record[1]),int(record[3]));pairs.setdefault(key,set()).add(int(record[0]))
538
+ hbonds['occupancy']=[{'donor_index':a,'acceptor_index':b,'fraction':len(fs)/max(1,len(frames))}
539
+ for (a,b),fs in sorted(pairs.items())]
540
+ except Exception as exc:
541
+ hbonds={'status':'unavailable','count':0,'occupancy':[],'diagnostic':str(exc)}
542
+ out=new_output_dir(output_parent,f"MD_{top.stem}")
543
+ with (out/'md_rmsd_rg.csv').open('w',newline='',encoding='utf-8-sig') as f:
544
+ w=csv.DictWriter(f,fieldnames=list(frames[0]));w.writeheader();w.writerows(frames)
545
+ (out/'md_summary.json').write_text(json.dumps({'topology':str(top),'trajectory':str(traj),
546
+ 'frames':len(frames),'atoms':len(universe.atoms),'cluster_count':k,'hbond_analysis':hbonds,
547
+ 'warning':'未自动处理周期边界;聚类基于对齐 RMSD/Rg 两个特征,不是全原子自由能聚类。'},
548
+ indent=2,ensure_ascii=False),encoding='utf-8')
549
+ return out
550
+
551
+
552
+ def calculate_pair_energy_components(csv_path: str | Path, output_parent: str | Path) -> Path:
553
+ """Calculate component-wise E(AB)-E(A)-E(B) from exported GROMACS energy means.
554
+
555
+ CSV columns: system (AB/A/B), component, mean_kj_mol. This is a classical
556
+ force-field rerun decomposition; it is not a quantum-chemical sobEDA result.
557
+ """
558
+ p=Path(csv_path).resolve();values={}
559
+ with p.open(newline='',encoding='utf-8-sig') as f:
560
+ reader=csv.DictReader(f)
561
+ required={'system','component','mean_kj_mol'}
562
+ if not required.issubset(set(reader.fieldnames or [])):
563
+ raise ValueError('CSV 必须包含 system, component, mean_kj_mol 三列;system 使用 AB、A、B。')
564
+ for row in reader: values.setdefault(row['system'].strip().upper(),{})[row['component'].strip()]=float(row['mean_kj_mol'])
565
+ if not all(x in values for x in ('AB','A','B')): raise ValueError('输入数据必须包含 AB、A、B 三个体系。')
566
+ common=set(values['AB'])&set(values['A'])&set(values['B'])
567
+ if not common: raise ValueError('三个体系没有同名能量分量。')
568
+ result=[{'component':k,'AB_kj_mol':values['AB'][k],'A_kj_mol':values['A'][k],
569
+ 'B_kj_mol':values['B'][k],'interaction_kj_mol':values['AB'][k]-values['A'][k]-values['B'][k]}
570
+ for k in sorted(common)]
571
+ out=new_output_dir(output_parent,f"Gromacs_EDA_{p.stem}")
572
+ with (out/'interaction_energy_components.csv').open('w',newline='',encoding='utf-8-sig') as f:
573
+ w=csv.DictWriter(f,fieldnames=list(result[0]));w.writeheader();w.writerows(result)
574
+ (out/'method.txt').write_text('经典力场 rerun 分量差:ΔE(component)=E_AB-E_A-E_B。此结果不是 sobEDA/量子化学能量分解。\n',encoding='utf-8')
575
+ return out
576
+
577
+
578
+ def _write_rectangle_svg(records, output):
579
+ width,height=1050,620;left,right,top,bottom=100,35,40,90
580
+ emin=min(-6.5,min(r['homo_ev'] for r in records)-.4);emax=max(-2.2,max(r['lumo_ev'] for r in records)+.4)
581
+ y=lambda e:top+(emax-e)/(emax-emin)*(height-top-bottom)
582
+ step=(width-left-right)/len(records);parts=[f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}"><rect width="100%" height="100%" fill="white"/>']
583
+ for k in range(math.ceil(emin*2),math.floor(emax*2)+1):
584
+ e=k/2; yy=y(e);parts.append(f'<path d="M{left} {yy:.1f}H{width-right}" stroke="#e2e8ef"/><text x="{left-10}" y="{yy+4:.1f}" text-anchor="end" font-size="13">{e:.1f}</text>')
585
+ colors=['#227c83','#d8793d','#4f73aa','#759452','#a45d91']
586
+ for i,r in enumerate(records):
587
+ cx=left+(i+.5)*step; y1,y2=y(r['lumo_ev']),y(r['homo_ev']); c=colors[i%len(colors)]
588
+ parts += [f'<rect x="{cx-45:.1f}" y="{y1:.1f}" width="90" height="{max(2,y2-y1):.1f}" fill="{c}" fill-opacity=".13" stroke="{c}" stroke-width="3"/>',
589
+ f'<text x="{cx}" y="{y1-8:.1f}" text-anchor="middle" font-size="13">LUMO {r["lumo_ev"]:.2f}</text>',
590
+ f'<text x="{cx}" y="{y2+20:.1f}" text-anchor="middle" font-size="13">HOMO {r["homo_ev"]:.2f}</text>',
591
+ f'<text x="{cx}" y="{height-bottom+24}" text-anchor="middle" font-size="14">{_xml(r["source"])}</text>']
592
+ parts.append('</svg>');Path(output).write_text('\n'.join(parts),encoding='utf-8')
593
+
594
+
595
+ def _write_grid_svg(records, output):
596
+ width=max(800,240*len(records));height=620;gap=width/len(records);parts=[f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}"><rect width="100%" height="100%" fill="white"/>']
597
+ colors=['#267a83','#cf753b','#5175a8','#78954e','#a45e91']
598
+ for row,label,key in ((0,'LUMO','lumo_ev'),(1,'HOMO','homo_ev')):
599
+ ybase=210+row*270
600
+ parts.append(f'<text x="20" y="{ybase+15}" font-family="Arial" font-weight="bold" font-size="20">{label}</text>')
601
+ for i,r in enumerate(records):
602
+ cx=(i+.5)*gap;value=r[key];c=colors[i%len(colors)]
603
+ parts += [f'<path d="M{cx-38} {ybase}H{cx+38}" stroke="{c}" stroke-width="5"/>',
604
+ f'<text x="{cx}" y="{ybase-12}" text-anchor="middle" font-family="Arial" font-size="18">{value:.2f} eV</text>',
605
+ f'<text x="{cx}" y="{ybase+40}" text-anchor="middle" font-family="Arial" font-size="13">{_xml(r["source"])}</text>']
606
+ parts.append('</svg>');Path(output).write_text('\n'.join(parts),encoding='utf-8')
607
+
608
+
609
+ def _write_energy_workbook(records, output):
610
+ try:
611
+ from openpyxl import Workbook
612
+ from openpyxl.styles import Font,PatternFill,Alignment,Border,Side
613
+ except ImportError:
614
+ Path(str(output)+'.missing.txt').write_text('Install openpyxl to export this workbook.\n',encoding='utf-8');return
615
+ wb=Workbook();ws=wb.active;ws.title='HOMO_LUMO'
616
+ headers=['Molecule','HOMO (eV)','LUMO (eV)','Gap (eV)','Source validation']
617
+ ws.append(headers)
618
+ for r in records:ws.append([r['source'],r['homo_ev'],r['lumo_ev'],r['gap_ev'],r['validation']])
619
+ fill=PatternFill('solid',fgColor='D9E1F2');thin=Side(style='thin',color='AAB7C4')
620
+ for row in ws.iter_rows():
621
+ for cell in row:
622
+ cell.alignment=Alignment(horizontal='center',vertical='center');cell.border=Border(left=thin,right=thin,top=thin,bottom=thin)
623
+ if cell.row==1:cell.font=Font(bold=True);cell.fill=fill
624
+ for col,width in {'A':24,'B':16,'C':16,'D':14,'E':34}.items():ws.column_dimensions[col].width=width
625
+ note=wb.create_sheet('Notes');note.append(['Method','HOMO from alpha electron count; energies converted with 27.211386245988 eV/Ha.'])
626
+ note.append(['Validation','fchk and matching Gaussian log must agree within 0.05 eV.'])
627
+ wb.save(output)
628
+
629
+
630
+ def _write_editable_pptx(records, output):
631
+ try:
632
+ from pptx import Presentation
633
+ from pptx.util import Inches,Pt
634
+ from pptx.dml.color import RGBColor
635
+ from pptx.enum.text import PP_ALIGN
636
+ from pptx.enum.shapes import MSO_CONNECTOR
637
+ except ImportError:
638
+ Path(str(output)+'.missing.txt').write_text('Install python-pptx to export the editable PowerPoint.\n',encoding='utf-8');return
639
+ prs=Presentation();slide=prs.slides.add_slide(prs.slide_layouts[6]);left=1.1;right=12.3;top=.8;bottom=6.2
640
+ emin=min(-6.5,min(r['homo_ev'] for r in records)-.4);emax=max(-2.2,max(r['lumo_ev'] for r in records)+.4)
641
+ y=lambda e:top+(emax-e)/(emax-emin)*(bottom-top)
642
+ axis=slide.shapes.add_connector(MSO_CONNECTOR.STRAIGHT,Inches(left),Inches(top),Inches(left),Inches(bottom));axis.line.color.rgb=RGBColor(45,62,78)
643
+ for i,r in enumerate(records):
644
+ cx=left+.6+(right-left-1.2)*(i/max(1,len(records)-1))
645
+ for key,color in [('lumo_ev',RGBColor(210,88,62)),('homo_ev',RGBColor(38,79,95))]:
646
+ line=slide.shapes.add_connector(MSO_CONNECTOR.STRAIGHT,Inches(cx-.42),Inches(y(r[key])),Inches(cx+.42),Inches(y(r[key])))
647
+ line.line.color.rgb=color;line.line.width=Pt(3)
648
+ box=slide.shapes.add_textbox(Inches(cx-.6),Inches(y(r[key])-.25),Inches(1.2),Inches(.22));box.text_frame.text=f'{r[key]:.2f} eV';box.text_frame.paragraphs[0].alignment=PP_ALIGN.CENTER;box.text_frame.paragraphs[0].font.size=Pt(10)
649
+ box=slide.shapes.add_textbox(Inches(cx-.8),Inches(6.35),Inches(1.6),Inches(.35));box.text_frame.text=r['source'];box.text_frame.paragraphs[0].alignment=PP_ALIGN.CENTER;box.text_frame.paragraphs[0].font.size=Pt(10)
650
+ prs.save(output)