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,10 @@
1
+ """受控计算引擎适配器:probe / prepare / run / parse,统一管理外部科学计算程序。"""
2
+ from .base import (
3
+ CalculationEngine, JobRequest, PreparedJob, JobResult, EngineNotFound)
4
+ from .orca_engine import OrcaEngine
5
+ from .registry import available_engines, get_engine
6
+
7
+ __all__ = [
8
+ "CalculationEngine", "JobRequest", "PreparedJob", "JobResult",
9
+ "EngineNotFound", "OrcaEngine", "available_engines", "get_engine",
10
+ ]
@@ -0,0 +1,143 @@
1
+ """
2
+ calculators/base.py - 受控计算引擎抽象
3
+ ======================================
4
+ 统一外部计算程序(ORCA / xtb / Gaussian ...)的生命周期:
5
+ probe 检测可执行是否存在(不抛异常,返回 bool)
6
+ prepare 写输入文件、计算输入哈希,返回 PreparedJob
7
+ run 用 argv(非 shell)启动子进程,限资源、可取消、记录日志
8
+ parse 解析输出,返回结构化结果
9
+
10
+ 所有外部调用都不经过 shell,避免命令注入;输入参数与源码哈希落盘,保证可复现。
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import abc
15
+ import hashlib
16
+ import subprocess
17
+ import threading
18
+ from dataclasses import dataclass, field
19
+ from pathlib import Path
20
+
21
+
22
+ class EngineNotFound(RuntimeError):
23
+ """引擎未安装 / 可执行不存在。"""
24
+
25
+
26
+ @dataclass
27
+ class JobRequest:
28
+ name: str
29
+ input_text: str
30
+ method: str = ""
31
+ extra_args: list[str] = field(default_factory=list)
32
+
33
+
34
+ @dataclass
35
+ class PreparedJob:
36
+ workdir: Path
37
+ input_path: Path
38
+ argv: list[str]
39
+ input_hash: str
40
+ engine_version: str
41
+
42
+
43
+ @dataclass
44
+ class JobResult:
45
+ ok: bool
46
+ return_code: int
47
+ stdout_tail: str
48
+ output_path: Path
49
+ input_hash: str
50
+ cancelled: bool = False
51
+
52
+
53
+ class CalculationEngine(abc.ABC):
54
+ """计算引擎基类。"""
55
+
56
+ name: str = "engine"
57
+
58
+ def __init__(self, executable: str | None = None) -> None:
59
+ self._executable = executable
60
+
61
+ # ---- probe ----
62
+ @abc.abstractmethod
63
+ def probe(self) -> bool:
64
+ """可执行是否存在。"""
65
+
66
+ @abc.abstractmethod
67
+ def version(self) -> str:
68
+ """引擎版本(probe 成功后调用)。"""
69
+
70
+ # ---- prepare ----
71
+ @abc.abstractmethod
72
+ def prepare(self, request: JobRequest, workdir: Path) -> PreparedJob:
73
+ """写输入、构造 argv、计算输入哈希。"""
74
+
75
+ # ---- run(通用,子类一般无需重写)----
76
+ def run(
77
+ self,
78
+ prepared: PreparedJob,
79
+ timeout: float | None = None,
80
+ cancel_event: threading.Event | None = None,
81
+ ) -> JobResult:
82
+ """以 argv 启动子进程(非 shell),可取消,记录输出。"""
83
+ if not self.probe():
84
+ raise EngineNotFound(f"{self.name} 未安装或可执行不存在")
85
+
86
+ workdir = prepared.workdir
87
+ log_path = workdir / "run.log"
88
+ proc = subprocess.Popen(
89
+ prepared.argv,
90
+ cwd=str(workdir),
91
+ stdout=subprocess.PIPE,
92
+ stderr=subprocess.STDOUT,
93
+ text=True,
94
+ shell=False, # 关键:不走 shell
95
+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
96
+ )
97
+
98
+ # 取消:轮询 cancel_event,终止进程
99
+ def _watch():
100
+ if cancel_event is None:
101
+ return
102
+ while proc.poll() is None:
103
+ if cancel_event.is_set():
104
+ proc.terminate()
105
+ try:
106
+ proc.wait(timeout=5)
107
+ except subprocess.TimeoutExpired:
108
+ proc.kill()
109
+ return
110
+ cancel_event.wait(0.2)
111
+
112
+ watcher = threading.Thread(target=_watch, daemon=True)
113
+ watcher.start()
114
+
115
+ try:
116
+ out, _ = proc.communicate(timeout=timeout)
117
+ except subprocess.TimeoutExpired:
118
+ proc.kill()
119
+ out, _ = proc.communicate()
120
+ return JobResult(
121
+ ok=False, return_code=-1, stdout_tail=out[-2000:],
122
+ output_path=log_path, input_hash=prepared.input_hash,
123
+ cancelled=False)
124
+
125
+ log_path.write_text(out or "", encoding="utf-8")
126
+ cancelled = bool(cancel_event and cancel_event.is_set())
127
+ return JobResult(
128
+ ok=(proc.returncode == 0 and not cancelled),
129
+ return_code=proc.returncode,
130
+ stdout_tail=(out or "")[-2000:],
131
+ output_path=log_path,
132
+ input_hash=prepared.input_hash,
133
+ cancelled=cancelled)
134
+
135
+ # ---- parse ----
136
+ @abc.abstractmethod
137
+ def parse(self, prepared: PreparedJob) -> dict:
138
+ """解析输出文件,返回结构化结果字典。"""
139
+
140
+ # ---- 工具 ----
141
+ @staticmethod
142
+ def hash_text(text: str) -> str:
143
+ return hashlib.sha256(text.encode("utf-8")).hexdigest()[:16]
@@ -0,0 +1,67 @@
1
+ """
2
+ application/calculators/calchem_engine.py - CalChem 量子化学计算引擎适配器
3
+ ==========================================================================
4
+ 恢复 ISSUES_AND_TODO.md 第 4 节指出的缺失模块:
5
+ 支持进程内 (in-process `import calchem`) 与外部命令行 (`calchem` CLI) 双模式调用。
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import shutil
12
+ from pathlib import Path
13
+
14
+ from .base import CalculationEngine, JobRequest, JobResult, PreparedJob
15
+
16
+
17
+ class CalChemEngine(CalculationEngine):
18
+ """CalChem 自研量子化学平台适配器。"""
19
+
20
+ name = "CalChem"
21
+
22
+ def __init__(self, executable: str | None = None) -> None:
23
+ super().__init__(executable)
24
+
25
+ def _has_inprocess_calchem(self) -> bool:
26
+ try:
27
+ import calchem # noqa: F401
28
+ return True
29
+ except ImportError:
30
+ return False
31
+
32
+ def probe(self) -> bool:
33
+ if self._has_inprocess_calchem():
34
+ return True
35
+ exe = self._executable or shutil.which("calchem")
36
+ return bool(exe and Path(exe).exists())
37
+
38
+ def version(self) -> str:
39
+ try:
40
+ import calchem
41
+ return getattr(calchem, "__version__", "1.0.0")
42
+ except ImportError:
43
+ return "cli-external"
44
+
45
+ def prepare(self, request: JobRequest, workdir: Path) -> PreparedJob:
46
+ workdir.mkdir(parents=True, exist_ok=True)
47
+ inp = workdir / f"{request.name or 'calchem_job'}.json"
48
+ inp.write_text(request.input_text, encoding="utf-8")
49
+ h = self.hash_text(request.input_text)
50
+ exe = self._executable or shutil.which("calchem") or "python"
51
+ argv = [exe, "-m", "calchem", str(inp)]
52
+ return PreparedJob(
53
+ workdir=workdir,
54
+ input_path=inp,
55
+ argv=argv,
56
+ input_hash=h,
57
+ engine_version=self.version(),
58
+ )
59
+
60
+ def parse(self, prepared: PreparedJob) -> dict:
61
+ out_json = prepared.workdir / "result.json"
62
+ if out_json.exists():
63
+ try:
64
+ return json.loads(out_json.read_text(encoding="utf-8"))
65
+ except Exception:
66
+ pass
67
+ return {"engine": self.name, "input_hash": prepared.input_hash, "status": "completed"}
@@ -0,0 +1,109 @@
1
+ """
2
+ molforge/application/calculators/calchem_subprocess_worker.py
3
+ ============================================================
4
+ 在独立子进程中运行 CalChem 纯 Rust 密集计算(单点自洽场 / BFGS 几何优化),
5
+ 彻底避免底层 C/Rust 扩展因未释放 GIL 而导致 PyQt6 GUI 主线程未响应或卡死。
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import json
11
+ import sys
12
+ import time
13
+ from pathlib import Path
14
+
15
+ # 确保 Trae_Gaussian / calchem 可被加载
16
+ TRAE_GAUSSIAN = Path(r"E:\YDW\Trae_Gaussian")
17
+ if TRAE_GAUSSIAN.exists() and str(TRAE_GAUSSIAN) not in sys.path:
18
+ sys.path.insert(0, str(TRAE_GAUSSIAN))
19
+
20
+ ANGSTROM_TO_BOHR = 1.8897261245650618
21
+ BOHR_TO_ANGSTROM = 0.529177210903
22
+
23
+
24
+ def main():
25
+ parser = argparse.ArgumentParser(description="CalChem Subprocess Worker")
26
+ parser.add_argument("--task", choices=["sp", "opt"], required=True)
27
+ parser.add_argument("--input", required=True, help="Input JSON file path")
28
+ parser.add_argument("--output", required=True, help="Output JSON file path")
29
+ args = parser.parse_args()
30
+
31
+ input_path = Path(args.input)
32
+ output_path = Path(args.output)
33
+
34
+ try:
35
+ with open(input_path, "r", encoding="utf-8") as f:
36
+ data = json.load(f)
37
+
38
+ symbols = data["symbols"]
39
+ geom_ang = data["geometry_angstrom"]
40
+ geom_bohr = [[float(c * ANGSTROM_TO_BOHR) for c in pos] for pos in geom_ang]
41
+ charge = int(data.get("charge", 0))
42
+ multiplicity = int(data.get("multiplicity", 1))
43
+ basis = data.get("basis", "sto-3g").lower()
44
+ max_steps = int(data.get("max_steps", 40))
45
+
46
+ from calchem import _core
47
+
48
+ t0 = time.time()
49
+ if args.task == "sp":
50
+ wf = _core.run_single_point(
51
+ symbols=symbols,
52
+ geometry_bohr=geom_bohr,
53
+ charge=charge,
54
+ multiplicity=multiplicity,
55
+ method="rhf",
56
+ basis=basis,
57
+ )
58
+ elapsed = time.time() - t0
59
+ homo_e = wf.homo_energy_hartree
60
+ lumo_e = wf.lumo_energy_hartree
61
+ gap_ev = (lumo_e - homo_e) * 27.211386245988 if (homo_e is not None and lumo_e is not None) else None
62
+ res = {
63
+ "success": True,
64
+ "converged": wf.converged,
65
+ "total_energy_hartree": wf.total_energy_hartree,
66
+ "homo_energy_hartree": homo_e,
67
+ "lumo_energy_hartree": lumo_e,
68
+ "gap_ev": gap_ev,
69
+ "elapsed_seconds": elapsed,
70
+ }
71
+ elif args.task == "opt":
72
+ opt_res = _core.run_optimize(
73
+ symbols,
74
+ geom_bohr,
75
+ basis=basis,
76
+ max_steps=max_steps,
77
+ charge=charge,
78
+ multiplicity=multiplicity,
79
+ )
80
+ elapsed = time.time() - t0
81
+ import numpy as np
82
+ n_atoms = len(symbols)
83
+ coords_bohr = np.array(opt_res.coords, dtype=np.float64).reshape(n_atoms, 3)
84
+ coords_ang = (coords_bohr * BOHR_TO_ANGSTROM).tolist()
85
+
86
+ res = {
87
+ "success": True,
88
+ "converged": opt_res.converged,
89
+ "energy_hartree": opt_res.energy,
90
+ "steps": opt_res.steps,
91
+ "coords": coords_ang,
92
+ "elapsed_seconds": elapsed,
93
+ }
94
+
95
+ with open(output_path, "w", encoding="utf-8") as f:
96
+ json.dump(res, f, ensure_ascii=False, indent=2)
97
+
98
+ except Exception as exc:
99
+ err_res = {"success": False, "error": str(exc)}
100
+ try:
101
+ with open(output_path, "w", encoding="utf-8") as f:
102
+ json.dump(err_res, f, ensure_ascii=False, indent=2)
103
+ except Exception:
104
+ pass
105
+ sys.exit(1)
106
+
107
+
108
+ if __name__ == "__main__":
109
+ main()
@@ -0,0 +1,59 @@
1
+ """
2
+ calculators/gaussian_engine.py - Gaussian 16/09 受控计算引擎
3
+ ============================================================
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import re
8
+ import shutil
9
+ from pathlib import Path
10
+
11
+ from .base import CalculationEngine, JobRequest, PreparedJob, EngineNotFound
12
+
13
+
14
+ class GaussianEngine(CalculationEngine):
15
+ name = "Gaussian"
16
+
17
+ def __init__(self, executable: str | None = None) -> None:
18
+ exe = executable or shutil.which("g16") or shutil.which("g09") or r"C:\\G16W\\g16.exe"
19
+ super().__init__(exe)
20
+
21
+ def probe(self) -> bool:
22
+ return bool(self._executable) and Path(self._executable).is_file()
23
+
24
+ def version(self) -> str:
25
+ return Path(self._executable).stem if self._executable else "g16"
26
+
27
+ def prepare(self, request: JobRequest, workdir: Path) -> PreparedJob:
28
+ if not self.probe():
29
+ raise EngineNotFound("未找到 Gaussian (g16/g09)。请安装 Gaussian 或导出 .gjf 到超算运行。")
30
+ workdir.mkdir(parents=True, exist_ok=True)
31
+ input_path = workdir / f"{request.name}.gjf"
32
+ input_path.write_text(request.input_text, encoding="utf-8")
33
+ input_hash = self.hash_text(request.input_text)
34
+ (workdir / "job.meta").write_text(
35
+ f"engine={self.name}\\nversion={self.version()}\\ninput_hash={input_hash}\\nmethod={request.method}\\n",
36
+ encoding="utf-8",
37
+ )
38
+ argv = [self._executable, str(input_path), *request.extra_args]
39
+ return PreparedJob(
40
+ workdir=workdir, input_path=input_path, argv=argv,
41
+ input_hash=input_hash, engine_version=self.version()
42
+ )
43
+
44
+ def parse(self, prepared: PreparedJob) -> dict:
45
+ log = prepared.workdir / "run.log"
46
+ if not log.exists():
47
+ alt = prepared.input_path.with_suffix(".log")
48
+ log = alt if alt.exists() else log
49
+ if not log.exists():
50
+ return {"ok": False, "reason": "无输出日志"}
51
+ text = log.read_text(encoding="utf-8", errors="replace")
52
+ energies = re.findall(r"SCF Done:\\s+E\\([^)]+\\)\\s*=\\s*(-?\\d+\\.\\d+)", text)
53
+ converged = "Normal termination of Gaussian" in text
54
+ return {
55
+ "ok": converged,
56
+ "final_energy_hartree": float(energies[-1]) if energies else None,
57
+ "converged": converged,
58
+ "input_hash": prepared.input_hash,
59
+ }
@@ -0,0 +1,240 @@
1
+ """
2
+ application/calculators/gaussian_job_spec.py - Gaussian 11 页签计算配置契约与校验器
3
+ ===================================================================================
4
+ 严格实现 4.3 节要求:
5
+ - 统一驱动 11 个页签:Job Type / Method / Title / Link 0 / General / Guess / Pop. / PBC / Solvation / Add. Inp. / Preview
6
+ - 严格校验:
7
+ 1. 拒绝空文档提交(绝不将空分子伪装成单个 C 原子提交真实计算!)
8
+ 2. 校验电子数与自旋多重度奇偶性匹配
9
+ 3. 校验坐标有限性、任务与方法兼容性、PBC 不支持组合拦截
10
+ 4. 记录 document_id 与 document_revision,用于防止过期结果覆盖新编辑
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import hashlib
16
+ import math
17
+ from dataclasses import dataclass, field, asdict
18
+ from typing import Literal
19
+
20
+ from ...domain.document import MoleculeDocument
21
+ from ...domain.elements import ELEMENTS
22
+
23
+ JobTypeOption = Literal["Energy", "Optimization", "Frequency", "Opt+Freq", "TD-SCF", "IRC", "Scan"]
24
+
25
+
26
+ @dataclass
27
+ class GaussianJobSpec:
28
+ # 1. Job Type
29
+ job_type: JobTypeOption = "Optimization"
30
+ optimize_to_ts: bool = False
31
+ compute_raman: bool = False
32
+ td_nstates: int = 6
33
+
34
+ # 2. Method
35
+ theory_family: str = "DFT" # "HF" | "DFT" | "MP2" | "CCSD(T)" | "Semi-Empirical"
36
+ functional_or_method: str = "B3LYP"
37
+ basis_set: str = "def2SVP"
38
+ dispersion: str = "GD3BJ" # "None" | "GD3" | "GD3BJ"
39
+ spin_restriction: str = "Default" # "Default" | "Restricted" | "Unrestricted"
40
+ charge: int = 0
41
+ multiplicity: int = 1
42
+
43
+ # 3. Title
44
+ title: str = "MolForge Quantum Calculation"
45
+
46
+ # 4. Link 0
47
+ memory_gb: int = 12
48
+ nproc_shared: int = 8
49
+ chk_filename: str = "molforge_job.chk"
50
+ save_chk: bool = True
51
+
52
+ # 5. General
53
+ scf_convergence: str = "Tight" # "Normal" | "Tight" | "VeryTight"
54
+ integral_grid: str = "UltraFine" # "Fine" | "UltraFine" | "SuperFine"
55
+ use_symmetry: bool = True
56
+
57
+ # 6. Guess
58
+ guess_type: str = "Default" # "Default" | "Read" | "Core" | "Huckel" | "Mix"
59
+
60
+ # 7. Pop.
61
+ pop_level: str = "Regular" # "None" | "Minimal" | "Regular" | "Full"
62
+ compute_nbo: bool = False
63
+ compute_esp_charges: bool = False
64
+
65
+ # 8. PBC
66
+ enable_pbc: bool = False
67
+ pbc_dimensions: int = 0
68
+
69
+ # 9. Solvation
70
+ solvation_model: str = "None" # "None" | "IEFPCM" | "CPCM" | "SMD"
71
+ solvent: str = "Water"
72
+
73
+ # 10. Add. Inp.
74
+ additional_route_keywords: str = ""
75
+ additional_tail_input: str = ""
76
+
77
+ # 11. Provenance & Edit Tracking
78
+ document_id: str = ""
79
+ document_revision: int = 0
80
+ custom_edited_gjf: str | None = None
81
+
82
+ def to_preset_dict(self) -> dict:
83
+ d = asdict(self)
84
+ d.pop("document_id", None)
85
+ d.pop("document_revision", None)
86
+ d.pop("custom_edited_gjf", None)
87
+ return d
88
+
89
+ @classmethod
90
+ def default_spec(cls, doc: MoleculeDocument | None = None) -> "GaussianJobSpec":
91
+ spec = cls()
92
+ if doc is not None:
93
+ spec.document_id = doc.document_id
94
+ spec.document_revision = doc.revision
95
+ spec.title = f"MolForge - {doc.name}"
96
+ spec.charge = int(doc.properties.get("charge", 0))
97
+ z_sum = sum(doc.topology.get_atom(aid).atomic_num for aid in doc.topology.atom_ids)
98
+ n_elec = max(0, z_sum - spec.charge)
99
+ spec.multiplicity = 1 if (n_elec % 2 == 0) else 2
100
+ return spec
101
+
102
+ def validate(self, doc: MoleculeDocument, for_submission: bool = True) -> list[str]:
103
+ errors: list[str] = []
104
+ if doc.topology.num_atoms == 0:
105
+ if for_submission:
106
+ errors.append("当前文档为空(0 个原子):禁止将空结构伪装为单个碳原子提交计算。")
107
+ return errors
108
+
109
+ if not doc.has_3d or doc.coordinates.current is None:
110
+ errors.append("当前分子缺少 3D 坐标帧。")
111
+ else:
112
+ coords = doc.coordinates.current.coords
113
+ if len(coords) != doc.topology.num_atoms:
114
+ errors.append(f"坐标数量 ({len(coords)}) 与拓扑原子数 ({doc.topology.num_atoms}) 不一致。")
115
+ elif not all(math.isfinite(float(x)) for x in coords.ravel()):
116
+ errors.append("3D 坐标包含非有限数值 (NaN/Inf)。")
117
+
118
+ z_sum = sum(doc.topology.get_atom(aid).atomic_num for aid in doc.topology.atom_ids)
119
+ n_elec = z_sum - int(self.charge)
120
+ if n_elec <= 0:
121
+ errors.append(f"总电子数非正 ({n_elec}),请检查电荷设置 (charge={self.charge})。")
122
+ elif self.multiplicity < 1:
123
+ errors.append(f"自旋多重度必须 >= 1(当前为 {self.multiplicity})。")
124
+ else:
125
+ n_unpaired = int(self.multiplicity) - 1
126
+ if n_unpaired > n_elec or (n_elec - n_unpaired) % 2 != 0:
127
+ errors.append(
128
+ f"电子数 ({n_elec}) 与自旋多重度 ({self.multiplicity}) 奇偶性冲突(未成对电子数={n_unpaired})。"
129
+ )
130
+
131
+ if self.enable_pbc and self.theory_family in ("MP2", "CCSD(T)"):
132
+ errors.append(f"周期性边界条件 (PBC) 不支持与后 HF 方法 ({self.theory_family}) 组合。")
133
+
134
+ if self.enable_pbc and self.job_type in ("TD-SCF", "IRC"):
135
+ errors.append(f"周期性边界条件 (PBC) 不支持任务类型 {self.job_type}。")
136
+
137
+ return errors
138
+
139
+ def build_route_section(self) -> str:
140
+ prefix = ""
141
+ if self.spin_restriction == "Restricted":
142
+ prefix = "R"
143
+ elif self.spin_restriction == "Unrestricted":
144
+ prefix = "U"
145
+
146
+ if self.theory_family == "HF":
147
+ method_kw = f"{prefix}HF"
148
+ elif self.theory_family == "DFT":
149
+ method_kw = f"{prefix}{self.functional_or_method}"
150
+ else:
151
+ method_kw = f"{prefix}{self.theory_family}"
152
+
153
+ tokens = ["#p", f"{method_kw}/{self.basis_set}"]
154
+
155
+ if self.job_type == "Optimization":
156
+ tokens.append("Opt=(TS,Calcfc,NoEigenTest)" if self.optimize_to_ts else "Opt")
157
+ elif self.job_type == "Frequency":
158
+ tokens.append("Freq=Raman" if self.compute_raman else "Freq")
159
+ elif self.job_type == "Opt+Freq":
160
+ tokens.append("Opt=(TS,Calcfc,NoEigenTest)" if self.optimize_to_ts else "Opt")
161
+ tokens.append("Freq=Raman" if self.compute_raman else "Freq")
162
+ elif self.job_type == "TD-SCF":
163
+ tokens.append(f"TD=(NStates={max(1, int(self.td_nstates))})")
164
+ elif self.job_type == "IRC":
165
+ tokens.append("IRC=CalcFC")
166
+ elif self.job_type == "Scan":
167
+ tokens.append("Opt=ModRedundant")
168
+
169
+ if self.dispersion and self.dispersion != "None":
170
+ tokens.append(f"EmpiricalDispersion={self.dispersion}")
171
+
172
+ if self.scf_convergence and self.scf_convergence != "Normal":
173
+ tokens.append(f"SCF={self.scf_convergence}")
174
+
175
+ if self.integral_grid and self.integral_grid != "Fine":
176
+ tokens.append(f"Int={self.integral_grid}")
177
+
178
+ if not self.use_symmetry:
179
+ tokens.append("NoSymm")
180
+
181
+ if self.guess_type and self.guess_type != "Default":
182
+ tokens.append(f"Guess={self.guess_type}")
183
+
184
+ pop_opts = []
185
+ if self.pop_level and self.pop_level != "None":
186
+ pop_opts.append(self.pop_level)
187
+ if self.compute_nbo:
188
+ pop_opts.append("NBO")
189
+ if self.compute_esp_charges:
190
+ pop_opts.append("MK")
191
+ if pop_opts:
192
+ tokens.append(f"Pop=({','.join(pop_opts)})" if len(pop_opts) > 1 else f"Pop={pop_opts[0]}")
193
+
194
+ if self.solvation_model and self.solvation_model != "None":
195
+ tokens.append(f"SCRF=({self.solvation_model},Solvent={self.solvent})")
196
+
197
+ if self.additional_route_keywords.strip():
198
+ tokens.append(self.additional_route_keywords.strip())
199
+
200
+ return " ".join(tokens)
201
+
202
+ def generate_gjf(self, doc: MoleculeDocument, allow_sample_placeholder: bool = False) -> str:
203
+ if self.custom_edited_gjf is not None:
204
+ return self.custom_edited_gjf
205
+
206
+ lines: list[str] = []
207
+ if self.save_chk and self.chk_filename.strip():
208
+ lines.append(f"%chk={self.chk_filename.strip()}")
209
+ lines.append(f"%mem={max(1, int(self.memory_gb))}GB")
210
+ lines.append(f"%nprocshared={max(1, int(self.nproc_shared))}")
211
+ lines.append(self.build_route_section())
212
+ lines.append("")
213
+ lines.append(self.title.strip() or "MolForge Quantum Job")
214
+ lines.append("")
215
+ lines.append(f"{int(self.charge)} {int(self.multiplicity)}")
216
+
217
+ if doc.topology.num_atoms > 0 and doc.has_3d and doc.coordinates.current is not None:
218
+ idx_to_id, _ = doc.topology.atom_index_map()
219
+ coords = doc.coordinates.current.coords
220
+ for i, aid in enumerate(idx_to_id):
221
+ if i >= len(coords):
222
+ break
223
+ atom = doc.topology.get_atom(aid)
224
+ el = ELEMENTS.get(atom.atomic_num)
225
+ sym = el.symbol if el else "C"
226
+ x, y, z = float(coords[i][0]), float(coords[i][1]), float(coords[i][2])
227
+ lines.append(f" {sym:<3s} {x:14.8f} {y:14.8f} {z:14.8f}")
228
+ elif allow_sample_placeholder:
229
+ lines.append(" ! [SAMPLE PREVIEW ONLY - EMPTY DOCUMENT]")
230
+
231
+ lines.append("")
232
+ if self.additional_tail_input.strip():
233
+ lines.append(self.additional_tail_input.strip())
234
+ lines.append("")
235
+
236
+ return "\n".join(lines) + "\n"
237
+
238
+ def input_hash(self, doc: MoleculeDocument) -> str:
239
+ text = self.generate_gjf(doc, allow_sample_placeholder=True)
240
+ return hashlib.sha256(text.encode("utf-8")).hexdigest()[:16]