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
+ # readers 包:导入即触发 @register
2
+ # 注意顺序:专门 reader 先注册,OpenBabel 最后(自动去重)
3
+ from . import smi_reader # noqa: F401
4
+ from . import mol_reader # noqa: F401
5
+ from . import glog_reader # noqa: F401
6
+ from . import cube_reader # noqa: F401
7
+ from . import gjf_reader # noqa: F401
8
+ from . import xyz_reader # noqa: F401
9
+ from . import pdb_reader # noqa: F401
10
+ from . import mol2_reader # noqa: F401
@@ -0,0 +1,71 @@
1
+ """
2
+ cube_reader.py - Gaussian cube 文件读取
3
+ =========================================
4
+ cube 文件存三维网格上的标量场(分子轨道、电子密度)。
5
+ 这里只解析头和原子坐标,不解析庞大的网格数据(渲染时再按需读)。
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from pathlib import Path
11
+
12
+ from rdkit import Chem
13
+
14
+ from ..registry import FormatHandler, register
15
+ from ...core.molecule import Molecule
16
+ from ...core.conformer import Conformer
17
+
18
+
19
+ @register
20
+ class CubeReader(FormatHandler):
21
+ name = "Gaussian Cube"
22
+ extensions = [".cube", ".cub"]
23
+ description = "Cube 轨道/密度文件"
24
+ can_read = True
25
+ can_write = False
26
+
27
+ def read(self, path: Path) -> Molecule:
28
+ lines = path.read_text(encoding="utf-8", errors="replace").splitlines()
29
+
30
+ # cube 格式:
31
+ # Line 1-2: 注释
32
+ # Line 3: N_atoms origin_x origin_y origin_z
33
+ # Line 4: NX vx1 vx2 vx3
34
+ # Line 5: NY vy1 vy2 vy3
35
+ # Line 6: NZ vz1 vz2 vz3
36
+ # Line 7..: 原子序数 电荷 x y z(每原子一行)
37
+
38
+ n_atoms = int(lines[2].split()[0])
39
+ nx = int(lines[3].split()[0])
40
+ ny = int(lines[4].split()[0])
41
+ nz = int(lines[5].split()[0])
42
+
43
+ atoms = []
44
+ for i in range(6, 6 + n_atoms):
45
+ parts = lines[i].split()
46
+ atomic_num = int(float(parts[0]))
47
+ x, y, z = float(parts[2]), float(parts[3]), float(parts[4])
48
+ atoms.append((atomic_num, x, y, z))
49
+
50
+ # 建 RDKit Mol
51
+ sym_map = {1: "H", 6: "C", 7: "N", 8: "O", 9: "F", 15: "P", 16: "S", 17: "Cl"}
52
+ xyz = f"{n_atoms}\n\n"
53
+ for z, x, y, zc in atoms:
54
+ xyz += f"{sym_map.get(z, 'C')} {x:.6f} {y:.6f} {zc:.6f}\n"
55
+ mol = Chem.MolFromXYZBlock(xyz)
56
+ if mol is not None:
57
+ mol = Chem.AddHs(mol, addCoords=True)
58
+
59
+ m = Molecule.from_rdkit(mol or Chem.RWMol().GetMol(), name=path.stem)
60
+ m.source_format = "cube"
61
+ m.source_path = path
62
+ m.properties["grid"] = (nx, ny, nz)
63
+
64
+ if atoms:
65
+ import numpy as np
66
+ coords = [[x, y, zc] for _, x, y, zc in atoms]
67
+ m.conformers.append(Conformer(
68
+ coords=np.array(coords),
69
+ source="cube_file"
70
+ ))
71
+ return m
@@ -0,0 +1,110 @@
1
+ """
2
+ gjf_reader.py - Gaussian 输入文件读取
3
+ =======================================
4
+ 解析 .gjf/.com 文件:%chk、route、title、电荷/多重度、坐标。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from pathlib import Path
10
+
11
+ from rdkit import Chem
12
+
13
+ from ..registry import FormatHandler, register
14
+ from ...core.molecule import Molecule
15
+ from ...core.conformer import Conformer
16
+
17
+
18
+ @register
19
+ class GjfReader(FormatHandler):
20
+ name = "Gaussian Input"
21
+ extensions = [".gjf", ".com"]
22
+ description = "Gaussian 输入文件"
23
+ can_read = True
24
+ can_write = False # 写 gjf 在 writer 层
25
+
26
+ def read(self, path: Path) -> Molecule:
27
+ text = path.read_text(encoding="utf-8", errors="replace")
28
+ lines = text.splitlines()
29
+
30
+ chk = None
31
+ route = None
32
+ title = ""
33
+ charge = 0
34
+ multiplicity = 1
35
+ atoms = []
36
+
37
+ i = 0
38
+ # 1. % 开头的行
39
+ while i < len(lines) and lines[i].startswith("%"):
40
+ if lines[i].lower().startswith("%chk"):
41
+ chk = lines[i].split("=", 1)[1].strip()
42
+ i += 1
43
+
44
+ # 2. route 行(# 开头)
45
+ while i < len(lines) and not lines[i].strip():
46
+ i += 1
47
+ route_lines = []
48
+ while i < len(lines) and lines[i].strip().startswith("#"):
49
+ route_lines.append(lines[i].strip())
50
+ i += 1
51
+ route = " ".join(route_lines)
52
+
53
+ # 3. 空行后是 title
54
+ while i < len(lines) and not lines[i].strip():
55
+ i += 1
56
+ title_lines = []
57
+ while i < len(lines) and lines[i].strip():
58
+ title_lines.append(lines[i].strip())
59
+ i += 1
60
+ title = " ".join(title_lines)
61
+
62
+ # 4. 空行后是电荷/多重度
63
+ while i < len(lines) and not lines[i].strip():
64
+ i += 1
65
+ if i < len(lines):
66
+ parts = lines[i].split()
67
+ if len(parts) >= 2:
68
+ charge = int(parts[0])
69
+ multiplicity = int(parts[1])
70
+ i += 1
71
+
72
+ # 5. 坐标行(直到空行或文件尾)
73
+ while i < len(lines) and lines[i].strip():
74
+ parts = lines[i].split()
75
+ if len(parts) >= 4:
76
+ sym = parts[0]
77
+ try:
78
+ x, y, z = float(parts[1]), float(parts[2]), float(parts[3])
79
+ atoms.append((sym, x, y, z))
80
+ except ValueError:
81
+ pass
82
+ i += 1
83
+
84
+ # 建 RDKit Mol
85
+ if atoms:
86
+ xyz = f"{len(atoms)}\n{title}\n"
87
+ for sym, x, y, z in atoms:
88
+ xyz += f"{sym} {x:.6f} {y:.6f} {z:.6f}\n"
89
+ mol = Chem.MolFromXYZBlock(xyz)
90
+ if mol is not None:
91
+ mol = Chem.AddHs(mol, addCoords=True)
92
+ else:
93
+ mol = Chem.RWMol().GetMol()
94
+
95
+ m = Molecule.from_rdkit(mol, name=path.stem)
96
+ m.source_format = "gjf"
97
+ m.source_path = path
98
+ m.properties["route"] = route or ""
99
+ m.properties["charge"] = charge
100
+ m.properties["multiplicity"] = multiplicity
101
+ m.properties["chk"] = chk
102
+
103
+ if atoms:
104
+ import numpy as np
105
+ coords = [[x, y, z] for _, x, y, z in atoms]
106
+ m.conformers.append(Conformer(
107
+ coords=np.array(coords),
108
+ source="gjf_file"
109
+ ))
110
+ return m
@@ -0,0 +1,45 @@
1
+ """
2
+ glog_reader.py - Gaussian log 解析器(支持 Standard / Input / Z-Matrix orientation 与全 118 元素)
3
+ """
4
+ from __future__ import annotations
5
+
6
+ import re
7
+ from pathlib import Path
8
+ import numpy as np
9
+ from rdkit import Chem
10
+
11
+ from ..registry import FormatHandler, register
12
+ from ...core.molecule import Molecule
13
+ from ...core.conformer import Conformer
14
+ from ...core.orbital import Orbital
15
+ from ..rdkit_adapter import doc_to_rdkit, parse_gaussian_log_to_document
16
+
17
+
18
+ @register
19
+ class GaussianLogReader(FormatHandler):
20
+ name = "Gaussian Log"
21
+ extensions = [".log", ".out"]
22
+ description = "Gaussian / ORCA / REST 输出文件"
23
+ can_read = True
24
+ can_write = False
25
+
26
+ def read(self, path: Path) -> Molecule:
27
+ doc, props = parse_gaussian_log_to_document(path)
28
+ rdmol, _, _ = doc_to_rdkit(doc, sanitize=True)
29
+ m = Molecule.from_rdkit(rdmol, name=path.stem, attach_conformers=False)
30
+ m.source_format = "gaussian_log"
31
+ m.source_path = path
32
+ m.energy = (props.get("energy_ev") / 27.211386) if props.get("energy_ev") else None
33
+ m.properties.update(props)
34
+ if doc.has_3d and doc.coordinates.current is not None:
35
+ m.conformers.append(Conformer(
36
+ coords=doc.coordinates.current.coords.copy(),
37
+ energy=m.energy,
38
+ source="gaussian_optimized",
39
+ ))
40
+ if props.get("homo_ev") and props.get("lumo_ev"):
41
+ m.orbitals = [
42
+ Orbital(index=1, energy_ev=float(props["homo_ev"]), occupation=2.0),
43
+ Orbital(index=2, energy_ev=float(props["lumo_ev"]), occupation=0.0),
44
+ ]
45
+ return m
@@ -0,0 +1,36 @@
1
+ """
2
+ mol2_reader.py - SYBYL MOL2 格式读取
3
+ ======================================
4
+ RDKit 原生支持 MolFromMol2File。
5
+ MOL2 是 Tripos/SYBYL 的标准格式,常见于对接和力场参数化场景。
6
+ 注意:RDKit 不支持写 MOL2,写走 OpenBabel fallback。
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from pathlib import Path
12
+
13
+ from rdkit import Chem
14
+
15
+ from ..registry import FormatHandler, register
16
+ from ...core.molecule import Molecule
17
+
18
+
19
+ @register
20
+ class MOL2Reader(FormatHandler):
21
+ name = "MOL2 (SYBYL)"
22
+ extensions = [".mol2"]
23
+ description = "SYBYL MOL2 文件"
24
+ can_read = True
25
+ can_write = False
26
+
27
+ def read(self, path: Path) -> Molecule:
28
+ mol = Chem.MolFromMol2File(str(path), removeHs=False, sanitize=True)
29
+ if mol is None:
30
+ raise ValueError(f"无法从 {path.name} 读取 MOL2 文件")
31
+
32
+ m = Molecule.from_rdkit(mol, name=path.stem)
33
+ m.source_format = "mol2"
34
+ m.source_path = path
35
+ m.attach_rdkit_conformers(source="mol2_file")
36
+ return m
@@ -0,0 +1,56 @@
1
+ """
2
+ mol_reader.py - MOL/SDF 读取
3
+ =============================
4
+ MDL MOL 和 SDF 是化学领域最通用的结构交换格式。
5
+ RDKit 自带 SDMolSupplier。
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from pathlib import Path
11
+
12
+ try:
13
+ from rdkit import Chem
14
+ except ImportError:
15
+ Chem = None
16
+
17
+ from ..registry import FormatHandler, register
18
+ from ...core.molecule import Molecule
19
+ from ...core.conformer import Conformer
20
+
21
+
22
+ @register
23
+ class MolReader(FormatHandler):
24
+ name = "MOL/SDF"
25
+ extensions = [".mol", ".sdf", ".sd"]
26
+ description = "MOL/SDF 文件"
27
+ can_read = True
28
+ can_write = False # 写 MOL/SDF 放 writer 层
29
+
30
+ def read(self, path: Path) -> Molecule:
31
+ suppl = Chem.SDMolSupplier(str(path), sanitize=True, removeHs=False)
32
+ mol = None
33
+ for m in suppl:
34
+ if m is not None:
35
+ mol = m
36
+ break
37
+ if mol is None:
38
+ raise ValueError(f"无法从 {path.name} 读到有效分子")
39
+
40
+ m = Molecule.from_rdkit(mol, name=path.stem)
41
+ m.source_format = "mol/sdf"
42
+ m.source_path = path
43
+
44
+ # 如果文件里有 3D 坐标,转成 Conformer
45
+ if mol.GetNumConformers() > 0:
46
+ conf = mol.GetConformer()
47
+ coords = []
48
+ for i in range(mol.GetNumAtoms()):
49
+ p = conf.GetAtomPosition(i)
50
+ coords.append([p.x, p.y, p.z])
51
+ import numpy as np
52
+ m.conformers.append(Conformer(
53
+ coords=np.array(coords),
54
+ source="read_from_file"
55
+ ))
56
+ return m
@@ -0,0 +1,39 @@
1
+ """
2
+ pdb_reader.py - PDB 蛋白质数据库格式读取
3
+ ==========================================
4
+ RDKit 原生支持 MolFromPDBFile。
5
+ 保留残基名、链 ID 等蛋白质特有信息(写在分子属性里)。
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from pathlib import Path
11
+
12
+ from rdkit import Chem
13
+
14
+ from ..registry import FormatHandler, register
15
+ from ...core.molecule import Molecule
16
+
17
+
18
+ @register
19
+ class PDBReader(FormatHandler):
20
+ name = "PDB 蛋白质结构"
21
+ extensions = [".pdb", ".ent"]
22
+ description = "PDB / ENT 蛋白质结构文件"
23
+ can_read = True
24
+ can_write = False
25
+
26
+ def read(self, path: Path) -> Molecule:
27
+ mol = Chem.MolFromPDBFile(str(path), removeHs=False, sanitize=True)
28
+ if mol is None:
29
+ raise ValueError(f"无法从 {path.name} 读取 PDB 文件")
30
+
31
+ # PDB 读出来的构象默认 Is3D=False,手动标记为 3D
32
+ if mol.GetNumConformers() > 0:
33
+ mol.GetConformer().Set3D(True)
34
+
35
+ m = Molecule.from_rdkit(mol, name=path.stem)
36
+ m.source_format = "pdb"
37
+ m.source_path = path
38
+ m.attach_rdkit_conformers(source="pdb_file")
39
+ return m
@@ -0,0 +1,40 @@
1
+ """
2
+ smi_reader.py - SMILES 读取
3
+ =============================
4
+ SMILES 是文本格式,不是文件扩展名。
5
+ 这个 reader 主要给"粘贴 SMILES 到输入框"用,也支持 .smi/.smiles 文件。
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from pathlib import Path
11
+
12
+ try:
13
+ from rdkit import Chem
14
+ except ImportError:
15
+ Chem = None
16
+
17
+ from ..registry import FormatHandler, register
18
+ from ...core.molecule import Molecule
19
+
20
+
21
+ @register
22
+ class SmilesReader(FormatHandler):
23
+ name = "SMILES"
24
+ extensions = [".smi", ".smiles"]
25
+ description = "SMILES 文件"
26
+ can_read = True
27
+ can_write = False
28
+
29
+ def read(self, path: Path) -> Molecule:
30
+ text = path.read_text(encoding="utf-8").strip()
31
+ # .smi 文件每行一个 SMILES,取第一行第一个 token
32
+ first_line = text.splitlines()[0].strip() if text else ""
33
+ smiles = first_line.split()[0] if first_line else ""
34
+ mol = Chem.MolFromSmiles(smiles, sanitize=True)
35
+ if mol is None:
36
+ raise ValueError(f"SMILES 解析失败: {smiles!r}")
37
+ m = Molecule.from_rdkit(mol, name=path.stem)
38
+ m.source_format = "smiles"
39
+ m.source_path = path
40
+ return m
@@ -0,0 +1,47 @@
1
+ """
2
+ xyz_reader.py - XYZ 坐标格式读取
3
+ ==================================
4
+ XYZ 是计算化学最通用的纯坐标格式。
5
+ 每行一个原子:元素符号 x y z。
6
+ RDKit 原生支持。
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from pathlib import Path
12
+
13
+ from rdkit import Chem
14
+
15
+ from ..registry import FormatHandler, register
16
+ from ...core.molecule import Molecule
17
+
18
+
19
+ @register
20
+ class XYZReader(FormatHandler):
21
+ name = "XYZ 坐标"
22
+ extensions = [".xyz"]
23
+ description = "XYZ 坐标文件"
24
+ can_read = True
25
+ can_write = False
26
+
27
+ def read(self, path: Path) -> Molecule:
28
+ # MolFromXYZFile 只接受文件路径参数
29
+ mol = Chem.MolFromXYZFile(str(path))
30
+ if mol is None:
31
+ raise ValueError(f"无法从 {path.name} 读取 XYZ 文件")
32
+
33
+ # XYZ 文件只有坐标没有键信息,尝试 sanitize,失败也不阻断
34
+ try:
35
+ Chem.SanitizeMol(mol)
36
+ except Exception:
37
+ pass
38
+
39
+ # 手动标记构象为 3D
40
+ if mol.GetNumConformers() > 0:
41
+ mol.GetConformer().Set3D(True)
42
+
43
+ m = Molecule.from_rdkit(mol, name=path.stem)
44
+ m.source_format = "xyz"
45
+ m.source_path = path
46
+ m.attach_rdkit_conformers(source="xyz_file")
47
+ return m
@@ -0,0 +1,128 @@
1
+ """
2
+ registry.py - 格式注册表
3
+ =========================
4
+ 每个 reader/writer 是一个 FormatHandler 子类,用 @register 装饰器注册。
5
+ UI 打开/保存文件时,从注册表查扩展名找对应的 handler。
6
+
7
+ 加新格式 = 写一个新类加 @register,不动主流程。
8
+
9
+ 设计:读和写分开映射,同一个扩展名可以有独立的 reader 和 writer。
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from abc import ABC, abstractmethod
15
+ from pathlib import Path
16
+
17
+ from ..core.molecule import Molecule
18
+
19
+
20
+ class FormatHandler(ABC):
21
+ """格式处理器抽象基类。"""
22
+
23
+ # 子类必须定义
24
+ name: str = "" # 格式名,例如 'Gaussian Log'
25
+ extensions: list[str] = [] # 支持的扩展名,例如 ['.log', '.out']
26
+ description: str = "" # 文件对话框里显示的描述
27
+
28
+ # 子类声明自己能读/能写
29
+ can_read: bool = False
30
+ can_write: bool = False
31
+
32
+ def read(self, path: Path) -> Molecule:
33
+ """从文件读一个 Molecule。"""
34
+ raise NotImplementedError(f"{self.name} 不支持读取")
35
+
36
+ def write(self, mol: Molecule, path: Path) -> None:
37
+ """把 Molecule 写到文件。"""
38
+ raise NotImplementedError(f"{self.name} 不支持写入")
39
+
40
+
41
+ # 注册表:所有 handler 列表
42
+ _REGISTRY: list[FormatHandler] = []
43
+
44
+ # 读/写分开的扩展名映射
45
+ _READ_MAP: dict[str, FormatHandler] = {}
46
+ _WRITE_MAP: dict[str, FormatHandler] = {}
47
+
48
+ # 向后兼容:保留 _EXT_MAP(OpenBabel handler 用来检查去重)
49
+ # 现在指向 _READ_MAP,主要用于"该扩展名是否已有专门 reader"的检查
50
+ _EXT_MAP: dict[str, FormatHandler] = _READ_MAP
51
+
52
+
53
+ def register(handler_cls: type[FormatHandler]) -> type[FormatHandler]:
54
+ """类装饰器:把一个 FormatHandler 子类注册进去。"""
55
+ instance = handler_cls()
56
+ _REGISTRY.append(instance)
57
+ for ext in instance.extensions:
58
+ ext_lower = ext.lower()
59
+ if instance.can_read:
60
+ _READ_MAP[ext_lower] = instance
61
+ if instance.can_write:
62
+ _WRITE_MAP[ext_lower] = instance
63
+ return handler_cls
64
+
65
+
66
+ def get_reader_for_ext(ext: str) -> FormatHandler | None:
67
+ """按扩展名找读 handler(不区分大小写)。"""
68
+ return _READ_MAP.get(ext.lower())
69
+
70
+
71
+ def get_writer_for_ext(ext: str) -> FormatHandler | None:
72
+ """按扩展名找写 handler(不区分大小写)。"""
73
+ return _WRITE_MAP.get(ext.lower())
74
+
75
+
76
+ def get_handler_for_ext(ext: str) -> FormatHandler | None:
77
+ """
78
+ 按扩展名找 handler(兼容旧接口)。
79
+ 优先返回 reader,没有再返回 writer。
80
+ """
81
+ return get_reader_for_ext(ext) or get_writer_for_ext(ext)
82
+
83
+
84
+ def supported_open_filters() -> str:
85
+ """
86
+ 生成文件对话框的打开过滤器字符串。
87
+ 例如: "MOL/SDF (*.mol *.sdf);;Gaussian Log (*.log *.out);;所有文件 (*.*)"
88
+ """
89
+ parts = []
90
+ for h in _REGISTRY:
91
+ if not h.can_read:
92
+ continue
93
+ exts = " ".join(f"*{e}" for e in h.extensions)
94
+ parts.append(f"{h.description or h.name} ({exts})")
95
+ parts.append("所有文件 (*.*)")
96
+ return ";;".join(parts)
97
+
98
+
99
+ def supported_save_filters() -> str:
100
+ """生成保存对话框的过滤器。"""
101
+ parts = []
102
+ for h in _REGISTRY:
103
+ if not h.can_write:
104
+ continue
105
+ exts = " ".join(f"*{e}" for e in h.extensions)
106
+ parts.append(f"{h.description or h.name} ({exts})")
107
+ return ";;".join(parts)
108
+
109
+
110
+ def read_file(path: Path) -> Molecule:
111
+ """
112
+ 统一读文件入口。按扩展名找 reader handler。
113
+ 找不到就抛 ValueError。
114
+ """
115
+ ext = path.suffix.lower()
116
+ handler = get_reader_for_ext(ext)
117
+ if handler is None:
118
+ raise ValueError(f"不支持的文件格式: {ext}(文件 {path.name})")
119
+ return handler.read(path)
120
+
121
+
122
+ def write_file(mol: Molecule, path: Path) -> None:
123
+ """统一写文件入口。按扩展名找 writer handler。"""
124
+ ext = path.suffix.lower()
125
+ handler = get_writer_for_ext(ext)
126
+ if handler is None:
127
+ raise ValueError(f"不支持的文件格式: {ext}")
128
+ handler.write(mol, path)
@@ -0,0 +1,7 @@
1
+ # writers 包:导入即触发 @register
2
+ # 注意顺序:专门 writer 先注册,OpenBabel 最后(自动去重)
3
+ from . import gjf_writer # noqa: F401
4
+ from . import svg_writer # noqa: F401
5
+ from . import png_writer # noqa: F401
6
+ from . import xyz_writer # noqa: F401
7
+ from . import pdb_writer # noqa: F401
@@ -0,0 +1,68 @@
1
+ """
2
+ gjf_writer.py - Gaussian 输入文件写出
3
+ =======================================
4
+ 从 Molecule 对象生成 .gjf 文件。
5
+ 默认 route: # B3LYP/6-31G(d,p) opt(可在 properties 里覆盖)。
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from pathlib import Path
11
+
12
+ from ..registry import FormatHandler, register
13
+ from ...core.molecule import Molecule
14
+
15
+
16
+ @register
17
+ class GjfWriter(FormatHandler):
18
+ name = "Gaussian Input"
19
+ extensions = [".gjf"]
20
+ description = "Gaussian 输入文件"
21
+ can_read = False
22
+ can_write = True
23
+
24
+ def write(self, mol: Molecule, path: Path) -> None:
25
+ rmol = mol.rdkit_mol
26
+
27
+ route = mol.properties.get("route", "# B3LYP/6-31G(d,p) opt")
28
+ charge = mol.properties.get("charge", 0)
29
+ multiplicity = mol.properties.get("multiplicity", 1)
30
+ chk = mol.properties.get("chk", path.stem + ".chk")
31
+
32
+ # 取 3D 坐标(如果有),否则用 2D 坐标
33
+ if mol.has_3d:
34
+ conf = mol.conformers[0]
35
+ coords = conf.coords
36
+ else:
37
+ # 没有 3D 坐标,用 RDKit 2D 坐标(z=0)
38
+ from rdkit.Chem import AllChem
39
+ AllChem.Compute2DCoords(rmol)
40
+ rdkit_conf = rmol.GetConformer()
41
+ coords = []
42
+ for i in range(rmol.GetNumAtoms()):
43
+ p = rdkit_conf.GetAtomPosition(i)
44
+ coords.append([p.x, p.y, 0.0])
45
+
46
+ # 元素符号
47
+ from rdkit.Chem import GetPeriodicTable
48
+ pt = GetPeriodicTable()
49
+ syms = []
50
+ for atom in rmol.GetAtoms():
51
+ syms.append(pt.GetElementSymbol(atom.GetAtomicNum()))
52
+
53
+ # 组装 gjf 文本
54
+ lines = []
55
+ lines.append(f"%chk={chk}")
56
+ lines.append(f"%nprocshared=4")
57
+ lines.append(f"%mem=4GB")
58
+ lines.append(route)
59
+ lines.append("")
60
+ lines.append(mol.name or path.stem)
61
+ lines.append("")
62
+ lines.append(f"{charge} {multiplicity}")
63
+ for sym, (x, y, z) in zip(syms, coords):
64
+ lines.append(f" {sym:<3s} {x:>14.6f} {y:>14.6f} {z:>14.6f}")
65
+ lines.append("") # 坐标后必须空一行
66
+ lines.append("") # 再一个空行结束
67
+
68
+ path.write_text("\n".join(lines), encoding="utf-8")