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,231 @@
|
|
|
1
|
+
"""Trajectory and conformer ensemble mathematical analysis engine.
|
|
2
|
+
|
|
3
|
+
Adheres strictly to scientific invariants:
|
|
4
|
+
1. Kabsch alignment: All RMSD and RMSF calculations factor out rigid body
|
|
5
|
+
translations and rotations using SVD optimal superposition with reflection parity.
|
|
6
|
+
2. Streaming Welford RMSF: Online mean and variance accumulation over frames,
|
|
7
|
+
achieving O(1) memory and numerical stability without storing entire trajectories.
|
|
8
|
+
3. PBC & NoJump: Designed to accept unwrapped/aligned coordinates.
|
|
9
|
+
4. Conformer Ensemble Clustering: Pairwise Kabsch RMSD distance matrix with
|
|
10
|
+
medoid-based clustering and structural representative identification.
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from typing import List, Dict, Tuple, Optional, Any
|
|
15
|
+
import numpy as np
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def kabsch_align(P: np.ndarray, Q: np.ndarray) -> Tuple[np.ndarray, float, np.ndarray]:
|
|
19
|
+
"""Kabsch 最佳刚体叠合算法。
|
|
20
|
+
|
|
21
|
+
将坐标集 P 刚体叠合到参考坐标集 Q 上,最小化均方根偏差 (RMSD)。
|
|
22
|
+
|
|
23
|
+
参数
|
|
24
|
+
----
|
|
25
|
+
P : np.ndarray, shape (N, 3) 待对齐坐标 (单位 Å)
|
|
26
|
+
Q : np.ndarray, shape (N, 3) 参考坐标 (单位 Å)
|
|
27
|
+
|
|
28
|
+
返回
|
|
29
|
+
----
|
|
30
|
+
(P_aligned, rmsd, R)
|
|
31
|
+
- P_aligned: 对齐后的坐标 (N, 3)
|
|
32
|
+
- rmsd: 最小化后的 RMSD 值 (Å)
|
|
33
|
+
- R: 3x3 旋转矩阵
|
|
34
|
+
"""
|
|
35
|
+
P_arr = np.asarray(P, dtype=float)
|
|
36
|
+
Q_arr = np.asarray(Q, dtype=float)
|
|
37
|
+
if P_arr.shape != Q_arr.shape or P_arr.ndim != 2 or P_arr.shape[1] != 3:
|
|
38
|
+
raise ValueError(f"Kabsch 输入形状必须一致且为 (N, 3),收到 {P_arr.shape} 与 {Q_arr.shape}")
|
|
39
|
+
|
|
40
|
+
n = len(P_arr)
|
|
41
|
+
if n == 0:
|
|
42
|
+
return P_arr.copy(), 0.0, np.eye(3)
|
|
43
|
+
|
|
44
|
+
p_center = np.mean(P_arr, axis=0)
|
|
45
|
+
q_center = np.mean(Q_arr, axis=0)
|
|
46
|
+
P_c = P_arr - p_center
|
|
47
|
+
Q_c = Q_arr - q_center
|
|
48
|
+
|
|
49
|
+
# 协方差矩阵 H = P_c^T @ Q_c
|
|
50
|
+
H = P_c.T @ Q_c
|
|
51
|
+
U, S, Vt = np.linalg.svd(H)
|
|
52
|
+
R = U @ Vt
|
|
53
|
+
|
|
54
|
+
# 检查手性反转 (反射解)
|
|
55
|
+
if np.linalg.det(R) < 0:
|
|
56
|
+
U[:, -1] *= -1
|
|
57
|
+
R = U @ Vt
|
|
58
|
+
|
|
59
|
+
P_aligned = P_c @ R + q_center
|
|
60
|
+
rmsd = float(np.sqrt(np.mean(np.sum((P_aligned - Q_arr) ** 2, axis=-1))))
|
|
61
|
+
return P_aligned, rmsd, R
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def calculate_radius_of_gyration(coords: np.ndarray) -> float:
|
|
65
|
+
"""计算回旋半径 (Radius of Gyration, Rg)。
|
|
66
|
+
|
|
67
|
+
Rg = sqrt( (1/N) * sum_i || r_i - r_com ||^2 )
|
|
68
|
+
"""
|
|
69
|
+
c = np.asarray(coords, dtype=float)
|
|
70
|
+
if len(c) == 0:
|
|
71
|
+
return 0.0
|
|
72
|
+
com = np.mean(c, axis=0)
|
|
73
|
+
diff = c - com
|
|
74
|
+
return float(np.sqrt(np.mean(np.sum(diff ** 2, axis=-1))))
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class StreamingWelfordRMSF:
|
|
78
|
+
"""流式 Welford 算法计算逐原子均方根波动 (RMSF),自动施加 Kabsch 叠合。
|
|
79
|
+
|
|
80
|
+
避免将庞大轨迹的所有坐标全部载入内存,且严格过滤由于整体刚体平动/转动导致的虚假涨落。
|
|
81
|
+
"""
|
|
82
|
+
|
|
83
|
+
def __init__(self, ref_coords: np.ndarray):
|
|
84
|
+
self.ref = np.asarray(ref_coords, dtype=float)
|
|
85
|
+
self.n_atoms = len(self.ref)
|
|
86
|
+
self.count: int = 0
|
|
87
|
+
self.mean = np.zeros_like(self.ref)
|
|
88
|
+
self.M2 = np.zeros_like(self.ref)
|
|
89
|
+
self.rmsd_history: List[float] = []
|
|
90
|
+
|
|
91
|
+
def update(self, frame_coords: np.ndarray) -> float:
|
|
92
|
+
"""输入新的一帧,自动对齐到参考结构并流式更新统计量。返回当前帧对齐后的 RMSD。"""
|
|
93
|
+
aligned, rmsd, _ = kabsch_align(frame_coords, self.ref)
|
|
94
|
+
self.rmsd_history.append(rmsd)
|
|
95
|
+
self.count += 1
|
|
96
|
+
delta = aligned - self.mean
|
|
97
|
+
self.mean += delta / self.count
|
|
98
|
+
delta2 = aligned - self.mean
|
|
99
|
+
self.M2 += delta * delta2
|
|
100
|
+
return rmsd
|
|
101
|
+
|
|
102
|
+
def get_rmsf(self) -> np.ndarray:
|
|
103
|
+
"""返回所有原子的 RMSF 数组 (N,),单位 Å。"""
|
|
104
|
+
if self.count <= 1:
|
|
105
|
+
return np.zeros(self.n_atoms)
|
|
106
|
+
var = self.M2 / self.count
|
|
107
|
+
return np.sqrt(np.sum(var, axis=-1))
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def calculate_trajectory_metrics(
|
|
111
|
+
adapter: Any,
|
|
112
|
+
ref_frame: int = 0,
|
|
113
|
+
stride: int = 1,
|
|
114
|
+
max_frames: Optional[int] = None,
|
|
115
|
+
) -> Dict[str, Any]:
|
|
116
|
+
"""批量/流式计算轨迹的时序物理指标 (RMSD、Rg、RMSF)。
|
|
117
|
+
|
|
118
|
+
参数
|
|
119
|
+
----
|
|
120
|
+
adapter : TrajectoryAdapter 实例
|
|
121
|
+
ref_frame : 参考帧索引 (默认第 0 帧)
|
|
122
|
+
stride : 抽样步长
|
|
123
|
+
max_frames : 最大分析帧数 (防止极端长轨迹耗尽主循环)
|
|
124
|
+
|
|
125
|
+
返回
|
|
126
|
+
----
|
|
127
|
+
包含 frame_indices, times_ps, rmsd, rg, rmsf, mean_rmsd, max_rmsd 的字典。
|
|
128
|
+
"""
|
|
129
|
+
total_frames = adapter.n_frames
|
|
130
|
+
indices = list(range(0, total_frames, max(1, stride)))
|
|
131
|
+
if max_frames and len(indices) > max_frames:
|
|
132
|
+
indices = indices[:max_frames]
|
|
133
|
+
|
|
134
|
+
ref_coords = adapter.get_frame(ref_frame)
|
|
135
|
+
streamer = StreamingWelfordRMSF(ref_coords)
|
|
136
|
+
|
|
137
|
+
times_ps: List[float] = []
|
|
138
|
+
rmsd_list: List[float] = []
|
|
139
|
+
rg_list: List[float] = []
|
|
140
|
+
|
|
141
|
+
for fi in indices:
|
|
142
|
+
coords = adapter.get_frame(fi)
|
|
143
|
+
rmsd = streamer.update(coords)
|
|
144
|
+
rg = calculate_radius_of_gyration(coords)
|
|
145
|
+
t = adapter.frame_time_ps(fi)
|
|
146
|
+
times_ps.append(t)
|
|
147
|
+
rmsd_list.append(rmsd)
|
|
148
|
+
rg_list.append(rg)
|
|
149
|
+
|
|
150
|
+
rmsf = streamer.get_rmsf()
|
|
151
|
+
|
|
152
|
+
return {
|
|
153
|
+
"frame_indices": indices,
|
|
154
|
+
"times_ps": times_ps,
|
|
155
|
+
"rmsd": rmsd_list,
|
|
156
|
+
"rg": rg_list,
|
|
157
|
+
"rmsf": rmsf,
|
|
158
|
+
"mean_rmsd": float(np.mean(rmsd_list)) if rmsd_list else 0.0,
|
|
159
|
+
"max_rmsd": float(np.max(rmsd_list)) if rmsd_list else 0.0,
|
|
160
|
+
"mean_rg": float(np.mean(rg_list)) if rg_list else 0.0,
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def cluster_conformer_ensemble(
|
|
165
|
+
coords_list: List[np.ndarray],
|
|
166
|
+
rmsd_threshold: float = 0.5,
|
|
167
|
+
) -> Dict[str, Any]:
|
|
168
|
+
"""对多构象集合进行全对偶 Kabsch RMSD 矩阵计算与结构聚类。
|
|
169
|
+
|
|
170
|
+
参数
|
|
171
|
+
----
|
|
172
|
+
coords_list : List of (N, 3) 构象坐标
|
|
173
|
+
rmsd_threshold : 聚类截断半径 (单位 Å)
|
|
174
|
+
|
|
175
|
+
返回
|
|
176
|
+
----
|
|
177
|
+
{
|
|
178
|
+
"matrix": np.ndarray (M, M),
|
|
179
|
+
"clusters": Dict[int, List[int]], # cluster_id -> [conformer_indices]
|
|
180
|
+
"medoids": Dict[int, int], # cluster_id -> center_conformer_index
|
|
181
|
+
"n_clusters": int,
|
|
182
|
+
}
|
|
183
|
+
"""
|
|
184
|
+
M = len(coords_list)
|
|
185
|
+
if M == 0:
|
|
186
|
+
return {"matrix": np.zeros((0, 0)), "clusters": {}, "medoids": {}, "n_clusters": 0}
|
|
187
|
+
|
|
188
|
+
# 1. 计算对偶 RMSD 距离矩阵
|
|
189
|
+
dist_mat = np.zeros((M, M), dtype=float)
|
|
190
|
+
for i in range(M):
|
|
191
|
+
for j in range(i + 1, M):
|
|
192
|
+
_, d, _ = kabsch_align(coords_list[i], coords_list[j])
|
|
193
|
+
dist_mat[i, j] = d
|
|
194
|
+
dist_mat[j, i] = d
|
|
195
|
+
|
|
196
|
+
# 2. 贪心中心聚类 (Greedy Medoids / Leader Algorithm)
|
|
197
|
+
unassigned = set(range(M))
|
|
198
|
+
clusters: Dict[int, List[int]] = {}
|
|
199
|
+
medoids: Dict[int, int] = {}
|
|
200
|
+
cid = 0
|
|
201
|
+
|
|
202
|
+
while unassigned:
|
|
203
|
+
# 选择在当前未分配集合中与其它成员平均距离最小的构象作为种子中心 (Medoid)
|
|
204
|
+
best_medoid = -1
|
|
205
|
+
best_avg_dist = float("inf")
|
|
206
|
+
unassigned_list = list(unassigned)
|
|
207
|
+
|
|
208
|
+
for cand in unassigned_list:
|
|
209
|
+
dists = [dist_mat[cand, other] for other in unassigned_list]
|
|
210
|
+
avg_d = sum(dists) / len(dists)
|
|
211
|
+
if avg_d < best_avg_dist:
|
|
212
|
+
best_avg_dist = avg_d
|
|
213
|
+
best_medoid = cand
|
|
214
|
+
|
|
215
|
+
# 归属到该类中 (距离 <= rmsd_threshold)
|
|
216
|
+
members = [m for m in unassigned_list if dist_mat[best_medoid, m] <= rmsd_threshold]
|
|
217
|
+
if not members:
|
|
218
|
+
members = [best_medoid]
|
|
219
|
+
|
|
220
|
+
clusters[cid] = sorted(members)
|
|
221
|
+
medoids[cid] = best_medoid
|
|
222
|
+
for m in members:
|
|
223
|
+
unassigned.remove(m)
|
|
224
|
+
cid += 1
|
|
225
|
+
|
|
226
|
+
return {
|
|
227
|
+
"matrix": dist_mat,
|
|
228
|
+
"clusters": clusters,
|
|
229
|
+
"medoids": medoids,
|
|
230
|
+
"n_clusters": len(clusters),
|
|
231
|
+
}
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
"""
|
|
2
|
+
application/workspace_registry.py - 全局工作区与 G:M:V 视图注册表
|
|
3
|
+
=================================================================
|
|
4
|
+
严格实现 2.3 / 2.4 节 G:M:V 契约:
|
|
5
|
+
- GroupSession (G): 管理分子组编号 G1, G2...(单调递增计数器,关闭窗口后重建绝不产生标签冲突)
|
|
6
|
+
- DocumentSession (M): 组内分子 M1, M2... 对应唯一 DocumentSession
|
|
7
|
+
- ViewSession (V): 同一分子的不同视图 V1, V2... 共享同一个 DocumentSession,但拥有各自独立的
|
|
8
|
+
ViewSession(相机预设、渲染样式、1/2/4 Pane 布局 P1..P4、活动子视口)
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import uuid
|
|
14
|
+
from dataclasses import dataclass, field
|
|
15
|
+
from typing import Literal
|
|
16
|
+
|
|
17
|
+
from ..domain.document import MoleculeDocument
|
|
18
|
+
from .document_session import DocumentSession
|
|
19
|
+
|
|
20
|
+
PaneCount = Literal[1, 2, 4]
|
|
21
|
+
CameraPreset = Literal["perspective", "front", "side", "top"]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass
|
|
25
|
+
class PaneState:
|
|
26
|
+
pane_id: str # "P1" | "P2" | "P3" | "P4"
|
|
27
|
+
camera_preset: CameraPreset = "perspective"
|
|
28
|
+
render_style: str = "ball_and_stick"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass
|
|
32
|
+
class ViewSession:
|
|
33
|
+
view_uuid: str
|
|
34
|
+
gmv_tag: str # 例如 "G1:M1:V1"
|
|
35
|
+
group_id: int
|
|
36
|
+
molecule_index: int
|
|
37
|
+
view_index: int
|
|
38
|
+
document_id: str
|
|
39
|
+
pane_count: PaneCount = 1
|
|
40
|
+
active_pane: str = "P1"
|
|
41
|
+
sync_cameras: bool = False
|
|
42
|
+
panes: dict[str, PaneState] = field(default_factory=dict)
|
|
43
|
+
|
|
44
|
+
def __post_init__(self) -> None:
|
|
45
|
+
if not self.panes:
|
|
46
|
+
self.set_pane_layout(self.pane_count)
|
|
47
|
+
|
|
48
|
+
def set_pane_layout(self, count: PaneCount) -> None:
|
|
49
|
+
if count not in (1, 2, 4):
|
|
50
|
+
raise ValueError(f"Unsupported pane count: {count} (expected 1, 2, or 4)")
|
|
51
|
+
self.pane_count = count
|
|
52
|
+
if count == 1:
|
|
53
|
+
self.panes = {"P1": PaneState("P1", "perspective")}
|
|
54
|
+
elif count == 2:
|
|
55
|
+
self.panes = {
|
|
56
|
+
"P1": PaneState("P1", "front"),
|
|
57
|
+
"P2": PaneState("P2", "perspective"),
|
|
58
|
+
}
|
|
59
|
+
else:
|
|
60
|
+
self.panes = {
|
|
61
|
+
"P1": PaneState("P1", "front"),
|
|
62
|
+
"P2": PaneState("P2", "side"),
|
|
63
|
+
"P3": PaneState("P3", "top"),
|
|
64
|
+
"P4": PaneState("P4", "perspective"),
|
|
65
|
+
}
|
|
66
|
+
if self.active_pane not in self.panes:
|
|
67
|
+
self.active_pane = "P1"
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
@dataclass
|
|
71
|
+
class GroupSession:
|
|
72
|
+
group_id: int
|
|
73
|
+
next_molecule_index: int = 1
|
|
74
|
+
molecule_sessions: dict[int, str] = field(default_factory=dict) # m_idx -> document_id
|
|
75
|
+
next_view_index_by_m: dict[int, int] = field(default_factory=dict)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class WorkspaceRegistry:
|
|
79
|
+
"""应用级工作区注册表(管理所有 DocumentSession、GroupSession 与 ViewSession)。"""
|
|
80
|
+
|
|
81
|
+
_singleton: "WorkspaceRegistry | None" = None
|
|
82
|
+
|
|
83
|
+
def __init__(self) -> None:
|
|
84
|
+
self._documents: dict[str, DocumentSession] = {}
|
|
85
|
+
self._groups: dict[int, GroupSession] = {}
|
|
86
|
+
self._views: dict[str, ViewSession] = {} # gmv_tag -> ViewSession
|
|
87
|
+
self._next_group_id: int = 1
|
|
88
|
+
|
|
89
|
+
@classmethod
|
|
90
|
+
def instance(cls) -> "WorkspaceRegistry":
|
|
91
|
+
if cls._singleton is None:
|
|
92
|
+
cls._singleton = cls()
|
|
93
|
+
return cls._singleton
|
|
94
|
+
|
|
95
|
+
def reset_for_testing(self) -> None:
|
|
96
|
+
self._documents.clear()
|
|
97
|
+
self._groups.clear()
|
|
98
|
+
self._views.clear()
|
|
99
|
+
self._next_group_id = 1
|
|
100
|
+
|
|
101
|
+
def get_or_create_session(self, document: MoleculeDocument) -> DocumentSession:
|
|
102
|
+
doc_id = document.document_id
|
|
103
|
+
if doc_id not in self._documents:
|
|
104
|
+
self._documents[doc_id] = DocumentSession(document)
|
|
105
|
+
return self._documents[doc_id]
|
|
106
|
+
|
|
107
|
+
def get_session(self, document_id: str) -> DocumentSession | None:
|
|
108
|
+
return self._documents.get(document_id)
|
|
109
|
+
|
|
110
|
+
def create_new_group_view(self, document: MoleculeDocument, pane_count: PaneCount = 1) -> tuple[DocumentSession, ViewSession]:
|
|
111
|
+
session = self.get_or_create_session(document)
|
|
112
|
+
g_id = self._next_group_id
|
|
113
|
+
self._next_group_id += 1
|
|
114
|
+
grp = GroupSession(group_id=g_id, next_molecule_index=2)
|
|
115
|
+
grp.molecule_sessions[1] = session.document_id
|
|
116
|
+
grp.next_view_index_by_m[1] = 2
|
|
117
|
+
self._groups[g_id] = grp
|
|
118
|
+
|
|
119
|
+
tag = f"G{g_id}:M1:V1"
|
|
120
|
+
view = ViewSession(
|
|
121
|
+
view_uuid=uuid.uuid4().hex[:12],
|
|
122
|
+
gmv_tag=tag,
|
|
123
|
+
group_id=g_id,
|
|
124
|
+
molecule_index=1,
|
|
125
|
+
view_index=1,
|
|
126
|
+
document_id=session.document_id,
|
|
127
|
+
pane_count=pane_count,
|
|
128
|
+
)
|
|
129
|
+
self._views[tag] = view
|
|
130
|
+
return session, view
|
|
131
|
+
|
|
132
|
+
def add_molecule_to_group(self, group_id: int, document: MoleculeDocument, pane_count: PaneCount = 1) -> tuple[DocumentSession, ViewSession]:
|
|
133
|
+
session = self.get_or_create_session(document)
|
|
134
|
+
if group_id not in self._groups:
|
|
135
|
+
self._groups[group_id] = GroupSession(group_id=group_id)
|
|
136
|
+
if group_id >= self._next_group_id:
|
|
137
|
+
self._next_group_id = group_id + 1
|
|
138
|
+
grp = self._groups[group_id]
|
|
139
|
+
m_idx = grp.next_molecule_index
|
|
140
|
+
grp.next_molecule_index += 1
|
|
141
|
+
grp.molecule_sessions[m_idx] = session.document_id
|
|
142
|
+
grp.next_view_index_by_m[m_idx] = 2
|
|
143
|
+
|
|
144
|
+
tag = f"G{group_id}:M{m_idx}:V1"
|
|
145
|
+
view = ViewSession(
|
|
146
|
+
view_uuid=uuid.uuid4().hex[:12],
|
|
147
|
+
gmv_tag=tag,
|
|
148
|
+
group_id=group_id,
|
|
149
|
+
molecule_index=m_idx,
|
|
150
|
+
view_index=1,
|
|
151
|
+
document_id=session.document_id,
|
|
152
|
+
pane_count=pane_count,
|
|
153
|
+
)
|
|
154
|
+
self._views[tag] = view
|
|
155
|
+
return session, view
|
|
156
|
+
|
|
157
|
+
def clone_view(self, source_gmv_tag: str, pane_count: PaneCount = 1) -> tuple[DocumentSession, ViewSession]:
|
|
158
|
+
if source_gmv_tag in self._views:
|
|
159
|
+
src_v = self._views[source_gmv_tag]
|
|
160
|
+
g_id = src_v.group_id
|
|
161
|
+
m_idx = src_v.molecule_index
|
|
162
|
+
doc_id = src_v.document_id
|
|
163
|
+
session = self._documents[doc_id]
|
|
164
|
+
else:
|
|
165
|
+
raise KeyError(f"Unknown source GMV tag: '{source_gmv_tag}'")
|
|
166
|
+
|
|
167
|
+
grp = self._groups[g_id]
|
|
168
|
+
v_idx = grp.next_view_index_by_m.get(m_idx, 1)
|
|
169
|
+
grp.next_view_index_by_m[m_idx] = v_idx + 1
|
|
170
|
+
|
|
171
|
+
tag = f"G{g_id}:M{m_idx}:V{v_idx}"
|
|
172
|
+
view = ViewSession(
|
|
173
|
+
view_uuid=uuid.uuid4().hex[:12],
|
|
174
|
+
gmv_tag=tag,
|
|
175
|
+
group_id=g_id,
|
|
176
|
+
molecule_index=m_idx,
|
|
177
|
+
view_index=v_idx,
|
|
178
|
+
document_id=session.document_id,
|
|
179
|
+
pane_count=pane_count,
|
|
180
|
+
)
|
|
181
|
+
self._views[tag] = view
|
|
182
|
+
return session, view
|
|
183
|
+
|
|
184
|
+
def register_explicit_tag(self, gmv_tag: str, document: MoleculeDocument, pane_count: PaneCount = 1) -> tuple[DocumentSession, ViewSession]:
|
|
185
|
+
session = self.get_or_create_session(document)
|
|
186
|
+
if gmv_tag in self._views:
|
|
187
|
+
return session, self._views[gmv_tag]
|
|
188
|
+
parts = gmv_tag.upper().split(":")
|
|
189
|
+
g_id = int(parts[0].lstrip("G")) if len(parts) >= 1 and parts[0].lstrip("G").isdigit() else self._next_group_id
|
|
190
|
+
m_idx = int(parts[1].lstrip("M")) if len(parts) >= 2 and parts[1].lstrip("M").isdigit() else 1
|
|
191
|
+
v_idx = int(parts[2].lstrip("V")) if len(parts) >= 3 and parts[2].lstrip("V").isdigit() else 1
|
|
192
|
+
|
|
193
|
+
if g_id >= self._next_group_id:
|
|
194
|
+
self._next_group_id = g_id + 1
|
|
195
|
+
if g_id not in self._groups:
|
|
196
|
+
self._groups[g_id] = GroupSession(group_id=g_id)
|
|
197
|
+
grp = self._groups[g_id]
|
|
198
|
+
grp.molecule_sessions[m_idx] = session.document_id
|
|
199
|
+
if m_idx >= grp.next_molecule_index:
|
|
200
|
+
grp.next_molecule_index = m_idx + 1
|
|
201
|
+
cur_next_v = grp.next_view_index_by_m.get(m_idx, 1)
|
|
202
|
+
if v_idx >= cur_next_v:
|
|
203
|
+
grp.next_view_index_by_m[m_idx] = v_idx + 1
|
|
204
|
+
|
|
205
|
+
view = ViewSession(
|
|
206
|
+
view_uuid=uuid.uuid4().hex[:12],
|
|
207
|
+
gmv_tag=gmv_tag,
|
|
208
|
+
group_id=g_id,
|
|
209
|
+
molecule_index=m_idx,
|
|
210
|
+
view_index=v_idx,
|
|
211
|
+
document_id=session.document_id,
|
|
212
|
+
pane_count=pane_count,
|
|
213
|
+
)
|
|
214
|
+
self._views[gmv_tag] = view
|
|
215
|
+
return session, view
|
|
216
|
+
|
|
217
|
+
def close_view(self, gmv_tag: str) -> None:
|
|
218
|
+
view = self._views.pop(gmv_tag, None)
|
|
219
|
+
if view is not None:
|
|
220
|
+
still_used = any(v.document_id == view.document_id for v in self._views.values())
|
|
221
|
+
if not still_used:
|
|
222
|
+
self._documents.pop(view.document_id, None)
|
|
223
|
+
|
|
224
|
+
@property
|
|
225
|
+
def active_views(self) -> dict[str, ViewSession]:
|
|
226
|
+
return dict(self._views)
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"""
|
|
2
|
+
core/ - 核心数据模型层
|
|
3
|
+
======================
|
|
4
|
+
最底层,不依赖 PyQt6/AI/IO。所有上层都依赖它。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from .molecule import Molecule
|
|
8
|
+
from .conformer import Conformer
|
|
9
|
+
from .orbital import Orbital
|
|
10
|
+
from .properties import compute_properties
|
|
11
|
+
|
|
12
|
+
__all__ = ["Molecule", "Conformer", "Orbital", "compute_properties"]
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
"""
|
|
2
|
+
conformer.py - 3D 构象
|
|
3
|
+
======================
|
|
4
|
+
一个 Conformer 就是一组原子的 3D 坐标。
|
|
5
|
+
一个分子可能有多个构象(比如不同的 rotamer)。
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from dataclasses import dataclass, field
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
import numpy as np
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass
|
|
17
|
+
class Conformer:
|
|
18
|
+
"""
|
|
19
|
+
单个 3D 构象。
|
|
20
|
+
|
|
21
|
+
属性:
|
|
22
|
+
coords: N×3 的 numpy 数组,每行是一个原子的 (x, y, z),单位 Å
|
|
23
|
+
energy: 这个构象的能量(如果做过优化),单位 eV 或 Hartree
|
|
24
|
+
source: 构象来源('etkdg' / 'optimized' / 'read_from_file')
|
|
25
|
+
"""
|
|
26
|
+
coords: np.ndarray
|
|
27
|
+
energy: float | None = None
|
|
28
|
+
source: str = "unknown"
|
|
29
|
+
|
|
30
|
+
def __post_init__(self):
|
|
31
|
+
if not isinstance(self.coords, np.ndarray):
|
|
32
|
+
self.coords = np.array(self.coords, dtype=float)
|
|
33
|
+
if self.coords.ndim != 2 or self.coords.shape[1] != 3:
|
|
34
|
+
raise ValueError(
|
|
35
|
+
f"coords 必须是 N×3 数组,当前形状 {self.coords.shape}"
|
|
36
|
+
)
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def num_atoms(self) -> int:
|
|
40
|
+
return len(self.coords)
|
|
41
|
+
|
|
42
|
+
def atom_position(self, index: int) -> tuple[float, float, float]:
|
|
43
|
+
"""取第 index 个原子的坐标。"""
|
|
44
|
+
x, y, z = self.coords[index]
|
|
45
|
+
return float(x), float(y), float(z)
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
"""
|
|
2
|
+
molecule.py - 分子一等公民对象
|
|
3
|
+
==============================
|
|
4
|
+
Molecule 是整个软件的核心数据模型。所有 io/render/ai/ui 都围绕它转。
|
|
5
|
+
|
|
6
|
+
它不只是包一层 RDKit Mol,而是一个完整的化学对象:
|
|
7
|
+
- 2D 结构(原子、键、芳香性)→ rdkit_mol
|
|
8
|
+
- 3D 构象 → conformers 列表
|
|
9
|
+
- 计算结果 → energy、orbitals
|
|
10
|
+
- 来源信息 → source_format、source_path
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import uuid
|
|
16
|
+
from dataclasses import dataclass, field
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
import numpy as np
|
|
20
|
+
try:
|
|
21
|
+
from rdkit import Chem
|
|
22
|
+
except ImportError:
|
|
23
|
+
Chem = None
|
|
24
|
+
|
|
25
|
+
from .conformer import Conformer
|
|
26
|
+
from .orbital import Orbital
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _new_id() -> str:
|
|
30
|
+
return uuid.uuid4().hex[:12]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass
|
|
34
|
+
class Molecule:
|
|
35
|
+
"""
|
|
36
|
+
分子对象(一等公民)。
|
|
37
|
+
|
|
38
|
+
属性:
|
|
39
|
+
id: 唯一 ID(自动生成)
|
|
40
|
+
name: 用户起的名字(可选)
|
|
41
|
+
rdkit_mol: RDKit 分子对象(2D 结构核心)
|
|
42
|
+
conformers: 3D 构象列表
|
|
43
|
+
energy: 单点能(Hartree,如果有)
|
|
44
|
+
orbitals: 分子轨道列表(如果有)
|
|
45
|
+
source_format: 来源格式('smiles' / 'mol' / 'gjf' / 'gaussian_log')
|
|
46
|
+
source_path: 来源文件路径
|
|
47
|
+
properties: 缓存的性质字典
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
rdkit_mol: Chem.Mol
|
|
51
|
+
id: str = field(default_factory=_new_id)
|
|
52
|
+
name: str | None = None
|
|
53
|
+
conformers: list[Conformer] = field(default_factory=list)
|
|
54
|
+
energy: float | None = None
|
|
55
|
+
orbitals: list[Orbital] | None = None
|
|
56
|
+
source_format: str = "unknown"
|
|
57
|
+
source_path: Path | None = None
|
|
58
|
+
properties: dict = field(default_factory=dict)
|
|
59
|
+
|
|
60
|
+
# ---------- 便捷属性 ----------
|
|
61
|
+
|
|
62
|
+
@property
|
|
63
|
+
def num_atoms(self) -> int:
|
|
64
|
+
return self.rdkit_mol.GetNumAtoms()
|
|
65
|
+
|
|
66
|
+
@property
|
|
67
|
+
def num_bonds(self) -> int:
|
|
68
|
+
return self.rdkit_mol.GetNumBonds()
|
|
69
|
+
|
|
70
|
+
@property
|
|
71
|
+
def formula(self) -> str:
|
|
72
|
+
"""分子式,例如 C9H8O4。"""
|
|
73
|
+
from rdkit.Chem import rdMolDescriptors
|
|
74
|
+
return rdMolDescriptors.CalcMolFormula(self.rdkit_mol)
|
|
75
|
+
|
|
76
|
+
@property
|
|
77
|
+
def has_3d(self) -> bool:
|
|
78
|
+
return len(self.conformers) > 0
|
|
79
|
+
|
|
80
|
+
@property
|
|
81
|
+
def homo(self) -> Orbital | None:
|
|
82
|
+
"""最高占据分子轨道。"""
|
|
83
|
+
if not self.orbitals:
|
|
84
|
+
return None
|
|
85
|
+
occupied = [o for o in self.orbitals if o.is_occupied]
|
|
86
|
+
return max(occupied, key=lambda o: o.energy_ev) if occupied else None
|
|
87
|
+
|
|
88
|
+
@property
|
|
89
|
+
def lumo(self) -> Orbital | None:
|
|
90
|
+
"""最低空分子轨道。"""
|
|
91
|
+
if not self.orbitals:
|
|
92
|
+
return None
|
|
93
|
+
virtual = [o for o in self.orbitals if not o.is_occupied]
|
|
94
|
+
return min(virtual, key=lambda o: o.energy_ev) if virtual else None
|
|
95
|
+
|
|
96
|
+
@property
|
|
97
|
+
def gap_ev(self) -> float | None:
|
|
98
|
+
"""HOMO-LUMO gap(eV)。"""
|
|
99
|
+
if self.homo and self.lumo:
|
|
100
|
+
return self.lumo.energy_ev - self.homo.energy_ev
|
|
101
|
+
return None
|
|
102
|
+
|
|
103
|
+
# ---------- 构造方法 ----------
|
|
104
|
+
|
|
105
|
+
@classmethod
|
|
106
|
+
def from_rdkit(cls, mol: Chem.Mol, name: str | None = None, attach_conformers: bool = True) -> "Molecule":
|
|
107
|
+
"""
|
|
108
|
+
从 RDKit Mol 对象构造。
|
|
109
|
+
|
|
110
|
+
Args:
|
|
111
|
+
mol: RDKit Mol 对象
|
|
112
|
+
name: 分子名称
|
|
113
|
+
attach_conformers: 是否自动把 RDKit 的 3D 构象转成 MolForge Conformer
|
|
114
|
+
"""
|
|
115
|
+
instance = cls(rdkit_mol=mol, name=name)
|
|
116
|
+
if attach_conformers:
|
|
117
|
+
instance.attach_rdkit_conformers(source="from_rdkit")
|
|
118
|
+
return instance
|
|
119
|
+
|
|
120
|
+
def attach_rdkit_conformers(self, source: str = "read_from_file") -> int:
|
|
121
|
+
"""
|
|
122
|
+
把 RDKit Mol 里的所有 3D 构象转成 MolForge Conformer 挂到当前分子上。
|
|
123
|
+
|
|
124
|
+
返回:成功附加的构象数量。
|
|
125
|
+
"""
|
|
126
|
+
n = 0
|
|
127
|
+
if self.rdkit_mol.GetNumConformers() == 0:
|
|
128
|
+
return 0
|
|
129
|
+
for conf in self.rdkit_mol.GetConformers():
|
|
130
|
+
if not conf.Is3D():
|
|
131
|
+
continue
|
|
132
|
+
n_atoms = self.rdkit_mol.GetNumAtoms()
|
|
133
|
+
coords = np.zeros((n_atoms, 3), dtype=float)
|
|
134
|
+
for i in range(n_atoms):
|
|
135
|
+
p = conf.GetAtomPosition(i)
|
|
136
|
+
coords[i] = [p.x, p.y, p.z]
|
|
137
|
+
self.conformers.append(Conformer(coords=coords, source=source))
|
|
138
|
+
n += 1
|
|
139
|
+
return n
|
|
140
|
+
|
|
141
|
+
def summary(self) -> str:
|
|
142
|
+
"""一行人类可读摘要。"""
|
|
143
|
+
parts = [f"{self.formula}"]
|
|
144
|
+
if self.name:
|
|
145
|
+
parts.insert(0, self.name)
|
|
146
|
+
if self.energy is not None:
|
|
147
|
+
parts.append(f"E={self.energy:.6f} Ha")
|
|
148
|
+
if self.gap_ev is not None:
|
|
149
|
+
parts.append(f"gap={self.gap_ev:.2f} eV")
|
|
150
|
+
return " | ".join(parts)
|
molforge/core/orbital.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
"""
|
|
2
|
+
orbital.py - 分子轨道
|
|
3
|
+
======================
|
|
4
|
+
一个 Orbital 记录一个分子轨道(MO)的信息:
|
|
5
|
+
- 轨道编号(1, 2, 3...)
|
|
6
|
+
- 轨道能量(eV)
|
|
7
|
+
- 占据数(2 = 占据,0 = 空)
|
|
8
|
+
- 对应的 cube 文件路径(如果有,用来渲染轨道图)
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
from dataclasses import dataclass, field
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass
|
|
18
|
+
class Orbital:
|
|
19
|
+
"""单个分子轨道。"""
|
|
20
|
+
|
|
21
|
+
index: int # 轨道编号(从 1 开始)
|
|
22
|
+
energy_ev: float # 轨道能量(eV)
|
|
23
|
+
occupation: float # 占据数(闭壳层 = 2.0,空轨道 = 0.0)
|
|
24
|
+
cube_path: Path | None = None # 对应的 cube 文件(如果有)
|
|
25
|
+
|
|
26
|
+
@property
|
|
27
|
+
def is_occupied(self) -> bool:
|
|
28
|
+
return self.occupation > 0.5
|
|
29
|
+
|
|
30
|
+
@property
|
|
31
|
+
def label(self) -> str:
|
|
32
|
+
"""人类可读标签,例如 'HOMO', 'LUMO', 'HOMO-1'。"""
|
|
33
|
+
return f"MO {self.index}"
|