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,37 @@
1
+ """
2
+ pdb_writer.py - PDB 格式写入
3
+ ==============================
4
+ RDKit 原生支持 MolToPDBFile。
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
+
16
+
17
+ @register
18
+ class PDBWriter(FormatHandler):
19
+ name = "PDB 蛋白质结构"
20
+ extensions = [".pdb"]
21
+ description = "PDB 文件"
22
+ can_read = False
23
+ can_write = True
24
+
25
+ def write(self, mol: Molecule, path: Path) -> None:
26
+ if mol.has_3d:
27
+ rmol = Chem.Mol(mol.rdkit_mol)
28
+ conf = Chem.Conformer(rmol.GetNumAtoms())
29
+ coords = mol.conformers[0].coords
30
+ for i in range(rmol.GetNumAtoms()):
31
+ conf.SetAtomPosition(i, coords[i, 0], coords[i, 1], coords[i, 2])
32
+ rmol.RemoveAllConformers()
33
+ rmol.AddConformer(conf, assignId=True)
34
+ else:
35
+ rmol = mol.rdkit_mol
36
+
37
+ Chem.MolToPDBFile(rmol, str(path))
@@ -0,0 +1,31 @@
1
+ """
2
+ png_writer.py - 2D 结构图导出 PNG
3
+ ====================================
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from pathlib import Path
9
+
10
+ from rdkit import Chem
11
+ from rdkit.Chem import Draw
12
+
13
+ from ..registry import FormatHandler, register
14
+ from ...core.molecule import Molecule
15
+
16
+
17
+ @register
18
+ class PngWriter(FormatHandler):
19
+ name = "PNG"
20
+ extensions = [".png"]
21
+ description = "PNG 位图"
22
+ can_read = False
23
+ can_write = True
24
+
25
+ def write(self, mol: Molecule, path: Path) -> None:
26
+ Draw.MolToFile(
27
+ mol.rdkit_mol,
28
+ str(path),
29
+ size=(600, 400),
30
+ kekulize=True,
31
+ )
@@ -0,0 +1,111 @@
1
+ """
2
+ svg_writer.py - 2D 结构图导出 SVG
3
+ ===================================
4
+ 用 RDKit 的 MolToFile 直接写 SVG。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ from rdkit import Chem
13
+ from rdkit.Chem import AllChem, Draw
14
+ from rdkit.Chem.Draw import rdMolDraw2D
15
+
16
+ from ..registry import FormatHandler, register
17
+ from ...core.molecule import Molecule
18
+
19
+
20
+ def write_svg_2d(doc: Any, path: str | Path, width: int = 800, height: int = 560) -> None:
21
+ """将 MoleculeDocument 或 Molecule 导出为高清晰度 2D SVG 矢量图。"""
22
+ out = Path(path)
23
+ out.parent.mkdir(parents=True, exist_ok=True)
24
+ if isinstance(doc, Molecule) and getattr(doc, "rdkit_mol", None) is not None:
25
+ Draw.MolToFile(doc.rdkit_mol, str(out), size=(width, height), kekulize=True)
26
+ return
27
+
28
+ from ..rdkit_adapter import doc_to_rdkit
29
+
30
+ try:
31
+ rdmol, aid_to_idx, _ = doc_to_rdkit(doc, sanitize=True, strict=False)
32
+ if rdmol.GetNumAtoms() > 0:
33
+ coords_2d = getattr(doc, "coords_2d", {}) or {}
34
+ if len(coords_2d) >= rdmol.GetNumAtoms():
35
+ conf = Chem.Conformer(rdmol.GetNumAtoms())
36
+ conf.Set3D(False)
37
+ for aid, idx in aid_to_idx.items():
38
+ x, y = coords_2d.get(aid, (0.0, 0.0))
39
+ conf.SetAtomPosition(idx, (float(x), float(-y), 0.0))
40
+ rdmol.RemoveAllConformers()
41
+ rdmol.AddConformer(conf, assignId=True)
42
+ else:
43
+ AllChem.Compute2DCoords(rdmol)
44
+ drawer = rdMolDraw2D.MolDraw2DSVG(width, height)
45
+ try:
46
+ drawer.DrawMolecule(rdmol)
47
+ except Exception:
48
+ rdMolDraw2D.PrepareAndDrawMolecule(drawer, rdmol, kekulize=False)
49
+ drawer.FinishDrawing()
50
+ out.write_text(drawer.GetDrawingText(), encoding="utf-8")
51
+ return
52
+ except Exception:
53
+ pass
54
+
55
+ # 纯 Python 回退 SVG(避免超非常规价态/异常结构导出失败)
56
+ from ...domain.elements import get_element
57
+ coords_2d = getattr(doc, "coords_2d", {}) or {}
58
+ lines = [
59
+ f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" viewBox="0 0 {width} {height}">',
60
+ f'<rect width="100%" height="100%" fill="#ffffff"/>',
61
+ ]
62
+ if hasattr(doc, "topology") and doc.topology.num_atoms > 0:
63
+ xs = [coords_2d.get(aid, (0.0, 0.0))[0] for aid in doc.topology.atom_ids]
64
+ ys = [coords_2d.get(aid, (0.0, 0.0))[1] for aid in doc.topology.atom_ids]
65
+ min_x, max_x = min(xs), max(xs)
66
+ min_y, max_y = min(ys), max(ys)
67
+ span = max(max_x - min_x, max_y - min_y, 1.0)
68
+ pad = 48.0
69
+ scale = min(width - 2 * pad, height - 2 * pad) / span
70
+
71
+ def _tx(x: float, y: float) -> tuple[float, float]:
72
+ return (
73
+ width * 0.5 + (x - (min_x + max_x) * 0.5) * scale,
74
+ height * 0.5 + (y - (min_y + max_y) * 0.5) * scale,
75
+ )
76
+
77
+ for bid in doc.topology.bond_ids:
78
+ b = doc.topology.get_bond(bid)
79
+ x1, y1 = _tx(*coords_2d.get(b.begin, (0.0, 0.0)))
80
+ x2, y2 = _tx(*coords_2d.get(b.end, (0.0, 0.0)))
81
+ lines.append(f'<line x1="{x1:.1f}" y1="{y1:.1f}" x2="{x2:.1f}" y2="{y2:.1f}" stroke="#222" stroke-width="2"/>')
82
+ for aid in doc.topology.atom_ids:
83
+ atom = doc.topology.get_atom(aid)
84
+ if atom.atomic_num == 6:
85
+ continue
86
+ x, y = _tx(*coords_2d.get(aid, (0.0, 0.0)))
87
+ elem = get_element(atom.atomic_num)
88
+ sym = elem.symbol if elem else "?"
89
+ lines.append(
90
+ f'<text x="{x:.1f}" y="{y + 4:.1f}" font-family="sans-serif" font-size="13" '
91
+ f'text-anchor="middle" fill="#111">{sym}</text>'
92
+ )
93
+ lines.append("</svg>")
94
+ out.write_text("\n".join(lines), encoding="utf-8")
95
+
96
+
97
+ @register
98
+ class SvgWriter(FormatHandler):
99
+ name = "SVG"
100
+ extensions = [".svg"]
101
+ description = "SVG 矢量图"
102
+ can_read = False
103
+ can_write = True
104
+
105
+ def write(self, mol: Molecule, path: Path) -> None:
106
+ Draw.MolToFile(
107
+ mol.rdkit_mol,
108
+ str(path),
109
+ size=(600, 400),
110
+ kekulize=True,
111
+ )
@@ -0,0 +1,39 @@
1
+ """
2
+ xyz_writer.py - XYZ 坐标格式写入
3
+ ==================================
4
+ RDKit 原生支持 MolToXYZFile。
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
+
16
+
17
+ @register
18
+ class XYZWriter(FormatHandler):
19
+ name = "XYZ 坐标"
20
+ extensions = [".xyz"]
21
+ description = "XYZ 坐标文件"
22
+ can_read = False
23
+ can_write = True
24
+
25
+ def write(self, mol: Molecule, path: Path) -> None:
26
+ # 如果有 3D 构象,把坐标写进 RDKit Mol 再导出
27
+ if mol.has_3d:
28
+ import numpy as np
29
+ rmol = Chem.Mol(mol.rdkit_mol)
30
+ conf = Chem.Conformer(rmol.GetNumAtoms())
31
+ coords = mol.conformers[0].coords
32
+ for i in range(rmol.GetNumAtoms()):
33
+ conf.SetAtomPosition(i, coords[i, 0], coords[i, 1], coords[i, 2])
34
+ rmol.RemoveAllConformers()
35
+ rmol.AddConformer(conf, assignId=True)
36
+ else:
37
+ rmol = mol.rdkit_mol
38
+
39
+ Chem.MolToXYZFile(rmol, str(path))
@@ -0,0 +1,21 @@
1
+ """
2
+ rendering/ - 渲染层
3
+ =====================
4
+ 负责把 domain 数据可视化。
5
+ 不包含业务逻辑,只负责绘制。
6
+
7
+ 目录结构:
8
+ contracts.py - Renderer3D Protocol(抽象接口)
9
+ materials.py - Scientific/Studio 材质预设
10
+ representations.py - 表示方式定义(球棍/CPK/表面/轨道)
11
+ vtk/ - VTK 后端实现
12
+ render2d/ - 2D 渲染(QGraphicsView + RDKit)
13
+ """
14
+
15
+ from .contracts import Renderer3D, RenderSnapshot, RepresentationMode
16
+ from .materials import MaterialPreset, ScientificPreset, StudioPreset
17
+
18
+ __all__ = [
19
+ "Renderer3D", "RenderSnapshot", "RepresentationMode",
20
+ "MaterialPreset", "ScientificPreset", "StudioPreset",
21
+ ]
@@ -0,0 +1,121 @@
1
+ """
2
+ rendering/benchmark.py - 渲染性能基准
3
+ =========================================
4
+ 测量 FPS、帧时间、首帧时间、选择延迟等。
5
+
6
+ 验收门槛:
7
+ - 1000 原子场景:60 FPS(Studio 模式)
8
+ - 选择延迟 P95:< 50ms
9
+ - 缩放延迟 P95:< 100ms
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import time
15
+ from dataclasses import dataclass, field
16
+ from typing import Any
17
+
18
+
19
+ @dataclass
20
+ class BenchmarkResult:
21
+ """性能基准结果。"""
22
+ n_atoms: int = 0
23
+ n_bonds: int = 0
24
+ preset: str = "Studio"
25
+ fps: float = 0.0
26
+ frame_time_ms: float = 0.0
27
+ first_frame_ms: float = 0.0
28
+ selection_p95_ms: float = 0.0
29
+ zoom_p95_ms: float = 0.0
30
+ cpu_bottleneck: bool = False
31
+ gpu_bottleneck: bool = False
32
+ io_bottleneck: bool = False
33
+
34
+
35
+ class PerformanceBenchmark:
36
+ """
37
+ 性能基准测试器。
38
+
39
+ 用法:
40
+ bench = PerformanceBenchmark()
41
+ result = bench.run(backend, n_atoms=1000)
42
+ """
43
+
44
+ def __init__(self) -> None:
45
+ self._frame_times: list[float] = []
46
+ self._selection_times: list[float] = []
47
+ self._zoom_times: list[float] = []
48
+
49
+ def start_frame(self) -> float:
50
+ """开始计时一帧。"""
51
+ return time.perf_counter()
52
+
53
+ def end_frame(self, start: float) -> float:
54
+ """结束计时一帧,返回帧时间(ms)。"""
55
+ elapsed = (time.perf_counter() - start) * 1000
56
+ self._frame_times.append(elapsed)
57
+ return elapsed
58
+
59
+ def measure_selection(self, func: callable) -> float:
60
+ """测量选择操作延迟。"""
61
+ start = time.perf_counter()
62
+ func()
63
+ elapsed = (time.perf_counter() - start) * 1000
64
+ self._selection_times.append(elapsed)
65
+ return elapsed
66
+
67
+ def measure_zoom(self, func: callable) -> float:
68
+ """测量缩放操作延迟。"""
69
+ start = time.perf_counter()
70
+ func()
71
+ elapsed = (time.perf_counter() - start) * 1000
72
+ self._zoom_times.append(elapsed)
73
+ return elapsed
74
+
75
+ def p95(self, values: list[float]) -> float:
76
+ """计算 P95 值。"""
77
+ if not values:
78
+ return 0.0
79
+ sorted_v = sorted(values)
80
+ idx = int(len(sorted_v) * 0.95)
81
+ return sorted_v[min(idx, len(sorted_v) - 1)]
82
+
83
+ def get_result(self, n_atoms: int, n_bonds: int, preset: str) -> BenchmarkResult:
84
+ """获取基准结果。"""
85
+ avg_frame = sum(self._frame_times) / max(len(self._frame_times), 1)
86
+ fps = 1000 / avg_frame if avg_frame > 0 else 0
87
+
88
+ # 判断瓶颈
89
+ cpu_bottleneck = avg_frame > 16.6 # > 60fps 帧时间
90
+ gpu_bottleneck = False # TODO: 用 GPU 时间查询
91
+ io_bottleneck = False
92
+
93
+ return BenchmarkResult(
94
+ n_atoms=n_atoms,
95
+ n_bonds=n_bonds,
96
+ preset=preset,
97
+ fps=fps,
98
+ frame_time_ms=avg_frame,
99
+ selection_p95_ms=self.p95(self._selection_times),
100
+ zoom_p95_ms=self.p95(self._zoom_times),
101
+ cpu_bottleneck=cpu_bottleneck,
102
+ gpu_bottleneck=gpu_bottleneck,
103
+ io_bottleneck=io_bottleneck,
104
+ )
105
+
106
+ def reset(self) -> None:
107
+ """重置基准数据。"""
108
+ self._frame_times.clear()
109
+ self._selection_times.clear()
110
+ self._zoom_times.clear()
111
+
112
+ def check_threshold(self, result: BenchmarkResult) -> list[str]:
113
+ """检查是否达到性能门槛,返回警告列表。"""
114
+ warnings = []
115
+ if result.fps < 60 and result.n_atoms <= 1000:
116
+ warnings.append(f"FPS 过低:{result.fps:.1f} < 60({result.n_atoms} 原子)")
117
+ if result.selection_p95_ms > 50:
118
+ warnings.append(f"选择延迟 P95 过高:{result.selection_p95_ms:.1f}ms > 50ms")
119
+ if result.zoom_p95_ms > 100:
120
+ warnings.append(f"缩放延迟 P95 过高:{result.zoom_p95_ms:.1f}ms > 100ms")
121
+ return warnings
@@ -0,0 +1,60 @@
1
+ """
2
+ rendering/bridge.py - 新旧架构桥接层
3
+ =====================================
4
+ 把旧的 core/Molecule 转成新架构的 RenderSnapshot。
5
+ 过渡期使用,最终主窗口完全迁移到 MoleculeDocument。
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import numpy as np
11
+ from rdkit import Chem
12
+
13
+ from .contracts import RenderSnapshot, RepresentationMode
14
+ from ..domain.ids import AtomId
15
+
16
+
17
+ def rdkit_mol_to_snapshot(
18
+ rmol: Chem.Mol,
19
+ mode: RepresentationMode = RepresentationMode.BALL_AND_STICK,
20
+ ) -> RenderSnapshot:
21
+ """
22
+ 从 RDKit Mol 生成 RenderSnapshot。
23
+
24
+ 过渡期桥接:旧代码用 RDKit Mol,新架构用 MoleculeDocument。
25
+ 这个函数把 RDKit Mol 转成渲染器能消费的快照。
26
+ """
27
+ # 原子
28
+ n_atoms = rmol.GetNumAtoms()
29
+ atomic_numbers = np.zeros(n_atoms, dtype=np.int32)
30
+ atom_ids = []
31
+
32
+ # 坐标(取第一个构象)
33
+ coordinates = np.zeros((n_atoms, 3), dtype=np.float64)
34
+ has_3d = rmol.GetNumConformers() > 0
35
+
36
+ for i in range(n_atoms):
37
+ atom = rmol.GetAtomWithIdx(i)
38
+ atomic_numbers[i] = atom.GetAtomicNum()
39
+ atom_ids.append(AtomId(i)) # 临时用索引作为 AtomId
40
+
41
+ if has_3d:
42
+ conf = rmol.GetConformer()
43
+ p = conf.GetAtomPosition(i)
44
+ coordinates[i] = [p.x, p.y, p.z]
45
+
46
+ # 键
47
+ bonds = []
48
+ for bond in rmol.GetBonds():
49
+ begin = bond.GetBeginAtomIdx()
50
+ end = bond.GetEndAtomIdx()
51
+ order = int(bond.GetBondTypeAsDouble())
52
+ bonds.append((begin, end, order))
53
+
54
+ return RenderSnapshot(
55
+ atom_ids=atom_ids,
56
+ atomic_numbers=atomic_numbers,
57
+ bonds=bonds,
58
+ coordinates=coordinates,
59
+ mode=mode,
60
+ )
@@ -0,0 +1,119 @@
1
+ """
2
+ rendering/contracts.py - 渲染器抽象接口(支持逐原子/逐键独立大小与颜色控制,兼容 bond_scales / bond_widths)
3
+ ==============================================================================================================
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from abc import ABC, abstractmethod
9
+ from dataclasses import dataclass
10
+ from enum import Enum
11
+ from typing import Any, Sequence
12
+
13
+ import numpy as np
14
+
15
+ from ..domain.document import MoleculeDocument
16
+ from ..domain.ids import AtomId, BondId
17
+
18
+
19
+ class RepresentationMode(Enum):
20
+ """分子表示模式。"""
21
+ BALL_AND_STICK = "ball_stick" # 球棍模型
22
+ STICK = "stick" # 棍状模型 (Licorice)
23
+ CPK = "cpk" # CPK 大球
24
+ LINE = "line" # 细线框 (Wireframe)
25
+ SURFACE = "surface" # 分子表面
26
+ CARTOON = "cartoon" # 卡通/飘带(蛋白质)
27
+ SPACE_FILL = "space_fill" # 空间填充
28
+
29
+
30
+ @dataclass
31
+ class RenderSnapshot:
32
+ """
33
+ 渲染快照:从 domain 提取的只读数据,传给渲染器。
34
+ 同时支持 atom_scales / atom_colors 与 bond_scales / bond_widths / bond_colors。
35
+ """
36
+ atom_ids: list[AtomId]
37
+ atomic_numbers: np.ndarray # shape (N,)
38
+ bonds: list[tuple[int, int, int]] # (begin_idx, end_idx, order)
39
+ coordinates: np.ndarray # shape (N, 3),单位 Å
40
+
41
+ mode: RepresentationMode = RepresentationMode.BALL_AND_STICK
42
+
43
+ selected_atoms: set[AtomId] | None = None
44
+ selected_bonds: set[BondId] | None = None
45
+ bond_ids: list[BondId] | None = None
46
+ measure_chain: list[AtomId] | tuple[AtomId, ...] | None = None
47
+
48
+ atom_scales: dict[Any, float] | list[float] | np.ndarray | None = None
49
+ atom_colors: dict[Any, tuple[float, float, float]] | None = None
50
+
51
+ atom_opacities: list[float] | None = None
52
+ atom_glows: dict[int, tuple[float, float, float, float]] | None = None
53
+
54
+ bond_scales: dict[Any, float] | list[float] | np.ndarray | None = None
55
+ bond_widths: dict[Any, float] | list[float] | np.ndarray | None = None
56
+ bond_colors: dict[Any, tuple[float, float, float]] | None = None
57
+
58
+ show_hydrogens: bool = True
59
+ show_bonds: bool = True
60
+ show_labels: bool = False
61
+ show_symbols: bool = False
62
+ show_axes: bool = True
63
+ color_scheme: str = "Default Scheme"
64
+ cell_matrix: np.ndarray | None = None # 可选晶胞向量矩阵,行为 a/b/c 矢量
65
+ cell_origin: np.ndarray | None = None # 晶胞原点平移偏移(使居中后分子仍位于晶胞内部)
66
+
67
+ def __post_init__(self) -> None:
68
+ if self.bond_scales is None and self.bond_widths is not None:
69
+ self.bond_scales = self.bond_widths
70
+ elif self.bond_widths is None and self.bond_scales is not None:
71
+ self.bond_widths = self.bond_scales
72
+
73
+ @property
74
+ def num_atoms(self) -> int:
75
+ return len(self.atom_ids)
76
+
77
+
78
+ class Renderer3D(ABC):
79
+ """3D 渲染器抽象基类。"""
80
+
81
+ @abstractmethod
82
+ def attach(self, widget: Any) -> None:
83
+ ...
84
+
85
+ @abstractmethod
86
+ def set_snapshot(self, snapshot: RenderSnapshot) -> None:
87
+ ...
88
+
89
+ @abstractmethod
90
+ def update_coordinates(self, coordinates: np.ndarray) -> None:
91
+ ...
92
+
93
+ @abstractmethod
94
+ def set_mode(self, mode: RepresentationMode) -> None:
95
+ ...
96
+
97
+ @abstractmethod
98
+ def set_selection(
99
+ self,
100
+ selected: set[AtomId],
101
+ selected_bonds: set[BondId] | None = None,
102
+ measure_chain: Sequence[AtomId] | None = None,
103
+ ) -> None:
104
+ ...
105
+
106
+ @abstractmethod
107
+ def reset_camera(self) -> None:
108
+ ...
109
+
110
+ @abstractmethod
111
+ def export_image(self, path: str, width: int = 1920, height: int = 1080) -> None:
112
+ ...
113
+
114
+ @abstractmethod
115
+ def render(self) -> None:
116
+ ...
117
+
118
+ def set_material_preset(self, preset_name: str) -> None:
119
+ pass