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,155 @@
|
|
|
1
|
+
"""
|
|
2
|
+
io/mdanalysis_adapter.py - MDAnalysis 轨迹播放与缓存
|
|
3
|
+
=====================================================
|
|
4
|
+
加载拓扑 + 轨迹(XTC/DCD/TRR),提供:
|
|
5
|
+
- 原子数 / 帧数 / 时间单位(ps)/ 播放节拍
|
|
6
|
+
- 错序轨迹拒绝(时间戳必须单调递增)
|
|
7
|
+
- chunk LRU 缓存 + 后台线程异步预取(不冻结主线程)
|
|
8
|
+
- 切帧坐标(numpy,单位 Å)
|
|
9
|
+
|
|
10
|
+
不复制分子真相源,只读取轨迹并产出坐标帧。
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import threading
|
|
15
|
+
from collections import OrderedDict
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
import numpy as np
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class TrajectoryError(ValueError):
|
|
22
|
+
"""轨迹无法可靠读取(错序、原子数不一致等)。"""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class TrajectoryAdapter:
|
|
26
|
+
"""MDAnalysis 轨迹适配器。"""
|
|
27
|
+
|
|
28
|
+
def __init__(
|
|
29
|
+
self,
|
|
30
|
+
topology: str | Path,
|
|
31
|
+
trajectory: str | Path,
|
|
32
|
+
chunk_size: int = 10,
|
|
33
|
+
max_chunks: int = 6,
|
|
34
|
+
) -> None:
|
|
35
|
+
import MDAnalysis as mda
|
|
36
|
+
|
|
37
|
+
self.topology = str(topology)
|
|
38
|
+
self.trajectory = str(trajectory)
|
|
39
|
+
self.u = mda.Universe(self.topology, self.trajectory)
|
|
40
|
+
|
|
41
|
+
self.n_atoms: int = len(self.u.atoms)
|
|
42
|
+
self.n_frames: int = len(self.u.trajectory)
|
|
43
|
+
self.dt_ps: float = float(self.u.trajectory.dt) # 帧间隔(ps)
|
|
44
|
+
self.total_time_ps: float = float(self.u.trajectory.totaltime)
|
|
45
|
+
|
|
46
|
+
# 元素(若拓扑提供,否则用原子名推断)
|
|
47
|
+
try:
|
|
48
|
+
self.elements = list(self.u.atoms.elements)
|
|
49
|
+
except Exception:
|
|
50
|
+
self.elements = self._guess_elements()
|
|
51
|
+
|
|
52
|
+
# chunk LRU
|
|
53
|
+
self._chunk_size = max(1, int(chunk_size))
|
|
54
|
+
self._max_chunks = max(1, int(max_chunks))
|
|
55
|
+
self._chunks: OrderedDict[int, np.ndarray] = OrderedDict()
|
|
56
|
+
self._lock = threading.Lock()
|
|
57
|
+
self._prefetch_thread: threading.Thread | None = None
|
|
58
|
+
|
|
59
|
+
self._validate()
|
|
60
|
+
|
|
61
|
+
# ---------- 校验 ----------
|
|
62
|
+
|
|
63
|
+
def _validate(self) -> None:
|
|
64
|
+
"""检查原子数一致与时间戳单调(错序拒绝)。"""
|
|
65
|
+
prev_time = None
|
|
66
|
+
for i, ts in enumerate(self.u.trajectory):
|
|
67
|
+
if ts.n_atoms != self.n_atoms:
|
|
68
|
+
raise TrajectoryError(
|
|
69
|
+
f"第 {i} 帧原子数 {ts.n_atoms} 与拓扑 {self.n_atoms} 不一致")
|
|
70
|
+
t = float(ts.time)
|
|
71
|
+
if prev_time is not None and t < prev_time - 1e-9:
|
|
72
|
+
raise TrajectoryError(
|
|
73
|
+
f"轨迹时间戳错序:第 {i-1} 帧 {prev_time} ps > 第 {i} 帧 {t} ps")
|
|
74
|
+
prev_time = t
|
|
75
|
+
# 校验后回到第 0 帧
|
|
76
|
+
self.u.trajectory[0]
|
|
77
|
+
|
|
78
|
+
def _guess_elements(self) -> list[str]:
|
|
79
|
+
out = []
|
|
80
|
+
for name in self.u.atoms.names:
|
|
81
|
+
s = "".join(c for c in str(name) if c.isalpha())
|
|
82
|
+
out.append(s[:2].capitalize() if s else "X")
|
|
83
|
+
return out
|
|
84
|
+
|
|
85
|
+
# ---------- chunk 缓存 ----------
|
|
86
|
+
|
|
87
|
+
def _chunk_index(self, frame: int) -> int:
|
|
88
|
+
return frame // self._chunk_size
|
|
89
|
+
|
|
90
|
+
def _load_chunk(self, chunk: int) -> np.ndarray:
|
|
91
|
+
"""加载一个 chunk 的全部帧坐标,返回 (chunk_len, n_atoms, 3)。"""
|
|
92
|
+
start = chunk * self._chunk_size
|
|
93
|
+
end = min(start + self._chunk_size, self.n_frames)
|
|
94
|
+
data = np.empty((end - start, self.n_atoms, 3), dtype=np.float32)
|
|
95
|
+
for j, fi in enumerate(range(start, end)):
|
|
96
|
+
self.u.trajectory[fi]
|
|
97
|
+
data[j] = self.u.trajectory.ts.positions
|
|
98
|
+
return data
|
|
99
|
+
|
|
100
|
+
def get_frame(self, frame: int) -> np.ndarray:
|
|
101
|
+
"""获取某帧坐标 (n_atoms, 3),单位 Å,带 LRU。线程安全。"""
|
|
102
|
+
if not 0 <= frame < self.n_frames:
|
|
103
|
+
raise IndexError(f"帧 {frame} 越界(共 {self.n_frames} 帧)")
|
|
104
|
+
chunk = self._chunk_index(frame)
|
|
105
|
+
with self._lock:
|
|
106
|
+
if chunk in self._chunks:
|
|
107
|
+
self._chunks.move_to_end(chunk)
|
|
108
|
+
data = self._chunks[chunk]
|
|
109
|
+
else:
|
|
110
|
+
data = self._load_chunk(chunk)
|
|
111
|
+
self._chunks[chunk] = data
|
|
112
|
+
while len(self._chunks) > self._max_chunks:
|
|
113
|
+
self._chunks.popitem(last=False)
|
|
114
|
+
offset = frame - chunk * self._chunk_size
|
|
115
|
+
return data[offset]
|
|
116
|
+
|
|
117
|
+
# ---------- 异步预取 ----------
|
|
118
|
+
|
|
119
|
+
def prefetch_async(self, frames: list[int]) -> None:
|
|
120
|
+
"""后台线程预取指定帧所在的 chunk,不阻塞主线程。"""
|
|
121
|
+
needed = sorted({self._chunk_index(f) for f in frames})
|
|
122
|
+
with self._lock:
|
|
123
|
+
missing = [c for c in needed if c not in self._chunks]
|
|
124
|
+
if not missing:
|
|
125
|
+
return
|
|
126
|
+
if self._prefetch_thread and self._prefetch_thread.is_alive():
|
|
127
|
+
return
|
|
128
|
+
self._prefetch_thread = threading.Thread(
|
|
129
|
+
target=self._prefetch_worker, args=(missing,), daemon=True)
|
|
130
|
+
self._prefetch_thread.start()
|
|
131
|
+
|
|
132
|
+
def _prefetch_worker(self, chunks: list[int]) -> None:
|
|
133
|
+
for c in chunks:
|
|
134
|
+
with self._lock:
|
|
135
|
+
if c in self._chunks:
|
|
136
|
+
self._chunks.move_to_end(c)
|
|
137
|
+
continue
|
|
138
|
+
# 在锁内调用 _load_chunk(c),防止后台预取线程与主线程同时修改同一个 MDAnalysis Universe 游标
|
|
139
|
+
data = self._load_chunk(c)
|
|
140
|
+
self._chunks[c] = data
|
|
141
|
+
while len(self._chunks) > self._max_chunks:
|
|
142
|
+
self._chunks.popitem(last=False)
|
|
143
|
+
|
|
144
|
+
def wait_prefetch(self, timeout: float | None = None) -> None:
|
|
145
|
+
if self._prefetch_thread:
|
|
146
|
+
self._prefetch_thread.join(timeout)
|
|
147
|
+
|
|
148
|
+
# ---------- 播放节拍 ----------
|
|
149
|
+
|
|
150
|
+
def frame_time_ps(self, frame: int) -> float:
|
|
151
|
+
return frame * self.dt_ps
|
|
152
|
+
|
|
153
|
+
def cached_chunk_count(self) -> int:
|
|
154
|
+
with self._lock:
|
|
155
|
+
return len(self._chunks)
|
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Reliable .mforge project ZIP persistence, compatible with v4's Domain model.
|
|
3
|
+
|
|
4
|
+
This replaces the original loader's TODOs: BondId, AtomId, 2D layout, frames,
|
|
5
|
+
per-atom/per-bond appearance, and document metadata round-trip. Save writes to
|
|
6
|
+
a sibling temporary file then atomically replaces the destination.
|
|
7
|
+
|
|
8
|
+
The ZIP reader NEVER extracts paths and accepts only the two expected JSON
|
|
9
|
+
entries. Large trajectory/blobs require future bounded streaming support;
|
|
10
|
+
this JSON-based v1.1 deliberately rejects too-large archives.
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import hashlib
|
|
15
|
+
import json
|
|
16
|
+
import math
|
|
17
|
+
import os
|
|
18
|
+
from pathlib import Path
|
|
19
|
+
import tempfile
|
|
20
|
+
import zipfile
|
|
21
|
+
|
|
22
|
+
import numpy as np
|
|
23
|
+
|
|
24
|
+
from ..domain.document import MoleculeDocument, DocumentStatus
|
|
25
|
+
from ..domain.ids import AtomId, BondId
|
|
26
|
+
|
|
27
|
+
SCHEMA = "1.1"
|
|
28
|
+
MAX_DOCUMENT_BYTES = 128 * 1024 * 1024
|
|
29
|
+
MAX_MANIFEST_BYTES = 1024 * 1024
|
|
30
|
+
MAX_ARCHIVE_BYTES = 160 * 1024 * 1024
|
|
31
|
+
|
|
32
|
+
def _rgb(value):
|
|
33
|
+
if value is None:
|
|
34
|
+
return None
|
|
35
|
+
if not isinstance(value, (list, tuple)) or len(value) != 3:
|
|
36
|
+
raise ValueError("invalid RGB color in .mforge")
|
|
37
|
+
color = tuple(float(q) for q in value)
|
|
38
|
+
if not all(math.isfinite(q) and 0 <= q <= 1 for q in color):
|
|
39
|
+
raise ValueError("non-finite/out-of-range RGB color")
|
|
40
|
+
return color
|
|
41
|
+
|
|
42
|
+
def _atom_properties(value):
|
|
43
|
+
if not isinstance(value,dict):
|
|
44
|
+
raise ValueError("invalid atom properties")
|
|
45
|
+
output=dict(value)
|
|
46
|
+
if "frozen" in output and not isinstance(output["frozen"],bool):
|
|
47
|
+
raise ValueError("frozen must be boolean")
|
|
48
|
+
for key in ("opacity","glow"):
|
|
49
|
+
if key in output:
|
|
50
|
+
number=float(output[key])
|
|
51
|
+
if not math.isfinite(number) or not 0<=number<=1:
|
|
52
|
+
raise ValueError("invalid atom "+key)
|
|
53
|
+
output[key]=number
|
|
54
|
+
if "glow_color" in output:
|
|
55
|
+
output["glow_color"]=list(_rgb(output["glow_color"]))
|
|
56
|
+
return output
|
|
57
|
+
|
|
58
|
+
def _scale(value):
|
|
59
|
+
number = float(value)
|
|
60
|
+
if not math.isfinite(number) or not 0.15 <= number <= 6:
|
|
61
|
+
raise ValueError("invalid appearance scale")
|
|
62
|
+
return number
|
|
63
|
+
|
|
64
|
+
def _limited_json(zf: zipfile.ZipFile, name: str, maximum: int):
|
|
65
|
+
info=zf.getinfo(name)
|
|
66
|
+
if info.file_size > maximum:
|
|
67
|
+
raise ValueError(f"{name}: exceeds size limit")
|
|
68
|
+
if info.file_size > 100_000 and info.file_size / max(info.compress_size, 1) > 1000:
|
|
69
|
+
raise ValueError(f"{name}: suspicious compression ratio")
|
|
70
|
+
with zf.open(info) as stream:
|
|
71
|
+
data=stream.read(maximum + 1)
|
|
72
|
+
if len(data)>maximum:
|
|
73
|
+
raise ValueError(f"{name}: expanded data too large")
|
|
74
|
+
return json.loads(data.decode("utf-8")), data
|
|
75
|
+
|
|
76
|
+
def serialize_document_to_dict(doc: MoleculeDocument) -> dict:
|
|
77
|
+
"""将 MoleculeDocument 序列化为规范标准字典结构。"""
|
|
78
|
+
atoms = []
|
|
79
|
+
for aid in doc.topology.atom_ids:
|
|
80
|
+
a = doc.topology.get_atom(aid)
|
|
81
|
+
atoms.append({
|
|
82
|
+
"id": aid.value, "atomic_num": a.atomic_num,
|
|
83
|
+
"formal_charge": a.formal_charge, "aromatic": a.aromatic,
|
|
84
|
+
"implicit_h": a.implicit_h, "color": _rgb(a.color),
|
|
85
|
+
"scale": _scale(a.scale), "properties": _atom_properties(a.properties)
|
|
86
|
+
})
|
|
87
|
+
bonds = []
|
|
88
|
+
for bid in doc.topology.bond_ids:
|
|
89
|
+
b = doc.topology.get_bond(bid)
|
|
90
|
+
bonds.append({
|
|
91
|
+
"id": bid.value, "begin": b.begin.value, "end": b.end.value,
|
|
92
|
+
"order": b.order, "aromatic": b.aromatic,
|
|
93
|
+
"color": _rgb(b.color), "width_scale": _scale(b.width_scale),
|
|
94
|
+
"properties": b.properties
|
|
95
|
+
})
|
|
96
|
+
frames = []
|
|
97
|
+
if doc._coordinates is not None:
|
|
98
|
+
for frame in doc._coordinates:
|
|
99
|
+
if frame.coords.shape != (doc.num_atoms, 3) or not np.all(np.isfinite(frame.coords)):
|
|
100
|
+
raise ValueError("coordinate shape or NaN/Inf mismatch")
|
|
101
|
+
frames.append({"coords": frame.coords.tolist(), "energy": frame.energy, "source": frame.source})
|
|
102
|
+
coords2d = []
|
|
103
|
+
for aid, xy in doc.coords_2d.items():
|
|
104
|
+
if aid not in doc.topology._atoms or len(xy) != 2 or not all(math.isfinite(float(q)) for q in xy):
|
|
105
|
+
raise ValueError("invalid 2D layout coordinates")
|
|
106
|
+
coords2d.append([aid.value, float(xy[0]), float(xy[1])])
|
|
107
|
+
return {
|
|
108
|
+
"document_id": doc.document_id, "name": doc.name, "revision": doc.revision,
|
|
109
|
+
"status": doc.status.value, "source_format": doc.source_format,
|
|
110
|
+
"source_path": doc.source_path, "properties": doc.properties,
|
|
111
|
+
"units": doc.units, "topology": {"atoms": atoms, "bonds": bonds},
|
|
112
|
+
"coordinates": {"frames": frames,
|
|
113
|
+
"current_index": doc._coordinates.current_index if doc._coordinates is not None else -1},
|
|
114
|
+
"coords_2d": coords2d,
|
|
115
|
+
"id_counter": doc.topology._id_counter.state_dict()
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def save_mforge(doc: MoleculeDocument, path: str | Path) -> None:
|
|
120
|
+
dest=Path(path)
|
|
121
|
+
# Only structural checks; full RDKit sanitization isn't applicable to
|
|
122
|
+
# all drafts/metals. This must not destroy a user's in-progress sketch.
|
|
123
|
+
old_status = doc.status
|
|
124
|
+
try:
|
|
125
|
+
problems=doc.check_invariants()
|
|
126
|
+
finally:
|
|
127
|
+
# validate()/check_invariants() mutates status in v4; Save must be read-only.
|
|
128
|
+
doc.status = old_status
|
|
129
|
+
if problems:
|
|
130
|
+
raise ValueError("Refusing to save inconsistent document: " + "; ".join(problems))
|
|
131
|
+
record = serialize_document_to_dict(doc)
|
|
132
|
+
document_bytes=json.dumps(record,ensure_ascii=False,allow_nan=False,separators=(",",":")).encode("utf-8")
|
|
133
|
+
if len(document_bytes)>MAX_DOCUMENT_BYTES:
|
|
134
|
+
raise ValueError("project is too large for current JSON-based .mforge; streaming project required")
|
|
135
|
+
manifest={
|
|
136
|
+
"format":"mforge","version":SCHEMA,"document_id":doc.document_id,
|
|
137
|
+
"name":doc.name,"revision":doc.revision,
|
|
138
|
+
"num_atoms":doc.num_atoms,"num_bonds":doc.num_bonds,
|
|
139
|
+
"document_sha256":hashlib.sha256(document_bytes).hexdigest()
|
|
140
|
+
}
|
|
141
|
+
manifest_bytes=json.dumps(manifest,ensure_ascii=False,separators=(",",":")).encode("utf-8")
|
|
142
|
+
dest.parent.mkdir(parents=True,exist_ok=True)
|
|
143
|
+
tmp_name=None
|
|
144
|
+
try:
|
|
145
|
+
with tempfile.NamedTemporaryFile(mode="wb",suffix=".mforge.tmp",
|
|
146
|
+
prefix="."+dest.name+".",dir=dest.parent,
|
|
147
|
+
delete=False) as f:
|
|
148
|
+
tmp_name=f.name
|
|
149
|
+
with zipfile.ZipFile(tmp_name,"w",compression=zipfile.ZIP_DEFLATED,
|
|
150
|
+
compresslevel=6) as z:
|
|
151
|
+
z.writestr("manifest.json",manifest_bytes)
|
|
152
|
+
z.writestr("document.json",document_bytes)
|
|
153
|
+
with open(tmp_name,"r+b") as f:
|
|
154
|
+
os.fsync(f.fileno())
|
|
155
|
+
os.replace(tmp_name,dest)
|
|
156
|
+
tmp_name=None
|
|
157
|
+
finally:
|
|
158
|
+
if tmp_name and os.path.exists(tmp_name):
|
|
159
|
+
os.unlink(tmp_name)
|
|
160
|
+
|
|
161
|
+
def load_mforge(path: str | Path) -> MoleculeDocument:
|
|
162
|
+
src=Path(path)
|
|
163
|
+
if not src.is_file():raise FileNotFoundError(src)
|
|
164
|
+
if src.stat().st_size>MAX_ARCHIVE_BYTES:
|
|
165
|
+
raise ValueError("project archive exceeds safe size limit")
|
|
166
|
+
with zipfile.ZipFile(src,"r") as z:
|
|
167
|
+
names=z.namelist()
|
|
168
|
+
if len(names)!=2 or set(names)!={"manifest.json","document.json"}:
|
|
169
|
+
raise ValueError("invalid .mforge archive structure")
|
|
170
|
+
manifest,_=_limited_json(z,"manifest.json",MAX_MANIFEST_BYTES)
|
|
171
|
+
data,raw=_limited_json(z,"document.json",MAX_DOCUMENT_BYTES)
|
|
172
|
+
if not isinstance(manifest,dict) or manifest.get("format")!="mforge":
|
|
173
|
+
raise ValueError("incorrect .mforge manifest")
|
|
174
|
+
if manifest.get("version") not in ("1.0","1.1"):
|
|
175
|
+
raise ValueError("unsupported .mforge schema")
|
|
176
|
+
if manifest.get("document_sha256") and hashlib.sha256(raw).hexdigest()!=manifest["document_sha256"]:
|
|
177
|
+
raise ValueError("document checksum mismatch")
|
|
178
|
+
if not isinstance(data,dict) or not isinstance(data.get("topology"),dict):
|
|
179
|
+
raise ValueError("missing document topology")
|
|
180
|
+
topo=data["topology"]
|
|
181
|
+
atom_data=topo.get("atoms")
|
|
182
|
+
bond_data=topo.get("bonds")
|
|
183
|
+
if not isinstance(atom_data,list) or not isinstance(bond_data,list):
|
|
184
|
+
raise ValueError("invalid atom/bond list")
|
|
185
|
+
if manifest.get("num_atoms")!=len(atom_data) or manifest.get("num_bonds")!=len(bond_data):
|
|
186
|
+
raise ValueError("manifest atom/bond counts disagree with document")
|
|
187
|
+
doc=MoleculeDocument(name=str(data.get("name",manifest.get("name","untitled"))))
|
|
188
|
+
doc.document_id=str(data.get("document_id",manifest["document_id"]))
|
|
189
|
+
doc.revision=int(data.get("revision",manifest.get("revision",0)))
|
|
190
|
+
doc.source_format=data.get("source_format","mforge")
|
|
191
|
+
doc.source_path=data.get("source_path")
|
|
192
|
+
doc.properties=data.get("properties",{})
|
|
193
|
+
doc.units=data.get("units",doc.units)
|
|
194
|
+
seen_atoms=set()
|
|
195
|
+
for a in atom_data:
|
|
196
|
+
aid=AtomId(int(a["id"]))
|
|
197
|
+
if aid.value<0 or aid in seen_atoms:
|
|
198
|
+
raise ValueError("duplicate/negative AtomId in project")
|
|
199
|
+
seen_atoms.add(aid)
|
|
200
|
+
doc.topology.add_atom(int(a["atomic_num"]),
|
|
201
|
+
formal_charge=int(a.get("formal_charge",0)),
|
|
202
|
+
aromatic=bool(a.get("aromatic",False)),atom_id=aid)
|
|
203
|
+
atom=doc.topology.get_atom(aid)
|
|
204
|
+
atom.implicit_h=int(a.get("implicit_h",0))
|
|
205
|
+
atom.color=_rgb(a.get("color"))
|
|
206
|
+
atom.scale=_scale(a.get("scale",1.0))
|
|
207
|
+
atom.properties=_atom_properties(a.get("properties",{}))
|
|
208
|
+
seen_bonds=set()
|
|
209
|
+
for b in bond_data:
|
|
210
|
+
bid=BondId(int(b["id"]))
|
|
211
|
+
if bid.value<0 or bid in seen_bonds:
|
|
212
|
+
raise ValueError("duplicate/negative BondId")
|
|
213
|
+
seen_bonds.add(bid)
|
|
214
|
+
a=AtomId(int(b["begin"])); c=AtomId(int(b["end"]))
|
|
215
|
+
if doc.topology.bond_between(a,c) is not None:
|
|
216
|
+
raise ValueError("two bonds share same endpoints")
|
|
217
|
+
doc.topology.add_bond(a,c,order=int(b["order"]),
|
|
218
|
+
aromatic=bool(b.get("aromatic",False)),bond_id=bid)
|
|
219
|
+
bond=doc.topology.get_bond(bid)
|
|
220
|
+
bond.color=_rgb(b.get("color"))
|
|
221
|
+
bond.width_scale=_scale(b.get("width_scale",1.0))
|
|
222
|
+
bond.properties=b.get("properties",{})
|
|
223
|
+
coords=data.get("coordinates",{})
|
|
224
|
+
frames=coords.get("frames",[])
|
|
225
|
+
if not isinstance(frames,list):
|
|
226
|
+
raise ValueError("invalid coordinate frame list")
|
|
227
|
+
if frames:
|
|
228
|
+
store=doc.ensure_coordinates()
|
|
229
|
+
for fr in frames:
|
|
230
|
+
array=np.asarray(fr["coords"],dtype=np.float32)
|
|
231
|
+
if array.shape!=(doc.num_atoms,3) or not np.all(np.isfinite(array)):
|
|
232
|
+
raise ValueError("invalid frame shape/values")
|
|
233
|
+
store.add_frame(array,energy=fr.get("energy"),source=fr.get("source","mforge"))
|
|
234
|
+
current=int(coords.get("current_index",0))
|
|
235
|
+
store.current_index=current
|
|
236
|
+
layout=data.get("coords_2d",[])
|
|
237
|
+
if not isinstance(layout,list):
|
|
238
|
+
raise ValueError("invalid 2D layout list")
|
|
239
|
+
for value in layout:
|
|
240
|
+
aid=AtomId(int(value[0]))
|
|
241
|
+
if aid not in seen_atoms or aid in doc.coords_2d:
|
|
242
|
+
raise ValueError("2D layout AtomId mismatch")
|
|
243
|
+
xy=(float(value[1]),float(value[2]))
|
|
244
|
+
if not all(math.isfinite(x) for x in xy):
|
|
245
|
+
raise ValueError("2D layout contains non-finite numbers")
|
|
246
|
+
doc.coords_2d[aid]=xy
|
|
247
|
+
counters=data.get("id_counter")
|
|
248
|
+
if counters is not None:
|
|
249
|
+
if (int(counters["next_atom"])<=max([x.value for x in seen_atoms],default=-1)
|
|
250
|
+
or int(counters["next_bond"])<=max([x.value for x in seen_bonds],default=-1)):
|
|
251
|
+
raise ValueError("ID counter would reuse prior persistent identifiers")
|
|
252
|
+
doc.topology._id_counter.load_state_dict(
|
|
253
|
+
{"next_atom":int(counters["next_atom"]),
|
|
254
|
+
"next_bond":int(counters["next_bond"])})
|
|
255
|
+
errors=doc.check_invariants()
|
|
256
|
+
if errors:raise ValueError("project failed structural invariants: "+"; ".join(errors))
|
|
257
|
+
doc.status=DocumentStatus(data.get("status",manifest.get("status","draft")))
|
|
258
|
+
if doc.document_id!=manifest["document_id"]:
|
|
259
|
+
raise ValueError("document identity mismatch")
|
|
260
|
+
return doc
|
|
261
|
+
|