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.
- main.py +71 -0
- molforge/__init__.py +19 -0
- molforge/ai/__init__.py +15 -0
- molforge/ai/deepseek_harness.py +185 -0
- molforge/ai/mcp/desktop_client.py +38 -0
- molforge/ai/mcp/desktop_service.py +121 -0
- molforge/ai/mcp/mcp_server.py +780 -0
- molforge/ai/mcp_bridge.py +945 -0
- molforge/ai/observation.py +152 -0
- molforge/ai/tools.py +455 -0
- molforge/application/__init__.py +22 -0
- molforge/application/ai/__init__.py +1 -0
- molforge/application/ai/deepseek_client.py +293 -0
- molforge/application/ai/observation.py +161 -0
- molforge/application/ai/tools.py +200 -0
- molforge/application/ai_proposals.py +166 -0
- molforge/application/bio_selection.py +143 -0
- molforge/application/builtin_commands.py +1445 -0
- molforge/application/calculators/__init__.py +10 -0
- molforge/application/calculators/base.py +143 -0
- molforge/application/calculators/calchem_engine.py +67 -0
- molforge/application/calculators/calchem_subprocess_worker.py +109 -0
- molforge/application/calculators/gaussian_engine.py +59 -0
- molforge/application/calculators/gaussian_job_spec.py +240 -0
- molforge/application/calculators/orca_engine.py +92 -0
- molforge/application/calculators/qc_input_generator.py +300 -0
- molforge/application/calculators/registry.py +29 -0
- molforge/application/calculators/rest_engine.py +262 -0
- molforge/application/command_bus.py +139 -0
- molforge/application/commands.py +55 -0
- molforge/application/conformers.py +143 -0
- molforge/application/document_session.py +156 -0
- molforge/application/events.py +74 -0
- molforge/application/fragment_catalog.py +422 -0
- molforge/application/fragment_commands.py +268 -0
- molforge/application/geometry_commands.py +84 -0
- molforge/application/history.py +105 -0
- molforge/application/internal_coordinates.py +293 -0
- molforge/application/invalidation.py +1174 -0
- molforge/application/jobs.py +185 -0
- molforge/application/measurement.py +167 -0
- molforge/application/measurement_targets.py +264 -0
- molforge/application/modeling_commands.py +61 -0
- molforge/application/plugins.py +197 -0
- molforge/application/ports/editor2d.py +85 -0
- molforge/application/reaction.py +75 -0
- molforge/application/selection.py +164 -0
- molforge/application/selection_commands.py +31 -0
- molforge/application/trajectory.py +120 -0
- molforge/application/trajectory_analysis.py +231 -0
- molforge/application/workspace_registry.py +226 -0
- molforge/core/__init__.py +12 -0
- molforge/core/conformer.py +45 -0
- molforge/core/molecule.py +150 -0
- molforge/core/orbital.py +33 -0
- molforge/core/properties.py +43 -0
- molforge/domain/__init__.py +12 -0
- molforge/domain/biomolecule.py +99 -0
- molforge/domain/chemical_summary.py +129 -0
- molforge/domain/chemistry.py +13 -0
- molforge/domain/coordinate_store.py +164 -0
- molforge/domain/coordination.py +133 -0
- molforge/domain/custom_fragments.py +255 -0
- molforge/domain/document.py +469 -0
- molforge/domain/element_reference.json +598 -0
- molforge/domain/elements.py +188 -0
- molforge/domain/ids.py +58 -0
- molforge/domain/massive_system.py +246 -0
- molforge/domain/periodic.py +116 -0
- molforge/domain/provenance.py +115 -0
- molforge/domain/topology.py +364 -0
- molforge/infrastructure/__init__.py +23 -0
- molforge/infrastructure/hpc/cluster_config.py +122 -0
- molforge/infrastructure/hpc/remote_executor.py +212 -0
- molforge/infrastructure/hpc/slurm_generator.py +93 -0
- molforge/io/__init__.py +35 -0
- molforge/io/calchem_bridge.py +407 -0
- molforge/io/calculators.py +893 -0
- molforge/io/cclib_adapter.py +422 -0
- molforge/io/conformers.py +183 -0
- molforge/io/cube_reader.py +215 -0
- molforge/io/custom_fragments.py +79 -0
- molforge/io/format_matrix.py +157 -0
- molforge/io/gemmi_adapter.py +150 -0
- molforge/io/history_skill.py +46 -0
- molforge/io/mdanalysis_adapter.py +155 -0
- molforge/io/mforge_storage.py +261 -0
- molforge/io/multiwfn_driver.py +614 -0
- molforge/io/openbabel_adapter.py +265 -0
- molforge/io/openbabel_handler.py +33 -0
- molforge/io/rdkit_adapter.py +1865 -0
- molforge/io/readers/__init__.py +10 -0
- molforge/io/readers/cube_reader.py +71 -0
- molforge/io/readers/gjf_reader.py +110 -0
- molforge/io/readers/glog_reader.py +45 -0
- molforge/io/readers/mol2_reader.py +36 -0
- molforge/io/readers/mol_reader.py +56 -0
- molforge/io/readers/pdb_reader.py +39 -0
- molforge/io/readers/smi_reader.py +40 -0
- molforge/io/readers/xyz_reader.py +47 -0
- molforge/io/registry.py +128 -0
- molforge/io/writers/__init__.py +7 -0
- molforge/io/writers/gjf_writer.py +68 -0
- molforge/io/writers/pdb_writer.py +37 -0
- molforge/io/writers/png_writer.py +31 -0
- molforge/io/writers/svg_writer.py +111 -0
- molforge/io/writers/xyz_writer.py +39 -0
- molforge/rendering/__init__.py +21 -0
- molforge/rendering/benchmark.py +121 -0
- molforge/rendering/bridge.py +60 -0
- molforge/rendering/contracts.py +119 -0
- molforge/rendering/glyph_scene.py +279 -0
- molforge/rendering/ketcher_bridge.py +131 -0
- molforge/rendering/ketcher_id_mapping.py +110 -0
- molforge/rendering/materials.py +127 -0
- molforge/rendering/molstar_backend.py +245 -0
- molforge/rendering/native_labels.py +134 -0
- molforge/rendering/orbitals.py +139 -0
- molforge/rendering/vtk_backend.py +2294 -0
- molforge/runtime.py +29 -0
- molforge/server/__init__.py +1 -0
- molforge/server/api_bridge.py +947 -0
- molforge/ui/__init__.py +1 -0
- molforge/ui/assets/caffeine_2d.svg +150 -0
- molforge/ui/assets/caffeine_3d_preview.svg +209 -0
- molforge/ui/assets/caffeine_preview.json +302 -0
- molforge/ui/assets/icons/atom.svg +1 -0
- molforge/ui/assets/icons/bond.svg +1 -0
- molforge/ui/assets/icons/cleanup.svg +1 -0
- molforge/ui/assets/icons/export.svg +1 -0
- molforge/ui/assets/icons/fragments.svg +1 -0
- molforge/ui/assets/icons/history.svg +1 -0
- molforge/ui/assets/icons/jobs.svg +1 -0
- molforge/ui/assets/icons/measure.svg +1 -0
- molforge/ui/assets/icons/molecules.svg +1 -0
- molforge/ui/assets/icons/overview.svg +1 -0
- molforge/ui/assets/icons/ring.svg +1 -0
- molforge/ui/assets/icons/search.svg +1 -0
- molforge/ui/assets/icons/select.svg +1 -0
- molforge/ui/assets/icons/settings.svg +1 -0
- molforge/ui/assets/icons/templates.svg +1 -0
- molforge/ui/assets/molforge_logo.ico +0 -0
- molforge/ui/assets/molforge_logo.png +0 -0
- molforge/ui/atom_labels.py +92 -0
- molforge/ui/bio_structure_dialog.py +57 -0
- molforge/ui/conformer_dialog.py +151 -0
- molforge/ui/dialogs/__init__.py +2 -0
- molforge/ui/dialogs/aim_qtaim_dialog.py +533 -0
- molforge/ui/dialogs/calchem_orbitals_dialog.py +287 -0
- molforge/ui/dialogs/element_fragments.py +130 -0
- molforge/ui/dialogs/gaussian_calculation_setup.py +308 -0
- molforge/ui/dialogs/hpc_job_dialog.py +427 -0
- molforge/ui/dialogs/vibrational_spectrum_dialog.py +381 -0
- molforge/ui/editor2d_widget.py +1803 -0
- molforge/ui/element_picker.py +218 -0
- molforge/ui/gmv_window_manager.py +65 -0
- molforge/ui/gromacs_job_dialog.py +47 -0
- molforge/ui/hotkeys.py +107 -0
- molforge/ui/i18n.py +237 -0
- molforge/ui/live_llm_dialog.py +135 -0
- molforge/ui/llm_config_dialog.py +103 -0
- molforge/ui/modeling_actions.py +176 -0
- molforge/ui/molstar_widget.py +98 -0
- molforge/ui/molstar_window.py +85 -0
- molforge/ui/panels.py +2966 -0
- molforge/ui/qc_result_dialog.py +1924 -0
- molforge/ui/render3d_widget.py +1579 -0
- molforge/ui/scrolling.py +52 -0
- molforge/ui/settings_panel.py +330 -0
- molforge/ui/shells/__init__.py +4 -0
- molforge/ui/shells/base_shell.py +72 -0
- molforge/ui/shells/document_tabs.py +715 -0
- molforge/ui/shells/studio_2d.py +339 -0
- molforge/ui/shells/studio_3d.py +401 -0
- molforge/ui/shells/studio_split.py +370 -0
- molforge/ui/shells/workflow_inputs.py +698 -0
- molforge/ui/theme.py +719 -0
- molforge/ui/trajectory_window.py +333 -0
- molforge/ui/views.py +892 -0
- molforge/ui/vtk_multiview_widget.py +141 -0
- molforge/ui/welcome_window.py +223 -0
- molforge/ui/window.py +3320 -0
- molforge/workflows/__init__.py +25 -0
- molforge/workflows/assets/OSC_MD_workflows/templates/01-MD/delete_solvent.py +216 -0
- molforge/workflows/assets/OSC_MD_workflows/templates/02-RDF/extract_atoms.py +60 -0
- molforge/workflows/assets/OSC_MD_workflows/templates/02-RDF/extract_atoms_example.py +22 -0
- 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
- 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
- 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
- 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
- molforge/workflows/assets/esp-surface-analysis/scripts/compute_descriptors.py +134 -0
- molforge/workflows/assets/esp-surface-analysis/scripts/parse_surfanalysis.py +58 -0
- molforge/workflows/assets/esp-surface-analysis/scripts/plot_esp_hist.py +115 -0
- molforge/workflows/assets/homo-lumo-plot/extract_orb_energy.py +57 -0
- molforge/workflows/assets/homo-lumo-plot/make_level_plot.py +76 -0
- molforge/workflows/assets/homo-lumo-plot/run_pipeline.py +84 -0
- molforge/workflows/assets/osc-energy-level-diagram/scripts/extract_levels.py +60 -0
- molforge/workflows/assets/osc-energy-level-diagram/scripts/make_editable_pptx.py +122 -0
- molforge/workflows/assets/osc-energy-level-diagram/scripts/make_energy_table.py +66 -0
- molforge/workflows/assets/osc-energy-level-diagram/scripts/make_level_lines_diagram.py +148 -0
- molforge/workflows/assets/osc-energy-level-diagram/scripts/make_rectangle_diagram.py +148 -0
- molforge/workflows/assets/osc-energy-level-diagram/scripts/verify_from_log.py +45 -0
- molforge/workflows/dipole_analysis.py +32 -0
- molforge/workflows/esp_surface.py +36 -0
- molforge/workflows/gromacs_submit.py +167 -0
- molforge/workflows/homo_lumo_plot.py +59 -0
- molforge/workflows/igmh_interaction.py +111 -0
- molforge/workflows/md_rdf_analysis.py +134 -0
- molforge/workflows/md_studio.py +255 -0
- molforge/workflows/osc_energy_diagram.py +24 -0
- molforge/workflows/planarity_analysis.py +66 -0
- molforge/workflows/reorganization_energy.py +166 -0
- molforge/workflows/scientific_workflows.py +650 -0
- molforge_studio-7.4.3.dist-info/METADATA +215 -0
- molforge_studio-7.4.3.dist-info/RECORD +219 -0
- molforge_studio-7.4.3.dist-info/WHEEL +5 -0
- molforge_studio-7.4.3.dist-info/entry_points.txt +3 -0
- molforge_studio-7.4.3.dist-info/licenses/LICENSE +93 -0
- molforge_studio-7.4.3.dist-info/top_level.txt +2 -0
|
@@ -0,0 +1,245 @@
|
|
|
1
|
+
"""
|
|
2
|
+
rendering/molstar_backend.py - Mol* 渲染后端
|
|
3
|
+
==============================================
|
|
4
|
+
基于 QWebEngineView + Mol* (WebGL) 的渲染后端。
|
|
5
|
+
实现 Renderer3D 接口,与 VtkRendererBackend 做 A/B 竞选。
|
|
6
|
+
|
|
7
|
+
技术栈:
|
|
8
|
+
- QWebEngineView 嵌入 Mol* 网页
|
|
9
|
+
- QWebChannel 实现 Python ↔ JS 双向通信
|
|
10
|
+
- CDN 加载 Mol* JS(不需要本地安装)
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
from typing import Callable, Sequence
|
|
17
|
+
|
|
18
|
+
from PyQt6.QtCore import QObject, pyqtSlot, QUrl
|
|
19
|
+
|
|
20
|
+
# WebEngine 可能因 DLL 缺失加载失败,优雅降级
|
|
21
|
+
_WEBENGINE_AVAILABLE = False
|
|
22
|
+
try:
|
|
23
|
+
from PyQt6.QtWebEngineWidgets import QWebEngineView
|
|
24
|
+
from PyQt6.QtWebChannel import QWebChannel
|
|
25
|
+
_WEBENGINE_AVAILABLE = True
|
|
26
|
+
except ImportError:
|
|
27
|
+
QWebEngineView = None
|
|
28
|
+
QWebChannel = None
|
|
29
|
+
|
|
30
|
+
from .contracts import Renderer3D, RenderSnapshot, RepresentationMode
|
|
31
|
+
from ..domain.ids import AtomId, BondId
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def is_webengine_available() -> bool:
|
|
35
|
+
"""检查 WebEngine 是否可用(用于 A/B 竞选时判断)。"""
|
|
36
|
+
return _WEBENGINE_AVAILABLE
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
class _PyBridge(QObject):
|
|
40
|
+
"""Python ↔ JS 桥接对象,注册到 WebChannel。"""
|
|
41
|
+
|
|
42
|
+
def __init__(
|
|
43
|
+
self,
|
|
44
|
+
on_atom_click: Callable[[str, int], None],
|
|
45
|
+
on_status: Callable[[str, bool], None],
|
|
46
|
+
on_molecule_loaded: Callable[[int], None],
|
|
47
|
+
):
|
|
48
|
+
super().__init__()
|
|
49
|
+
self._on_atom_click = on_atom_click
|
|
50
|
+
self._on_status = on_status
|
|
51
|
+
self._on_molecule_loaded = on_molecule_loaded
|
|
52
|
+
|
|
53
|
+
@pyqtSlot(str, int)
|
|
54
|
+
def onAtomClicked(self, element: str, atomIndex: int):
|
|
55
|
+
"""JS 端点击原子时调用:传回元素符号和索引。"""
|
|
56
|
+
self._on_atom_click(element, atomIndex)
|
|
57
|
+
|
|
58
|
+
@pyqtSlot(str, bool)
|
|
59
|
+
def onStatus(self, message: str, isError: bool):
|
|
60
|
+
"""JS 端状态日志回调。"""
|
|
61
|
+
self._on_status(message, isError)
|
|
62
|
+
|
|
63
|
+
@pyqtSlot(int)
|
|
64
|
+
def onMoleculeLoaded(self, atomCount: int):
|
|
65
|
+
"""JS 端分子加载完成回调。"""
|
|
66
|
+
self._on_molecule_loaded(atomCount)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
class MolStarRendererBackend(Renderer3D):
|
|
70
|
+
"""
|
|
71
|
+
Mol* 渲染后端(WebGL 路线)。
|
|
72
|
+
|
|
73
|
+
与 VtkRendererBackend 实现同一个接口,用于 A/B 对比测试。
|
|
74
|
+
"""
|
|
75
|
+
|
|
76
|
+
def __init__(self) -> None:
|
|
77
|
+
self._view = None # QWebEngineView
|
|
78
|
+
self._channel = None
|
|
79
|
+
self._bridge = None
|
|
80
|
+
self._mode = RepresentationMode.BALL_AND_STICK
|
|
81
|
+
self._selected: set[AtomId] = set()
|
|
82
|
+
|
|
83
|
+
# 回调
|
|
84
|
+
self._on_atom_click: Callable[[str, int], None] | None = None
|
|
85
|
+
self._on_status: Callable[[str, bool], None] = lambda msg, err: print(f"[Mol*] {'ERROR: ' if err else ''}{msg}")
|
|
86
|
+
self._on_molecule_loaded: Callable[[int], None] = lambda n: print(f"[Mol*] 分子加载完成,{n} 个原子")
|
|
87
|
+
|
|
88
|
+
# 状态
|
|
89
|
+
self._is_initialized = False
|
|
90
|
+
self._atom_count = 0
|
|
91
|
+
|
|
92
|
+
def attach(self, widget) -> None:
|
|
93
|
+
"""把渲染器挂到 QWebEngineView 上。"""
|
|
94
|
+
if not _WEBENGINE_AVAILABLE:
|
|
95
|
+
raise RuntimeError("WebEngine 不可用,无法初始化 Mol* 后端")
|
|
96
|
+
|
|
97
|
+
self._view = QWebEngineView(widget)
|
|
98
|
+
layout = widget.layout()
|
|
99
|
+
if layout is None:
|
|
100
|
+
from PyQt6.QtWidgets import QVBoxLayout
|
|
101
|
+
layout = QVBoxLayout(widget)
|
|
102
|
+
widget.setLayout(layout)
|
|
103
|
+
layout.addWidget(self._view)
|
|
104
|
+
|
|
105
|
+
# 加载 HTML
|
|
106
|
+
html_path = Path(__file__).parent / "molstar_viewer.html"
|
|
107
|
+
self._view.setUrl(QUrl.fromLocalFile(str(html_path)))
|
|
108
|
+
|
|
109
|
+
# 设置 WebChannel
|
|
110
|
+
self._channel = QWebChannel()
|
|
111
|
+
self._bridge = _PyBridge(
|
|
112
|
+
on_atom_click=self._handle_atom_click,
|
|
113
|
+
on_status=self._handle_status,
|
|
114
|
+
on_molecule_loaded=self._handle_molecule_loaded,
|
|
115
|
+
)
|
|
116
|
+
self._channel.registerObject("pybridge", self._bridge)
|
|
117
|
+
self._view.page().setWebChannel(self._channel)
|
|
118
|
+
|
|
119
|
+
def set_snapshot(self, snapshot: RenderSnapshot) -> None:
|
|
120
|
+
"""设置渲染数据:从 snapshot 生成 SDF,发给 JS。"""
|
|
121
|
+
if self._view is None:
|
|
122
|
+
return
|
|
123
|
+
|
|
124
|
+
# 从 snapshot 生成 SDF
|
|
125
|
+
sdf_text = self._snapshot_to_sdf(snapshot)
|
|
126
|
+
self.load_sdf(sdf_text)
|
|
127
|
+
|
|
128
|
+
def _snapshot_to_sdf(self, snapshot: RenderSnapshot) -> str:
|
|
129
|
+
"""把 RenderSnapshot 转成 SDF 字符串。"""
|
|
130
|
+
lines = []
|
|
131
|
+
n = snapshot.num_atoms
|
|
132
|
+
bonds = snapshot.bonds
|
|
133
|
+
|
|
134
|
+
# SDF 头
|
|
135
|
+
lines.append("MolForge snapshot")
|
|
136
|
+
lines.append(" RDKit")
|
|
137
|
+
lines.append("")
|
|
138
|
+
|
|
139
|
+
# 原子计数行
|
|
140
|
+
lines.append(f"{n:3d}{len(bonds):3d} 0 0 0 0 0 0 0 0999 V2000")
|
|
141
|
+
|
|
142
|
+
# 原子坐标
|
|
143
|
+
element_map = {1: 'H', 6: 'C', 7: 'N', 8: 'O', 9: 'F', 15: 'P', 16: 'S', 17: 'Cl'}
|
|
144
|
+
for i in range(n):
|
|
145
|
+
x, y, z = snapshot.coordinates[i]
|
|
146
|
+
elem = element_map.get(int(snapshot.atomic_numbers[i]), 'C')
|
|
147
|
+
lines.append(f" {x:10.4f} {y:10.4f} {z:10.4f} {elem:<3s} 0 0 0 0 0 0 0 0 0 0 0 0")
|
|
148
|
+
|
|
149
|
+
# 键
|
|
150
|
+
for begin, end, order in bonds:
|
|
151
|
+
lines.append(f"{begin+1:3d}{end+1:3d}{order:3d} 0 0 0 0")
|
|
152
|
+
|
|
153
|
+
lines.append("M END")
|
|
154
|
+
lines.append("$$$$")
|
|
155
|
+
|
|
156
|
+
return "\n".join(lines)
|
|
157
|
+
|
|
158
|
+
def load_sdf(self, sdf_text: str) -> None:
|
|
159
|
+
"""直接加载 SDF 字符串。"""
|
|
160
|
+
if self._view is None:
|
|
161
|
+
return
|
|
162
|
+
|
|
163
|
+
# 通过 JS 调用加载
|
|
164
|
+
escaped = sdf_text.replace("\\", "\\\\").replace("'", "\\'").replace("\n", "\\n")
|
|
165
|
+
js = f"loadMoleculeSDF('{escaped}')"
|
|
166
|
+
self._view.page().runJavaScript(js)
|
|
167
|
+
|
|
168
|
+
def update_coordinates(self, coordinates) -> None:
|
|
169
|
+
"""只更新坐标(轨迹播放用)。"""
|
|
170
|
+
# TODO: 实现坐标更新
|
|
171
|
+
pass
|
|
172
|
+
|
|
173
|
+
def set_mode(self, mode: RepresentationMode) -> None:
|
|
174
|
+
"""切换表示模式。"""
|
|
175
|
+
self._mode = mode
|
|
176
|
+
mode_map = {
|
|
177
|
+
RepresentationMode.BALL_AND_STICK: 'ball_and_stick',
|
|
178
|
+
RepresentationMode.CPK: 'cpk',
|
|
179
|
+
RepresentationMode.SURFACE: 'surface',
|
|
180
|
+
RepresentationMode.LINE: 'line',
|
|
181
|
+
}
|
|
182
|
+
js_mode = mode_map.get(mode, 'ball_and_stick')
|
|
183
|
+
self._view.page().runJavaScript(f"setRepresentation('{js_mode}')")
|
|
184
|
+
|
|
185
|
+
def set_selection(
|
|
186
|
+
self,
|
|
187
|
+
selected: set[AtomId],
|
|
188
|
+
selected_bonds: set[BondId] | None = None,
|
|
189
|
+
measure_chain: Sequence[AtomId] | None = None,
|
|
190
|
+
) -> None:
|
|
191
|
+
"""设置选中原子高亮。"""
|
|
192
|
+
self._selected = selected
|
|
193
|
+
# 高亮第一个选中的原子(演示用)
|
|
194
|
+
if selected:
|
|
195
|
+
first_idx = next(iter(selected)).value
|
|
196
|
+
self._view.page().runJavaScript(f"highlightAtom({first_idx})")
|
|
197
|
+
|
|
198
|
+
def highlight_atom(self, atom_index: int) -> None:
|
|
199
|
+
"""高亮指定索引的原子。"""
|
|
200
|
+
self._view.page().runJavaScript(f"highlightAtom({atom_index})")
|
|
201
|
+
|
|
202
|
+
# ---------- 回调注册 ----------
|
|
203
|
+
|
|
204
|
+
def set_atom_click_callback(self, callback: Callable[[str, int], None]) -> None:
|
|
205
|
+
"""注册原子点击回调:接收 (元素符号, 原子索引)。"""
|
|
206
|
+
self._on_atom_click = callback
|
|
207
|
+
|
|
208
|
+
def set_status_callback(self, callback: Callable[[str, bool], None]) -> None:
|
|
209
|
+
"""注册状态日志回调:接收 (消息, 是否错误)。"""
|
|
210
|
+
self._on_status = callback
|
|
211
|
+
|
|
212
|
+
def set_molecule_loaded_callback(self, callback: Callable[[int], None]) -> None:
|
|
213
|
+
"""注册分子加载完成回调:接收 (原子数)。"""
|
|
214
|
+
self._on_molecule_loaded = callback
|
|
215
|
+
|
|
216
|
+
# ---------- 内部处理 ----------
|
|
217
|
+
|
|
218
|
+
def _handle_atom_click(self, element: str, atom_index: int) -> None:
|
|
219
|
+
"""处理 JS 端的原子点击。"""
|
|
220
|
+
if self._on_atom_click:
|
|
221
|
+
self._on_atom_click(element, atom_index)
|
|
222
|
+
|
|
223
|
+
def _handle_status(self, message: str, is_error: bool) -> None:
|
|
224
|
+
"""处理 JS 端的状态日志。"""
|
|
225
|
+
self._on_status(message, is_error)
|
|
226
|
+
|
|
227
|
+
def _handle_molecule_loaded(self, atom_count: int) -> None:
|
|
228
|
+
"""处理分子加载完成。"""
|
|
229
|
+
self._atom_count = atom_count
|
|
230
|
+
self._is_initialized = True
|
|
231
|
+
self._on_molecule_loaded(atom_count)
|
|
232
|
+
|
|
233
|
+
# ---------- 其他 ----------
|
|
234
|
+
|
|
235
|
+
def reset_camera(self) -> None:
|
|
236
|
+
if self._view:
|
|
237
|
+
self._view.page().runJavaScript("resetCamera()")
|
|
238
|
+
|
|
239
|
+
def export_image(self, path: str, width: int = 1920, height: int = 1080) -> None:
|
|
240
|
+
# TODO: Mol* 截图功能
|
|
241
|
+
pass
|
|
242
|
+
|
|
243
|
+
def render(self) -> None:
|
|
244
|
+
# Mol* 自动渲染,不需要手动触发
|
|
245
|
+
pass
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"""World-anchored labels rendered in the same VTK pass as the molecule."""
|
|
2
|
+
import math
|
|
3
|
+
import numpy as np
|
|
4
|
+
import vtk
|
|
5
|
+
from ..domain.elements import get_element
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class NativeAtomLabels:
|
|
9
|
+
def __init__(self, backend, renderer):
|
|
10
|
+
self.backend = backend
|
|
11
|
+
self.renderer = renderer
|
|
12
|
+
self.points = vtk.vtkPoints()
|
|
13
|
+
self.strings = vtk.vtkStringArray(); self.strings.SetName('atom_label')
|
|
14
|
+
self.types = vtk.vtkIntArray(); self.types.SetName('label_style')
|
|
15
|
+
self.data = vtk.vtkPolyData(); self.data.SetPoints(self.points)
|
|
16
|
+
self.data.GetPointData().AddArray(self.strings)
|
|
17
|
+
self.data.GetPointData().AddArray(self.types)
|
|
18
|
+
mapper_type = getattr(vtk,'vtkBatchedLabeledDataMapper',vtk.vtkLabeledDataMapper)
|
|
19
|
+
self.mapper = mapper_type()
|
|
20
|
+
self.mapper.SetInputData(self.data)
|
|
21
|
+
self.mapper.SetLabelModeToLabelFieldData(); self.mapper.SetFieldDataName('atom_label')
|
|
22
|
+
self.mapper.SetInputArrayToProcess(0,0,0,vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS,'label_style')
|
|
23
|
+
if hasattr(self.mapper,'SetTextAnchor'):
|
|
24
|
+
self.mapper.SetTextAnchor(self.mapper.Center)
|
|
25
|
+
self.properties=[]
|
|
26
|
+
for index,color in enumerate(((.03,.035,.04),(.96,.98,1.))):
|
|
27
|
+
prop=vtk.vtkTextProperty();prop.SetColor(*color);prop.SetFontFamilyToArial()
|
|
28
|
+
prop.BoldOff();prop.ShadowOff();prop.SetFontSize(14)
|
|
29
|
+
prop.SetJustificationToCentered();prop.SetVerticalJustificationToCentered()
|
|
30
|
+
self.mapper.SetLabelTextProperty(prop,index);self.properties.append(prop)
|
|
31
|
+
self.actor=vtk.vtkActor2D();self.actor.SetMapper(self.mapper);self.actor.PickableOff()
|
|
32
|
+
self.actor.VisibilityOff()
|
|
33
|
+
self._font=14;self._median_radius=.4;self._max_radius=.4;self.render_frames=0;self.data_updates=0
|
|
34
|
+
self._views=[]
|
|
35
|
+
self.set_views([renderer])
|
|
36
|
+
|
|
37
|
+
def set_views(self, renderers):
|
|
38
|
+
self.close()
|
|
39
|
+
for view_index,renderer in enumerate(renderers):
|
|
40
|
+
window=renderer.GetRenderWindow()
|
|
41
|
+
overlay=None
|
|
42
|
+
mapper=self.mapper if view_index==0 else self.mapper.NewInstance()
|
|
43
|
+
if view_index:
|
|
44
|
+
mapper.SetLabelModeToLabelFieldData();mapper.SetFieldDataName('atom_label')
|
|
45
|
+
mapper.SetInputArrayToProcess(0,0,0,vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS,'label_style')
|
|
46
|
+
if hasattr(mapper,'SetTextAnchor'):mapper.SetTextAnchor(mapper.Center)
|
|
47
|
+
for i,prop in enumerate(self.properties):mapper.SetLabelTextProperty(prop,i)
|
|
48
|
+
actor=self.actor if view_index==0 else vtk.vtkActor2D()
|
|
49
|
+
actor.SetMapper(mapper);actor.PickableOff();actor.SetVisibility(self.actor.GetVisibility())
|
|
50
|
+
visible=None
|
|
51
|
+
if window is not None:
|
|
52
|
+
window.SetNumberOfLayers(max(3,window.GetNumberOfLayers()))
|
|
53
|
+
overlay=vtk.vtkRenderer();overlay.SetLayer(2)
|
|
54
|
+
overlay.SetInteractive(False);overlay.SetPreserveColorBuffer(True)
|
|
55
|
+
overlay.SetPreserveDepthBuffer(False)
|
|
56
|
+
overlay.SetActiveCamera(renderer.GetActiveCamera());overlay.SetViewport(renderer.GetViewport())
|
|
57
|
+
overlay.AddViewProp(actor);window.AddRenderer(overlay)
|
|
58
|
+
visible=vtk.vtkSelectVisiblePoints();visible.SetInputData(self.data)
|
|
59
|
+
visible.SetRenderer(renderer);visible.SetTolerance(0.);visible.SetToleranceWorld(self._max_radius*1.02)
|
|
60
|
+
mapper.SetInputConnection(visible.GetOutputPort())
|
|
61
|
+
else:
|
|
62
|
+
renderer.AddViewProp(actor);mapper.SetInputData(self.data)
|
|
63
|
+
observer=renderer.AddObserver('StartEvent',self._prepare_frame)
|
|
64
|
+
finish=renderer.AddObserver('EndEvent',self._finish_frame)
|
|
65
|
+
self._views.append((renderer,overlay,observer,finish,visible,actor))
|
|
66
|
+
|
|
67
|
+
def close(self):
|
|
68
|
+
for renderer,overlay,observer,finish,visible,actor in getattr(self,'_views',[]):
|
|
69
|
+
renderer.RemoveObserver(observer)
|
|
70
|
+
renderer.RemoveObserver(finish)
|
|
71
|
+
if overlay is not None and overlay.GetRenderWindow() is not None:
|
|
72
|
+
overlay.GetRenderWindow().RemoveRenderer(overlay)
|
|
73
|
+
elif overlay is None:
|
|
74
|
+
renderer.RemoveViewProp(actor)
|
|
75
|
+
self._views=[]
|
|
76
|
+
|
|
77
|
+
def update(self):
|
|
78
|
+
b=self.backend
|
|
79
|
+
if not (b.show_labels or b.show_symbols) or b._coordinates is None or (b._n_atoms > 2000 and b.label_scope != 'selected'):
|
|
80
|
+
self.actor.VisibilityOff()
|
|
81
|
+
for *_,actor in self._views:actor.VisibilityOff()
|
|
82
|
+
return
|
|
83
|
+
self.points.Reset();self.strings.Reset();self.types.Reset()
|
|
84
|
+
scope=b.label_scope;radii=[]
|
|
85
|
+
for i,(position,aid) in enumerate(zip(b._coordinates,b._atom_ids)):
|
|
86
|
+
z=int(b._atomic_numbers[i])
|
|
87
|
+
if z==1 and not b.show_hydrogens:continue
|
|
88
|
+
if scope=='selected' and aid not in b._selected:continue
|
|
89
|
+
if scope=='heavy' and z==1 and aid not in b._selected:continue
|
|
90
|
+
if i<len(b._atom_opacities) and b._atom_opacities[i]<=0:continue
|
|
91
|
+
symbol=get_element(z).symbol if get_element(z) else '?'
|
|
92
|
+
text=(symbol if b.show_symbols else '')+(str(aid.value+1) if b.show_labels else '')
|
|
93
|
+
self.points.InsertNextPoint(*[float(x) for x in position]);self.strings.InsertNextValue(text)
|
|
94
|
+
color=b.get_effective_atom_color(i)
|
|
95
|
+
luminance=.2126*color[0]+.7152*color[1]+.0722*color[2]
|
|
96
|
+
self.types.InsertNextValue(0 if luminance>.32 else 1)
|
|
97
|
+
radii.append(b.get_effective_atom_radius(i))
|
|
98
|
+
self._median_radius=float(np.median(radii)) if radii else .4
|
|
99
|
+
self._max_radius=max(radii,default=.4)
|
|
100
|
+
self.points.Modified();self.strings.Modified();self.types.Modified();self.data.Modified()
|
|
101
|
+
self.actor.SetVisibility(bool(radii))
|
|
102
|
+
for _,_,_,_,visible,actor in self._views:
|
|
103
|
+
actor.SetVisibility(bool(radii))
|
|
104
|
+
if visible is not None:visible.SetToleranceWorld(self._max_radius*1.02)
|
|
105
|
+
self.data_updates+=1
|
|
106
|
+
|
|
107
|
+
def _prepare_frame(self, renderer, event):
|
|
108
|
+
# O(1) camera work only. No per-atom projection, text layout or collision search.
|
|
109
|
+
self.render_frames+=1
|
|
110
|
+
for source,overlay,*_ in self._views:
|
|
111
|
+
if source is renderer and overlay is not None:
|
|
112
|
+
overlay.SetViewport(renderer.GetViewport())
|
|
113
|
+
overlay.SetActiveCamera(renderer.GetActiveCamera())
|
|
114
|
+
if not self.actor.GetVisibility():return
|
|
115
|
+
window=renderer.GetRenderWindow()
|
|
116
|
+
if window is None:return
|
|
117
|
+
camera=renderer.GetActiveCamera();viewport=renderer.GetViewport()
|
|
118
|
+
height=window.GetSize()[1]*(viewport[3]-viewport[1])
|
|
119
|
+
if camera.GetParallelProjection():
|
|
120
|
+
radius_px=height*self._median_radius/(2*max(1e-8,camera.GetParallelScale()))
|
|
121
|
+
else:
|
|
122
|
+
distance=np.linalg.norm(np.asarray(camera.GetPosition())-camera.GetFocalPoint())
|
|
123
|
+
radius_px=height*self._median_radius/(2*max(1e-8,distance)*math.tan(math.radians(camera.GetViewAngle()/2)))
|
|
124
|
+
font=int(np.clip(round(radius_px*.95/2)*2,10,36))
|
|
125
|
+
if font != self._font:
|
|
126
|
+
for prop in self.properties:prop.SetFontSize(font)
|
|
127
|
+
self._font=font
|
|
128
|
+
|
|
129
|
+
def _finish_frame(self, renderer, event):
|
|
130
|
+
# Native C++ depth test of glyph centres after the molecule is rendered.
|
|
131
|
+
if not self.actor.GetVisibility():return
|
|
132
|
+
for source,_,_,_,visible,_ in self._views:
|
|
133
|
+
if source is renderer and visible is not None:
|
|
134
|
+
visible.Modified();visible.Update()
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
"""
|
|
2
|
+
rendering/orbitals.py - 分子轨道等值面渲染
|
|
3
|
+
=============================================
|
|
4
|
+
基于 Cube 文件渲染分子轨道(HOMO/LUMO)和电子密度等值面。
|
|
5
|
+
|
|
6
|
+
特性:
|
|
7
|
+
- 识别 Cube 网格原点/轴/体素维度
|
|
8
|
+
- 等值面提取和相位区分(正/负波函数)
|
|
9
|
+
- 渲染透明体
|
|
10
|
+
- 联动 geometry_ref
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from dataclasses import dataclass
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
import numpy as np
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@dataclass
|
|
21
|
+
class CubeData:
|
|
22
|
+
"""Cube 文件数据。"""
|
|
23
|
+
origin: np.ndarray # (3,) 原点
|
|
24
|
+
axes: np.ndarray # (3, 3) 网格轴向量
|
|
25
|
+
n_voxels: tuple[int, int, int] # 每个轴的体素数
|
|
26
|
+
data: np.ndarray # (nx, ny, nz) 标量场
|
|
27
|
+
atom_coords: np.ndarray # (N, 3) 原子坐标
|
|
28
|
+
atomic_numbers: list[int]
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class CubeParser:
|
|
32
|
+
"""Cube 文件解析器。"""
|
|
33
|
+
|
|
34
|
+
def parse(self, filepath: str | Path) -> CubeData:
|
|
35
|
+
"""
|
|
36
|
+
解析 Cube 文件。
|
|
37
|
+
|
|
38
|
+
Args:
|
|
39
|
+
filepath: .cube 文件路径
|
|
40
|
+
|
|
41
|
+
Returns:
|
|
42
|
+
CubeData
|
|
43
|
+
"""
|
|
44
|
+
filepath = Path(filepath)
|
|
45
|
+
with open(filepath, "r") as f:
|
|
46
|
+
lines = f.readlines()
|
|
47
|
+
|
|
48
|
+
# 前两行是注释
|
|
49
|
+
# 第三行:原子数 + 原点
|
|
50
|
+
line3 = lines[2].split()
|
|
51
|
+
n_atoms = int(line3[0])
|
|
52
|
+
origin = np.array([float(line3[1]), float(line3[2]), float(line3[3])])
|
|
53
|
+
|
|
54
|
+
# 接下来三行:网格轴
|
|
55
|
+
axes = np.zeros((3, 3))
|
|
56
|
+
n_voxels = [0, 0, 0]
|
|
57
|
+
for i in range(3):
|
|
58
|
+
parts = lines[3 + i].split()
|
|
59
|
+
n_voxels[i] = int(parts[0])
|
|
60
|
+
axes[i] = [float(parts[1]), float(parts[2]), float(parts[3])]
|
|
61
|
+
|
|
62
|
+
# 接下来 n_atoms 行:原子信息
|
|
63
|
+
atom_coords = np.zeros((n_atoms, 3))
|
|
64
|
+
atomic_numbers = []
|
|
65
|
+
for i in range(n_atoms):
|
|
66
|
+
parts = lines[6 + i].split()
|
|
67
|
+
atomic_numbers.append(int(parts[0]))
|
|
68
|
+
atom_coords[i] = [float(parts[2]), float(parts[3]), float(parts[4])]
|
|
69
|
+
|
|
70
|
+
# 剩下的是体素数据
|
|
71
|
+
data_start = 6 + n_atoms
|
|
72
|
+
data_values = []
|
|
73
|
+
for line in lines[data_start:]:
|
|
74
|
+
data_values.extend([float(x) for x in line.split()])
|
|
75
|
+
|
|
76
|
+
data = np.array(data_values).reshape(n_voxels[0], n_voxels[1], n_voxels[2])
|
|
77
|
+
|
|
78
|
+
return CubeData(
|
|
79
|
+
origin=origin,
|
|
80
|
+
axes=axes,
|
|
81
|
+
n_voxels=tuple(n_voxels),
|
|
82
|
+
data=data,
|
|
83
|
+
atom_coords=atom_coords,
|
|
84
|
+
atomic_numbers=atomic_numbers,
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class OrbitalRenderer:
|
|
89
|
+
"""
|
|
90
|
+
分子轨道渲染器。
|
|
91
|
+
|
|
92
|
+
用法:
|
|
93
|
+
renderer = OrbitalRenderer()
|
|
94
|
+
renderer.load_cube("homo.cube")
|
|
95
|
+
renderer.set_isovalue(0.05)
|
|
96
|
+
# 然后在 VTK 场景中显示
|
|
97
|
+
"""
|
|
98
|
+
|
|
99
|
+
def __init__(self) -> None:
|
|
100
|
+
self._cube: CubeData | None = None
|
|
101
|
+
self._isovalue = 0.05
|
|
102
|
+
self._positive_color = (0.2, 0.5, 1.0) # 蓝色 = 正相位
|
|
103
|
+
self._negative_color = (1.0, 0.3, 0.3) # 红色 = 负相位
|
|
104
|
+
self._opacity = 0.5
|
|
105
|
+
|
|
106
|
+
def load_cube(self, filepath: str | Path) -> None:
|
|
107
|
+
"""加载 Cube 文件。"""
|
|
108
|
+
parser = CubeParser()
|
|
109
|
+
self._cube = parser.parse(filepath)
|
|
110
|
+
|
|
111
|
+
def set_isovalue(self, value: float) -> None:
|
|
112
|
+
"""设置等值面阈值。"""
|
|
113
|
+
self._isovalue = value
|
|
114
|
+
|
|
115
|
+
def get_positive_grid(self) -> np.ndarray | None:
|
|
116
|
+
"""获取正相位标量场(负值设为 0)。"""
|
|
117
|
+
if self._cube is None:
|
|
118
|
+
return None
|
|
119
|
+
return np.where(self._cube.data > 0, self._cube.data, 0)
|
|
120
|
+
|
|
121
|
+
def get_negative_grid(self) -> np.ndarray | None:
|
|
122
|
+
"""获取负相位标量场(正值设为 0,取绝对值)。"""
|
|
123
|
+
if self._cube is None:
|
|
124
|
+
return None
|
|
125
|
+
return np.where(self._cube.data < 0, -self._cube.data, 0)
|
|
126
|
+
|
|
127
|
+
def get_bounds(self) -> tuple[float, float, float, float, float, float] | None:
|
|
128
|
+
"""获取网格的空间范围。"""
|
|
129
|
+
if self._cube is None:
|
|
130
|
+
return None
|
|
131
|
+
origin = self._cube.origin
|
|
132
|
+
axes = self._cube.axes
|
|
133
|
+
n = self._cube.n_voxels
|
|
134
|
+
end = origin + axes[0] * n[0] + axes[1] * n[1] + axes[2] * n[2]
|
|
135
|
+
return (
|
|
136
|
+
min(origin[0], end[0]), max(origin[0], end[0]),
|
|
137
|
+
min(origin[1], end[1]), max(origin[1], end[1]),
|
|
138
|
+
min(origin[2], end[2]), max(origin[2], end[2]),
|
|
139
|
+
)
|