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,333 @@
1
+ """轨迹播放与动力学动力学分析窗口:MDAnalysis 加载 + VTK 零拷贝流式渲染 + QTimer 播放 + Kabsch RMSD/RMSF。"""
2
+ from __future__ import annotations
3
+
4
+ import csv
5
+ import threading
6
+ from pathlib import Path
7
+ from typing import Optional
8
+
9
+ import numpy as np
10
+ from PyQt6.QtCore import Qt, QTimer, pyqtSignal, QObject
11
+ from PyQt6.QtWidgets import (
12
+ QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QPushButton, QSlider, QLabel,
13
+ QComboBox, QSplitter, QGroupBox, QTableWidget, QTableWidgetItem, QHeaderView,
14
+ QFileDialog, QMessageBox, QProgressBar
15
+ )
16
+ from pyvistaqt import QtInteractor
17
+ import pyvista as pv
18
+
19
+ from molforge.io.mdanalysis_adapter import TrajectoryAdapter
20
+ from molforge.application.trajectory_analysis import (
21
+ kabsch_align, calculate_radius_of_gyration, calculate_trajectory_metrics
22
+ )
23
+
24
+ # 残基类型配色(ACC 给/受体区分)
25
+ _RES_COLORS = {
26
+ "ACC": (0.40, 0.87, 0.79), # 青
27
+ "DON": (0.49, 0.68, 0.98), # 蓝
28
+ "DIO": (0.85, 0.71, 0.47), # 琥珀
29
+ }
30
+
31
+
32
+ class _AnalysisWorker(QObject):
33
+ finished = pyqtSignal(dict)
34
+ error = pyqtSignal(str)
35
+
36
+ def __init__(self, adapter: TrajectoryAdapter, stride: int = 1):
37
+ super().__init__()
38
+ self.adapter = adapter
39
+ self.stride = stride
40
+
41
+ def run(self):
42
+ try:
43
+ res = calculate_trajectory_metrics(self.adapter, ref_frame=0, stride=self.stride)
44
+ self.finished.emit(res)
45
+ except Exception as e:
46
+ self.error.emit(str(e))
47
+
48
+
49
+ class TrajectoryWindow(QMainWindow):
50
+ def __init__(self, topology: str, trajectory: str, name: str = "trajectory", parent=None):
51
+ super().__init__(parent)
52
+ self.setWindowTitle(f"分子动力学轨迹流式播放器 · {name}")
53
+ self.resize(1350, 880)
54
+
55
+ self.adapter = TrajectoryAdapter(topology, trajectory, chunk_size=10, max_chunks=8)
56
+ self.frame = 0
57
+ self.playing = False
58
+ self.ref_coords = self.adapter.get_frame(0)
59
+ self.analysis_data: Optional[dict] = None
60
+
61
+ central = QWidget()
62
+ self.setCentralWidget(central)
63
+ main_layout = QHBoxLayout(central)
64
+ main_layout.setContentsMargins(6, 6, 6, 6)
65
+ main_layout.setSpacing(6)
66
+
67
+ splitter = QSplitter(Qt.Orientation.Horizontal)
68
+ main_layout.addWidget(splitter)
69
+
70
+ # ---------------- 左侧:3D 视图与播放控制 ----------------
71
+ left_widget = QWidget()
72
+ left_layout = QVBoxLayout(left_widget)
73
+ left_layout.setContentsMargins(0, 0, 0, 0)
74
+ left_layout.setSpacing(6)
75
+
76
+ # VTK 视图
77
+ self.plotter = QtInteractor(left_widget)
78
+ self.plotter.set_background([0.06, 0.10, 0.16], top=[0.12, 0.18, 0.26])
79
+ left_layout.addWidget(self.plotter, 1)
80
+
81
+ # 第一帧网格初始化
82
+ self._build_mesh(self.ref_coords)
83
+ self.plotter.reset_camera()
84
+ self.plotter.camera.zoom(1.2)
85
+
86
+ # 控制条
87
+ ctrl = QHBoxLayout()
88
+ self.btn_prev = QPushButton("⏮ 上一帧")
89
+ self.btn_play = QPushButton("▶ 播放")
90
+ self.btn_next = QPushButton("⏭ 下一帧")
91
+ self.btn_prev.clicked.connect(self.prev_frame)
92
+ self.btn_play.clicked.connect(self.toggle_play)
93
+ self.btn_next.clicked.connect(self.next_frame)
94
+ for b in (self.btn_prev, self.btn_play, self.btn_next):
95
+ ctrl.addWidget(b)
96
+
97
+ self.slider = QSlider(Qt.Orientation.Horizontal)
98
+ self.slider.setRange(0, self.adapter.n_frames - 1)
99
+ self.slider.valueChanged.connect(self._slider_frame)
100
+ ctrl.addWidget(self.slider, 1)
101
+
102
+ self.time_label = QLabel()
103
+ self.time_label.setStyleSheet("font-weight: bold; color: #40C4FF; min-width: 160px;")
104
+ ctrl.addWidget(self.time_label)
105
+
106
+ self.speed = QComboBox()
107
+ for label, ms in [("0.5x", 200), ("1x", 100), ("2x", 50), ("4x", 25), ("10x", 10)]:
108
+ self.speed.addItem(label, ms)
109
+ self.speed.setCurrentIndex(1)
110
+ self.speed.currentIndexChanged.connect(self._restart_timer)
111
+ ctrl.addWidget(self.speed)
112
+
113
+ self.btn_toggle_panel = QPushButton("📊 动力学指标面板")
114
+ self.btn_toggle_panel.setCheckable(True)
115
+ self.btn_toggle_panel.setChecked(True)
116
+ self.btn_toggle_panel.toggled.connect(self._toggle_panel)
117
+ ctrl.addWidget(self.btn_toggle_panel)
118
+
119
+ left_layout.addLayout(ctrl)
120
+ splitter.addWidget(left_widget)
121
+
122
+ # ---------------- 右侧:动力学物理指标面板 ----------------
123
+ self.side_panel = QWidget()
124
+ side_layout = QVBoxLayout(self.side_panel)
125
+ side_layout.setContentsMargins(4, 4, 4, 4)
126
+ side_layout.setSpacing(8)
127
+
128
+ # 实时单帧指标
129
+ live_grp = QGroupBox("当前帧物理量 (对齐初始构象)")
130
+ live_layout = QVBoxLayout(live_grp)
131
+ self.lbl_live_rmsd = QLabel("Kabsch RMSD: 0.000 Å")
132
+ self.lbl_live_rg = QLabel("回旋半径 Rg: 0.000 Å")
133
+ self.lbl_live_atoms = QLabel(f"体系原子数: {self.adapter.n_atoms} | 总帧数: {self.adapter.n_frames}")
134
+ for l in (self.lbl_live_rmsd, self.lbl_live_rg, self.lbl_live_atoms):
135
+ l.setStyleSheet("font-size: 12px; padding: 2px;")
136
+ live_layout.addWidget(l)
137
+ side_layout.addWidget(live_grp)
138
+
139
+ # 全轨迹统计与流式计算
140
+ stats_grp = QGroupBox("全轨迹统计分析 (Streaming Welford)")
141
+ stats_layout = QVBoxLayout(stats_grp)
142
+
143
+ btn_run_analysis = QPushButton("🚀 运行全轨迹 RMSD & RMSF 批处理")
144
+ btn_run_analysis.setProperty("role", "action")
145
+ btn_run_analysis.clicked.connect(self._run_batch_analysis)
146
+ stats_layout.addWidget(btn_run_analysis)
147
+
148
+ self.analysis_progress = QProgressBar()
149
+ self.analysis_progress.setVisible(False)
150
+ self.analysis_progress.setRange(0, 0) # 忙碌等待状态
151
+ stats_layout.addWidget(self.analysis_progress)
152
+
153
+ self.lbl_stats_summary = QLabel("尚未运行全轨迹分析。\n点击上方按钮进行后台非阻塞计算。")
154
+ self.lbl_stats_summary.setStyleSheet("color: #888; font-size: 11px;")
155
+ self.lbl_stats_summary.setWordWrap(True)
156
+ stats_layout.addWidget(self.lbl_stats_summary)
157
+
158
+ # 高涨落原子列表 (Top RMSF)
159
+ self.table_rmsf = QTableWidget(0, 3)
160
+ self.table_rmsf.setHorizontalHeaderLabels(["原子序号", "元素/残基", "RMSF (Å)"])
161
+ self.table_rmsf.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
162
+ stats_layout.addWidget(self.table_rmsf, 1)
163
+
164
+ btn_export = QPushButton("💾 导出分析数据 (CSV)...")
165
+ btn_export.clicked.connect(self._export_analysis_csv)
166
+ stats_layout.addWidget(btn_export)
167
+
168
+ side_layout.addWidget(stats_grp, 1)
169
+ splitter.addWidget(self.side_panel)
170
+ splitter.setSizes([950, 400])
171
+
172
+ # 播放定时器(主线程,按节拍切帧)
173
+ self.timer = QTimer(self)
174
+ self.timer.timeout.connect(self._tick)
175
+
176
+ self._update_label()
177
+
178
+ def _residue_colors(self):
179
+ try:
180
+ resnames = np.array(self.adapter.u.atoms.resnames)
181
+ colors = np.zeros((self.adapter.n_atoms, 3), dtype=np.float32)
182
+ for r, c in _RES_COLORS.items():
183
+ colors[resnames == r] = c
184
+ return colors
185
+ except Exception:
186
+ return np.full((self.adapter.n_atoms, 3), 0.7, dtype=np.float32)
187
+
188
+ def _build_mesh(self, coords):
189
+ self.mesh = pv.PolyData(np.asarray(coords, dtype=np.float32))
190
+ self.mesh.point_data["colors"] = self._residue_colors()
191
+ self.plotter.add_mesh(
192
+ self.mesh, scalars="colors", rgb=True, style="points",
193
+ point_size=4, render_points_as_spheres=True)
194
+
195
+ def _show_frame(self, i: int):
196
+ self.frame = i
197
+ coords = self.adapter.get_frame(i)
198
+ # 零拷贝快速更新点集
199
+ self.mesh.points = np.asarray(coords, dtype=np.float32)
200
+ self.plotter.render()
201
+
202
+ if self.slider.value() != i:
203
+ self.slider.blockSignals(True)
204
+ self.slider.setValue(i)
205
+ self.slider.blockSignals(False)
206
+
207
+ self._update_label()
208
+ self._update_live_metrics(coords)
209
+
210
+ # 异步预取后续帧
211
+ self.adapter.prefetch_async(
212
+ [(i + k) % self.adapter.n_frames for k in range(1, 21)])
213
+
214
+ def _update_live_metrics(self, current_coords: np.ndarray):
215
+ try:
216
+ _, rmsd, _ = kabsch_align(current_coords, self.ref_coords)
217
+ rg = calculate_radius_of_gyration(current_coords)
218
+ self.lbl_live_rmsd.setText(f"Kabsch RMSD: {rmsd:.3f} Å")
219
+ self.lbl_live_rg.setText(f"回旋半径 Rg: {rg:.3f} Å")
220
+ except Exception:
221
+ pass
222
+
223
+ def _tick(self):
224
+ nxt = self.frame + 1
225
+ if nxt >= self.adapter.n_frames:
226
+ nxt = 0
227
+ self._show_frame(nxt)
228
+
229
+ def toggle_play(self):
230
+ self.playing = not self.playing
231
+ if self.playing:
232
+ self.timer.start(self.speed.currentData())
233
+ self.btn_play.setText("⏸ 暂停")
234
+ else:
235
+ self.timer.stop()
236
+ self.btn_play.setText("▶ 播放")
237
+
238
+ def _restart_timer(self):
239
+ if self.playing:
240
+ self.timer.start(self.speed.currentData())
241
+
242
+ def next_frame(self):
243
+ self._show_frame(min(self.frame + 1, self.adapter.n_frames - 1))
244
+
245
+ def prev_frame(self):
246
+ self._show_frame(max(self.frame - 1, 0))
247
+
248
+ def _slider_frame(self, i: int):
249
+ if i != self.frame:
250
+ self._show_frame(i)
251
+
252
+ def _update_label(self):
253
+ t = self.adapter.frame_time_ps(self.frame)
254
+ self.time_label.setText(
255
+ f"帧 {self.frame}/{self.adapter.n_frames-1} · {t:.1f} ps")
256
+
257
+ def _toggle_panel(self, checked: bool):
258
+ self.side_panel.setVisible(checked)
259
+
260
+ # ---------------- 后台批处理动力学指标 ----------------
261
+
262
+ def _run_batch_analysis(self):
263
+ self.analysis_progress.setVisible(True)
264
+ self.lbl_stats_summary.setText("正在后台进行流式 Kabsch RMSD 与 Welford RMSF 分析...")
265
+
266
+ stride = max(1, self.adapter.n_frames // 500) # 若帧数过多,自动步进抽样
267
+ self.worker = _AnalysisWorker(self.adapter, stride=stride)
268
+ self.thread = threading.Thread(target=self._worker_wrapper, args=(stride,), daemon=True)
269
+ self.thread.start()
270
+
271
+ def _worker_wrapper(self, stride: int):
272
+ try:
273
+ res = calculate_trajectory_metrics(self.adapter, ref_frame=0, stride=stride)
274
+ QTimer.singleShot(0, lambda: self._on_analysis_finished(res))
275
+ except Exception as e:
276
+ err = str(e)
277
+ QTimer.singleShot(0, lambda: self._on_analysis_error(err))
278
+
279
+ def _on_analysis_finished(self, res: dict):
280
+ self.analysis_progress.setVisible(False)
281
+ self.analysis_data = res
282
+
283
+ mean_rmsd = res.get("mean_rmsd", 0.0)
284
+ max_rmsd = res.get("max_rmsd", 0.0)
285
+ mean_rg = res.get("mean_rg", 0.0)
286
+
287
+ self.lbl_stats_summary.setText(
288
+ f"✅ 分析完成 (采样帧数: {len(res['frame_indices'])})\n"
289
+ f"平均 RMSD: {mean_rmsd:.3f} Å | 最大 RMSD: {max_rmsd:.3f} Å\n"
290
+ f"平均回旋半径 Rg: {mean_rg:.3f} Å"
291
+ )
292
+ self.lbl_stats_summary.setStyleSheet("color: #4CAF50; font-size: 12px; font-weight: bold;")
293
+
294
+ # 填充高 RMSF 原子前 20 名
295
+ rmsf = res.get("rmsf", np.zeros(0))
296
+ if len(rmsf) > 0:
297
+ top_indices = np.argsort(rmsf)[::-1][:20]
298
+ self.table_rmsf.setRowCount(len(top_indices))
299
+ for row, aidx in enumerate(top_indices):
300
+ val = rmsf[aidx]
301
+ elem = self.adapter.elements[aidx] if aidx < len(self.adapter.elements) else "X"
302
+ self.table_rmsf.setItem(row, 0, QTableWidgetItem(str(aidx + 1)))
303
+ self.table_rmsf.setItem(row, 1, QTableWidgetItem(str(elem)))
304
+ self.table_rmsf.setItem(row, 2, QTableWidgetItem(f"{val:.3f}"))
305
+
306
+ def _on_analysis_error(self, err_msg: str):
307
+ self.analysis_progress.setVisible(False)
308
+ self.lbl_stats_summary.setText(f"❌ 分析失败: {err_msg}")
309
+ self.lbl_stats_summary.setStyleSheet("color: #F44336; font-size: 11px;")
310
+
311
+ def _export_analysis_csv(self):
312
+ if not self.analysis_data:
313
+ QMessageBox.information(self, "提示", "请先运行全轨迹分析以生成数据。")
314
+ return
315
+
316
+ path, _ = QFileDialog.getSaveFileName(self, "导出轨迹分析 CSV", "trajectory_metrics.csv", "CSV Files (*.csv)")
317
+ if not path:
318
+ return
319
+
320
+ try:
321
+ with open(path, "w", newline="", encoding="utf-8") as f:
322
+ writer = csv.writer(f)
323
+ writer.writerow(["Frame", "Time_ps", "Kabsch_RMSD_A", "Radius_of_Gyration_A"])
324
+ indices = self.analysis_data["frame_indices"]
325
+ times = self.analysis_data["times_ps"]
326
+ rmsds = self.analysis_data["rmsd"]
327
+ rgs = self.analysis_data["rg"]
328
+ for i in range(len(indices)):
329
+ writer.writerow([indices[i], f"{times[i]:.2f}", f"{rmsds[i]:.4f}", f"{rgs[i]:.4f}"])
330
+
331
+ QMessageBox.information(self, "成功", f"轨迹时序数据已成功导出至:\n{path}")
332
+ except Exception as e:
333
+ QMessageBox.critical(self, "错误", f"导出失败: {e}")