molforge-studio 7.4.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (219) hide show
  1. main.py +71 -0
  2. molforge/__init__.py +19 -0
  3. molforge/ai/__init__.py +15 -0
  4. molforge/ai/deepseek_harness.py +185 -0
  5. molforge/ai/mcp/desktop_client.py +38 -0
  6. molforge/ai/mcp/desktop_service.py +121 -0
  7. molforge/ai/mcp/mcp_server.py +780 -0
  8. molforge/ai/mcp_bridge.py +945 -0
  9. molforge/ai/observation.py +152 -0
  10. molforge/ai/tools.py +455 -0
  11. molforge/application/__init__.py +22 -0
  12. molforge/application/ai/__init__.py +1 -0
  13. molforge/application/ai/deepseek_client.py +293 -0
  14. molforge/application/ai/observation.py +161 -0
  15. molforge/application/ai/tools.py +200 -0
  16. molforge/application/ai_proposals.py +166 -0
  17. molforge/application/bio_selection.py +143 -0
  18. molforge/application/builtin_commands.py +1445 -0
  19. molforge/application/calculators/__init__.py +10 -0
  20. molforge/application/calculators/base.py +143 -0
  21. molforge/application/calculators/calchem_engine.py +67 -0
  22. molforge/application/calculators/calchem_subprocess_worker.py +109 -0
  23. molforge/application/calculators/gaussian_engine.py +59 -0
  24. molforge/application/calculators/gaussian_job_spec.py +240 -0
  25. molforge/application/calculators/orca_engine.py +92 -0
  26. molforge/application/calculators/qc_input_generator.py +300 -0
  27. molforge/application/calculators/registry.py +29 -0
  28. molforge/application/calculators/rest_engine.py +262 -0
  29. molforge/application/command_bus.py +139 -0
  30. molforge/application/commands.py +55 -0
  31. molforge/application/conformers.py +143 -0
  32. molforge/application/document_session.py +156 -0
  33. molforge/application/events.py +74 -0
  34. molforge/application/fragment_catalog.py +422 -0
  35. molforge/application/fragment_commands.py +268 -0
  36. molforge/application/geometry_commands.py +84 -0
  37. molforge/application/history.py +105 -0
  38. molforge/application/internal_coordinates.py +293 -0
  39. molforge/application/invalidation.py +1174 -0
  40. molforge/application/jobs.py +185 -0
  41. molforge/application/measurement.py +167 -0
  42. molforge/application/measurement_targets.py +264 -0
  43. molforge/application/modeling_commands.py +61 -0
  44. molforge/application/plugins.py +197 -0
  45. molforge/application/ports/editor2d.py +85 -0
  46. molforge/application/reaction.py +75 -0
  47. molforge/application/selection.py +164 -0
  48. molforge/application/selection_commands.py +31 -0
  49. molforge/application/trajectory.py +120 -0
  50. molforge/application/trajectory_analysis.py +231 -0
  51. molforge/application/workspace_registry.py +226 -0
  52. molforge/core/__init__.py +12 -0
  53. molforge/core/conformer.py +45 -0
  54. molforge/core/molecule.py +150 -0
  55. molforge/core/orbital.py +33 -0
  56. molforge/core/properties.py +43 -0
  57. molforge/domain/__init__.py +12 -0
  58. molforge/domain/biomolecule.py +99 -0
  59. molforge/domain/chemical_summary.py +129 -0
  60. molforge/domain/chemistry.py +13 -0
  61. molforge/domain/coordinate_store.py +164 -0
  62. molforge/domain/coordination.py +133 -0
  63. molforge/domain/custom_fragments.py +255 -0
  64. molforge/domain/document.py +469 -0
  65. molforge/domain/element_reference.json +598 -0
  66. molforge/domain/elements.py +188 -0
  67. molforge/domain/ids.py +58 -0
  68. molforge/domain/massive_system.py +246 -0
  69. molforge/domain/periodic.py +116 -0
  70. molforge/domain/provenance.py +115 -0
  71. molforge/domain/topology.py +364 -0
  72. molforge/infrastructure/__init__.py +23 -0
  73. molforge/infrastructure/hpc/cluster_config.py +122 -0
  74. molforge/infrastructure/hpc/remote_executor.py +212 -0
  75. molforge/infrastructure/hpc/slurm_generator.py +93 -0
  76. molforge/io/__init__.py +35 -0
  77. molforge/io/calchem_bridge.py +407 -0
  78. molforge/io/calculators.py +893 -0
  79. molforge/io/cclib_adapter.py +422 -0
  80. molforge/io/conformers.py +183 -0
  81. molforge/io/cube_reader.py +215 -0
  82. molforge/io/custom_fragments.py +79 -0
  83. molforge/io/format_matrix.py +157 -0
  84. molforge/io/gemmi_adapter.py +150 -0
  85. molforge/io/history_skill.py +46 -0
  86. molforge/io/mdanalysis_adapter.py +155 -0
  87. molforge/io/mforge_storage.py +261 -0
  88. molforge/io/multiwfn_driver.py +614 -0
  89. molforge/io/openbabel_adapter.py +265 -0
  90. molforge/io/openbabel_handler.py +33 -0
  91. molforge/io/rdkit_adapter.py +1865 -0
  92. molforge/io/readers/__init__.py +10 -0
  93. molforge/io/readers/cube_reader.py +71 -0
  94. molforge/io/readers/gjf_reader.py +110 -0
  95. molforge/io/readers/glog_reader.py +45 -0
  96. molforge/io/readers/mol2_reader.py +36 -0
  97. molforge/io/readers/mol_reader.py +56 -0
  98. molforge/io/readers/pdb_reader.py +39 -0
  99. molforge/io/readers/smi_reader.py +40 -0
  100. molforge/io/readers/xyz_reader.py +47 -0
  101. molforge/io/registry.py +128 -0
  102. molforge/io/writers/__init__.py +7 -0
  103. molforge/io/writers/gjf_writer.py +68 -0
  104. molforge/io/writers/pdb_writer.py +37 -0
  105. molforge/io/writers/png_writer.py +31 -0
  106. molforge/io/writers/svg_writer.py +111 -0
  107. molforge/io/writers/xyz_writer.py +39 -0
  108. molforge/rendering/__init__.py +21 -0
  109. molforge/rendering/benchmark.py +121 -0
  110. molforge/rendering/bridge.py +60 -0
  111. molforge/rendering/contracts.py +119 -0
  112. molforge/rendering/glyph_scene.py +279 -0
  113. molforge/rendering/ketcher_bridge.py +131 -0
  114. molforge/rendering/ketcher_id_mapping.py +110 -0
  115. molforge/rendering/materials.py +127 -0
  116. molforge/rendering/molstar_backend.py +245 -0
  117. molforge/rendering/native_labels.py +134 -0
  118. molforge/rendering/orbitals.py +139 -0
  119. molforge/rendering/vtk_backend.py +2294 -0
  120. molforge/runtime.py +29 -0
  121. molforge/server/__init__.py +1 -0
  122. molforge/server/api_bridge.py +947 -0
  123. molforge/ui/__init__.py +1 -0
  124. molforge/ui/assets/caffeine_2d.svg +150 -0
  125. molforge/ui/assets/caffeine_3d_preview.svg +209 -0
  126. molforge/ui/assets/caffeine_preview.json +302 -0
  127. molforge/ui/assets/icons/atom.svg +1 -0
  128. molforge/ui/assets/icons/bond.svg +1 -0
  129. molforge/ui/assets/icons/cleanup.svg +1 -0
  130. molforge/ui/assets/icons/export.svg +1 -0
  131. molforge/ui/assets/icons/fragments.svg +1 -0
  132. molforge/ui/assets/icons/history.svg +1 -0
  133. molforge/ui/assets/icons/jobs.svg +1 -0
  134. molforge/ui/assets/icons/measure.svg +1 -0
  135. molforge/ui/assets/icons/molecules.svg +1 -0
  136. molforge/ui/assets/icons/overview.svg +1 -0
  137. molforge/ui/assets/icons/ring.svg +1 -0
  138. molforge/ui/assets/icons/search.svg +1 -0
  139. molforge/ui/assets/icons/select.svg +1 -0
  140. molforge/ui/assets/icons/settings.svg +1 -0
  141. molforge/ui/assets/icons/templates.svg +1 -0
  142. molforge/ui/assets/molforge_logo.ico +0 -0
  143. molforge/ui/assets/molforge_logo.png +0 -0
  144. molforge/ui/atom_labels.py +92 -0
  145. molforge/ui/bio_structure_dialog.py +57 -0
  146. molforge/ui/conformer_dialog.py +151 -0
  147. molforge/ui/dialogs/__init__.py +2 -0
  148. molforge/ui/dialogs/aim_qtaim_dialog.py +533 -0
  149. molforge/ui/dialogs/calchem_orbitals_dialog.py +287 -0
  150. molforge/ui/dialogs/element_fragments.py +130 -0
  151. molforge/ui/dialogs/gaussian_calculation_setup.py +308 -0
  152. molforge/ui/dialogs/hpc_job_dialog.py +427 -0
  153. molforge/ui/dialogs/vibrational_spectrum_dialog.py +381 -0
  154. molforge/ui/editor2d_widget.py +1803 -0
  155. molforge/ui/element_picker.py +218 -0
  156. molforge/ui/gmv_window_manager.py +65 -0
  157. molforge/ui/gromacs_job_dialog.py +47 -0
  158. molforge/ui/hotkeys.py +107 -0
  159. molforge/ui/i18n.py +237 -0
  160. molforge/ui/live_llm_dialog.py +135 -0
  161. molforge/ui/llm_config_dialog.py +103 -0
  162. molforge/ui/modeling_actions.py +176 -0
  163. molforge/ui/molstar_widget.py +98 -0
  164. molforge/ui/molstar_window.py +85 -0
  165. molforge/ui/panels.py +2966 -0
  166. molforge/ui/qc_result_dialog.py +1924 -0
  167. molforge/ui/render3d_widget.py +1579 -0
  168. molforge/ui/scrolling.py +52 -0
  169. molforge/ui/settings_panel.py +330 -0
  170. molforge/ui/shells/__init__.py +4 -0
  171. molforge/ui/shells/base_shell.py +72 -0
  172. molforge/ui/shells/document_tabs.py +715 -0
  173. molforge/ui/shells/studio_2d.py +339 -0
  174. molforge/ui/shells/studio_3d.py +401 -0
  175. molforge/ui/shells/studio_split.py +370 -0
  176. molforge/ui/shells/workflow_inputs.py +698 -0
  177. molforge/ui/theme.py +719 -0
  178. molforge/ui/trajectory_window.py +333 -0
  179. molforge/ui/views.py +892 -0
  180. molforge/ui/vtk_multiview_widget.py +141 -0
  181. molforge/ui/welcome_window.py +223 -0
  182. molforge/ui/window.py +3320 -0
  183. molforge/workflows/__init__.py +25 -0
  184. molforge/workflows/assets/OSC_MD_workflows/templates/01-MD/delete_solvent.py +216 -0
  185. molforge/workflows/assets/OSC_MD_workflows/templates/02-RDF/extract_atoms.py +60 -0
  186. molforge/workflows/assets/OSC_MD_workflows/templates/02-RDF/extract_atoms_example.py +22 -0
  187. molforge/workflows/assets/OSC_MD_workflows/templates/03-/342/225/244/320/225/342/225/250/342/226/221/342/225/250/320/246/342/225/244/320/227/342/225/250/342/225/226/342/225/250/342/224/220/342/225/244/320/225/342/225/250/320/247/342/225/250/342/226/221/342/225/244/320/224/321/202/320/245/320/254/342/225/250/320/265/analysis_mol.py +244 -0
  188. molforge/workflows/assets/OSC_MD_workflows/templates/04-/342/225/244/320/224/321/202/320/245/320/241/342/225/250/320/254/342/225/244/320/227/321/202/320/245/320/247/321/202/320/244/320/264/342/225/244/320/225/342/225/250/342/224/220/342/225/250/320/246/342/225/244/320/225/321/202/320/245/320/241/342/225/250/342/225/242/rms_roughness.py +33 -0
  189. molforge/workflows/assets/OSC_MD_workflows/templates/04-/342/225/244/320/224/321/202/320/245/320/241/342/225/250/320/254/342/225/244/320/227/321/202/320/245/320/247/321/202/320/244/320/264/342/225/244/320/225/342/225/250/342/224/220/342/225/250/320/246/342/225/244/320/225/321/202/320/245/320/241/342/225/250/342/225/242/xpm_2.py +117 -0
  190. molforge/workflows/assets/OSC_MD_workflows/templates/09-/342/225/244/320/231/342/225/250/320/240/342/225/250/320/277/342/225/244/320/227/342/225/250/320/256/342/225/250/320/247/marcus_rate.py +60 -0
  191. molforge/workflows/assets/esp-surface-analysis/scripts/compute_descriptors.py +134 -0
  192. molforge/workflows/assets/esp-surface-analysis/scripts/parse_surfanalysis.py +58 -0
  193. molforge/workflows/assets/esp-surface-analysis/scripts/plot_esp_hist.py +115 -0
  194. molforge/workflows/assets/homo-lumo-plot/extract_orb_energy.py +57 -0
  195. molforge/workflows/assets/homo-lumo-plot/make_level_plot.py +76 -0
  196. molforge/workflows/assets/homo-lumo-plot/run_pipeline.py +84 -0
  197. molforge/workflows/assets/osc-energy-level-diagram/scripts/extract_levels.py +60 -0
  198. molforge/workflows/assets/osc-energy-level-diagram/scripts/make_editable_pptx.py +122 -0
  199. molforge/workflows/assets/osc-energy-level-diagram/scripts/make_energy_table.py +66 -0
  200. molforge/workflows/assets/osc-energy-level-diagram/scripts/make_level_lines_diagram.py +148 -0
  201. molforge/workflows/assets/osc-energy-level-diagram/scripts/make_rectangle_diagram.py +148 -0
  202. molforge/workflows/assets/osc-energy-level-diagram/scripts/verify_from_log.py +45 -0
  203. molforge/workflows/dipole_analysis.py +32 -0
  204. molforge/workflows/esp_surface.py +36 -0
  205. molforge/workflows/gromacs_submit.py +167 -0
  206. molforge/workflows/homo_lumo_plot.py +59 -0
  207. molforge/workflows/igmh_interaction.py +111 -0
  208. molforge/workflows/md_rdf_analysis.py +134 -0
  209. molforge/workflows/md_studio.py +255 -0
  210. molforge/workflows/osc_energy_diagram.py +24 -0
  211. molforge/workflows/planarity_analysis.py +66 -0
  212. molforge/workflows/reorganization_energy.py +166 -0
  213. molforge/workflows/scientific_workflows.py +650 -0
  214. molforge_studio-7.4.3.dist-info/METADATA +215 -0
  215. molforge_studio-7.4.3.dist-info/RECORD +219 -0
  216. molforge_studio-7.4.3.dist-info/WHEEL +5 -0
  217. molforge_studio-7.4.3.dist-info/entry_points.txt +3 -0
  218. molforge_studio-7.4.3.dist-info/licenses/LICENSE +93 -0
  219. molforge_studio-7.4.3.dist-info/top_level.txt +2 -0
