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,947 @@
1
+ """
2
+ MolForge/molforge/server/api_bridge.py - Python 化学与量子计算后台引擎 HTTP/二进制桥接服务
3
+ ===================================================================================
4
+ 为新一代 Tauri 2 + React + WebGPU 前端提供:
5
+ - 零第三方 Web 依赖(基于 Python 标准库 ThreadingHTTPServer)
6
+ - 32 万原子级全矢量化二进制传输协议 (`/api/document/binary`, ~8.8 MB)
7
+ - 完整 CommandBus 原子/化学键/芳香环/元素/几何编辑与 Undo/Redo 栈
8
+ - 真实 Tight-Binding MO + 79 项 CapabilityResolver 科研分析 + .gjf/.ctrl.in/.pdb/.xyz/.mol 导出
9
+ - Windows 原生资源管理器文件选择框 (`/api/dialog/open_file`)
10
+ - Google A2UI (Agent-to-UI) 声明式卡片输出
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ from collections import Counter
16
+ import ctypes
17
+ from http import HTTPStatus
18
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
19
+ import json
20
+ import math
21
+ from pathlib import Path
22
+ import struct
23
+ import sys
24
+ import threading
25
+ import time
26
+ import traceback
27
+ from typing import Any
28
+ from urllib.parse import urlparse
29
+
30
+ import numpy as np
31
+
32
+ from ..application.builtin_commands import (
33
+ AddAtomCommand,
34
+ AddBondCommand,
35
+ AddRingCommand,
36
+ ChangeBondOrderCommand,
37
+ ChangeElementCommand,
38
+ CleanGeometry3DCommand,
39
+ DeleteAtomCommand,
40
+ DeleteBondCommand,
41
+ MoveAtom3DCommand,
42
+ )
43
+ from ..application.calculators.qc_input_generator import (
44
+ export_document_to_xyz,
45
+ generate_gaussian_gjf,
46
+ generate_rest_ctrl_in,
47
+ )
48
+ from ..application.command_bus import CommandBus
49
+ from ..application.invalidation import AnalysisRegistry, CapabilityResolver
50
+ from ..domain.chemical_summary import analyze_geometry_shape, resolve_spin_state
51
+ from ..domain.document import MoleculeDocument
52
+ from ..domain.elements import ELEMENTS
53
+ from ..domain.ids import AtomId, BondId
54
+ from ..domain.periodic import cell_from_document
55
+ from ..io.calculators import compute_tight_binding_mos
56
+ from ..io.rdkit_adapter import (
57
+ create_instant_caffeine_document,
58
+ create_molecule_from_smiles,
59
+ create_sample_molecule,
60
+ export_document_to_mol_v2000,
61
+ export_document_to_pdb,
62
+ load_molecule_document,
63
+ )
64
+ from ..rendering.vtk_backend import DEFAULT_VDW, STUDIO_CPK_COLORS
65
+
66
+ MAGIC_MOLF = 0x4D4F4C46 # "MOLF"
67
+
68
+ OSC_REFERENCE_MATERIALS: dict[str, tuple[float, float, str]] = {
69
+ "PM6 (经典给体)": (-5.50, -3.61, "#60A5FA"),
70
+ "Y6 (经典 A-DAD-A 受体)": (-5.65, -4.10, "#FB923C"),
71
+ "ITIC (经典非富勒烯受体)": (-5.48, -3.78, "#C084FC"),
72
+ "P3HT (标准聚噻吩给体)": (-4.85, -2.95, "#34D399"),
73
+ }
74
+
75
+ PRESET_MOLECULES: list[dict[str, str]] = [
76
+ {"id": "caffeine", "name": "咖啡因", "label": "Caffeine · 咖啡因", "category": "小分子参考", "smiles": "Cn1cnc2c1c(=O)n(C)c(=O)n2C"},
77
+ {"id": "benzene", "name": "苯", "label": "Benzene · 苯环", "category": "芳香体系", "smiles": "c1ccccc1"},
78
+ {"id": "pentacene", "name": "五并苯", "label": "Pentacene · 五并苯半导体", "category": "有机半导体", "smiles": "c1ccc2cc3cc4cc5ccccc5cc4cc3cc2c1"},
79
+ {"id": "thiophene_trimer", "name": "三聚噻吩", "label": "Terthiophene · 3T 寡聚物", "category": "有机半导体", "smiles": "s1cccc1-c2cccs2-c3cccs3"},
80
+ {"id": "aspirin", "name": "阿司匹林", "label": "Aspirin · 乙酰水杨酸", "category": "药物分子", "smiles": "CC(=O)Oc1ccccc1C(=O)O"},
81
+ {"id": "porphyrin", "name": "卟啉核", "label": "Porphyrin · 四吡咯大环", "category": "功能大环", "smiles": "c1cc2cc3ccc(cc4ccc(cc5ccc(cc1n2)[nH]5)n4)[nH]3"},
82
+ {"id": "bdt_core", "name": "PM6 核心单元", "label": "BDT-F 核心给体单元", "category": "OSC 给体", "smiles": "Fc1ccc(c2sc3cc(c4scc(F)c4)sc3c2)cc1"},
83
+ {"id": "triplet_o2", "name": "三线态氧 (O2)", "label": "O₂ (Triplet)", "category": "电子态验证", "smiles": "O=O"},
84
+ ]
85
+
86
+
87
+ def _pick_native_open_file_windows() -> str | None:
88
+ """使用 Windows 原生 Explorer 对话框选择分子文件(零额外依赖)。"""
89
+ if sys.platform != "win32":
90
+ return None
91
+ try:
92
+ from ctypes import wintypes
93
+
94
+ class OPENFILENAMEW(ctypes.Structure):
95
+ _fields_ = [
96
+ ("lStructSize", wintypes.DWORD),
97
+ ("hwndOwner", wintypes.HWND),
98
+ ("hInstance", wintypes.HINSTANCE),
99
+ ("lpstrFilter", wintypes.LPCWSTR),
100
+ ("lpstrCustomFilter", wintypes.LPWSTR),
101
+ ("nMaxCustFilter", wintypes.DWORD),
102
+ ("nFilterIndex", wintypes.DWORD),
103
+ ("lpstrFile", wintypes.LPWSTR),
104
+ ("nMaxFile", wintypes.DWORD),
105
+ ("lpstrFileTitle", wintypes.LPWSTR),
106
+ ("nMaxFileTitle", wintypes.DWORD),
107
+ ("lpstrInitialDir", wintypes.LPCWSTR),
108
+ ("lpstrTitle", wintypes.LPCWSTR),
109
+ ("Flags", wintypes.DWORD),
110
+ ("nFileOffset", wintypes.WORD),
111
+ ("nFileExtension", wintypes.WORD),
112
+ ("lpstrDefExt", wintypes.LPCWSTR),
113
+ ("lCustData", wintypes.LPARAM),
114
+ ("lpfnHook", ctypes.c_void_p),
115
+ ("lpTemplateName", wintypes.LPCWSTR),
116
+ ("pvReserved", ctypes.c_void_p),
117
+ ("dwReserved", wintypes.DWORD),
118
+ ("FlagsEx", wintypes.DWORD),
119
+ ]
120
+
121
+ buf = ctypes.create_unicode_buffer(4096)
122
+ flt = "分子结构文件 (*.pdb;*.xyz;*.mol;*.sdf;*.cif;*.mol2;*.mforge)\0*.pdb;*.xyz;*.mol;*.sdf;*.cif;*.mol2;*.mforge\0所有文件 (*.*)\0*.*\0\0"
123
+ ofn = OPENFILENAMEW()
124
+ ofn.lStructSize = ctypes.sizeof(OPENFILENAMEW)
125
+ ofn.lpstrFilter = flt
126
+ ofn.lpstrFile = ctypes.cast(buf, wintypes.LPWSTR)
127
+ ofn.nMaxFile = 4096
128
+ ofn.lpstrTitle = "选择分子结构或晶体工程文件"
129
+ ofn.Flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000008 # EXPLORER | FILEMUSTEXIST | PATHMUSTEXIST | NOCHANGEDIR
130
+ if ctypes.windll.comdlg32.GetOpenFileNameW(ctypes.byref(ofn)):
131
+ return buf.value
132
+ except Exception:
133
+ return None
134
+ return None
135
+
136
+
137
+ def _build_luts() -> tuple[np.ndarray, np.ndarray]:
138
+ color_lut = np.full((120, 4), [140, 158, 178, 255], dtype=np.uint8)
139
+ vdw_lut = np.full(120, float(DEFAULT_VDW), dtype=np.float32)
140
+ for z, elem in ELEMENTS.items():
141
+ if 0 <= z < 120:
142
+ c = elem.cpk_color
143
+ color_lut[z, :3] = [int(round(c[0] * 255)), int(round(c[1] * 255)), int(round(c[2] * 255))]
144
+ vdw_lut[z] = float(elem.vdw_radius)
145
+ for z, c in STUDIO_CPK_COLORS.items():
146
+ if 0 <= z < 120:
147
+ color_lut[z, :3] = [int(round(c[0] * 255)), int(round(c[1] * 255)), int(round(c[2] * 255))]
148
+ return color_lut, vdw_lut
149
+
150
+
151
+ _COLOR_LUT, _VDW_LUT = _build_luts()
152
+
153
+
154
+ def _chemical_formula(doc: MoleculeDocument) -> str:
155
+ counts: Counter[str] = Counter()
156
+ for aid in doc.topology.atom_ids:
157
+ counts[doc.topology.get_atom(aid).symbol] += 1
158
+ if not counts:
159
+ return "Empty"
160
+ order = ["C", "H"] + sorted(k for k in counts if k not in ("C", "H"))
161
+ parts = []
162
+ for sym in order:
163
+ n = counts.get(sym, 0)
164
+ if n == 1:
165
+ parts.append(sym)
166
+ elif n > 1:
167
+ parts.append(f"{sym}{n}")
168
+ return "".join(parts)
169
+
170
+
171
+ class MolForgeBridgeState:
172
+ """线程安全的 MolForge 后台状态容器,负责管理当前活动文档与撤销栈。"""
173
+
174
+ def __init__(self) -> None:
175
+ self._lock = threading.RLock()
176
+ self.document: MoleculeDocument = create_instant_caffeine_document()
177
+ self.command_bus: CommandBus = CommandBus(self.document)
178
+ self._last_binary_rev: int = -1
179
+ self._cached_binary: bytes = b""
180
+ self._source_path: str | None = None
181
+
182
+ def set_document(self, doc: MoleculeDocument, source_path: str | None = None) -> None:
183
+ with self._lock:
184
+ self.document = doc
185
+ self.command_bus = CommandBus(self.document)
186
+ self._last_binary_rev = -1
187
+ self._cached_binary = b""
188
+ self._source_path = source_path
189
+
190
+ def _invalidate_cache(self) -> None:
191
+ self._last_binary_rev = -1
192
+ self._cached_binary = b""
193
+
194
+ def summary_dict(self) -> dict[str, Any]:
195
+ with self._lock:
196
+ doc = self.document
197
+ n_atoms = doc.topology.num_atoms
198
+ n_bonds = doc.topology.num_bonds
199
+ coords = (
200
+ doc.coordinates.current.coords
201
+ if doc.has_3d and doc.coordinates.current is not None and len(doc.coordinates.current.coords) == n_atoms
202
+ else None
203
+ )
204
+ spin = resolve_spin_state(doc)
205
+ if n_atoms <= 3000 and coords is not None and len(coords) > 0:
206
+ geom = analyze_geometry_shape(coords)
207
+ geom_label = geom.label
208
+ point_group = geom.point_group
209
+ elif n_atoms > 3000:
210
+ geom_label = f"大体系 ({n_atoms:,} 原子 · GPU 管线)"
211
+ point_group = "Periodic / Bulk"
212
+ else:
213
+ geom_label = "2D / 未计算"
214
+ point_group = "未计算"
215
+
216
+ total_charge = 0
217
+ for aid in doc.topology.atom_ids:
218
+ total_charge += int(getattr(doc.topology.get_atom(aid), "formal_charge", 0))
219
+ if "charge" in doc.properties:
220
+ try:
221
+ total_charge = int(doc.properties["charge"])
222
+ except Exception:
223
+ pass
224
+
225
+ cell = cell_from_document(doc)
226
+ box_origin = doc.properties.get("box_origin")
227
+ return {
228
+ "name": doc.name or "Untitled",
229
+ "formula": _chemical_formula(doc) if n_atoms <= 50000 else f"{n_atoms:,} atoms",
230
+ "num_atoms": n_atoms,
231
+ "num_bonds": n_bonds,
232
+ "charge": total_charge,
233
+ "multiplicity": spin.multiplicity,
234
+ "spin_label": spin.label,
235
+ "geometry_label": geom_label,
236
+ "point_group": point_group,
237
+ "revision": doc.revision,
238
+ "can_undo": self.command_bus.can_undo,
239
+ "can_redo": self.command_bus.can_redo,
240
+ "has_2d": bool(doc.coords_2d),
241
+ "has_3d": bool(doc.has_3d),
242
+ "source_path": self._source_path or doc.source_path,
243
+ "cell": cell.to_dict() if cell is not None else None,
244
+ "box_origin": list(box_origin) if box_origin is not None else None,
245
+ "presets": PRESET_MOLECULES,
246
+ }
247
+
248
+ def binary_payload(self) -> bytes:
249
+ with self._lock:
250
+ doc = self.document
251
+ if self._last_binary_rev == doc.revision and self._cached_binary:
252
+ return self._cached_binary
253
+
254
+ aids, id2idx = doc.topology.atom_index_map()
255
+ n = len(aids)
256
+ b_ids = list(doc.topology.bond_ids)
257
+ b_cnt = len(b_ids)
258
+
259
+ if n > 0 and doc.has_3d and doc.coordinates.current is not None and len(doc.coordinates.current.coords) == n:
260
+ coords = np.ascontiguousarray(doc.coordinates.current.coords, dtype=np.float32)
261
+ elif n > 0 and doc.coords_2d:
262
+ coords = np.zeros((n, 3), dtype=np.float32)
263
+ for idx, aid in enumerate(aids):
264
+ p = doc.coords_2d.get(aid)
265
+ if p is not None:
266
+ coords[idx, 0] = float(p[0])
267
+ coords[idx, 1] = float(p[1])
268
+ else:
269
+ coords = np.zeros((0, 3), dtype=np.float32)
270
+
271
+ z_arr = np.fromiter((doc.topology.get_atom(aid).atomic_num for aid in aids), dtype=np.int32, count=n)
272
+ z_clip = np.clip(z_arr, 0, 119)
273
+ z_u8 = z_clip.astype(np.uint8)
274
+ vdw = _VDW_LUT[z_clip].astype(np.float32)
275
+ rgba = _COLOR_LUT[z_clip].copy()
276
+
277
+ for idx, aid in enumerate(aids):
278
+ atom = doc.topology.get_atom(aid)
279
+ col = getattr(atom, "color", None)
280
+ if col is not None:
281
+ rgba[idx, 0] = max(0, min(255, int(round(float(col[0]) * 255.0))))
282
+ rgba[idx, 1] = max(0, min(255, int(round(float(col[1]) * 255.0))))
283
+ rgba[idx, 2] = max(0, min(255, int(round(float(col[2]) * 255.0))))
284
+ op = atom.properties.get("opacity", 1.0)
285
+ if op != 1.0:
286
+ rgba[idx, 3] = max(0, min(255, int(round(float(op) * 255.0))))
287
+ sc = getattr(atom, "scale", 1.0)
288
+ if sc != 1.0:
289
+ vdw[idx] *= float(sc)
290
+
291
+ if b_cnt > 0:
292
+ bond_pairs = np.empty((b_cnt, 2), dtype=np.uint32)
293
+ bond_orders = np.empty(b_cnt, dtype=np.uint8)
294
+ valid_count = 0
295
+ for bid in b_ids:
296
+ bond = doc.topology.get_bond(bid)
297
+ i = id2idx.get(bond.begin, -1)
298
+ j = id2idx.get(bond.end, -1)
299
+ if 0 <= i < n and 0 <= j < n and i != j:
300
+ bond_pairs[valid_count, 0] = i
301
+ bond_pairs[valid_count, 1] = j
302
+ bond_orders[valid_count] = max(1, min(4, int(bond.order)))
303
+ valid_count += 1
304
+ bond_pairs = np.ascontiguousarray(bond_pairs[:valid_count])
305
+ bond_orders = np.ascontiguousarray(bond_orders[:valid_count])
306
+ else:
307
+ bond_pairs = np.zeros((0, 2), dtype=np.uint32)
308
+ bond_orders = np.zeros(0, dtype=np.uint8)
309
+ valid_count = 0
310
+
311
+ cell = cell_from_document(doc)
312
+ has_cell = 1 if cell is not None else 0
313
+ box_origin = np.asarray(doc.properties.get("box_origin") or [0.0, 0.0, 0.0], dtype=np.float32).reshape(3)
314
+
315
+ header = struct.pack("<8I", MAGIC_MOLF, 1, n, valid_count, int(doc.revision), has_cell, 0, 0)
316
+ z_pad = (-len(z_u8)) % 4
317
+ bo_pad = (-len(bond_orders)) % 4
318
+
319
+ chunks = [
320
+ header,
321
+ coords.tobytes(),
322
+ z_u8.tobytes(),
323
+ b"\x00" * z_pad,
324
+ vdw.tobytes(),
325
+ rgba.tobytes(),
326
+ bond_pairs.tobytes(),
327
+ bond_orders.tobytes(),
328
+ b"\x00" * bo_pad,
329
+ ]
330
+ if has_cell:
331
+ cell_mat = np.ascontiguousarray(cell.matrix, dtype=np.float32).reshape(9)
332
+ chunks.append(np.ascontiguousarray(box_origin, dtype=np.float32).tobytes())
333
+ chunks.append(cell_mat.tobytes())
334
+
335
+ payload = b"".join(chunks)
336
+ self._last_binary_rev = doc.revision
337
+ self._cached_binary = payload
338
+ return payload
339
+
340
+ def atoms_2d_dict(self, limit: int = 1500) -> dict[str, Any]:
341
+ with self._lock:
342
+ doc = self.document
343
+ aids, id2idx = doc.topology.atom_index_map()
344
+ n = len(aids)
345
+ if n > limit:
346
+ return {"truncated": True, "num_atoms": n, "atoms": [], "bonds": []}
347
+
348
+ coords_3d = doc.coordinates.current.coords if doc.has_3d and doc.coordinates.current is not None else None
349
+ atoms_out = []
350
+ for idx, aid in enumerate(aids):
351
+ atom = doc.topology.get_atom(aid)
352
+ p2 = doc.coords_2d.get(aid)
353
+ p3 = coords_3d[idx] if coords_3d is not None and idx < len(coords_3d) else (0.0, 0.0, 0.0)
354
+ col = getattr(atom, "color", None) or STUDIO_CPK_COLORS.get(atom.atomic_num, (0.55, 0.62, 0.70))
355
+ atoms_out.append({
356
+ "index": idx,
357
+ "atom_id": aid.value,
358
+ "display_id": aid.value + 1,
359
+ "symbol": atom.symbol,
360
+ "atomic_num": atom.atomic_num,
361
+ "x2": float(p2[0]) if p2 is not None else float(p3[0]),
362
+ "y2": float(p2[1]) if p2 is not None else float(p3[1]),
363
+ "x": float(p3[0]),
364
+ "y": float(p3[1]),
365
+ "z": float(p3[2]),
366
+ "formal_charge": int(getattr(atom, "formal_charge", 0)),
367
+ "color": [int(round(col[0] * 255)), int(round(col[1] * 255)), int(round(col[2] * 255))],
368
+ })
369
+ bonds_out = []
370
+ for bid in doc.topology.bond_ids:
371
+ bond = doc.topology.get_bond(bid)
372
+ i = id2idx.get(bond.begin, -1)
373
+ j = id2idx.get(bond.end, -1)
374
+ if 0 <= i < n and 0 <= j < n:
375
+ bonds_out.append({
376
+ "bond_id": bid.value,
377
+ "i": i,
378
+ "j": j,
379
+ "order": int(bond.order),
380
+ "aromatic": bool(getattr(bond, "aromatic", False)),
381
+ })
382
+ return {"truncated": False, "num_atoms": n, "atoms": atoms_out, "bonds": bonds_out}
383
+
384
+ def compute_qc_tb(self) -> dict[str, Any]:
385
+ with self._lock:
386
+ doc = self.document
387
+ if doc.topology.num_atoms == 0:
388
+ return {"error": "当前分子为空"}
389
+ if doc.topology.num_atoms > 350:
390
+ return {
391
+ "skipped": True,
392
+ "reason": f"体系含 {doc.topology.num_atoms:,} 个原子,已跳过实时 O(N³) Tight-Binding 对角化;可导出 PDB/GJF 或切换小分子。",
393
+ "references": [
394
+ {"name": k, "homo_ev": v[0], "lumo_ev": v[1], "color": v[2]}
395
+ for k, v in OSC_REFERENCE_MATERIALS.items()
396
+ ],
397
+ }
398
+ tb = compute_tight_binding_mos(doc)
399
+ tb["molecule_name"] = doc.name or "当前分子"
400
+ tb["formula"] = _chemical_formula(doc)
401
+ tb["references"] = [
402
+ {"name": k, "homo_ev": v[0], "lumo_ev": v[1], "color": v[2]}
403
+ for k, v in OSC_REFERENCE_MATERIALS.items()
404
+ ]
405
+ return tb
406
+
407
+ def analysis_catalog(self) -> list[dict[str, Any]]:
408
+ with self._lock:
409
+ doc = self.document
410
+ out = []
411
+ for defn in AnalysisRegistry.all():
412
+ st, msg = CapabilityResolver.resolve_status(defn.analysis_id, doc)
413
+ out.append({
414
+ "id": defn.analysis_id,
415
+ "category": defn.category,
416
+ "title": defn.title,
417
+ "engine": defn.backend_engine,
418
+ "state": st.value,
419
+ "note": msg,
420
+ })
421
+ return out
422
+
423
+ def run_analysis(self, analysis_id: str) -> dict[str, Any]:
424
+ with self._lock:
425
+ res = CapabilityResolver.execute_analysis(analysis_id, self.document)
426
+ lines = []
427
+ if res.warnings:
428
+ lines.extend(res.warnings)
429
+ prov_note = getattr(res.provenance, "notes", "") if res.provenance else ""
430
+ if prov_note:
431
+ lines.append(prov_note)
432
+ if not lines and res.metrics:
433
+ lines.append(f"已完成 {res.title} ({res.status})")
434
+ return {
435
+ "analysis_id": res.analysis_id,
436
+ "title": res.title,
437
+ "status": res.status,
438
+ "summary": "\n".join(lines) or res.title,
439
+ "metrics": dict(res.metrics or {}),
440
+ "plot_x": list(res.plot_x or []),
441
+ "plot_y": list(res.plot_y or []),
442
+ "x_label": getattr(res, "plot_xlabel", ""),
443
+ "y_label": getattr(res, "plot_ylabel", ""),
444
+ }
445
+
446
+ def export_text(self, fmt: str) -> tuple[str, str]:
447
+ with self._lock:
448
+ doc = self.document
449
+ stem = (doc.name or "molecule").replace(" ", "_")
450
+ f = fmt.lower().strip()
451
+ if f == "pdb":
452
+ return f"{stem}.pdb", export_document_to_pdb(doc)
453
+ if f == "mol":
454
+ return f"{stem}.mol", export_document_to_mol_v2000(doc)
455
+ if f == "gjf":
456
+ return f"{stem}.gjf", generate_gaussian_gjf(doc)
457
+ if f == "rest":
458
+ return "ctrl.in", generate_rest_ctrl_in(doc)
459
+ xyz_lines = []
460
+ from ..application.calculators.qc_input_generator import extract_xyz_lines
461
+ body = extract_xyz_lines(doc)
462
+ xyz_lines.append(str(len(body)))
463
+ xyz_lines.append(f"{doc.name or 'MolForge'} | {_chemical_formula(doc)}")
464
+ xyz_lines.extend(body)
465
+ return f"{stem}.xyz", "\n".join(xyz_lines) + "\n"
466
+
467
+ def handle_ai_prompt(self, prompt: str) -> dict[str, Any]:
468
+ text = prompt.strip()
469
+ lower = text.lower()
470
+ blocks: list[dict[str, Any]] = []
471
+ reply_parts: list[str] = []
472
+
473
+ if any(k in lower for k in ("构建", "生成", "画", "build", "smiles")) and any(
474
+ k in lower for k in ("苯", "咖啡因", "阿司匹林", "噻吩", "pentacene", "caffeine", "aspirin", "smiles:")
475
+ ):
476
+ target_preset = None
477
+ if "阿司匹林" in text or "aspirin" in lower:
478
+ target_preset = PRESET_MOLECULES[4]
479
+ elif "五并苯" in text or "pentacene" in lower:
480
+ target_preset = PRESET_MOLECULES[2]
481
+ elif "噻吩" in text:
482
+ target_preset = PRESET_MOLECULES[3]
483
+ elif "苯" in text:
484
+ target_preset = PRESET_MOLECULES[1]
485
+ elif "咖啡因" in text or "caffeine" in lower:
486
+ target_preset = PRESET_MOLECULES[0]
487
+
488
+ if target_preset is not None:
489
+ doc = create_molecule_from_smiles(target_preset["smiles"], target_preset["name"])
490
+ self.set_document(doc)
491
+ reply_parts.append(
492
+ f"已调用 MolForge RDKit ETKDG 引擎为您构建 **{target_preset['name']}**(`{target_preset['smiles']}`),并同步生成 2D 矢量图与 3D 构象。"
493
+ )
494
+ blocks.append({
495
+ "type": "action_row",
496
+ "title": "结构已更新",
497
+ "actions": [
498
+ {"label": "打开 OSC 能级图", "action": "open_qc_modal"},
499
+ {"label": "3D 几何优化", "action": "clean_3d"},
500
+ ],
501
+ })
502
+
503
+ summary = self.summary_dict()
504
+ reply_parts.append(
505
+ f"当前工作区活动分子为 **{summary['name']}**(`{summary['formula']}`,{summary['num_atoms']:,} 原子,{summary['num_bonds']:,} 键)。"
506
+ )
507
+ blocks.append({
508
+ "type": "metrics_card",
509
+ "title": f"{summary['name']} · 结构与化学态",
510
+ "items": [
511
+ {"label": "化学式", "value": summary["formula"]},
512
+ {"label": "原子 / 键", "value": f"{summary['num_atoms']:,} / {summary['num_bonds']:,}"},
513
+ {"label": "电荷 / 自旋", "value": f"{summary['charge']} / {summary['spin_label']}"},
514
+ {"label": "几何形态", "value": summary["geometry_label"]},
515
+ ],
516
+ })
517
+
518
+ qc = self.compute_qc_tb()
519
+ if not qc.get("skipped") and not qc.get("error"):
520
+ homo = float(qc.get("homo_ev", 0.0))
521
+ lumo = float(qc.get("lumo_ev", 0.0))
522
+ gap = float(qc.get("gap_ev", abs(lumo - homo)))
523
+ trans = qc.get("transitions") or []
524
+ s1_text = f"{trans[0]['wavelength_nm']:.1f} nm (f={trans[0]['oscillator_f']:.3f})" if trans else "—"
525
+ blocks.append({
526
+ "type": "orbital_card",
527
+ "title": f"Tight-Binding 前线轨道实算 ({summary['name']})",
528
+ "homo_ev": round(homo, 3),
529
+ "lumo_ev": round(lumo, 3),
530
+ "gap_ev": round(gap, 3),
531
+ "s1_text": s1_text,
532
+ "pm6_match": abs(lumo - (-3.61)) > 0.25 and abs(homo - (-5.50)) < 0.8,
533
+ })
534
+ reply_parts.append(
535
+ f"实时紧束缚求解得到 **HOMO = {homo:.3f} eV**、**LUMO = {lumo:.3f} eV**、能隙 **E_g = {gap:.3f} eV**。"
536
+ )
537
+ else:
538
+ reply_parts.append(qc.get("reason", ""))
539
+
540
+ try:
541
+ import urllib.request
542
+ from ..ai.mcp_bridge import get_llm_config
543
+ cfg = get_llm_config()
544
+ base_url = (cfg.get("base_url") or "").rstrip("/")
545
+ if base_url and "127.0.0.1" in base_url:
546
+ req = urllib.request.Request(
547
+ f"{base_url}/chat/completions",
548
+ data=json.dumps({
549
+ "model": cfg.get("model") or "gemini-3.8-flash",
550
+ "messages": [
551
+ {"role": "system", "content": "你是 MolForge 计算化学 AI 副驾驶,用简练严谨的中文回答科研建议(不超过120字)。"},
552
+ {"role": "user", "content": f"当前分子: {summary['name']} ({summary['formula']}, {summary['num_atoms']} atoms)。用户提问: {text}"},
553
+ ],
554
+ "max_tokens": 220,
555
+ }).encode("utf-8"),
556
+ headers={
557
+ "Content-Type": "application/json",
558
+ **({"Authorization": f"Bearer {cfg['api_key']}"} if cfg.get("api_key") else {}),
559
+ },
560
+ method="POST",
561
+ )
562
+ with urllib.request.urlopen(req, timeout=2.5) as resp:
563
+ payload = json.loads(resp.read().decode("utf-8"))
564
+ ai_msg = payload["choices"][0]["message"]["content"].strip()
565
+ if ai_msg:
566
+ reply_parts.append(ai_msg)
567
+ except Exception:
568
+ pass
569
+
570
+ return {
571
+ "reply": "\n\n".join(p for p in reply_parts if p),
572
+ "a2ui_blocks": blocks,
573
+ "document": summary,
574
+ }
575
+
576
+
577
+ def _elements_catalog() -> list[dict[str, Any]]:
578
+ items = []
579
+ for z in sorted(ELEMENTS.keys()):
580
+ el = ELEMENTS[z]
581
+ r, g, b = el.cpk_color
582
+ br = min(1.0, r * 1.15 + 0.08)
583
+ bg_g = min(1.0, g * 1.15 + 0.08)
584
+ bb = min(1.0, b * 1.15 + 0.08)
585
+ hex_bg = f"#{int(br * 255):02X}{int(bg_g * 255):02X}{int(bb * 255):02X}"
586
+ lum = 0.299 * r + 0.587 * g + 0.114 * b
587
+ fg = "#0F172A" if lum > 0.6 else "#F8FAFC"
588
+ items.append({
589
+ "atomic_number": el.atomic_number,
590
+ "symbol": el.symbol,
591
+ "name": el.name,
592
+ "name_cn": el.name_cn,
593
+ "atomic_weight": float(el.atomic_weight),
594
+ "electronegativity": float(el.electronegativity) if el.electronegativity is not None else None,
595
+ "vdw_radius": float(el.vdw_radius),
596
+ "covalent_radius": float(el.covalent_radius),
597
+ "electron_config": el.electron_config,
598
+ "group": int(el.group),
599
+ "period": int(el.period),
600
+ "block": el.block,
601
+ "category": el.category,
602
+ "hex_color": hex_bg,
603
+ "text_color": fg,
604
+ })
605
+ return items
606
+
607
+
608
+ def make_handler(state: MolForgeBridgeState):
609
+ class BridgeHandler(BaseHTTPRequestHandler):
610
+ protocol_version = "HTTP/1.1"
611
+
612
+ def log_message(self, format: str, *args: Any) -> None:
613
+ return
614
+
615
+ def _send_cors(self) -> None:
616
+ self.send_header("Access-Control-Allow-Origin", "*")
617
+ self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
618
+ self.send_header("Access-Control-Allow-Headers", "Content-Type, Authorization")
619
+
620
+ def _send_json(self, obj: Any, status: int = 200) -> None:
621
+ data = json.dumps(obj, ensure_ascii=False).encode("utf-8")
622
+ self.send_response(status)
623
+ self._send_cors()
624
+ self.send_header("Content-Type", "application/json; charset=utf-8")
625
+ self.send_header("Content-Length", str(len(data)))
626
+ self.end_headers()
627
+ self.wfile.write(data)
628
+
629
+ def _send_bytes(self, data: bytes, status: int = 200) -> None:
630
+ self.send_response(status)
631
+ self._send_cors()
632
+ self.send_header("Content-Type", "application/octet-stream")
633
+ self.send_header("Content-Length", str(len(data)))
634
+ self.end_headers()
635
+ self.wfile.write(data)
636
+
637
+ def _read_json(self) -> dict[str, Any]:
638
+ length = int(self.headers.get("Content-Length", "0") or 0)
639
+ if length <= 0:
640
+ return {}
641
+ raw = self.rfile.read(length)
642
+ return json.loads(raw.decode("utf-8"))
643
+
644
+ def do_OPTIONS(self) -> None:
645
+ self.send_response(HTTPStatus.NO_CONTENT)
646
+ self._send_cors()
647
+ self.send_header("Content-Length", "0")
648
+ self.end_headers()
649
+
650
+ def do_GET(self) -> None:
651
+ path = urlparse(self.path).path
652
+ try:
653
+ if path == "/api/health":
654
+ self._send_json({
655
+ "ok": True,
656
+ "service": "MolForge Chemical Engine Bridge",
657
+ "version": "8.0.0-alpha.2",
658
+ "document": state.summary_dict(),
659
+ })
660
+ elif path == "/api/document":
661
+ self._send_json(state.summary_dict())
662
+ elif path == "/api/document/binary":
663
+ self._send_bytes(state.binary_payload())
664
+ elif path == "/api/atoms":
665
+ self._send_json(state.atoms_2d_dict())
666
+ elif path == "/api/elements":
667
+ self._send_json({"elements": _elements_catalog()})
668
+ elif path == "/api/analysis/catalog":
669
+ self._send_json({"items": state.analysis_catalog()})
670
+ else:
671
+ self._send_json({"error": f"Unknown endpoint: {path}"}, status=404)
672
+ except Exception as exc:
673
+ self._send_json({"error": str(exc), "trace": traceback.format_exc()}, status=500)
674
+
675
+ def do_POST(self) -> None:
676
+ path = urlparse(self.path).path
677
+ try:
678
+ body = self._read_json()
679
+ if path == "/api/build/smiles":
680
+ smiles = str(body.get("smiles", "")).strip()
681
+ name = str(body.get("name", "")).strip() or smiles
682
+ if not smiles:
683
+ return self._send_json({"error": "SMILES 不能为空"}, status=400)
684
+ doc = create_molecule_from_smiles(smiles, name)
685
+ state.set_document(doc)
686
+ return self._send_json({"ok": True, "document": state.summary_dict()})
687
+
688
+ if path == "/api/build/preset":
689
+ preset_id = str(body.get("id", "caffeine")).strip().lower()
690
+ item = next((p for p in PRESET_MOLECULES if p["id"] == preset_id or p["name"] == preset_id), None)
691
+ if preset_id == "caffeine" or (item and item["id"] == "caffeine"):
692
+ doc = create_instant_caffeine_document()
693
+ elif preset_id == "triplet_o2":
694
+ doc = MoleculeDocument(name="Triplet O₂ (³Σg⁻)")
695
+ a0 = doc.topology.add_atom(8)
696
+ a1 = doc.topology.add_atom(8)
697
+ doc.topology.add_bond(a0, a1, order=2)
698
+ doc.ensure_coordinates()
699
+ doc.coordinates.current.coords[0] = [-0.604, 0.0, 0.0]
700
+ doc.coordinates.current.coords[1] = [0.604, 0.0, 0.0]
701
+ doc.coords_2d = {a0: (-0.604, 0.0), a1: (0.604, 0.0)}
702
+ doc.properties["multiplicity"] = 3
703
+ elif item is not None:
704
+ doc = create_molecule_from_smiles(item["smiles"], item["name"])
705
+ else:
706
+ doc = create_sample_molecule(str(body.get("name", "咖啡因")))
707
+ state.set_document(doc)
708
+ return self._send_json({"ok": True, "document": state.summary_dict()})
709
+
710
+ if path == "/api/open":
711
+ fpath = Path(str(body.get("path", "")).strip())
712
+ if not fpath.is_file():
713
+ return self._send_json({"error": f"文件不存在: {fpath}"}, status=404)
714
+ t0 = time.perf_counter()
715
+ doc, meta = load_molecule_document(fpath)
716
+ dt_ms = (time.perf_counter() - t0) * 1000.0
717
+ state.set_document(doc, source_path=str(fpath))
718
+ return self._send_json({"ok": True, "parse_ms": round(dt_ms, 1), "meta": meta, "document": state.summary_dict()})
719
+
720
+ if path == "/api/dialog/open_file":
721
+ chosen = _pick_native_open_file_windows()
722
+ if not chosen:
723
+ return self._send_json({"ok": False, "cancelled": True})
724
+ fpath = Path(chosen)
725
+ t0 = time.perf_counter()
726
+ doc, meta = load_molecule_document(fpath)
727
+ dt_ms = (time.perf_counter() - t0) * 1000.0
728
+ state.set_document(doc, source_path=str(fpath))
729
+ return self._send_json({
730
+ "ok": True,
731
+ "cancelled": False,
732
+ "path": str(fpath),
733
+ "parse_ms": round(dt_ms, 1),
734
+ "document": state.summary_dict(),
735
+ })
736
+
737
+ if path == "/api/edit/undo":
738
+ with state._lock:
739
+ ok = state.command_bus.undo().success
740
+ state._invalidate_cache()
741
+ return self._send_json({"ok": ok, "document": state.summary_dict()})
742
+
743
+ if path == "/api/edit/redo":
744
+ with state._lock:
745
+ ok = state.command_bus.redo().success
746
+ state._invalidate_cache()
747
+ return self._send_json({"ok": ok, "document": state.summary_dict()})
748
+
749
+ if path == "/api/edit/clean_3d":
750
+ with state._lock:
751
+ res = state.command_bus.execute(CleanGeometry3DCommand())
752
+ state._invalidate_cache()
753
+ return self._send_json({"ok": res.success, "message": res.message, "document": state.summary_dict()})
754
+
755
+ if path == "/api/edit/delete_atoms":
756
+ ids = [AtomId(int(x)) for x in body.get("atom_ids", [])]
757
+ with state._lock:
758
+ ok = True
759
+ for aid in ids:
760
+ r = state.command_bus.execute(DeleteAtomCommand(aid))
761
+ ok = ok and r.success
762
+ state._invalidate_cache()
763
+ return self._send_json({"ok": ok, "document": state.summary_dict()})
764
+
765
+ if path == "/api/edit/delete_indices":
766
+ indices = [int(x) for x in body.get("indices", [])]
767
+ with state._lock:
768
+ aids, _ = state.document.topology.atom_index_map()
769
+ targets = [aids[i] for i in indices if 0 <= i < len(aids)]
770
+ ok = bool(targets)
771
+ for aid in targets:
772
+ r = state.command_bus.execute(DeleteAtomCommand(aid))
773
+ ok = ok and r.success
774
+ state._invalidate_cache()
775
+ return self._send_json({"ok": ok, "document": state.summary_dict()})
776
+
777
+ if path == "/api/edit/add_atom":
778
+ atomic_num = int(body.get("atomic_num", 6))
779
+ pos_2d_raw = body.get("pos_2d")
780
+ pos_3d_raw = body.get("pos")
781
+ bond_to = body.get("bond_to")
782
+ with state._lock:
783
+ if pos_3d_raw is not None:
784
+ x, y, z = float(pos_3d_raw[0]), float(pos_3d_raw[1]), float(pos_3d_raw[2])
785
+ elif pos_2d_raw is not None:
786
+ x, y, z = float(pos_2d_raw[0]), float(pos_2d_raw[1]), 0.0
787
+ else:
788
+ x, y, z = None, None, None
789
+ cmd = AddAtomCommand(
790
+ atomic_num=atomic_num,
791
+ x=x,
792
+ y=y,
793
+ z=z,
794
+ bond_to=AtomId(int(bond_to)) if bond_to is not None else None,
795
+ pos_2d=(float(pos_2d_raw[0]), float(pos_2d_raw[1])) if pos_2d_raw is not None else None,
796
+ )
797
+ res = state.command_bus.execute(cmd)
798
+ state._invalidate_cache()
799
+ return self._send_json({"ok": res.success, "document": state.summary_dict()})
800
+
801
+ if path == "/api/edit/add_bond":
802
+ a = int(body["atom_a"])
803
+ b = int(body["atom_b"])
804
+ order = int(body.get("order", 1))
805
+ with state._lock:
806
+ res = state.command_bus.execute(AddBondCommand(AtomId(a), AtomId(b), order=order))
807
+ state._invalidate_cache()
808
+ return self._send_json({"ok": res.success, "document": state.summary_dict()})
809
+
810
+ if path == "/api/edit/delete_bond":
811
+ bid = int(body["bond_id"])
812
+ with state._lock:
813
+ res = state.command_bus.execute(DeleteBondCommand(BondId(bid)))
814
+ state._invalidate_cache()
815
+ return self._send_json({"ok": res.success, "document": state.summary_dict()})
816
+
817
+ if path == "/api/edit/cycle_bond_order":
818
+ bid = BondId(int(body["bond_id"]))
819
+ with state._lock:
820
+ bond = state.document.topology.get_bond(bid)
821
+ nxt = {1: 2, 2: 3, 3: 4, 4: 1}.get(int(bond.order), 1)
822
+ res = state.command_bus.execute(ChangeBondOrderCommand(bid, nxt))
823
+ state._invalidate_cache()
824
+ return self._send_json({"ok": res.success, "document": state.summary_dict()})
825
+
826
+ if path == "/api/edit/change_element":
827
+ aid = AtomId(int(body["atom_id"]))
828
+ z = int(body["atomic_num"])
829
+ with state._lock:
830
+ res = state.command_bus.execute(ChangeElementCommand(aid, z))
831
+ state._invalidate_cache()
832
+ return self._send_json({"ok": res.success, "document": state.summary_dict()})
833
+
834
+ if path == "/api/edit/add_ring":
835
+ size = int(body.get("size", 6))
836
+ aromatic = bool(body.get("aromatic", True))
837
+ hetero_raw = body.get("hetero") or {}
838
+ hetero = {int(k): int(v) for k, v in hetero_raw.items()}
839
+ attach_to = body.get("attach_to")
840
+ c2d = body.get("center_2d")
841
+ with state._lock:
842
+ cmd = AddRingCommand(
843
+ size=size,
844
+ aromatic=aromatic,
845
+ hetero_atoms=hetero,
846
+ center_2d=(float(c2d[0]), float(c2d[1])) if c2d is not None else None,
847
+ attach_to=AtomId(int(attach_to)) if attach_to is not None else None,
848
+ )
849
+ res = state.command_bus.execute(cmd)
850
+ state._invalidate_cache()
851
+ return self._send_json({"ok": res.success, "document": state.summary_dict()})
852
+
853
+ if path == "/api/edit/move_atom":
854
+ aid = AtomId(int(body["atom_id"]))
855
+ p2 = body.get("pos_2d")
856
+ with state._lock:
857
+ old_3d = state.document.get_atom_3d_pos(aid).copy()
858
+ old_2d = state.document.coords_2d.get(aid)
859
+ new_x = float(p2[0]) if p2 is not None else float(old_3d[0])
860
+ new_y = float(p2[1]) if p2 is not None else float(old_3d[1])
861
+ cmd = MoveAtom3DCommand(
862
+ aid,
863
+ (new_x, new_y, float(old_3d[2])),
864
+ old_pos=old_3d,
865
+ new_pos_2d=(new_x, new_y),
866
+ old_pos_2d=old_2d,
867
+ )
868
+ res = state.command_bus.execute(cmd)
869
+ state._invalidate_cache()
870
+ return self._send_json({"ok": res.success, "document": state.summary_dict()})
871
+
872
+ if path == "/api/edit/set_charge_spin":
873
+ with state._lock:
874
+ if "charge" in body:
875
+ state.document.properties["charge"] = int(body["charge"])
876
+ if "multiplicity" in body:
877
+ state.document.properties["multiplicity"] = max(1, int(body["multiplicity"]))
878
+ state._invalidate_cache()
879
+ return self._send_json({"ok": True, "document": state.summary_dict()})
880
+
881
+ if path == "/api/export":
882
+ fmt = str(body.get("format", "xyz"))
883
+ fname, content = state.export_text(fmt)
884
+ return self._send_json({"ok": True, "filename": fname, "content": content})
885
+
886
+ if path == "/api/qc/tight_binding":
887
+ return self._send_json(state.compute_qc_tb())
888
+
889
+ if path == "/api/qc/export_input":
890
+ kind = str(body.get("kind", "gaussian")).lower()
891
+ route = str(body.get("route", "#p B3LYP/6-31G(d) EmpiricalDispersion=GD3BJ opt freq"))
892
+ charge = int(body.get("charge", state.document.properties.get("charge", 0)))
893
+ spin = int(body.get("multiplicity", resolve_spin_state(state.document).multiplicity))
894
+ if kind == "rest":
895
+ txt = generate_rest_ctrl_in(
896
+ state.document,
897
+ xc=str(body.get("xc", "b3lyp")),
898
+ basis=str(body.get("basis", "def2-SVP")),
899
+ charge=float(charge),
900
+ spin=spin,
901
+ )
902
+ else:
903
+ txt = generate_gaussian_gjf(state.document, route=route, charge=charge, multiplicity=spin)
904
+ return self._send_json({"ok": True, "kind": kind, "content": txt})
905
+
906
+ if path == "/api/analysis/run":
907
+ aid = str(body.get("analysis_id", "")).strip()
908
+ if not aid:
909
+ return self._send_json({"error": "analysis_id 不能为空"}, status=400)
910
+ return self._send_json({"ok": True, "result": state.run_analysis(aid)})
911
+
912
+ if path == "/api/ai/chat":
913
+ prompt = str(body.get("prompt", "")).strip()
914
+ if not prompt:
915
+ return self._send_json({"error": "提问内容不能为空"}, status=400)
916
+ return self._send_json(state.handle_ai_prompt(prompt))
917
+
918
+ return self._send_json({"error": f"Unknown endpoint: {path}"}, status=404)
919
+ except Exception as exc:
920
+ return self._send_json({"error": str(exc), "trace": traceback.format_exc()}, status=500)
921
+
922
+ return BridgeHandler
923
+
924
+
925
+ def start_bridge_server(host: str = "127.0.0.1", port: int = 18765) -> tuple[ThreadingHTTPServer, MolForgeBridgeState]:
926
+ state = MolForgeBridgeState()
927
+ server = ThreadingHTTPServer((host, port), make_handler(state))
928
+ return server, state
929
+
930
+
931
+ def main() -> None:
932
+ parser = argparse.ArgumentParser(description="MolForge Next-Gen Chemical Engine HTTP/Binary Bridge")
933
+ parser.add_argument("--host", default="127.0.0.1")
934
+ parser.add_argument("--port", type=int, default=18765)
935
+ args = parser.parse_args()
936
+ server, _ = start_bridge_server(args.host, args.port)
937
+ print(f"[MolForge Bridge] listening on http://{args.host}:{args.port}", flush=True)
938
+ try:
939
+ server.serve_forever()
940
+ except KeyboardInterrupt:
941
+ pass
942
+ finally:
943
+ server.server_close()
944
+
945
+
946
+ if __name__ == "__main__":
947
+ main()