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,279 @@
1
+ """
2
+ True per-object VTK rendering for MolForge v4.
3
+
4
+ Two persistent, batched vtkGlyph3DMapper actors (atoms and bonds), not one actor
5
+ per atom. The VTK arrays are created from the Domain's stable AtomId/BondId
6
+ styles. Selection is a tint on the *actual atom glyph*, never a fake overlaid
7
+ sphere. No QWidget, Qt event loop or WebEngine import is needed by this module.
8
+
9
+ Atoms: unit sphere scaled by one float radius per AtomId.
10
+ Bonds: unit cylinder along +X, oriented along each bond and scaled by
11
+ (length, radius, radius). Double/triple bonds use parallel cylinders; an
12
+ aromatic bond is represented by two lanes as a visual approximation (its
13
+ aromatic *chemical* semantics stay in Domain).
14
+
15
+ This backend is appropriate for small/medium molecules. Benchmarks/LOD are
16
+ still required before claiming million-atom performance.
17
+ """
18
+ from __future__ import annotations
19
+
20
+ from dataclasses import dataclass
21
+ import math
22
+ from typing import Mapping
23
+ import numpy as np
24
+
25
+ try:
26
+ import vtk
27
+ from vtk.util import numpy_support
28
+ except ImportError: # Pure NumPy preparation can still be validated.
29
+ vtk = None
30
+ numpy_support = None
31
+
32
+ BASE_VDW_RADII = {1: 1.10, 5: 1.80, 6: 1.70, 7: 1.55, 8: 1.52,
33
+ 9: 1.47, 14: 2.10, 15: 1.80, 16: 1.80,
34
+ 17: 1.75, 35: 1.85, 53: 1.98}
35
+ BASE_CPK_COLOR = {
36
+ 1:(0.95,0.97,0.99), 5:(0.96,0.68,0.50), 6:(0.52,0.61,0.70),
37
+ 7:(0.32,0.62,0.98), 8:(0.96,0.36,0.38), 9:(0.36,0.88,0.58),
38
+ 14:(0.82,0.72,0.56), 15:(0.98,0.62,0.26), 16:(0.96,0.82,0.28),
39
+ 17:(0.30,0.84,0.52), 35:(0.68,0.28,0.22), 53:(0.58,0.24,0.68),
40
+ }
41
+ DEFAULT_VDW_RADIUS = 1.60
42
+ DEFAULT_COLOR = (0.60,0.68,0.74)
43
+ SELECTED_COLOR = (1.00,0.87,0.40)
44
+ DEFAULT_BOND_COLOR = (0.62,0.73,0.79)
45
+
46
+ @dataclass(frozen=True)
47
+ class InstanceBuffers:
48
+ atom_positions: np.ndarray
49
+ atom_radii: np.ndarray
50
+ atom_rgb: np.ndarray
51
+ bond_positions: np.ndarray
52
+ bond_directions: np.ndarray
53
+ bond_scales: np.ndarray
54
+ bond_rgb: np.ndarray
55
+ bond_source_indices: np.ndarray
56
+
57
+ def _rgb(value: object) -> np.ndarray:
58
+ arr = np.asarray(value, dtype=np.float64)
59
+ if arr.shape != (3,) or not np.all(np.isfinite(arr)) or np.any(arr < 0) or np.any(arr > 1):
60
+ raise ValueError("RGB must contain three finite color channels in [0,1]")
61
+ return np.rint(arr * 255.0).astype(np.uint8)
62
+
63
+ def _scale(value: object) -> float:
64
+ x = float(value)
65
+ if not math.isfinite(x) or not 0.15 <= x <= 6.0:
66
+ raise ValueError("Per-atom/bond scale must be finite and in [0.15,6]")
67
+ return x
68
+
69
+ def prepare_instances(
70
+ coordinates: np.ndarray,
71
+ atomic_numbers: np.ndarray,
72
+ atom_ids: list,
73
+ bonds: list[tuple[int,int,int]],
74
+ bond_ids: list | None = None,
75
+ atom_scales: Mapping | None = None,
76
+ atom_colors: Mapping | None = None,
77
+ bond_widths: Mapping | None = None,
78
+ bond_colors: Mapping | None = None,
79
+ selected_atoms: set | None = None,
80
+ *,
81
+ mode: str = "ball_stick",
82
+ global_atom_scale: float = 1.0,
83
+ global_bond_scale: float = 1.0,
84
+ ) -> InstanceBuffers:
85
+ """Build typed geometry arrays without VTK side effects.
86
+
87
+ `atom_colors` and `atom_scales` are keyed by *stable AtomId*.
88
+ `bond_colors` and `bond_widths` are keyed by *stable BondId*.
89
+ """
90
+ coords=np.asarray(coordinates, dtype=np.float64)
91
+ nums=np.asarray(atomic_numbers, dtype=np.int32)
92
+ n=len(atom_ids)
93
+ if coords.shape != (n,3) or nums.shape != (n,):
94
+ raise ValueError("RenderSnapshot coordinates/atomic_numbers/AtomIds shapes disagree")
95
+ if not np.all(np.isfinite(coords)):
96
+ raise ValueError("3D coordinates must be finite")
97
+ if np.any(nums < 1) or np.any(nums > 118):
98
+ raise ValueError("unsupported atomic number")
99
+ if bond_ids is not None and len(bond_ids) != len(bonds):
100
+ raise ValueError("bond ID ordering must match bond list")
101
+ if len(set(atom_ids))!=n:
102
+ raise ValueError("duplicate stable AtomId")
103
+ g_atom=_scale(global_atom_scale)
104
+ g_bond=_scale(global_bond_scale)
105
+ atom_scales=atom_scales or {}
106
+ atom_colors=atom_colors or {}
107
+ bond_widths=bond_widths or {}
108
+ bond_colors=bond_colors or {}
109
+ selected_atoms=selected_atoms or set()
110
+ if mode in ("cpk","space_fill"):factor=0.92
111
+ elif mode=="line":factor=0.10
112
+ else:factor=0.25
113
+ radii=np.empty(n,dtype=np.float32)
114
+ colors=np.empty((n,3),dtype=np.uint8)
115
+ for i,aid in enumerate(atom_ids):
116
+ z=int(nums[i])
117
+ radii[i]=BASE_VDW_RADII.get(z,DEFAULT_VDW_RADIUS)*factor*g_atom*_scale(atom_scales.get(aid,1.0))
118
+ actual=atom_colors.get(aid,BASE_CPK_COLOR.get(z,DEFAULT_COLOR))
119
+ if aid in selected_atoms:
120
+ # Selection is a subtle tint of the REAL glyph. The underlying custom
121
+ # RGB remains visible immediately even while the atom is selected.
122
+ actual=0.82*np.asarray(actual,dtype=np.float64)+0.18*np.asarray(SELECTED_COLOR)
123
+ colors[i]=_rgb(actual)
124
+
125
+ pos=[];directions=[];sizes=[];bond_rgb=[];source_index=[]
126
+ for bidx,(i,j,order) in enumerate(bonds):
127
+ if not (isinstance(i,(int,np.integer)) and isinstance(j,(int,np.integer))
128
+ and 0<=i<n and 0<=j<n and i!=j):
129
+ raise ValueError(f"bad bond endpoints at bond index {bidx}")
130
+ if int(order) not in (1,2,3,4):
131
+ raise ValueError("invalid bond order")
132
+ p1,p2=coords[int(i)],coords[int(j)]
133
+ vector=p2-p1
134
+ length=float(np.linalg.norm(vector))
135
+ if length<1e-6:
136
+ continue # Degenerate geometry is not drawable; topology remains untouched.
137
+ direction=vector/length
138
+ normal=np.cross(direction,np.array([0.,0.,1.]))
139
+ if np.linalg.norm(normal)<1e-6:
140
+ normal=np.cross(direction,np.array([0.,1.,0.]))
141
+ normal=normal/float(np.linalg.norm(normal))
142
+ bid=bond_ids[bidx] if bond_ids is not None else bidx
143
+ width=_scale(bond_widths.get(bid,1.0))
144
+ radius=(0.060 if mode=="line" else 0.085)*g_bond*width
145
+ rgb=_rgb(bond_colors.get(bid,DEFAULT_BOND_COLOR))
146
+ lanes={1:(0.,),2:(-0.10,+0.10),3:(-0.16,0.,+0.16),4:(-0.10,+0.10)}[int(order)]
147
+ for k,offset in enumerate(lanes):
148
+ pos.append((p1+p2)*0.5+normal*offset)
149
+ directions.append(direction)
150
+ sizes.append((length,radius*2.,radius*2.))
151
+ bond_rgb.append(rgb)
152
+ source_index.append(bidx)
153
+ m=len(pos)
154
+ def array(values,shape,dtype):
155
+ return np.ascontiguousarray(np.asarray(values,dtype=dtype).reshape(shape))
156
+ return InstanceBuffers(
157
+ atom_positions=array(coords,(n,3),np.float32),
158
+ atom_radii=np.ascontiguousarray(radii),
159
+ atom_rgb=np.ascontiguousarray(colors),
160
+ bond_positions=array(pos,(m,3),np.float32),
161
+ bond_directions=array(directions,(m,3),np.float32),
162
+ bond_scales=array(sizes,(m,3),np.float32),
163
+ bond_rgb=array(bond_rgb,(m,3),np.uint8),
164
+ bond_source_indices=array(source_index,(m,),np.int32),
165
+ )
166
+
167
+ def _set_array(poly, name:str, values:np.ndarray, *, scalars:bool=False):
168
+ vtka=numpy_support.numpy_to_vtk(np.ascontiguousarray(values),deep=True)
169
+ vtka.SetName(name)
170
+ if scalars:
171
+ poly.GetPointData().SetScalars(vtka)
172
+ else:
173
+ poly.GetPointData().AddArray(vtka)
174
+ return vtka
175
+
176
+ class GlyphMoleculeScene:
177
+ """Persistent two-actor VTK batching with true per-atom and per-bond style."""
178
+
179
+ def __init__(self, renderer):
180
+ if vtk is None:
181
+ raise RuntimeError("vtk is required for GlyphMoleculeScene")
182
+ self.renderer=renderer
183
+ self.atoms=vtk.vtkPolyData()
184
+ self.bonds=vtk.vtkPolyData()
185
+ self.atom_mapper=self._build_atom_mapper()
186
+ self.bond_mapper=self._build_bond_mapper()
187
+ self.atom_actor=vtk.vtkActor()
188
+ self.atom_actor.SetMapper(self.atom_mapper)
189
+ self.bond_actor=vtk.vtkActor()
190
+ self.bond_actor.SetMapper(self.bond_mapper)
191
+ for actor in (self.atom_actor,self.bond_actor):
192
+ actor.SetPickable(False) # stable ID pick uses backend math and same instance radii.
193
+ prop=actor.GetProperty()
194
+ prop.SetInterpolationToPhong()
195
+ prop.SetAmbient(0.25)
196
+ prop.SetDiffuse(0.76)
197
+ prop.SetSpecular(0.38)
198
+ prop.SetSpecularPower(38.0)
199
+ renderer.AddActor(actor)
200
+ self.buffers=None
201
+
202
+ def _build_atom_mapper(self):
203
+ source=vtk.vtkSphereSource()
204
+ source.SetRadius(1.0)
205
+ source.SetThetaResolution(20)
206
+ source.SetPhiResolution(16)
207
+ self.atom_source=source
208
+ mapper=vtk.vtkGlyph3DMapper()
209
+ mapper.SetSourceConnection(source.GetOutputPort())
210
+ mapper.SetInputData(self.atoms)
211
+ mapper.ScalingOn()
212
+ mapper.SetScaleArray("mf_atom_radius")
213
+ mapper.SetScaleModeToScaleByMagnitude()
214
+ mapper.SetScaleFactor(1.0)
215
+ mapper.SetColorModeToDirectScalars()
216
+ mapper.SetScalarModeToUsePointFieldData()
217
+ mapper.SelectColorArray("mf_rgb")
218
+ mapper.ScalarVisibilityOn()
219
+ return mapper
220
+
221
+ def _build_bond_mapper(self):
222
+ cylinder=vtk.vtkCylinderSource()
223
+ cylinder.SetRadius(1.0)
224
+ cylinder.SetHeight(1.0)
225
+ cylinder.SetResolution(14)
226
+ cylinder.CappingOn()
227
+ transform=vtk.vtkTransform()
228
+ transform.RotateZ(-90.0) # cylinder intrinsic +Y becomes +X
229
+ apply=vtk.vtkTransformFilter()
230
+ apply.SetTransform(transform)
231
+ apply.SetInputConnection(cylinder.GetOutputPort())
232
+ self.bond_source=cylinder
233
+ self.bond_source_transform=apply
234
+ mapper=vtk.vtkGlyph3DMapper()
235
+ mapper.SetSourceConnection(apply.GetOutputPort())
236
+ mapper.SetInputData(self.bonds)
237
+ mapper.ScalingOn()
238
+ mapper.SetScaleArray("mf_bond_xyz_scale")
239
+ mapper.SetScaleModeToScaleByVectorComponents()
240
+ mapper.SetOrientationArray("mf_bond_axis")
241
+ mapper.SetOrientationModeToDirection()
242
+ mapper.SetColorModeToDirectScalars()
243
+ mapper.SetScalarModeToUsePointFieldData()
244
+ mapper.SelectColorArray("mf_rgb")
245
+ mapper.ScalarVisibilityOn()
246
+ return mapper
247
+
248
+ @staticmethod
249
+ def _load_polydata(poly, xyz:np.ndarray, scale:np.ndarray, rgb:np.ndarray,
250
+ scale_name:str, axis:np.ndarray | None=None):
251
+ pts=vtk.vtkPoints()
252
+ pts.SetData(numpy_support.numpy_to_vtk(np.ascontiguousarray(xyz),deep=True))
253
+ poly.SetPoints(pts)
254
+ poly.GetPointData().Initialize()
255
+ _set_array(poly,scale_name,scale)
256
+ _set_array(poly,"mf_rgb",rgb,scalars=True)
257
+ if axis is not None:
258
+ _set_array(poly,"mf_bond_axis",axis)
259
+ poly.Modified()
260
+
261
+ def update(self,buffers:InstanceBuffers):
262
+ self.buffers=buffers
263
+ self._load_polydata(self.atoms,buffers.atom_positions,buffers.atom_radii,
264
+ buffers.atom_rgb,"mf_atom_radius")
265
+ self._load_polydata(self.bonds,buffers.bond_positions,buffers.bond_scales,
266
+ buffers.bond_rgb,"mf_bond_xyz_scale",buffers.bond_directions)
267
+ self.atom_mapper.Modified()
268
+ self.bond_mapper.Modified()
269
+
270
+ def set_material(self, *,roughness:float=None, metallic:float=None):
271
+ for actor in (self.atom_actor,self.bond_actor):
272
+ prop=actor.GetProperty()
273
+ if roughness is not None:
274
+ value=max(.05,min(.95,float(roughness)))
275
+ prop.SetSpecular(max(.1,1.-value))
276
+ prop.SetSpecularPower(max(10.,(1.-value)*65.))
277
+ if metallic is not None:
278
+ value=max(0.,min(1.,float(metallic)))
279
+ prop.SetAmbient(.22+.28*value)
@@ -0,0 +1,131 @@
1
+ """
2
+ rendering/ketcher_bridge.py - Ketcher 2D 编辑器桥接
3
+ ====================================================
4
+ 基于 QWebEngineView + Ketcher 的离线 2D 编辑器。
5
+
6
+ Ketcher 是一款开源的 Web 端化学结构编辑器。
7
+ 官方网站:https://github.com/epam/ketcher
8
+ """
9
+ from __future__ import annotations
10
+
11
+ from pathlib import Path
12
+ from typing import Callable
13
+
14
+ from PyQt6.QtCore import QObject, pyqtSlot, QUrl
15
+ from PyQt6.QtWidgets import QWidget, QVBoxLayout
16
+
17
+ # WebEngine 可能因 DLL 缺失加载失败,优雅降级
18
+ _WEBENGINE_AVAILABLE = False
19
+ try:
20
+ from PyQt6.QtWebEngineWidgets import QWebEngineView
21
+ from PyQt6.QtWebChannel import QWebChannel
22
+ _WEBENGINE_AVAILABLE = True
23
+ except ImportError:
24
+ QWebEngineView = None
25
+ QWebChannel = None
26
+
27
+
28
+ def is_ketcher_available() -> bool:
29
+ """检查 Ketcher 是否可用。"""
30
+ return _WEBENGINE_AVAILABLE
31
+
32
+
33
+ class _KetcherBridge(QObject):
34
+ """Python ↔ Ketcher JS 桥接对象。"""
35
+
36
+ def __init__(
37
+ self,
38
+ on_ready: Callable[[], None],
39
+ on_change: Callable[[str], None],
40
+ on_error: Callable[[str], None],
41
+ ):
42
+ super().__init__()
43
+ self._on_ready = on_ready
44
+ self._on_change = on_change
45
+ self._on_error = on_error
46
+
47
+ @pyqtSlot()
48
+ def onReady(self):
49
+ """Ketcher 初始化完成。"""
50
+ self._on_ready()
51
+
52
+ @pyqtSlot(str)
53
+ def onMolfileChanged(self, molfile: str):
54
+ """分子结构改变。"""
55
+ self._on_change(molfile)
56
+
57
+ @pyqtSlot(str)
58
+ def onError(self, message: str):
59
+ """错误回调。"""
60
+ self._on_error(message)
61
+
62
+
63
+ class KetcherWidget(QWidget):
64
+ """
65
+ Ketcher 2D 编辑器组件。
66
+
67
+ 用法:
68
+ widget = KetcherWidget()
69
+ widget.load_molfile("C1=CC=CC=C1") # 加载苯环
70
+ molfile = widget.get_molfile() # 获取 MOL 文件
71
+ """
72
+
73
+ def __init__(self, parent=None):
74
+ super().__init__(parent)
75
+ self._view = None
76
+ self._bridge = None
77
+ self._ready = False
78
+
79
+ layout = QVBoxLayout(self)
80
+ layout.setContentsMargins(0, 0, 0, 0)
81
+
82
+ if _WEBENGINE_AVAILABLE:
83
+ self._view = QWebEngineView()
84
+ layout.addWidget(self._view)
85
+
86
+ # WebChannel
87
+ self._channel = QWebChannel()
88
+ self._bridge = _KetcherBridge(
89
+ on_ready=self._on_ready,
90
+ on_change=self._on_change,
91
+ on_error=self._on_error,
92
+ )
93
+ self._channel.registerObject("pyBridge", self._bridge)
94
+ self._view.page().setWebChannel(self._channel)
95
+
96
+ # 加载本地 Ketcher HTML
97
+ html_path = Path(__file__).parent / "assets" / "ketcher" / "index.html"
98
+ if html_path.exists():
99
+ self._view.setUrl(QUrl.fromLocalFile(str(html_path)))
100
+ else:
101
+ # TODO: 显示占位符
102
+ pass
103
+
104
+ def _on_ready(self):
105
+ """Ketcher 初始化完成。"""
106
+ self._ready = True
107
+
108
+ def _on_change(self, molfile: str):
109
+ """分子结构改变。"""
110
+ pass
111
+
112
+ def _on_error(self, message: str):
113
+ """错误。"""
114
+ print(f"Ketcher 错误: {message}")
115
+
116
+ def load_molfile(self, molfile: str):
117
+ """加载 MOL 文件。"""
118
+ if not self._ready or self._view is None:
119
+ return
120
+ js_code = f"ketcher.setMolecule(`{molfile}`)"
121
+ self._view.page().runJavaScript(js_code)
122
+
123
+ def get_molfile(self, callback: Callable[[str], None]):
124
+ """获取 MOL 文件。"""
125
+ if not self._ready or self._view is None:
126
+ callback("")
127
+ return
128
+ self._view.page().runJavaScript(
129
+ "ketcher.getMolfile()",
130
+ callback,
131
+ )
@@ -0,0 +1,110 @@
1
+ """
2
+ rendering/ketcher_id_mapping.py - Ketcher 原子 ID 映射
3
+ ========================================================
4
+ 将 Ketcher 的原子索引映射到内部稳定的 AtomId。
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from dataclasses import dataclass, field
9
+ from typing import Any
10
+ from ..domain.ids import AtomId
11
+
12
+
13
+ @dataclass
14
+ class IdMapping:
15
+ """ID 映射表。"""
16
+ # ketcher_index -> atom_id
17
+ index_to_atom: dict[int, AtomId] = field(default_factory=dict)
18
+ # atom_id -> ketcher_index
19
+ atom_to_index: dict[AtomId, int] = field(default_factory=dict)
20
+
21
+ def add(self, index: int, atom_id: AtomId):
22
+ """添加映射。"""
23
+ self.index_to_atom[index] = atom_id
24
+ self.atom_to_index[atom_id] = index
25
+
26
+ def remove_by_index(self, index: int):
27
+ """按索引删除映射。"""
28
+ if index in self.index_to_atom:
29
+ atom_id = self.index_to_atom[index]
30
+ del self.index_to_atom[index]
31
+ if atom_id in self.atom_to_index:
32
+ del self.atom_to_index[atom_id]
33
+
34
+ def remove_by_atom(self, atom_id: AtomId):
35
+ """按原子 ID 删除映射。"""
36
+ if atom_id in self.atom_to_index:
37
+ index = self.atom_to_index[atom_id]
38
+ del self.atom_to_index[atom_id]
39
+ if index in self.index_to_atom:
40
+ del self.index_to_atom[index]
41
+
42
+ def get_atom_id(self, index: int) -> AtomId | None:
43
+ """通过索引获取原子 ID。"""
44
+ return self.index_to_atom.get(index)
45
+
46
+ def get_index(self, atom_id: AtomId) -> int | None:
47
+ """通过原子 ID 获取索引。"""
48
+ return self.atom_to_index.get(atom_id)
49
+
50
+ def clear(self):
51
+ """清空映射。"""
52
+ self.index_to_atom.clear()
53
+ self.atom_to_index.clear()
54
+
55
+
56
+ class AtomIdMapper:
57
+ """
58
+ 原子 ID 映射器。
59
+
60
+ 负责将 Ketcher 编辑器中的原子索引映射到内部稳定的 AtomId。
61
+ 支持局部增删和重新加载时的重映射。
62
+ """
63
+
64
+ def __init__(self):
65
+ self.mapping = IdMapping()
66
+ self._next_index: int = 0
67
+
68
+ def rebuild(self, atoms: list[Any]):
69
+ """
70
+ 重建映射表。
71
+
72
+ Args:
73
+ atoms: 原子列表,每个原子有 atom_id 属性
74
+ """
75
+ self.mapping.clear()
76
+ for i, atom in enumerate(atoms):
77
+ atom_id = getattr(atom, 'atom_id', None)
78
+ if atom_id is None:
79
+ # 如果没有 atom_id,创建一个
80
+ atom_id = AtomId()
81
+ self.mapping.add(i, atom_id)
82
+ self._next_index = len(atoms)
83
+
84
+ def add_atom(self, atom_id: AtomId) -> int:
85
+ """添加新原子,返回新索引。"""
86
+ index = self._next_index
87
+ self._next_index += 1
88
+ self.mapping.add(index, atom_id)
89
+ return index
90
+
91
+ def remove_atom_by_index(self, index: int):
92
+ """按索引删除原子。"""
93
+ self.mapping.remove_by_index(index)
94
+
95
+ def remove_atom_by_id(self, atom_id: AtomId):
96
+ """按原子 ID 删除原子。"""
97
+ self.mapping.remove_by_atom(atom_id)
98
+
99
+ def get_atom_id(self, index: int) -> AtomId | None:
100
+ """通过索引获取原子 ID。"""
101
+ return self.mapping.get_atom_id(index)
102
+
103
+ def get_index(self, atom_id: AtomId) -> int | None:
104
+ """通过原子 ID 获取索引。"""
105
+ return self.mapping.get_index(atom_id)
106
+
107
+ @property
108
+ def num_atoms(self) -> int:
109
+ """原子数量。"""
110
+ return len(self.mapping.index_to_atom)
@@ -0,0 +1,127 @@
1
+ """
2
+ rendering/materials.py - 材质预设
3
+ =====================================
4
+ 两套视觉预设:
5
+ - Scientific:精确、克制、颜色可辨,适合科研和论文
6
+ - Studio:柔和高光、真实阴影、精美材质,适合展示和封面
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from dataclasses import dataclass, field
12
+
13
+
14
+ @dataclass
15
+ class MaterialPreset:
16
+ """材质预设配置。"""
17
+ name: str
18
+ # 背景
19
+ background_top: tuple[float, float, float] = (0.95, 0.96, 0.98)
20
+ background_bottom: tuple[float, float, float] = (0.88, 0.90, 0.94)
21
+
22
+ # 光照
23
+ key_light_color: tuple[float, float, float] = (1.0, 0.95, 0.85)
24
+ key_light_intensity: float = 1.0
25
+ fill_light_color: tuple[float, float, float] = (0.80, 0.88, 1.0)
26
+ fill_light_intensity: float = 0.6
27
+ rim_light_color: tuple[float, float, float] = (1.0, 1.0, 1.0)
28
+ rim_light_intensity: float = 0.4
29
+
30
+ # 材质
31
+ metallic: float = 0.0
32
+ roughness: float = 0.42
33
+ ao_enabled: bool = True
34
+ ssao_radius: float = 0.55
35
+ tonemap_enabled: bool = True
36
+ fxaa_enabled: bool = True
37
+
38
+ # 元素配色(CPK 风格)
39
+ element_colors: dict[int, tuple[float, float, float]] = field(default_factory=dict)
40
+
41
+
42
+ # Scientific 预设:论文风格,清晰克制
43
+ ScientificPreset = MaterialPreset(
44
+ name="Scientific",
45
+ background_top=(0.96, 0.97, 0.99),
46
+ background_bottom=(0.90, 0.92, 0.95),
47
+ key_light_intensity=1.1,
48
+ fill_light_intensity=0.5,
49
+ rim_light_intensity=0.3,
50
+ roughness=0.5,
51
+ ssao_radius=0.4,
52
+ element_colors={
53
+ 1: (0.90, 0.90, 0.90), # H 浅灰
54
+ 6: (0.30, 0.35, 0.40), # C 深石墨
55
+ 7: (0.25, 0.40, 0.80), # N 蓝
56
+ 8: (0.80, 0.25, 0.25), # O 红
57
+ 9: (0.40, 0.70, 0.40), # F 绿
58
+ 15: (0.90, 0.60, 0.20), # P 橙
59
+ 16: (0.85, 0.75, 0.20), # S 黄
60
+ 17: (0.30, 0.65, 0.35), # Cl 绿
61
+ },
62
+ )
63
+
64
+ # Studio 预设:展示风格,柔和精美(按设计令牌)
65
+ StudioPreset = MaterialPreset(
66
+ name="Studio",
67
+ # 3D 背景:蓝灰色渐变(参考设计稿)
68
+ background_top=(0.376, 0.486, 0.573), # #607C92
69
+ background_bottom=(0.133, 0.224, 0.306), # #22394E
70
+ # 光照
71
+ key_light_color=(1.0, 0.95, 0.85),
72
+ key_light_intensity=1.3,
73
+ fill_light_color=(0.75, 0.85, 1.0),
74
+ fill_light_intensity=0.7,
75
+ rim_light_color=(1.0, 1.0, 1.0),
76
+ rim_light_intensity=0.6,
77
+ # 材质
78
+ metallic=0.05,
79
+ roughness=0.32,
80
+ ao_enabled=True,
81
+ ssao_radius=0.65,
82
+ tonemap_enabled=True,
83
+ fxaa_enabled=True,
84
+ # 元素配色(按设计令牌 chemistry_colors_dark)
85
+ element_colors={
86
+ 1: (0.953, 0.961, 0.949), # H #F3F5F2
87
+ 6: (0.463, 0.545, 0.620), # C #768B9E
88
+ 7: (0.353, 0.612, 0.949), # N #5A9CF2
89
+ 8: (0.949, 0.467, 0.471), # O #F27778
90
+ 9: (0.400, 0.800, 0.550), # F
91
+ 15: (0.933, 0.682, 0.404), # P #EEAE67
92
+ 16: (0.957, 0.808, 0.427), # S #F4CE6D
93
+ 17: (0.400, 0.800, 0.569), # Cl #66CC91
94
+ },
95
+ )
96
+
97
+ # Analysis 预设:分析风格,高性能(用于大分子)
98
+ AnalysisPreset = MaterialPreset(
99
+ name="Analysis",
100
+ # 深色背景,减少视觉干扰
101
+ background_top=(0.1, 0.1, 0.12),
102
+ background_bottom=(0.05, 0.05, 0.08),
103
+ # 光照:简化,提高性能
104
+ key_light_color=(1.0, 1.0, 1.0),
105
+ key_light_intensity=1.0,
106
+ fill_light_color=(0.8, 0.8, 0.9),
107
+ fill_light_intensity=0.3,
108
+ rim_light_intensity=0.0, # 关闭轮廓光
109
+ # 材质:关闭高级效果,提高性能
110
+ metallic=0.0,
111
+ roughness=0.6, # 更粗糙,减少高光计算
112
+ ao_enabled=False, # 关闭 SSAO
113
+ ssao_radius=0.0,
114
+ tonemap_enabled=False, # 关闭色调映射
115
+ fxaa_enabled=False, # 关闭抗锯齿
116
+ # 元素配色:高对比度,便于识别
117
+ element_colors={
118
+ 1: (0.9, 0.9, 0.9),
119
+ 6: (0.6, 0.6, 0.6),
120
+ 7: (0.3, 0.5, 1.0),
121
+ 8: (1.0, 0.3, 0.3),
122
+ 9: (0.3, 0.8, 0.3),
123
+ 15: (1.0, 0.6, 0.2),
124
+ 16: (1.0, 0.9, 0.2),
125
+ 17: (0.2, 0.8, 0.4),
126
+ },
127
+ )