@@ -0,0 +1,117 @@
1
+ #!/usr/bin/python3
2
+ # -*- coding: utf-8 -*-
3
+
4
+ '''
5
+ A simple code for plotting figure by reading xpm file generated by gromacs tools, such as gmx mdmat, gmx sham
6
+ gmx rms, gmx do_dssp, etc.
7
+ '''
8
+
9
+ #***********************************************************************#
10
+ # Update date: 2023.07.21 #
11
+ # Version: 1.2 #
12
+ # log: fix do_dssp bug #
13
+ #***********************************************************************#
14
+
15
+ import numpy as np
16
+ import matplotlib.pyplot as plt
17
+ import matplotlib.colors as cols
18
+ import sys
19
+
20
+ #运行方式python xpm_2.py x.xpm y.xpm
21
+ plt.rcParams['font.size'] = 32
22
+ #plt.rcParams['axes.linewidth'] = 2
23
+ plt.rcParams['font.family'] = 'Times New Roman'
24
+
25
+ def Read_XPM(fname):
26
+ color, x, y, arr, value_list = {}, [], [], [], []
27
+ title, legend, xlabel, ylabel = '', '', '', ''
28
+ color_map = {'Coil': (1, 1, 1), 'B-Sheet': (1, 0, 0), 'B-Bridge': (0, 0, 0), 'Bend': (0, 1, 0),
29
+ 'Turn': (1, 1, 0), 'A-Helix': (0, 0, 1), '5-Helix': (0.7, 0.3, 0.8), '3-Helix': (0.5, 0.5, 0.5),
30
+ 'Chain': (0, 0.5, 0.5)}
31
+ with open(fname, 'r') as f:
32
+ line = f.readline().rstrip('\n')
33
+ while line:
34
+ if 'title' in line:
35
+ title = line.split('"')[1]
36
+ elif 'legend' in line:
37
+ legend = line.split('"')[1]
38
+ elif 'x-label' in line:
39
+ xlabel = line.split('"')[1]
40
+ elif 'y-label' in line:
41
+ ylabel = line.split('"')[1]
42
+ # 矩阵维度dim[0]*dim[1], nframe * nres
43
+ elif 'static char' in line:
44
+ dim = np.array(f.readline().split('"')[1].split(), dtype=int)
45
+ for i in range(dim[2]):
46
+ temp = f.readline().rstrip('\n')
47
+ value = temp.split('"')[-2]
48
+ if value == "Chain_Separator":
49
+ value = "Chain"
50
+ value_list.append(value)
51
+ if 'Secondary' not in title:
52
+ color[temp[1]] = float(value) if 'Hydrogen' not in ylabel else 0 if value == 'None' else 1
53
+ else:
54
+ color[temp[1]] = i
55
+ # 坐标值
56
+ elif 'x-axis' in line:
57
+ x.extend(line.split()[2:-1])
58
+ elif 'y-axis' in line:
59
+ y.extend(line.split()[2:-1])
60
+ elif line[0] == '"' and line[dim[0]+1] == '"':
61
+ temp = [color[line[j]] for j in range(1, dim[0]+1)]
62
+ arr.append(temp)
63
+ line = f.readline().rstrip('\n')
64
+ # 必须按行反向列表,因为xpm中的数据默认是反向的,即最后一行数据才是开始值
65
+ arr.reverse()
66
+ # 处理一下维度,因为有的xpm文件坐标个数会大于下面的矩阵维度dim[0](如gmx sham)
67
+ if len(x) > dim[0]:
68
+ x.pop()
69
+ y.pop()
70
+
71
+ return title, legend, xlabel, ylabel, x, y, np.array(arr, dtype=float), value_list, color_map
72
+
73
+ def Plot_XPM(file1, file2):
74
+ title1, legend1, xlabel1, ylabel1, x1, y1, arr1, value_list1, color_map1 = Read_XPM(file1)
75
+ title2, legend2, xlabel2, ylabel2, x2, y2, arr2, value_list2, color_map2 = Read_XPM(file2)
76
+
77
+ # 假设两个文件的x和y轴标签相同
78
+ x = np.array(x1, dtype=float)
79
+ y = np.array(y1, dtype=float)
80
+ X, Y = np.meshgrid(x, y)
81
+
82
+ # 绘图
83
+ plt.figure(figsize=(8, 6))
84
+
85
+ # 绘制第一个文件的数据
86
+ Z1 = arr1
87
+ h1 = plt.contourf(X, Y, Z1, np.linspace(0, 300, 205), cmap="Greens", vmin=0, vmax=280, alpha=0.5)
88
+
89
+ # 绘制第二个文件的数据
90
+ Z2 = arr2
91
+ h2 = plt.contourf(X, Y, Z2, np.linspace(0, 300, 205), cmap="Greens", vmin=0, vmax=280, alpha=0.5)
92
+
93
+ cb = plt.colorbar(h1, ticks=np.linspace(0, 300, 5))
94
+ cb.ax.tick_params(labelsize=12)
95
+ cb.set_label(legend1, fontsize=18)
96
+
97
+ plt.title(title1, fontsize=18)
98
+ plt.xlabel(xlabel1, fontsize=18)
99
+ plt.ylabel(ylabel1, fontsize=18)
100
+ plt.xticks(fontsize=15)
101
+ plt.yticks(fontsize=15)
102
+ plt.xlim([np.min(x), np.max(x)])
103
+ plt.ylim([np.min(y), np.max(y)])
104
+ plt.savefig(file1.split('.')[0] + '_' + file2.split('.')[0] + '.png', dpi=300)
105
+ # 将坐标轴加粗显示
106
+ plt.gca().spines['bottom'].set_linewidth(15)
107
+ plt.gca().spines['left'].set_linewidth(15)
108
+
109
+ def Help(argv):
110
+ print('->>Description:\nThis program can read most common xpm file generated by gromacs tools, then plot figure')
111
+ print('Usage:\n\t./%s xxx.xpm yyy.xpm\n' % (argv))
112
+ exit(-1)
113
+
114
+ if __name__ == '__main__':
115
+ if len(sys.argv) < 3:
116
+ Help(sys.argv[0])
117
+ Plot_XPM(sys.argv[1], sys.argv[2])
@@ -0,0 +1,60 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ marcus_rate.py —— 标准 Marcus 电子转移速率计算模板
5
+
6
+ 公式(非绝热极限):
7
+ k = (2*pi/hbar) * |V|^2 / sqrt(4*pi*lambda*kB*T)
8
+ * exp[ -(dG + lambda)^2 / (4*lambda*kB*T) ]
9
+
10
+ 输入参数来源:
11
+ V 电子耦合 V_DA (eV) <- 08 电子耦合(Q-Chem GMH)
12
+ lambda 重组能 λ (eV) <- 06 重组能(Gaussian 4 点法)
13
+ dG 驱动力 ΔG (eV) <- 前线轨道能级差 / 电荷态能量差
14
+ T 温度 (K)
15
+
16
+ 用法:
17
+ python marcus_rate.py --V 0.98 --lam 0.82 --dG -0.77
18
+ # 或读取 CSV:列 = name,V,lambda,dG (--csv pairs.csv)
19
+ """
20
+ import argparse
21
+ import csv
22
+ import math
23
+
24
+ # 常数
25
+ HBAR_EVS = 6.582119569e-16 # hbar (eV*s)
26
+ PI = math.pi
27
+
28
+ def marcus_k(V_eV, lam_eV, dG_eV, T=300.0):
29
+ """返回 k (s^-1)"""
30
+ # 玻尔兹曼常数 (eV/K)
31
+ kB = 8.617333262e-5
32
+ prefactor = (2 * PI / HBAR_EVS) * (V_eV ** 2) / math.sqrt(4 * PI * lam_eV * kB * T)
33
+ exponent = -((dG_eV + lam_eV) ** 2) / (4 * lam_eV * kB * T)
34
+ return prefactor * math.exp(exponent)
35
+
36
+ def main():
37
+ ap = argparse.ArgumentParser()
38
+ ap.add_argument('--V', type=float, help='电子耦合 V_DA (eV)')
39
+ ap.add_argument('--lam', type=float, help='重组能 λ (eV)')
40
+ ap.add_argument('--dG', type=float, help='驱动力 ΔG (eV)')
41
+ ap.add_argument('--T', type=float, default=300.0, help='温度 (K),默认 300')
42
+ ap.add_argument('--csv', help='可选:CSV 文件,列 = name,V,lambda,dG(无表头)')
43
+ args = ap.parse_args()
44
+
45
+ if args.csv:
46
+ with open(args.csv) as f:
47
+ rows = list(csv.reader(f))
48
+ print('name V(eV) lambda(eV) dG(eV) k(s^-1)')
49
+ for r in rows:
50
+ name, V, lam, dG = r[0], float(r[1]), float(r[2]), float(r[3])
51
+ k = marcus_k(V, lam, dG, args.T)
52
+ print(f'{name:<12s} {V:8.4f} {lam:10.4f} {dG:8.4f} {k:.4e}')
53
+ else:
54
+ if None in (args.V, args.lam, args.dG):
55
+ ap.error('请提供 --V --lam --dG(或 --csv)')
56
+ k = marcus_k(args.V, args.lam, args.dG, args.T)
57
+ print(f'k = {k:.4e} s^-1 (V={args.V}, λ={args.lam}, ΔG={args.dG}, T={args.T}K)')
58
+
59
+ if __name__ == '__main__':
60
+ main()
@@ -0,0 +1,134 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ compute_descriptors.py
5
+ 从 vtx.pdb 直接计算 ESP 表面描述符,不需要 sum.txt。
6
+ vtx.pdb 的 B 因子列 = 每个表面顶点的 ESP 值 (kcal/mol)。
7
+
8
+ 输出:Vs_min, Vs_max, SASA, sigma2_pos/neg/tot, nu, Pi, MPI, polar_area_pct
9
+ """
10
+ import sys, csv, pathlib
11
+ import numpy as np
12
+
13
+ def read_vtx_bfactor(path):
14
+ vals = []
15
+ with open(path, "r", encoding="utf-8", errors="ignore") as f:
16
+ for line in f:
17
+ if not line.startswith("HETATM"):
18
+ continue
19
+ try:
20
+ bf = float(line[60:66])
21
+ vals.append(bf)
22
+ except ValueError:
23
+ continue
24
+ return np.array(vals, dtype=float)
25
+
26
+ def read_surfanalysis_extrema(path):
27
+ """从 surfanalysis.pdb 读 Vs_min / Vs_max"""
28
+ maxv, minv = [], []
29
+ with open(path, "r", encoding="utf-8", errors="ignore") as f:
30
+ for line in f:
31
+ if not line.startswith("HETATM"):
32
+ continue
33
+ try:
34
+ an = line[12:14].strip()
35
+ bf = float(line[60:66])
36
+ if an == "C": maxv.append(bf)
37
+ elif an == "O": minv.append(bf)
38
+ except (ValueError, IndexError):
39
+ continue
40
+ return max(maxv) if maxv else None, min(minv) if minv else None
41
+
42
+ def compute_descriptors(vtx_pdb, surf_pdb=None):
43
+ esp = read_vtx_bfactor(vtx_pdb)
44
+ n = len(esp)
45
+
46
+ # Vs_min / Vs_max 优先从 surfanalysis.pdb 读
47
+ if surf_pdb and pathlib.Path(surf_pdb).exists():
48
+ vs_max, vs_min = read_surfanalysis_extrema(surf_pdb)
49
+ else:
50
+ vs_min, vs_max = esp.min(), esp.max()
51
+
52
+ # SASA: 从 vtx.pdb 没法直接算,Multiwfn 输出的表面积需要从 sum.txt
53
+ # 这里用顶点数近似(不同分子密度不同,仅供参考)
54
+ # 实际 SASA 需要从 sum.txt 获取
55
+
56
+ pos = esp[esp > 0]
57
+ neg = esp[esp < 0]
58
+
59
+ # 面积加权平均(假设每个顶点面积相同)
60
+ avg_tot = esp.mean()
61
+ avg_pos = pos.mean() if len(pos) > 0 else 0
62
+ avg_neg = neg.mean() if len(neg) > 0 else 0
63
+
64
+ # 方差
65
+ var_tot = esp.var()
66
+ var_pos = pos.var() if len(pos) > 0 else 0
67
+ var_neg = neg.var() if len(neg) > 0 else 0
68
+
69
+ # 正负面积占比
70
+ area_pos = len(pos) / n * 100
71
+ area_neg = len(neg) / n * 100
72
+
73
+ # nu (电荷平衡度)
74
+ # nu = (|avg_neg| / (avg_pos + |avg_neg|) - 0.5) * 2 ... 不对
75
+ # 正确公式: nu = (|avg_neg| * sqrt(var_neg) - avg_pos * sqrt(var_pos)) / (|avg_neg|*sqrt(var_neg) + avg_pos*sqrt(var_pos))
76
+ # 简化版: nu = 2 * (|avg_neg|/(avg_pos+|avg_neg|) - 0.5)
77
+ if avg_pos > 0 and avg_neg < 0:
78
+ nu = abs(avg_neg) / (avg_pos + abs(avg_neg))
79
+ nu = (nu - 0.5) * 2 # -1 ~ +1
80
+ else:
81
+ nu = None
82
+
83
+ # Pi (内部分离强度) = sqrt(var_pos) + sqrt(var_neg) ... 不对
84
+ # Pi = avg_pos * sqrt(var_pos) + |avg_neg| * sqrt(var_neg)
85
+ Pi = avg_pos * np.sqrt(var_pos) + abs(avg_neg) * np.sqrt(var_neg)
86
+
87
+ # MPI (分子极性指数) = |avg(esp)|
88
+ MPI = abs(avg_tot)
89
+
90
+ # 极性面积占比 (|ESP| > 10 kcal/mol)
91
+ polar_area = (np.abs(esp) > 10).sum() / n * 100
92
+
93
+ return {
94
+ "vtx_file": pathlib.Path(vtx_pdb).name,
95
+ "n_vertices": n,
96
+ "Vs_min_kcal": round(vs_min, 2) if vs_min else None,
97
+ "Vs_max_kcal": round(vs_max, 2) if vs_max else None,
98
+ "avg_tot_kcal": round(avg_tot, 3),
99
+ "avg_pos_kcal": round(avg_pos, 3),
100
+ "avg_neg_kcal": round(avg_neg, 3),
101
+ "sigma2_pos": round(var_pos, 2),
102
+ "sigma2_neg": round(var_neg, 2),
103
+ "sigma2_tot": round(var_tot, 2),
104
+ "nu": round(nu, 4) if nu else None,
105
+ "Pi_kcal": round(Pi, 3),
106
+ "MPI_kcal": round(MPI, 3),
107
+ "polar_area_pct": round(polar_area, 2),
108
+ "pos_area_pct": round(area_pos, 2),
109
+ "neg_area_pct": round(area_neg, 2),
110
+ }
111
+
112
+ def main():
113
+ if len(sys.argv) < 2:
114
+ print("Usage: python compute_descriptors.py <vtx.pdb> [surfanalysis.pdb]")
115
+ sys.exit(1)
116
+
117
+ vtx = sys.argv[1]
118
+ surf = sys.argv[2] if len(sys.argv) > 2 else None
119
+
120
+ d = compute_descriptors(vtx, surf)
121
+ for k, v in d.items():
122
+ print(f" {k:20s}: {v}")
123
+
124
+ # 写 CSV
125
+ out_csv = pathlib.Path(vtx).parent / "esp_descriptors.csv"
126
+ new = not out_csv.exists()
127
+ with open(out_csv, "a", newline="", encoding="utf-8-sig") as f:
128
+ w = csv.DictWriter(f, fieldnames=list(d.keys()))
129
+ if new: w.writeheader()
130
+ w.writerow(d)
131
+ print(f"\nCSV appended: {out_csv}")
132
+
133
+ if __name__ == "__main__":
134
+ main()
@@ -0,0 +1,58 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ parse_surfanalysis.py
5
+ 解析 Multiwfn ESPrhoiso 输出的 <prefix>_sum.txt,提取 OSC 表面分析关键描述符。
6
+ 用法:
7
+ python parse_surfanalysis.py <sum.txt> [sum2.txt ...]
8
+ 输出: 控制台打印表格 + 同目录生成 esp_descriptors.csv
9
+ 关键描述符 (从 sum.txt 正则提取):
10
+ Vs,min / Vs,max kcal/mol 表面 ESP 极小/极大
11
+ SASA Angstrom^2 分子表面积
12
+ sigma2_pos/neg/tot (kcal/mol)^2 正/负/总方差
13
+ nu 电荷平衡度 (越小越平衡)
14
+ Pi (Omega) kcal/mol 内部分离强度
15
+ MPI kcal/mol 分子极性指数
16
+ Polar area ratio % |ESP|>10 kcal/mol 面积占比
17
+ """
18
+ import sys, re, json, csv, pathlib
19
+
20
+ PATTERNS = {
21
+ "Vs_min_kcal": r"Minimal value:\s+([-\d.]+)\s+kcal/mol",
22
+ "Vs_max_kcal": r"Maximal value:\s+([-\d.]+)\s+kcal/mol",
23
+ "SASA_A2": r"Overall surface area:\s+[\d.]+\s+Bohr\^2\s+\(\s*([\d.]+)\s+Angstrom\^2\)",
24
+ "sigma2_pos": r"Positive variance:\s+[\d.]+\s+a\.u\.\^2\s+\(\s*([\d.]+)\s+\(kcal/mol\)\^2\)",
25
+ "sigma2_neg": r"Negative variance:\s+[\d.]+\s+a\.u\.\^2\s+\(\s*([\d.]+)\s+\(kcal/mol\)\^2\)",
26
+ "sigma2_tot": r"Overall variance \(sigma\^2_tot\):\s+[\d.]+\s+a\.u\.\^2\s+\(\s*([\d.]+)\s+\(kcal/mol\)\^2\)",
27
+ "nu": r"Balance of charges \(nu\):\s+([-\d.]+)",
28
+ "Pi_kcal": r"Internal charge separation \(Pi\):\s+[\d.]+\s+a\.u\.\s+\(\s*([-\d.]+)\s+kcal/mol\)",
29
+ "MPI_kcal": r"Molecular polarity index \(MPI\):\s+[\d.]+\s+eV\s+\(\s*([-\d.]+)\s+kcal/mol\)",
30
+ "polar_area_pct": r"Polar surface area \(\|ESP\| > 10 kcal/mol\):\s+[\d.]+\s+Angstrom\^2\s+\(\s*([\d.]+)\s*%\)",
31
+ }
32
+
33
+ def parse_one(path):
34
+ text = pathlib.Path(path).read_text(encoding="utf-8", errors="ignore")
35
+ out = {"file": pathlib.Path(path).name}
36
+ for k, pat in PATTERNS.items():
37
+ m = re.search(pat, text)
38
+ out[k] = float(m.group(1)) if m else None
39
+ return out
40
+
41
+ def main():
42
+ if len(sys.argv) < 2:
43
+ print(__doc__); sys.exit(1)
44
+ rows = [parse_one(p) for p in sys.argv[1:]]
45
+ cols = ["file"] + list(PATTERNS.keys())
46
+ # 打印
47
+ for r in rows:
48
+ print(json.dumps(r, ensure_ascii=False, indent=2))
49
+ # 写 CSV 到第一个文件同目录
50
+ out_csv = pathlib.Path(sys.argv[1]).parent / "esp_descriptors.csv"
51
+ with open(out_csv, "w", newline="", encoding="utf-8-sig") as f:
52
+ w = csv.DictWriter(f, fieldnames=cols)
53
+ w.writeheader()
54
+ for r in rows: w.writerow(r)
55
+ print(f"\nCSV written: {out_csv}")
56
+
57
+ if __name__ == "__main__":
58
+ main()
@@ -0,0 +1,115 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ plot_esp_hist.py
5
+ 从 Multiwfn vtx.pdb (38万表面顶点, B因子=ESP kcal/mol) 画 ESP 表面面积百分比直方图。
6
+ 样式对齐论文图: x=ESP(kcal/mol), y=Area(%), bin=5 kcal/mol, 给体蓝/受体红。
7
+
8
+ 用法:
9
+ python plot_esp_hist.py <vtx.pdb> <MolName> [--color blue|red] [--out out.png]
10
+ [--bin 5.0] [--xmin -35] [--xmax 35] [--ymax 30]
11
+
12
+ 例:
13
+ python plot_esp_hist.py ClFFCl_vtx.pdb ClFFCl --color red --out ClFFCl_esp_hist.png
14
+ """
15
+ import sys, argparse, pathlib
16
+ import numpy as np
17
+ import matplotlib
18
+ matplotlib.use("Agg")
19
+ import matplotlib.pyplot as plt
20
+ from matplotlib import rcParams
21
+
22
+ # 论文字体
23
+ rcParams["font.family"] = "Arial"
24
+ rcParams["font.size"] = 14
25
+ rcParams["axes.linewidth"] = 1.2
26
+ rcParams["xtick.direction"] = "out"
27
+ rcParams["ytick.direction"] = "out"
28
+
29
+ COLORS = {
30
+ "blue": {"face": "#1f77d0", "edge": "white"}, # 给体/中性
31
+ "red": {"face": "#d63a3a", "edge": "white"}, # 受体/缺电子
32
+ "gray": {"face": "#888888", "edge": "white"},
33
+ }
34
+
35
+ def read_vtx_bfactor(path):
36
+ """读 vtx.pdb 的 B-factor 字段 (列5, kcal/mol)。只取 HETATM 行。"""
37
+ vals = []
38
+ with open(path, "r", encoding="utf-8", errors="ignore") as f:
39
+ for line in f:
40
+ if not line.startswith("HETATM"):
41
+ continue
42
+ # PDB 列格式: B-factor 在 61-66 列 (0-based 60:66)
43
+ try:
44
+ bf = float(line[60:66])
45
+ vals.append(bf)
46
+ except ValueError:
47
+ continue
48
+ return np.array(vals, dtype=float)
49
+
50
+ def main():
51
+ ap = argparse.ArgumentParser()
52
+ ap.add_argument("vtx_pdb")
53
+ ap.add_argument("molname")
54
+ ap.add_argument("--color", default="blue", choices=list(COLORS.keys()))
55
+ ap.add_argument("--out", default=None)
56
+ ap.add_argument("--bin", type=float, default=5.0)
57
+ ap.add_argument("--xmin", type=float, default=-35.0)
58
+ ap.add_argument("--xmax", type=float, default=35.0)
59
+ ap.add_argument("--ymax", type=float, default=30.0)
60
+ args = ap.parse_args()
61
+
62
+ vals = read_vtx_bfactor(args.vtx_pdb)
63
+ print(f"Loaded {len(vals)} surface vertices from {args.vtx_pdb}")
64
+ print(f"ESP range: {vals.min():.2f} ~ {vals.max():.2f} kcal/mol")
65
+
66
+ # 分箱
67
+ bins = np.arange(args.xmin, args.xmax + args.bin, args.bin)
68
+ counts, edges = np.histogram(vals, bins=bins)
69
+ pct = counts / counts.sum() * 100.0
70
+ centers = (edges[:-1] + edges[1:]) / 2.0
71
+
72
+ # 只画非零 bin (和参考图一致, 尾部空 bin 不画)
73
+ nonzero = pct > 0.05
74
+ c = centers[nonzero]
75
+ p = pct[nonzero]
76
+
77
+ # 画图
78
+ fig, ax = plt.subplots(figsize=(4.2, 3.6), dpi=300)
79
+ ax.bar(c, p, width=args.bin*0.92,
80
+ color=COLORS[args.color]["face"],
81
+ edgecolor=COLORS[args.color]["edge"],
82
+ linewidth=0.8)
83
+
84
+ ax.set_xlabel("ESP (kcal/mol)", fontsize=14)
85
+ ax.set_ylabel("Area (%)", fontsize=14)
86
+ ax.set_title(args.molname, fontsize=15, fontweight="bold", loc="left")
87
+
88
+ ax.set_xlim(args.xmin, args.xmax)
89
+ ax.set_ylim(0, args.ymax)
90
+ ax.set_xticks(np.arange(-30, 25, 10))
91
+ ax.set_yticks(np.arange(0, args.ymax+1, 5))
92
+
93
+ # 去掉上右边框
94
+ ax.spines["top"].set_visible(False)
95
+ ax.spines["right"].set_visible(False)
96
+
97
+ # 峰值标注
98
+ peak_idx = int(np.argmax(p))
99
+ ax.annotate(f"{p[peak_idx]:.1f}%",
100
+ xy=(c[peak_idx], p[peak_idx]),
101
+ xytext=(0, 4), textcoords="offset points",
102
+ ha="center", fontsize=11, fontweight="bold")
103
+
104
+ fig.tight_layout()
105
+ out = args.out or f"{args.molname}_esp_hist.png"
106
+ fig.savefig(out, dpi=300, bbox_inches="tight", facecolor="white")
107
+ print(f"Saved: {out}")
108
+
109
+ # 打印分箱数据供核对
110
+ print("\nBin center (kcal/mol) | Area (%)")
111
+ for ci, pi in zip(c, p):
112
+ print(f" {ci:7.1f} | {pi:5.2f}")
113
+
114
+ if __name__ == "__main__":
115
+ main()
@@ -0,0 +1,57 @@
1
+ # -*- coding: utf-8 -*-
2
+ """从 Gaussian fchk 提取 HOMO/LUMO 轨道能量 (Hartree -> eV)"""
3
+ import re, csv
4
+
5
+ HA2EV = 27.211386245988
6
+
7
+ def read_orb_energies(fchk_path):
8
+ with open(fchk_path, 'r') as f:
9
+ lines = f.readlines()
10
+ start = None
11
+ n = None
12
+ for i, ln in enumerate(lines):
13
+ if ln.startswith("Alpha Orbital Energies"):
14
+ m = re.search(r'N=\s*(\d+)', ln)
15
+ n = int(m.group(1)) if m else None
16
+ start = i + 1
17
+ break
18
+ if start is None:
19
+ raise RuntimeError("Alpha Orbital Energies not found in " + fchk_path)
20
+ vals = []
21
+ i = start
22
+ while len(vals) < (n or 1e9):
23
+ parts = lines[i].split()
24
+ for p in parts:
25
+ try:
26
+ vals.append(float(p.replace('D', 'E')))
27
+ except ValueError:
28
+ pass
29
+ i += 1
30
+ if i >= len(lines):
31
+ break
32
+ return vals
33
+
34
+ def extract_molecule(name, fchk_path, homo_orb_num):
35
+ """homo_orb_num: 1-based HOMO orbital index"""
36
+ e = read_orb_energies(fchk_path)
37
+ eh = e[homo_orb_num - 1] * HA2EV
38
+ el = e[homo_orb_num] * HA2EV
39
+ return {
40
+ 'name': name,
41
+ 'homo_ev': round(eh, 4),
42
+ 'lumo_ev': round(el, 4),
43
+ 'gap_ev': round(el - eh, 4),
44
+ 'homo_orb': homo_orb_num,
45
+ 'lumo_orb': homo_orb_num + 1,
46
+ }
47
+
48
+ if __name__ == '__main__':
49
+ import sys
50
+ if len(sys.argv) < 4:
51
+ print("Usage: python extract_orb_energy.py <fchk> <homo_orb_num> <name>")
52
+ sys.exit(1)
53
+ fchk = sys.argv[1]
54
+ homo_num = int(sys.argv[2])
55
+ name = sys.argv[3]
56
+ r = extract_molecule(name, fchk, homo_num)
57
+ print(f"{name}: HOMO={r['homo_ev']} eV, LUMO={r['lumo_ev']} eV, Gap={r['gap_ev']} eV")
@@ -0,0 +1,76 @@
1
+ # -*- coding: utf-8 -*-
2
+ """拼合 HOMO-LUMO 能级骨架 + 分子轨道等值面图"""
3
+ import matplotlib
4
+ matplotlib.use('Agg')
5
+ import matplotlib.pyplot as plt
6
+ import matplotlib.image as mpimg
7
+ import os, argparse
8
+
9
+ matplotlib.rcParams['font.family'] = 'Arial'
10
+ matplotlib.rcParams['font.size'] = 12
11
+
12
+ def make_plot(data, orb_dir, output_path, y_min=-6.5, y_max=-2.5, show_orbs=True):
13
+ """
14
+ data: list of dicts with keys: name, homo_ev, lumo_ev, gap_ev
15
+ orb_dir: directory containing {name}_HOMO.bmp and {name}_LUMO.bmp
16
+ """
17
+ n = len(data)
18
+ fig, ax = plt.subplots(figsize=(max(8, n * 1.8), 6))
19
+
20
+ x = range(n)
21
+ w = 0.35
22
+
23
+ for i, d in enumerate(data):
24
+ h, l = d['homo_ev'], d['lumo_ev']
25
+ g = d['gap_ev']
26
+ # HOMO line
27
+ ax.plot([i - w/2, i + w/2], [h, h], 'k-', linewidth=3)
28
+ # LUMO line
29
+ ax.plot([i - w/2, i + w/2], [l, l], 'k-', linewidth=3)
30
+ # Double arrow
31
+ ax.annotate('', xy=(i, l), xytext=(i, h),
32
+ arrowprops=dict(arrowstyle='<->', color='#2c3e50', lw=1.5))
33
+ # Gap label
34
+ ax.text(i, (h + l) / 2, f'{g:.2f} eV', ha='center', va='center',
35
+ fontsize=11, fontweight='bold', color='#2c3e50',
36
+ bbox=dict(boxstyle='round,pad=0.3', fc='white', ec='none', alpha=0.85))
37
+ # HOMO/LUMO text labels
38
+ ax.text(i, h - 0.1, 'HOMO', ha='center', va='top', fontsize=10, color='#333')
39
+ ax.text(i, l + 0.1, 'LUMO', ha='center', va='bottom', fontsize=10, color='#333')
40
+
41
+ # Insert orbital images
42
+ if show_orbs:
43
+ homo_img = os.path.join(orb_dir, f"{d['name']}_HOMO.bmp")
44
+ lumo_img = os.path.join(orb_dir, f"{d['name']}_LUMO.bmp")
45
+ if os.path.exists(homo_img):
46
+ img = mpimg.imread(homo_img)
47
+ ax.imshow(img, extent=[i-0.3, i+0.3, h-0.6, h-0.15], aspect='auto', zorder=5)
48
+ if os.path.exists(lumo_img):
49
+ img = mpimg.imread(lumo_img)
50
+ ax.imshow(img, extent=[i-0.3, i+0.3, l+0.15, l+0.6], aspect='auto', zorder=5)
51
+
52
+ ax.set_xticks(list(x))
53
+ ax.set_xticklabels([d['name'] for d in data], fontsize=12)
54
+ ax.set_ylabel('Energy Level (eV)', fontsize=13, fontweight='bold')
55
+ ax.set_ylim(y_min, y_max)
56
+ ax.set_xlim(-0.6, n - 0.4)
57
+ ax.grid(axis='y', linestyle='--', alpha=0.3)
58
+ ax.spines['top'].set_visible(False)
59
+ ax.spines['right'].set_visible(False)
60
+
61
+ plt.title('HOMO-LUMO Energy Levels', fontsize=14, fontweight='bold', pad=15)
62
+ plt.tight_layout()
63
+ plt.savefig(output_path, dpi=300, bbox_inches='tight')
64
+ plt.close()
65
+ print(f"Saved: {output_path}")
66
+
67
+ if __name__ == '__main__':
68
+ parser = argparse.ArgumentParser()
69
+ parser.add_argument('--data-json', required=True)
70
+ parser.add_argument('--orb-dir', required=True)
71
+ parser.add_argument('--output', required=True)
72
+ args = parser.parse_args()
73
+ import json
74
+ with open(args.data_json) as f:
75
+ data = json.load(f)
76
+ make_plot(data, args.orb_dir, args.output)