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,115 @@
|
|
|
1
|
+
"""
|
|
2
|
+
domain/provenance.py - 科学来源 / 版本溯源中心
|
|
3
|
+
============================================
|
|
4
|
+
为每个主要数值结果(工件)记录:
|
|
5
|
+
sha256(自动计算)、来源、方法、单位、参数、软件与版本、时间、对应几何,
|
|
6
|
+
derived_from 完整上游图,以及 kind(计算事实 / 实验观测 / AI 假设)。
|
|
7
|
+
|
|
8
|
+
任何主要数值都能沿 derived_from 图回溯到来源、方法和几何。
|
|
9
|
+
"""
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import hashlib
|
|
13
|
+
import platform
|
|
14
|
+
import time
|
|
15
|
+
import uuid
|
|
16
|
+
from dataclasses import dataclass, field
|
|
17
|
+
from enum import Enum
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class ProvenanceKind(Enum):
|
|
22
|
+
COMPUTED = "computed"
|
|
23
|
+
EXPERIMENT = "experiment"
|
|
24
|
+
AI_ASSUMED = "ai_assumed"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass
|
|
28
|
+
class ProvenanceRecord:
|
|
29
|
+
record_id: str
|
|
30
|
+
artifact: str
|
|
31
|
+
sha256: str
|
|
32
|
+
source: str
|
|
33
|
+
method: str = ""
|
|
34
|
+
units: dict[str, str] = field(default_factory=dict)
|
|
35
|
+
params: dict[str, Any] = field(default_factory=dict)
|
|
36
|
+
software: str = ""
|
|
37
|
+
version: str = ""
|
|
38
|
+
geometry_ref: str = ""
|
|
39
|
+
kind: ProvenanceKind = ProvenanceKind.COMPUTED
|
|
40
|
+
derived_from: list[str] = field(default_factory=list)
|
|
41
|
+
created_at: float = 0.0
|
|
42
|
+
|
|
43
|
+
@property
|
|
44
|
+
def is_fact(self) -> bool:
|
|
45
|
+
return self.kind in (ProvenanceKind.COMPUTED, ProvenanceKind.EXPERIMENT)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class ProvenanceGraph:
|
|
49
|
+
def __init__(self) -> None:
|
|
50
|
+
self._records: dict[str, ProvenanceRecord] = {}
|
|
51
|
+
|
|
52
|
+
def add(
|
|
53
|
+
self,
|
|
54
|
+
artifact: str,
|
|
55
|
+
payload: bytes | str,
|
|
56
|
+
source: str,
|
|
57
|
+
method: str = "",
|
|
58
|
+
units: dict | None = None,
|
|
59
|
+
params: dict | None = None,
|
|
60
|
+
software: str = "MolForge",
|
|
61
|
+
version: str = "",
|
|
62
|
+
geometry_ref: str = "",
|
|
63
|
+
kind: ProvenanceKind = ProvenanceKind.COMPUTED,
|
|
64
|
+
derived_from: list[str] | None = None,
|
|
65
|
+
) -> ProvenanceRecord:
|
|
66
|
+
if isinstance(payload, str):
|
|
67
|
+
payload = payload.encode("utf-8")
|
|
68
|
+
sha = hashlib.sha256(payload).hexdigest()
|
|
69
|
+
rec = ProvenanceRecord(
|
|
70
|
+
record_id=uuid.uuid4().hex[:12], artifact=artifact, sha256=sha,
|
|
71
|
+
source=source, method=method, units=units or {},
|
|
72
|
+
params=params or {}, software=software,
|
|
73
|
+
version=version or f"Python {platform.python_version()}",
|
|
74
|
+
geometry_ref=geometry_ref, kind=kind,
|
|
75
|
+
derived_from=list(derived_from or []), created_at=time.time())
|
|
76
|
+
self._records[rec.record_id] = rec
|
|
77
|
+
return rec
|
|
78
|
+
|
|
79
|
+
def get(self, record_id: str) -> ProvenanceRecord:
|
|
80
|
+
return self._records[record_id]
|
|
81
|
+
|
|
82
|
+
def by_artifact(self, name: str) -> list[ProvenanceRecord]:
|
|
83
|
+
return [r for r in self._records.values() if r.artifact == name]
|
|
84
|
+
|
|
85
|
+
def trace_back(self, record_id: str) -> list[ProvenanceRecord]:
|
|
86
|
+
"""沿 derived_from 完整回溯(含自身,去环)。"""
|
|
87
|
+
out: list[ProvenanceRecord] = []
|
|
88
|
+
stack = [record_id]
|
|
89
|
+
seen = set()
|
|
90
|
+
while stack:
|
|
91
|
+
rid = stack.pop()
|
|
92
|
+
if rid in seen or rid not in self._records:
|
|
93
|
+
continue
|
|
94
|
+
seen.add(rid)
|
|
95
|
+
rec = self._records[rid]
|
|
96
|
+
out.append(rec)
|
|
97
|
+
stack.extend(rec.derived_from)
|
|
98
|
+
return out
|
|
99
|
+
|
|
100
|
+
def explain(self, record_id: str) -> dict:
|
|
101
|
+
rec = self.get(record_id)
|
|
102
|
+
return {
|
|
103
|
+
"artifact": rec.artifact, "method": rec.method,
|
|
104
|
+
"source": rec.source, "software": rec.software,
|
|
105
|
+
"version": rec.version, "geometry_ref": rec.geometry_ref,
|
|
106
|
+
"units": rec.units, "kind": rec.kind.value,
|
|
107
|
+
"is_fact": rec.is_fact, "sha256": rec.sha256,
|
|
108
|
+
"derived_from": rec.derived_from}
|
|
109
|
+
|
|
110
|
+
def all_records(self) -> list[ProvenanceRecord]:
|
|
111
|
+
return list(self._records.values())
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
# 向后兼容别名
|
|
115
|
+
ProvenanceTracker = ProvenanceGraph
|
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
"""
|
|
2
|
+
domain/topology.py - 分子拓扑(带稳定双向 AtomId <-> 数组索引映射)
|
|
3
|
+
===================================================================
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
from typing import Iterator
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
|
|
13
|
+
from .ids import AtomId, BondId, IdCounter
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass
|
|
17
|
+
class Atom:
|
|
18
|
+
"""一个原子的静态属性(不含坐标)。"""
|
|
19
|
+
id: AtomId
|
|
20
|
+
atomic_num: int # 原子序数(6=C, 7=N...)
|
|
21
|
+
formal_charge: int = 0 # 形式电荷
|
|
22
|
+
implicit_h: int = 0 # 隐式氢数
|
|
23
|
+
aromatic: bool = False # 是否芳香原子
|
|
24
|
+
color: tuple | None = None # 自定义颜色 (r,g,b) 0-1;None 用默认 CPK
|
|
25
|
+
scale: float = 1.0 # 单原子显示缩放
|
|
26
|
+
properties: dict = field(default_factory=dict)
|
|
27
|
+
|
|
28
|
+
@property
|
|
29
|
+
def element(self) -> int:
|
|
30
|
+
return self.atomic_num
|
|
31
|
+
|
|
32
|
+
@element.setter
|
|
33
|
+
def element(self, val: int) -> None:
|
|
34
|
+
self.atomic_num = int(val)
|
|
35
|
+
|
|
36
|
+
@property
|
|
37
|
+
def symbol(self) -> str:
|
|
38
|
+
from .elements import get_element
|
|
39
|
+
el = get_element(self.atomic_num)
|
|
40
|
+
return el.symbol if el else "X"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass
|
|
44
|
+
class Bond:
|
|
45
|
+
"""一个键的静态属性。"""
|
|
46
|
+
id: BondId
|
|
47
|
+
begin: AtomId
|
|
48
|
+
end: AtomId
|
|
49
|
+
order: int = 1 # 键级:1=单, 2=双, 3=三, 4=芳香
|
|
50
|
+
aromatic: bool = False
|
|
51
|
+
color: tuple | None = None
|
|
52
|
+
width_scale: float = 1.0
|
|
53
|
+
properties: dict = field(default_factory=dict)
|
|
54
|
+
|
|
55
|
+
def other_end(self, aid: AtomId) -> AtomId | None:
|
|
56
|
+
if self.begin == aid:
|
|
57
|
+
return self.end
|
|
58
|
+
if self.end == aid:
|
|
59
|
+
return self.begin
|
|
60
|
+
return None
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class Topology:
|
|
64
|
+
"""
|
|
65
|
+
分子拓扑:原子 + 键的连接关系,维护稳定的双向 ID <-> 索引映射。
|
|
66
|
+
"""
|
|
67
|
+
|
|
68
|
+
def __init__(self) -> None:
|
|
69
|
+
self._atoms: dict[AtomId, Atom] = {}
|
|
70
|
+
self._bonds: dict[BondId, Bond] = {}
|
|
71
|
+
self._adjacency: dict[AtomId, list[BondId]] = {}
|
|
72
|
+
self._id_counter = IdCounter()
|
|
73
|
+
self._atom_index_cache: tuple[list[AtomId], dict[AtomId, int]] | None = None
|
|
74
|
+
self._bond_index_cache: tuple[list[BondId], dict[BondId, int]] | None = None
|
|
75
|
+
|
|
76
|
+
# ---------- 双向映射表(Phase 1 核心要求) ----------
|
|
77
|
+
|
|
78
|
+
def invalidate_index_caches(self) -> None:
|
|
79
|
+
self._atom_index_cache = None
|
|
80
|
+
self._bond_index_cache = None
|
|
81
|
+
self._ring_bonds_cache = None
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def atom_index_map(self) -> tuple[list[AtomId], dict[AtomId, int]]:
|
|
85
|
+
"""返回 (idx_to_atom_id 列表, atom_id_to_idx 字典)。"""
|
|
86
|
+
cache = getattr(self, "_atom_index_cache", None)
|
|
87
|
+
atoms_dict = self._atoms
|
|
88
|
+
if cache is None or cache[0] != id(atoms_dict) or cache[1] != len(atoms_dict):
|
|
89
|
+
idx_to_id = list(atoms_dict.keys())
|
|
90
|
+
id_to_idx = {aid: i for i, aid in enumerate(idx_to_id)}
|
|
91
|
+
cache = (id(atoms_dict), len(atoms_dict), idx_to_id, id_to_idx)
|
|
92
|
+
self._atom_index_cache = cache
|
|
93
|
+
return cache[2], cache[3]
|
|
94
|
+
|
|
95
|
+
def bond_index_map(self) -> tuple[list[BondId], dict[BondId, int]]:
|
|
96
|
+
"""返回 (idx_to_bond_id 列表, bond_id_to_idx 字典)。"""
|
|
97
|
+
cache = getattr(self, "_bond_index_cache", None)
|
|
98
|
+
bonds_dict = self._bonds
|
|
99
|
+
if cache is None or cache[0] != id(bonds_dict) or cache[1] != len(bonds_dict):
|
|
100
|
+
idx_to_id = list(bonds_dict.keys())
|
|
101
|
+
id_to_idx = {bid: i for i, bid in enumerate(idx_to_id)}
|
|
102
|
+
cache = (id(bonds_dict), len(bonds_dict), idx_to_id, id_to_idx)
|
|
103
|
+
self._bond_index_cache = cache
|
|
104
|
+
return cache[2], cache[3]
|
|
105
|
+
|
|
106
|
+
# ---------- 原子操作 ----------
|
|
107
|
+
|
|
108
|
+
def add_atom(
|
|
109
|
+
self,
|
|
110
|
+
atomic_num: int,
|
|
111
|
+
formal_charge: int = 0,
|
|
112
|
+
aromatic: bool = False,
|
|
113
|
+
atom_id: AtomId | None = None,
|
|
114
|
+
) -> AtomId:
|
|
115
|
+
"""添加一个原子,返回新原子 ID。若传入 atom_id(如 redo),则复用该 ID 防止漂移。"""
|
|
116
|
+
if atom_id is not None:
|
|
117
|
+
aid = atom_id
|
|
118
|
+
if hasattr(self._id_counter, "_next_atom") and aid.value >= self._id_counter._next_atom:
|
|
119
|
+
self._id_counter._next_atom = aid.value + 1
|
|
120
|
+
else:
|
|
121
|
+
aid = self._id_counter.next_atom()
|
|
122
|
+
|
|
123
|
+
atom = Atom(
|
|
124
|
+
id=aid,
|
|
125
|
+
atomic_num=int(atomic_num),
|
|
126
|
+
formal_charge=int(formal_charge),
|
|
127
|
+
aromatic=bool(aromatic),
|
|
128
|
+
)
|
|
129
|
+
self._atoms[aid] = atom
|
|
130
|
+
if aid not in self._adjacency:
|
|
131
|
+
self._adjacency[aid] = []
|
|
132
|
+
self._atom_index_cache = None
|
|
133
|
+
return aid
|
|
134
|
+
|
|
135
|
+
def restore_atom(self, atom: Atom, index: int | None = None) -> AtomId:
|
|
136
|
+
"""恢复已删除的原子(保持原有 AtomId 与在拓扑中的顺序索引)。"""
|
|
137
|
+
aid = atom.id
|
|
138
|
+
if hasattr(self._id_counter, "_next_atom") and aid.value >= self._id_counter._next_atom:
|
|
139
|
+
self._id_counter._next_atom = aid.value + 1
|
|
140
|
+
if index is None or index >= len(self._atoms):
|
|
141
|
+
self._atoms[aid] = atom
|
|
142
|
+
else:
|
|
143
|
+
items = list(self._atoms.items())
|
|
144
|
+
items.insert(max(0, index), (aid, atom))
|
|
145
|
+
self._atoms = dict(items)
|
|
146
|
+
if aid not in self._adjacency:
|
|
147
|
+
self._adjacency[aid] = []
|
|
148
|
+
self._atom_index_cache = None
|
|
149
|
+
return aid
|
|
150
|
+
|
|
151
|
+
def remove_atom(self, aid: AtomId) -> None:
|
|
152
|
+
"""删除原子,同时删除所有关联键。"""
|
|
153
|
+
if aid not in self._atoms:
|
|
154
|
+
return
|
|
155
|
+
bond_ids = list(self._adjacency.get(aid, []))
|
|
156
|
+
for bid in bond_ids:
|
|
157
|
+
self.remove_bond(bid)
|
|
158
|
+
del self._atoms[aid]
|
|
159
|
+
del self._adjacency[aid]
|
|
160
|
+
self._atom_index_cache = None
|
|
161
|
+
|
|
162
|
+
def get_atom(self, aid: AtomId) -> Atom:
|
|
163
|
+
return self._atoms[aid]
|
|
164
|
+
|
|
165
|
+
def index_of_atom(self, aid: AtomId) -> int:
|
|
166
|
+
"""返回原子在当前拓扑序列中的索引(0-based)。"""
|
|
167
|
+
_, id_to_idx = self.atom_index_map()
|
|
168
|
+
idx = id_to_idx.get(aid)
|
|
169
|
+
if idx is None:
|
|
170
|
+
raise KeyError(f"原子 {aid} 不存在")
|
|
171
|
+
return idx
|
|
172
|
+
|
|
173
|
+
@property
|
|
174
|
+
def num_atoms(self) -> int:
|
|
175
|
+
return len(self._atoms)
|
|
176
|
+
|
|
177
|
+
@property
|
|
178
|
+
def atom_ids(self) -> Iterator[AtomId]:
|
|
179
|
+
return iter(self._atoms.keys())
|
|
180
|
+
|
|
181
|
+
# ---------- 键操作 ----------
|
|
182
|
+
|
|
183
|
+
def add_bond(
|
|
184
|
+
self,
|
|
185
|
+
a: AtomId,
|
|
186
|
+
b: AtomId,
|
|
187
|
+
order: int = 1,
|
|
188
|
+
aromatic: bool = False,
|
|
189
|
+
bond_id: BondId | None = None,
|
|
190
|
+
) -> BondId:
|
|
191
|
+
"""在两个原子之间添加键。若传入 bond_id(如 redo),则复用该 ID。"""
|
|
192
|
+
if a not in self._atoms or b not in self._atoms:
|
|
193
|
+
raise ValueError("键的两端原子必须存在")
|
|
194
|
+
if a == b:
|
|
195
|
+
raise ValueError("不能在同一原子上建立自环键")
|
|
196
|
+
existing = self.bond_between(a, b)
|
|
197
|
+
if existing is not None:
|
|
198
|
+
bond = self._bonds[existing]
|
|
199
|
+
bond.order = int(order)
|
|
200
|
+
bond.aromatic = bool(aromatic)
|
|
201
|
+
return existing
|
|
202
|
+
|
|
203
|
+
if bond_id is not None:
|
|
204
|
+
bid = bond_id
|
|
205
|
+
if hasattr(self._id_counter, "_next_bond") and bid.value >= self._id_counter._next_bond:
|
|
206
|
+
self._id_counter._next_bond = bid.value + 1
|
|
207
|
+
else:
|
|
208
|
+
bid = self._id_counter.next_bond()
|
|
209
|
+
|
|
210
|
+
bond = Bond(id=bid, begin=a, end=b, order=int(order), aromatic=bool(aromatic))
|
|
211
|
+
self._bonds[bid] = bond
|
|
212
|
+
self._adjacency[a].append(bid)
|
|
213
|
+
self._adjacency[b].append(bid)
|
|
214
|
+
self._bond_index_cache = None
|
|
215
|
+
return bid
|
|
216
|
+
|
|
217
|
+
def restore_bond(self, bond: Bond) -> BondId:
|
|
218
|
+
"""恢复已删除的键(保持原有 BondId)。"""
|
|
219
|
+
if bond.begin not in self._atoms or bond.end not in self._atoms:
|
|
220
|
+
raise ValueError("恢复键失败:端点原子不存在")
|
|
221
|
+
bid = bond.id
|
|
222
|
+
if hasattr(self._id_counter, "_next_bond") and bid.value >= self._id_counter._next_bond:
|
|
223
|
+
self._id_counter._next_bond = bid.value + 1
|
|
224
|
+
self._bonds[bid] = bond
|
|
225
|
+
if bid not in self._adjacency[bond.begin]:
|
|
226
|
+
self._adjacency[bond.begin].append(bid)
|
|
227
|
+
if bid not in self._adjacency[bond.end]:
|
|
228
|
+
self._adjacency[bond.end].append(bid)
|
|
229
|
+
self._bond_index_cache = None
|
|
230
|
+
return bid
|
|
231
|
+
|
|
232
|
+
def remove_bond(self, bid: BondId) -> None:
|
|
233
|
+
"""删除键。"""
|
|
234
|
+
if bid not in self._bonds:
|
|
235
|
+
return
|
|
236
|
+
bond = self._bonds[bid]
|
|
237
|
+
if bond.begin in self._adjacency and bid in self._adjacency[bond.begin]:
|
|
238
|
+
self._adjacency[bond.begin].remove(bid)
|
|
239
|
+
if bond.end in self._adjacency and bid in self._adjacency[bond.end]:
|
|
240
|
+
self._adjacency[bond.end].remove(bid)
|
|
241
|
+
del self._bonds[bid]
|
|
242
|
+
self._bond_index_cache = None
|
|
243
|
+
|
|
244
|
+
def get_bond(self, bid: BondId) -> Bond:
|
|
245
|
+
return self._bonds[bid]
|
|
246
|
+
|
|
247
|
+
@property
|
|
248
|
+
def num_bonds(self) -> int:
|
|
249
|
+
return len(self._bonds)
|
|
250
|
+
|
|
251
|
+
@property
|
|
252
|
+
def bond_ids(self) -> Iterator[BondId]:
|
|
253
|
+
return iter(self._bonds.keys())
|
|
254
|
+
|
|
255
|
+
# ---------- 查询 ----------
|
|
256
|
+
|
|
257
|
+
def all_atom_ids(self) -> list[AtomId]:
|
|
258
|
+
return list(self._atoms.keys())
|
|
259
|
+
|
|
260
|
+
def adjacent_atoms(self, aid: AtomId) -> list[AtomId]:
|
|
261
|
+
return self.neighbors_of(aid)
|
|
262
|
+
|
|
263
|
+
def bonds_of(self, aid: AtomId) -> list[BondId]:
|
|
264
|
+
"""返回与指定原子相连的所有化学键 ID。"""
|
|
265
|
+
return list(self._adjacency.get(aid, []))
|
|
266
|
+
|
|
267
|
+
def neighbors_of(self, aid: AtomId) -> list[AtomId]:
|
|
268
|
+
"""返回与指定原子直接相连的所有原子 ID。"""
|
|
269
|
+
result = []
|
|
270
|
+
for bid in self._adjacency.get(aid, []):
|
|
271
|
+
bond = self._bonds.get(bid)
|
|
272
|
+
if bond is None:
|
|
273
|
+
continue
|
|
274
|
+
other = bond.end if bond.begin == aid else bond.begin
|
|
275
|
+
result.append(other)
|
|
276
|
+
return result
|
|
277
|
+
|
|
278
|
+
def bond_between(self, a: AtomId, b: AtomId) -> BondId | None:
|
|
279
|
+
"""查找两个原子之间的键,不存在返回 None。"""
|
|
280
|
+
for bid in self._adjacency.get(a, []):
|
|
281
|
+
bond = self._bonds.get(bid)
|
|
282
|
+
if bond is None:
|
|
283
|
+
continue
|
|
284
|
+
if (bond.begin == b and bond.end == a) or (bond.begin == a and bond.end == b):
|
|
285
|
+
return bid
|
|
286
|
+
return None
|
|
287
|
+
|
|
288
|
+
def atom_count_array(self) -> np.ndarray:
|
|
289
|
+
"""返回所有原子的原子序数数组(按添加顺序)。"""
|
|
290
|
+
return np.array(
|
|
291
|
+
[self._atoms[aid].atomic_num for aid in self._atoms],
|
|
292
|
+
dtype=np.int32,
|
|
293
|
+
)
|
|
294
|
+
|
|
295
|
+
def connected_components(self) -> list[set[AtomId]]:
|
|
296
|
+
"""计算拓扑中所有不连通的子图/连通分量集合列表。"""
|
|
297
|
+
visited = set()
|
|
298
|
+
components: list[set[AtomId]] = []
|
|
299
|
+
for aid in self._atoms:
|
|
300
|
+
if aid not in visited:
|
|
301
|
+
comp: set[AtomId] = set()
|
|
302
|
+
queue = [aid]
|
|
303
|
+
visited.add(aid)
|
|
304
|
+
while queue:
|
|
305
|
+
curr = queue.pop(0)
|
|
306
|
+
comp.add(curr)
|
|
307
|
+
for nbr in self.neighbors_of(curr):
|
|
308
|
+
if nbr not in visited:
|
|
309
|
+
visited.add(nbr)
|
|
310
|
+
queue.append(nbr)
|
|
311
|
+
components.append(comp)
|
|
312
|
+
return components
|
|
313
|
+
|
|
314
|
+
def rings_count(self) -> int:
|
|
315
|
+
"""根据图论圈秩(Cyclomatic Number / SSSR 基础环数)严格计算环数:
|
|
316
|
+
R = E - V + C,其中 C 为连通分量数。对于独立多分子体系也能精准给出真值。
|
|
317
|
+
"""
|
|
318
|
+
v = len(self._atoms)
|
|
319
|
+
if v == 0:
|
|
320
|
+
return 0
|
|
321
|
+
e = len(self._bonds)
|
|
322
|
+
c = len(self.connected_components())
|
|
323
|
+
return max(0, e - v + c)
|
|
324
|
+
|
|
325
|
+
def is_bond_in_ring(self, bid: BondId) -> bool:
|
|
326
|
+
"""判断指定化学键是否属于任意分子环内(即非桥接/非割边割链化学键)。"""
|
|
327
|
+
if bid not in self._bonds:
|
|
328
|
+
return False
|
|
329
|
+
cache = getattr(self, "_ring_bonds_cache", None)
|
|
330
|
+
bonds_dict = self._bonds
|
|
331
|
+
if cache is None or cache[0] != id(bonds_dict) or cache[1] != len(bonds_dict):
|
|
332
|
+
self._compute_ring_bonds()
|
|
333
|
+
cache = self._ring_bonds_cache
|
|
334
|
+
return bid in cache[2]
|
|
335
|
+
|
|
336
|
+
def _compute_ring_bonds(self) -> None:
|
|
337
|
+
"""使用图论备用路径搜索检测所有环内化学键。
|
|
338
|
+
化学键 (u, v) 在环内 当且仅当 从 u 到 v 存在不经过该键的第二条路径。
|
|
339
|
+
"""
|
|
340
|
+
ring_bonds: set[BondId] = set()
|
|
341
|
+
for bid, bond in self._bonds.items():
|
|
342
|
+
# Aromaticity is a bond-property, not proof of a topological cycle.
|
|
343
|
+
u, v = bond.begin, bond.end
|
|
344
|
+
visited = {u}
|
|
345
|
+
queue = [u]
|
|
346
|
+
found = False
|
|
347
|
+
while queue and not found:
|
|
348
|
+
curr = queue.pop(0)
|
|
349
|
+
for b_other in self._adjacency.get(curr, []):
|
|
350
|
+
if b_other == bid:
|
|
351
|
+
continue
|
|
352
|
+
other_atom = self._bonds[b_other].other_end(curr)
|
|
353
|
+
if other_atom is None:
|
|
354
|
+
continue
|
|
355
|
+
if other_atom == v:
|
|
356
|
+
found = True
|
|
357
|
+
break
|
|
358
|
+
if other_atom not in visited:
|
|
359
|
+
visited.add(other_atom)
|
|
360
|
+
queue.append(other_atom)
|
|
361
|
+
if found:
|
|
362
|
+
ring_bonds.add(bid)
|
|
363
|
+
self._ring_bonds_cache = (id(self._bonds), len(self._bonds), ring_bonds)
|
|
364
|
+
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""
|
|
2
|
+
infrastructure/ - 基础设施层
|
|
3
|
+
==============================
|
|
4
|
+
IO、计算后端、LLM 适配器等外部依赖。
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
__all__ = ["FormatHandler", "registry", "glog_reader", "gjf_writer"]
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def __getattr__(name: str):
|
|
11
|
+
if name == "FormatHandler":
|
|
12
|
+
from ..io.registry import FormatHandler
|
|
13
|
+
return FormatHandler
|
|
14
|
+
elif name == "registry":
|
|
15
|
+
from ..io import registry
|
|
16
|
+
return registry
|
|
17
|
+
elif name == "glog_reader":
|
|
18
|
+
from ..io.readers import glog_reader
|
|
19
|
+
return glog_reader
|
|
20
|
+
elif name == "gjf_writer":
|
|
21
|
+
from ..io.writers import gjf_writer
|
|
22
|
+
return gjf_writer
|
|
23
|
+
raise AttributeError(f"module '{__name__}' has no attribute '{name}'")
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""
|
|
2
|
+
molforge/infrastructure/hpc/cluster_config.py - Linux 超算/服务器连接与调度配置模型
|
|
3
|
+
=============================================================================
|
|
4
|
+
支持配置多台 Linux 计算节点/超算集群:
|
|
5
|
+
- 协议: SSH (密钥或密码) / 本地 WSL2 (Windows Subsystem for Linux)
|
|
6
|
+
- 调度系统: Slurm (sbatch/squeue/scancel), PBS/Torque (qsub/qstat), 直接后台 nohup
|
|
7
|
+
- 环境初始化: module load, conda activate, 环境变量预置
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import json
|
|
13
|
+
from dataclasses import dataclass, field, asdict
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any, Dict, List, Literal, Optional
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass
|
|
19
|
+
class ClusterProfile:
|
|
20
|
+
"""Linux 计算主机档案。"""
|
|
21
|
+
name: str = "Default_Linux_Cluster"
|
|
22
|
+
host_type: Literal["ssh", "wsl", "local"] = "ssh"
|
|
23
|
+
hostname: str = "hpc.university.edu"
|
|
24
|
+
port: int = 22
|
|
25
|
+
username: str = "chem_user"
|
|
26
|
+
key_path: str = "" # 推荐: ~/.ssh/id_rsa
|
|
27
|
+
password: str = "" # 可选或交互输入
|
|
28
|
+
remote_workdir: str = "~/molforge_jobs" # 远程临时计算基目录
|
|
29
|
+
scheduler: Literal["slurm", "pbs", "nohup"] = "slurm"
|
|
30
|
+
default_partition: str = "compute"
|
|
31
|
+
default_nodes: int = 1
|
|
32
|
+
default_ntasks: int = 16
|
|
33
|
+
default_memory_mb: int = 32000
|
|
34
|
+
default_walltime: str = "24:00:00"
|
|
35
|
+
env_preamble: List[str] = field(default_factory=lambda: [
|
|
36
|
+
"module purge",
|
|
37
|
+
"module load gaussian/g16-c01",
|
|
38
|
+
"module load orca/6.0.0",
|
|
39
|
+
"module load openmpi/4.1.4",
|
|
40
|
+
])
|
|
41
|
+
app_paths: Dict[str, str] = field(default_factory=lambda: {
|
|
42
|
+
"g16": "g16",
|
|
43
|
+
"orca": "orca",
|
|
44
|
+
"xtb": "xtb",
|
|
45
|
+
"gromacs": "gmx",
|
|
46
|
+
"calchem": "calchem-cli",
|
|
47
|
+
"rest": "/home/administrator/miniforge3/envs/rest-py311/bin/rest",
|
|
48
|
+
})
|
|
49
|
+
|
|
50
|
+
def to_dict(self) -> Dict[str, Any]:
|
|
51
|
+
return asdict(self)
|
|
52
|
+
|
|
53
|
+
@classmethod
|
|
54
|
+
def from_dict(cls, data: Dict[str, Any]) -> ClusterProfile:
|
|
55
|
+
return cls(**{k: v for k, v in data.items() if k in cls.__dataclass_fields__})
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class ClusterConfigManager:
|
|
59
|
+
"""集群配置持久化管理器。"""
|
|
60
|
+
|
|
61
|
+
def __init__(self, config_dir: Optional[Path] = None):
|
|
62
|
+
if config_dir is None:
|
|
63
|
+
from ...runtime import data_dir
|
|
64
|
+
config_dir = data_dir() / "settings"
|
|
65
|
+
self.config_file = Path(config_dir) / "clusters.json"
|
|
66
|
+
self.profiles: Dict[str, ClusterProfile] = {}
|
|
67
|
+
self.load()
|
|
68
|
+
|
|
69
|
+
def load(self) -> None:
|
|
70
|
+
if self.config_file.exists():
|
|
71
|
+
try:
|
|
72
|
+
with open(self.config_file, "r", encoding="utf-8") as f:
|
|
73
|
+
data = json.load(f)
|
|
74
|
+
self.profiles = {
|
|
75
|
+
name: ClusterProfile.from_dict(prof)
|
|
76
|
+
for name, prof in data.get("profiles", {}).items()
|
|
77
|
+
}
|
|
78
|
+
except Exception:
|
|
79
|
+
self._create_default()
|
|
80
|
+
else:
|
|
81
|
+
self._create_default()
|
|
82
|
+
|
|
83
|
+
def _create_default(self) -> None:
|
|
84
|
+
default_prof = ClusterProfile()
|
|
85
|
+
wsl_prof = ClusterProfile(
|
|
86
|
+
name="Local_WSL2_Ubuntu",
|
|
87
|
+
host_type="wsl",
|
|
88
|
+
hostname="localhost",
|
|
89
|
+
username="",
|
|
90
|
+
remote_workdir="/tmp/molforge_wsl",
|
|
91
|
+
scheduler="nohup",
|
|
92
|
+
env_preamble=[
|
|
93
|
+
"source /home/administrator/miniforge3/etc/profile.d/conda.sh && conda activate rest-py311",
|
|
94
|
+
"export REST_BASIS_DIR=/mnt/e/YDW/REST/knowledge_base/rest_github/basis-set-pool",
|
|
95
|
+
],
|
|
96
|
+
app_paths={
|
|
97
|
+
"g16": "g16",
|
|
98
|
+
"orca": "orca",
|
|
99
|
+
"xtb": "xtb",
|
|
100
|
+
"gromacs": "gmx",
|
|
101
|
+
"calchem": "calchem-cli",
|
|
102
|
+
"rest": "/home/administrator/miniforge3/envs/rest-py311/bin/rest",
|
|
103
|
+
},
|
|
104
|
+
)
|
|
105
|
+
self.profiles = {default_prof.name: default_prof, wsl_prof.name: wsl_prof}
|
|
106
|
+
self.save()
|
|
107
|
+
|
|
108
|
+
def save(self) -> None:
|
|
109
|
+
self.config_file.parent.mkdir(parents=True, exist_ok=True)
|
|
110
|
+
data = {
|
|
111
|
+
"version": "1.0",
|
|
112
|
+
"profiles": {name: p.to_dict() for name, p in self.profiles.items()},
|
|
113
|
+
}
|
|
114
|
+
with open(self.config_file, "w", encoding="utf-8") as f:
|
|
115
|
+
json.dump(data, f, indent=2, ensure_ascii=False)
|
|
116
|
+
|
|
117
|
+
def get(self, name: str) -> Optional[ClusterProfile]:
|
|
118
|
+
return self.profiles.get(name)
|
|
119
|
+
|
|
120
|
+
def set(self, profile: ClusterProfile) -> None:
|
|
121
|
+
self.profiles[profile.name] = profile
|
|
122
|
+
self.save()
|