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,152 @@
1
+ """
2
+ ai/observation.py - AI 观察工具
3
+ =================================
4
+ 让 AI 能读取分子结构、几何和工件信息。
5
+
6
+ 特性:
7
+ - 暴露已选 AtomId/Conformer/Artifact
8
+ - 返回单位与 stale 状态
9
+ - 限制数据量并筛选权限
10
+ - 不虚构数值、不自动传文件
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from dataclasses import dataclass, field
16
+ from typing import Any
17
+
18
+ from ..domain.document import MoleculeDocument
19
+ from ..domain.ids import AtomId
20
+ from ..application.selection import SelectionService
21
+ from ..application.invalidation import InvalidationService
22
+
23
+
24
+ @dataclass
25
+ class AtomInfo:
26
+ """原子信息(给 AI 看的)。"""
27
+ atom_id: str
28
+ element: str
29
+ atomic_num: int
30
+ formal_charge: int
31
+ aromatic: bool
32
+ coordinate: tuple[float, float, float] | None = None
33
+
34
+
35
+ @dataclass
36
+ class MoleculeSummary:
37
+ """分子摘要(给 AI 看的)。"""
38
+ name: str
39
+ n_atoms: int
40
+ n_bonds: int
41
+ has_3d: bool
42
+ selected_atoms: list[str] = field(default_factory=list)
43
+ stale: bool = False
44
+ warning: str = ""
45
+
46
+
47
+ class ObservationTool:
48
+ """
49
+ AI 观察工具:让 AI 读取分子状态。
50
+
51
+ 用法:
52
+ tool = ObservationTool(doc, selection, invalidation)
53
+ summary = tool.get_molecule_summary()
54
+ atom = tool.get_atom_info("atom_123")
55
+ """
56
+
57
+ def __init__(self,
58
+ document: MoleculeDocument,
59
+ selection: SelectionService,
60
+ invalidation: InvalidationService) -> None:
61
+ self._doc = document
62
+ self._selection = selection
63
+ self._invalidation = invalidation
64
+
65
+ def get_molecule_summary(self) -> MoleculeSummary:
66
+ """获取分子摘要。"""
67
+ selected = [aid.value for aid in self._selection.selected_atoms]
68
+ warning = self._invalidation.get_warning_message()
69
+
70
+ return MoleculeSummary(
71
+ name=self._doc.name,
72
+ n_atoms=self._doc.num_atoms,
73
+ n_bonds=self._doc.num_bonds,
74
+ has_3d=self._doc.has_3d,
75
+ selected_atoms=selected,
76
+ stale=bool(self._invalidation.get_stale_markers()),
77
+ warning=warning,
78
+ )
79
+
80
+ def get_atom_info(self, atom_id: str) -> AtomInfo | None:
81
+ """获取原子详细信息。"""
82
+ from ..domain.ids import AtomId
83
+ aid = AtomId(atom_id)
84
+
85
+ try:
86
+ atom = self._doc.topology.get_atom(aid)
87
+ except KeyError:
88
+ return None
89
+
90
+ # 坐标
91
+ coord = None
92
+ if self._doc.has_3d and self._doc.coordinates.current is not None:
93
+ # 找到原子索引
94
+ for i, a in enumerate(self._doc.topology.atom_ids):
95
+ if a == aid:
96
+ c = self._doc.coordinates.current.coords[i]
97
+ coord = (float(c[0]), float(c[1]), float(c[2]))
98
+ break
99
+
100
+ return AtomInfo(
101
+ atom_id=atom_id,
102
+ element=atom.symbol if hasattr(atom, "symbol") else "?",
103
+ atomic_num=atom.atomic_num,
104
+ formal_charge=atom.formal_charge,
105
+ aromatic=atom.aromatic,
106
+ coordinate=coord,
107
+ )
108
+
109
+ def get_selected_atoms(self) -> list[AtomInfo]:
110
+ """获取所有选中原子的信息。"""
111
+ result = []
112
+ for aid in self._selection.selected_atoms:
113
+ info = self.get_atom_info(aid.value)
114
+ if info:
115
+ result.append(info)
116
+ return result
117
+
118
+ def get_bond_info(self, bond_id: str) -> dict[str, Any] | None:
119
+ """获取键信息。"""
120
+ from ..domain.ids import BondId
121
+ bid = BondId(bond_id)
122
+ try:
123
+ bond = self._doc.topology.get_bond(bid)
124
+ except KeyError:
125
+ return None
126
+
127
+ return {
128
+ "bond_id": bond_id,
129
+ "begin": bond.begin.value,
130
+ "end": bond.end.value,
131
+ "order": bond.order,
132
+ "aromatic": bond.aromatic,
133
+ }
134
+
135
+ def get_conformer_list(self) -> list[dict[str, Any]]:
136
+ """获取构象列表。"""
137
+ if not self._doc.has_3d:
138
+ return []
139
+
140
+ result = []
141
+ for i, frame in enumerate(self._doc.coordinates):
142
+ result.append({
143
+ "index": i,
144
+ "source": frame.source,
145
+ "energy": frame.energy,
146
+ "units": "eV" if frame.energy else None,
147
+ })
148
+ return result
149
+
150
+ def get_warning(self) -> str:
151
+ """获取警告信息(过期等)。"""
152
+ return self._invalidation.get_warning_message()
molforge/ai/tools.py ADDED
@@ -0,0 +1,455 @@
1
+ """
2
+ tools.py - AI 工具集 + Tool Registry
3
+ ======================================
4
+ 按 ChatGPT 技术报告建议:
5
+ - 工具入参用 Pydantic / JSON Schema 校验
6
+ - LLM 只能访问 Tool Registry 里的工具,不能执行任意 Python
7
+ - 变更结构、覆写文件、提交成本高的外部计算前要求用户确认
8
+
9
+ 权限分级:
10
+ - Read: 只读查询(describe_molecule, compute_properties)
11
+ - View: 视图相关(获取构象列表)
12
+ - Edit: 修改结构(generate_conformer)
13
+ - Execute: 运行计算(运行 xTB/Gaussian)
14
+ - Export: 导出文件(export_gjf, export_svg)
15
+
16
+ 安全边界:
17
+ - 无 shell / eval 注入
18
+ - 调用次数限制
19
+ - 执行收据和日志
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import json
25
+ import time
26
+ import uuid
27
+ from dataclasses import dataclass, field
28
+ from enum import Enum
29
+ from pathlib import Path
30
+ from typing import Any, Callable
31
+
32
+ from ..core.molecule import Molecule
33
+ from ..core.properties import compute_properties
34
+ from ..core.conformer import Conformer
35
+ from ..io import read_file, write_file
36
+
37
+
38
+ class ToolPermission(Enum):
39
+ """工具权限级别。"""
40
+ READ = "read"
41
+ VIEW = "view"
42
+ EDIT = "edit"
43
+ EXECUTE = "execute"
44
+ EXPORT = "export"
45
+
46
+
47
+ @dataclass
48
+ class ToolReceipt:
49
+ """工具执行收据。"""
50
+ receipt_id: str
51
+ tool_name: str
52
+ arguments: dict[str, Any]
53
+ success: bool
54
+ result: Any = None
55
+ error: str = ""
56
+ started_at: float = 0.0
57
+ finished_at: float = 0.0
58
+ duration_ms: float = 0.0
59
+
60
+
61
+
62
+ class AIContext:
63
+ """
64
+ AI 操作分子的上下文。
65
+
66
+ 一个 AIContext 绑定一个 Molecule 和一个工作目录。
67
+ AI 所有操作都通过这个上下文进行,不直接碰 UI。
68
+ """
69
+
70
+ def __init__(self, mol: Molecule, workdir: Path | None = None):
71
+ self.mol = mol
72
+ self.workdir = workdir or Path.cwd()
73
+
74
+ # ---------- 信息查询工具 ----------
75
+
76
+ def describe_molecule(self) -> dict:
77
+ """返回当前分子的摘要:分子式、原子数、键数、能量、HOMO/LUMO gap。"""
78
+ return {
79
+ "name": self.mol.name,
80
+ "formula": self.mol.formula,
81
+ "num_atoms": self.mol.num_atoms,
82
+ "num_bonds": self.mol.num_bonds,
83
+ "energy_hartree": self.mol.energy,
84
+ "homo_ev": self.mol.homo.energy_ev if self.mol.homo else None,
85
+ "lumo_ev": self.mol.lumo.energy_ev if self.mol.lumo else None,
86
+ "gap_ev": self.mol.gap_ev,
87
+ "source": self.mol.source_format,
88
+ }
89
+
90
+ def compute_properties(self) -> dict:
91
+ """计算并返回分子性质(MW、LogP、TPSA、HBA/HBD、环数...)。"""
92
+ props = compute_properties(self.mol)
93
+ self.mol.properties.update(props)
94
+ return props
95
+
96
+ # ---------- 计算工具 ----------
97
+
98
+ def generate_conformer(self, seed: int = 42) -> dict:
99
+ """
100
+ 生成 3D 构象(ETKDG + MMFF 优化)。
101
+ 成功后把构象加到当前分子。
102
+ """
103
+ from rdkit.Chem import AllChem
104
+ mol = self.mol.rdkit_mol
105
+ mol = AllChem.AddHs(mol)
106
+ params = AllChem.ETKDGv3()
107
+ params.randomSeed = seed
108
+ if AllChem.EmbedMolecule(mol, params) != 0:
109
+ return {"ok": False, "error": "构象生成失败"}
110
+ try:
111
+ AllChem.MMFFOptimizeMolecule(mol, maxIters=200)
112
+ except Exception:
113
+ pass
114
+
115
+ # 提取坐标
116
+ conf = mol.GetConformer()
117
+ import numpy as np
118
+ coords = []
119
+ for i in range(mol.GetNumAtoms()):
120
+ p = conf.GetAtomPosition(i)
121
+ coords.append([p.x, p.y, p.z])
122
+ self.mol.conformers.append(Conformer(
123
+ coords=np.array(coords),
124
+ source="etkdg_mmff"
125
+ ))
126
+ return {
127
+ "ok": True,
128
+ "num_atoms": self.mol.num_atoms,
129
+ "message": f"已生成 3D 构象({len(self.mol.conformers)} 个构象)"
130
+ }
131
+
132
+ # ---------- 文件工具 ----------
133
+
134
+ def open_file(self, path: str) -> dict:
135
+ """打开一个分子文件(支持 .mol/.sdf/.gjf/.log/.cube/.smi)。"""
136
+ p = Path(path)
137
+ if not p.exists():
138
+ return {"ok": False, "error": f"文件不存在: {path}"}
139
+ try:
140
+ self.mol = read_file(p)
141
+ return {
142
+ "ok": True,
143
+ "name": self.mol.name,
144
+ "formula": self.mol.formula,
145
+ "source": self.mol.source_format,
146
+ }
147
+ except Exception as e:
148
+ return {"ok": False, "error": str(e)}
149
+
150
+ def export_gjf(self, route: str = "# B3LYP/6-31G(d,p) opt",
151
+ path: str | None = None) -> dict:
152
+ """
153
+ 导出 Gaussian 输入文件。
154
+ route 例:'# B3LYP/6-31G(d,p) opt freq'
155
+ """
156
+ self.mol.properties["route"] = route
157
+ out = Path(path) if path else (self.workdir / f"{self.mol.name or 'mol'}.gjf")
158
+ try:
159
+ write_file(self.mol, out)
160
+ return {"ok": True, "path": str(out)}
161
+ except Exception as e:
162
+ return {"ok": False, "error": str(e)}
163
+
164
+ def export_svg(self, path: str | None = None) -> dict:
165
+ """导出 2D 结构图为 SVG。"""
166
+ out = Path(path) if path else (self.workdir / f"{self.mol.name or 'mol'}.svg")
167
+ try:
168
+ write_file(self.mol, out)
169
+ return {"ok": True, "path": str(out)}
170
+ except Exception as e:
171
+ return {"ok": False, "error": str(e)}
172
+
173
+ # ---------- Gaussian 工作流 ----------
174
+
175
+ def read_gaussian_log(self, path: str) -> dict:
176
+ """
177
+ 读 Gaussian log 文件,解析能量、HOMO/LUMO、终止状态。
178
+ 结果会更新到当前 Molecule。
179
+ """
180
+ p = Path(path)
181
+ if not p.exists():
182
+ return {"ok": False, "error": f"文件不存在: {path}"}
183
+ try:
184
+ log_mol = read_file(p)
185
+ # 合并到当前分子
186
+ self.mol.energy = log_mol.energy
187
+ self.mol.orbitals = log_mol.orbitals
188
+ self.mol.properties.update(log_mol.properties)
189
+ if log_mol.conformers:
190
+ self.mol.conformers = log_mol.conformers
191
+ return {
192
+ "ok": True,
193
+ "termination": log_mol.properties.get("termination"),
194
+ "energy_hartree": log_mol.energy,
195
+ "homo_ev": self.mol.homo.energy_ev if self.mol.homo else None,
196
+ "lumo_ev": self.mol.lumo.energy_ev if self.mol.lumo else None,
197
+ "gap_ev": self.mol.gap_ev,
198
+ "scf_cycles": log_mol.properties.get("scf_cycles"),
199
+ "dipole_debye": log_mol.properties.get("dipole_debye"),
200
+ }
201
+ except Exception as e:
202
+ return {"ok": False, "error": str(e)}
203
+
204
+ # ---------- AI 建议工具 ----------
205
+
206
+ def suggest_next_step(self) -> list[str]:
207
+ """
208
+ 根据当前分子状态,建议下一步计算。
209
+ 这是规则式建议,不是 LLM 生成的。
210
+ """
211
+ suggestions = []
212
+ if self.mol.energy is None:
213
+ suggestions.append("当前分子还没有计算结果,建议先跑单点能(SP)。")
214
+ if self.mol.gap_ev is None:
215
+ suggestions.append("还没有 HOMO/LUMO 数据,建议跑一个含轨道输出的单点能。")
216
+ if not self.mol.has_3d:
217
+ suggestions.append("还没有 3D 构象,建议先 generate_conformer()。")
218
+ if self.mol.properties.get("termination") == "normal":
219
+ suggestions.append("计算正常结束,可以导出 gjf 跑下一步(如 freq 频率分析)。")
220
+ if self.mol.properties.get("termination") == "error":
221
+ suggestions.append("计算错误终止,建议检查 log 文件末尾的错误信息。")
222
+ if not suggestions:
223
+ suggestions.append("当前状态完整,可以做发表级图导出(export_svg)。")
224
+ return suggestions
225
+
226
+
227
+ # ---------- Tool Registry ----------
228
+
229
+ class ToolRegistry:
230
+ """
231
+ 工具注册表(按 ChatGPT 技术报告建议)。
232
+
233
+ 把 AIContext 的方法注册成带 JSON Schema 的工具,
234
+ LLM 通过 function calling 调用,不能执行任意 Python。
235
+
236
+ 安全边界:
237
+ - 工具入参用 JSON Schema 校验
238
+ - LLM 只能访问注册的工具,不能执行任意代码
239
+ - 变更结构、覆写文件、提交成本高的外部计算前要求用户确认
240
+ - 权限分级:Read/View/Edit/Execute/Export
241
+ - 调用次数限制
242
+ - 执行收据和日志
243
+ """
244
+
245
+ def __init__(self, context: AIContext, max_calls_per_session: int = 50):
246
+ self.context = context
247
+ self._tools: dict[str, dict] = {}
248
+ self._call_log: list[ToolReceipt] = []
249
+ self._call_count: int = 0
250
+ self._max_calls = max_calls_per_session
251
+ self._register_default_tools()
252
+
253
+ def _register_default_tools(self):
254
+ """注册默认工具集。"""
255
+ # Read 权限:信息查询
256
+ self.register_tool(
257
+ name="describe_molecule",
258
+ description="返回当前分子的摘要:分子式、原子数、键数、能量、HOMO/LUMO gap",
259
+ parameters={"type": "object", "properties": {}},
260
+ handler=self.context.describe_molecule,
261
+ permission=ToolPermission.READ,
262
+ )
263
+
264
+ self.register_tool(
265
+ name="compute_properties",
266
+ description="计算并返回分子性质(MW、LogP、TPSA、HBA/HBD、环数...)",
267
+ parameters={"type": "object", "properties": {}},
268
+ handler=self.context.compute_properties,
269
+ permission=ToolPermission.READ,
270
+ )
271
+
272
+ # Edit 权限:修改结构
273
+ self.register_tool(
274
+ name="generate_conformer",
275
+ description="生成 3D 构象(ETKDG + MMFF 优化)",
276
+ parameters={
277
+ "type": "object",
278
+ "properties": {
279
+ "seed": {"type": "integer", "description": "随机种子", "default": 42},
280
+ },
281
+ },
282
+ handler=self.context.generate_conformer,
283
+ permission=ToolPermission.EDIT,
284
+ )
285
+
286
+ # Read 权限:打开文件
287
+ self.register_tool(
288
+ name="open_file",
289
+ description="打开一个分子文件(支持 .mol/.sdf/.gjf/.log/.cube/.smi)",
290
+ parameters={
291
+ "type": "object",
292
+ "properties": {
293
+ "path": {"type": "string", "description": "文件路径"},
294
+ },
295
+ "required": ["path"],
296
+ },
297
+ handler=self.context.open_file,
298
+ permission=ToolPermission.READ,
299
+ )
300
+
301
+ # Export 权限:导出文件
302
+ self.register_tool(
303
+ name="export_gjf",
304
+ description="导出 Gaussian 输入文件",
305
+ parameters={
306
+ "type": "object",
307
+ "properties": {
308
+ "route": {"type": "string", "description": "Gaussian route line", "default": "# B3LYP/6-31G(d,p) opt"},
309
+ "path": {"type": "string", "description": "输出路径(可选)"},
310
+ },
311
+ },
312
+ handler=self.context.export_gjf,
313
+ permission=ToolPermission.EXPORT,
314
+ )
315
+
316
+ self.register_tool(
317
+ name="export_svg",
318
+ description="导出 2D 结构图为 SVG",
319
+ parameters={
320
+ "type": "object",
321
+ "properties": {
322
+ "path": {"type": "string", "description": "输出路径(可选)"},
323
+ },
324
+ },
325
+ handler=self.context.export_svg,
326
+ permission=ToolPermission.EXPORT,
327
+ )
328
+
329
+ # Read 权限:读 Gaussian log
330
+ self.register_tool(
331
+ name="read_gaussian_log",
332
+ description="读 Gaussian log 文件,解析能量、HOMO/LUMO、终止状态",
333
+ parameters={
334
+ "type": "object",
335
+ "properties": {
336
+ "path": {"type": "string", "description": "log 文件路径"},
337
+ },
338
+ "required": ["path"],
339
+ },
340
+ handler=self.context.read_gaussian_log,
341
+ permission=ToolPermission.READ,
342
+ )
343
+
344
+ # Read 权限:AI 建议
345
+ self.register_tool(
346
+ name="suggest_next_step",
347
+ description="根据当前分子状态,建议下一步计算",
348
+ parameters={"type": "object", "properties": {}},
349
+ handler=self.context.suggest_next_step,
350
+ permission=ToolPermission.READ,
351
+ )
352
+
353
+ def register_tool(self, name: str, description: str,
354
+ parameters: dict, handler: Callable,
355
+ permission: ToolPermission = ToolPermission.READ,
356
+ requires_confirmation: bool | None = None):
357
+ """注册一个工具。"""
358
+ # 需要确认的工具:Edit/Execute/Export 级别默认需要确认
359
+ if requires_confirmation is None:
360
+ requires_confirmation = permission in (ToolPermission.EDIT, ToolPermission.EXECUTE, ToolPermission.EXPORT)
361
+
362
+ self._tools[name] = {
363
+ "name": name,
364
+ "description": description,
365
+ "parameters": parameters,
366
+ "handler": handler,
367
+ "permission": permission,
368
+ "requires_confirmation": requires_confirmation,
369
+ }
370
+
371
+ def get_tool_definitions(self) -> list[dict]:
372
+ """返回 OpenAI function calling 格式的工具定义。"""
373
+ return [
374
+ {
375
+ "type": "function",
376
+ "function": {
377
+ "name": name,
378
+ "description": tool["description"],
379
+ "parameters": tool["parameters"],
380
+ },
381
+ }
382
+ for name, tool in self._tools.items()
383
+ ]
384
+
385
+ def call_tool(self, name: str, arguments: dict[str, Any]) -> ToolReceipt:
386
+ """
387
+ 调用一个工具,返回执行收据。
388
+
389
+ 安全检查:
390
+ - 工具必须在注册表中
391
+ - 调用次数限制
392
+ - 无 shell/eval 注入
393
+ """
394
+ # 检查调用次数
395
+ if self._call_count >= self._max_calls:
396
+ return ToolReceipt(
397
+ receipt_id=uuid.uuid4().hex[:12],
398
+ tool_name=name,
399
+ arguments=arguments,
400
+ success=False,
401
+ error=f"超过会话调用次数限制({self._max_calls})",
402
+ )
403
+
404
+ if name not in self._tools:
405
+ return ToolReceipt(
406
+ receipt_id=uuid.uuid4().hex[:12],
407
+ tool_name=name,
408
+ arguments=arguments,
409
+ success=False,
410
+ error=f"未知工具: {name}",
411
+ )
412
+
413
+ tool = self._tools[name]
414
+ self._call_count += 1
415
+
416
+ # 执行
417
+ start = time.time()
418
+ try:
419
+ result = tool["handler"](**arguments)
420
+ success = True
421
+ error = ""
422
+ except Exception as e:
423
+ result = None
424
+ success = False
425
+ error = str(e)
426
+
427
+ end = time.time()
428
+
429
+ receipt = ToolReceipt(
430
+ receipt_id=uuid.uuid4().hex[:12],
431
+ tool_name=name,
432
+ arguments=arguments,
433
+ success=success,
434
+ result=result,
435
+ error=error,
436
+ started_at=start,
437
+ finished_at=end,
438
+ duration_ms=(end - start) * 1000,
439
+ )
440
+
441
+ self._call_log.append(receipt)
442
+ return receipt
443
+
444
+ def list_tools(self) -> list[str]:
445
+ """列出所有已注册工具名。"""
446
+ return list(self._tools.keys())
447
+
448
+ def get_call_log(self) -> list[ToolReceipt]:
449
+ """获取调用日志。"""
450
+ return self._call_log.copy()
451
+
452
+ def reset_call_count(self) -> None:
453
+ """重置调用计数(新会话时调用)。"""
454
+ self._call_count = 0
455
+ self._call_log.clear()
@@ -0,0 +1,22 @@
1
+ """
2
+ application/ - 应用层
3
+ ========================
4
+ 用例和业务逻辑。只依赖 domain 层,不依赖 GUI/VTK/SDK。
5
+
6
+ 核心:
7
+ - CommandBus:所有修改的统一入口(UI 和 AI 都走这里)
8
+ - UndoHistory:撤销/重做历史
9
+ - SelectionService:选择状态管理
10
+ """
11
+
12
+ from .commands import Command, CommandResult
13
+ from .command_bus import CommandBus
14
+ from .history import UndoHistory
15
+ from .selection import SelectionService
16
+
17
+ __all__ = [
18
+ "Command", "CommandResult",
19
+ "CommandBus",
20
+ "UndoHistory",
21
+ "SelectionService",
22
+ ]
@@ -0,0 +1 @@
1
+ """AI 应用层:观察、工具协议、预览/提交。"""