duivyinteractions 0.0.1__tar.gz

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 (61) hide show
  1. duivyinteractions-0.0.1/DuIvyInteractions/DII.py +149 -0
  2. duivyinteractions-0.0.1/DuIvyInteractions/__init__.py +1 -0
  3. duivyinteractions-0.0.1/DuIvyInteractions/core/__init__.py +25 -0
  4. duivyinteractions-0.0.1/DuIvyInteractions/core/constants.py +46 -0
  5. duivyinteractions-0.0.1/DuIvyInteractions/core/datas.py +265 -0
  6. duivyinteractions-0.0.1/DuIvyInteractions/core/interfaces.py +627 -0
  7. duivyinteractions-0.0.1/DuIvyInteractions/group_identifiers/__init__.py +11 -0
  8. duivyinteractions-0.0.1/DuIvyInteractions/group_identifiers/amber_ff_identifier.py +816 -0
  9. duivyinteractions-0.0.1/DuIvyInteractions/interaction_detectors/__init__.py +54 -0
  10. duivyinteractions-0.0.1/DuIvyInteractions/interaction_detectors/halogen_bond_detector_per_frame.py +248 -0
  11. duivyinteractions-0.0.1/DuIvyInteractions/interaction_detectors/halogen_bond_detector_per_tuple.py +127 -0
  12. duivyinteractions-0.0.1/DuIvyInteractions/interaction_detectors/halogen_bond_detector_two_pass.py +175 -0
  13. duivyinteractions-0.0.1/DuIvyInteractions/interaction_detectors/hydrogen_bond_detector_per_frame.py +181 -0
  14. duivyinteractions-0.0.1/DuIvyInteractions/interaction_detectors/hydrogen_bond_detector_per_tuple.py +101 -0
  15. duivyinteractions-0.0.1/DuIvyInteractions/interaction_detectors/hydrogen_bond_detector_two_pass.py +193 -0
  16. duivyinteractions-0.0.1/DuIvyInteractions/interaction_detectors/hydrophobic_detector_per_frame.py +186 -0
  17. duivyinteractions-0.0.1/DuIvyInteractions/interaction_detectors/hydrophobic_detector_per_tuple.py +114 -0
  18. duivyinteractions-0.0.1/DuIvyInteractions/interaction_detectors/hydrophobic_detector_two_pass.py +137 -0
  19. duivyinteractions-0.0.1/DuIvyInteractions/interaction_detectors/metal_coordination_detector_per_frame.py +143 -0
  20. duivyinteractions-0.0.1/DuIvyInteractions/interaction_detectors/metal_coordination_detector_per_tuple.py +78 -0
  21. duivyinteractions-0.0.1/DuIvyInteractions/interaction_detectors/metal_coordination_detector_two_pass.py +135 -0
  22. duivyinteractions-0.0.1/DuIvyInteractions/interaction_detectors/pi_cation_detector_per_frame.py +259 -0
  23. duivyinteractions-0.0.1/DuIvyInteractions/interaction_detectors/pi_cation_detector_per_tuple.py +156 -0
  24. duivyinteractions-0.0.1/DuIvyInteractions/interaction_detectors/pi_cation_detector_two_pass.py +208 -0
  25. duivyinteractions-0.0.1/DuIvyInteractions/interaction_detectors/pi_stacking_detector_per_frame.py +374 -0
  26. duivyinteractions-0.0.1/DuIvyInteractions/interaction_detectors/pi_stacking_detector_per_tuple.py +305 -0
  27. duivyinteractions-0.0.1/DuIvyInteractions/interaction_detectors/pi_stacking_detector_two_pass.py +302 -0
  28. duivyinteractions-0.0.1/DuIvyInteractions/interaction_detectors/saltbridge_detector_per_frame.py +204 -0
  29. duivyinteractions-0.0.1/DuIvyInteractions/interaction_detectors/saltbridge_detector_per_tuple.py +97 -0
  30. duivyinteractions-0.0.1/DuIvyInteractions/interaction_detectors/saltbridge_detector_two_pass.py +140 -0
  31. duivyinteractions-0.0.1/DuIvyInteractions/interaction_detectors/water_bridge_detector_per_frame.py +230 -0
  32. duivyinteractions-0.0.1/DuIvyInteractions/interaction_detectors/water_bridge_detector_per_tuple.py +148 -0
  33. duivyinteractions-0.0.1/DuIvyInteractions/interaction_detectors/water_bridge_detector_two_pass.py +256 -0
  34. duivyinteractions-0.0.1/DuIvyInteractions/io/__init__.py +20 -0
  35. duivyinteractions-0.0.1/DuIvyInteractions/io/h5.py +341 -0
  36. duivyinteractions-0.0.1/DuIvyInteractions/io/halogen_bond_exporter.py +39 -0
  37. duivyinteractions-0.0.1/DuIvyInteractions/io/hydrogen_bond_exporter.py +37 -0
  38. duivyinteractions-0.0.1/DuIvyInteractions/io/hydrophobic_exporter.py +34 -0
  39. duivyinteractions-0.0.1/DuIvyInteractions/io/interaction_exporter.py +398 -0
  40. duivyinteractions-0.0.1/DuIvyInteractions/io/metal_coordination_exporter.py +34 -0
  41. duivyinteractions-0.0.1/DuIvyInteractions/io/pi_cation_exporter.py +39 -0
  42. duivyinteractions-0.0.1/DuIvyInteractions/io/pi_stacking_exporter.py +100 -0
  43. duivyinteractions-0.0.1/DuIvyInteractions/io/saltbridge_exporter.py +38 -0
  44. duivyinteractions-0.0.1/DuIvyInteractions/io/water_bridge_exporter.py +42 -0
  45. duivyinteractions-0.0.1/DuIvyInteractions/pipeline.py +114 -0
  46. duivyinteractions-0.0.1/DuIvyInteractions/system_readers/__init__.py +7 -0
  47. duivyinteractions-0.0.1/DuIvyInteractions/system_readers/gmx_tpr_dump_reader.py +447 -0
  48. duivyinteractions-0.0.1/DuIvyInteractions/system_readers/gmx_tpr_reader.py +147 -0
  49. duivyinteractions-0.0.1/DuIvyInteractions/utils/__init__.py +1 -0
  50. duivyinteractions-0.0.1/DuIvyInteractions/visualizers/__init__.py +2 -0
  51. duivyinteractions-0.0.1/DuIvyInteractions.egg-info/PKG-INFO +103 -0
  52. duivyinteractions-0.0.1/DuIvyInteractions.egg-info/SOURCES.txt +65 -0
  53. duivyinteractions-0.0.1/DuIvyInteractions.egg-info/dependency_links.txt +1 -0
  54. duivyinteractions-0.0.1/DuIvyInteractions.egg-info/entry_points.txt +2 -0
  55. duivyinteractions-0.0.1/DuIvyInteractions.egg-info/requires.txt +8 -0
  56. duivyinteractions-0.0.1/DuIvyInteractions.egg-info/top_level.txt +1 -0
  57. duivyinteractions-0.0.1/LICENSE +674 -0
  58. duivyinteractions-0.0.1/PKG-INFO +103 -0
  59. duivyinteractions-0.0.1/README.md +72 -0
  60. duivyinteractions-0.0.1/pyproject.toml +50 -0
  61. duivyinteractions-0.0.1/setup.cfg +4 -0
@@ -0,0 +1,149 @@
1
+ # -*- coding: utf-8 -*-
2
+ """DuIvyInteraction 命令行入口。"""
3
+
4
+ import argparse
5
+ import os
6
+
7
+ import numpy as np
8
+
9
+ from .group_identifiers import IDENTIFIER_CLASSES
10
+
11
+ # 概览显示的 Top N 个占位率
12
+ OVERVIEW_TOP_N = 5
13
+
14
+
15
+ def build_parser() -> argparse.ArgumentParser:
16
+ """构建命令行参数解析器。"""
17
+ parser = argparse.ArgumentParser(
18
+ prog="dii", description="DuIvyInteraction - 基于 MD 拓扑力场参数的相互作用判定工具")
19
+ sub = parser.add_subparsers(dest="command", required=True)
20
+
21
+ # run 子命令
22
+ run_p = sub.add_parser("run", help="运行相互作用检测并保存 h5")
23
+ run_p.add_argument("-t", "--tpr", required=True, help="GROMACS 拓扑文件")
24
+ run_p.add_argument("-f", "--xtc", required=True, help="轨迹文件")
25
+ run_p.add_argument("-o", "--output", required=True, help="输出目录")
26
+ run_p.add_argument("--ff", required=True,
27
+ choices=list(IDENTIFIER_CLASSES),
28
+ help=f"力场(当前支持: {', '.join(IDENTIFIER_CLASSES)})")
29
+ run_p.add_argument("--interactions", default="all",
30
+ help="相互作用类型(逗号分隔),默认 all")
31
+ run_p.add_argument("--strategy", default="two_pass",
32
+ choices=["two_pass", "per_frame", "per_tuple"],
33
+ help="检测策略,默认 two_pass")
34
+
35
+ # export 子命令
36
+ export_p = sub.add_parser("export", help="导出 h5 结果为 xvg/xpm/csv 并打印概览")
37
+ export_p.add_argument("-i", "--input", required=True, help="h5 文件路径")
38
+ export_p.add_argument("-o", "--output", required=True, help="输出目录(自动创建)")
39
+
40
+ return parser
41
+
42
+
43
+ def _run_export(args) -> None:
44
+ """导出 h5 结果为 xvg/xpm/csv,并打印概览。"""
45
+ from .io.h5 import load_interactions
46
+ from .io import (
47
+ HydrogenBondExporter, SaltBridgeExporter, PiStackingExporter, PiCationExporter,
48
+ HalogenBondExporter, HydrophobicExporter, MetalCoordinationExporter, WaterBridgeExporter,
49
+ )
50
+
51
+ # h5 里的 interaction_type(检测器名)→ Exporter 子类
52
+ exporter_classes = {
53
+ "hydrogen_bond": HydrogenBondExporter,
54
+ "pi_stacking": PiStackingExporter,
55
+ "salt_bridge": SaltBridgeExporter,
56
+ "hydrophobic": HydrophobicExporter,
57
+ "halogen_bond": HalogenBondExporter,
58
+ "metal_coordination": MetalCoordinationExporter,
59
+ "water_bridge": WaterBridgeExporter,
60
+ "pi_cation": PiCationExporter,
61
+ }
62
+
63
+ try:
64
+ interactions = load_interactions(args.input)
65
+ except OSError:
66
+ raise SystemExit(
67
+ f"无法读取 h5 文件: {args.input}(文件可能损坏或不存在)")
68
+ if not interactions:
69
+ raise SystemExit(f"h5 中无相互作用结果: {args.input}")
70
+
71
+ os.makedirs(args.output, exist_ok=True)
72
+
73
+ # 同类型重复时追加序号(如 salt_bridge_2_*)
74
+ seen_types = {}
75
+ for it in interactions:
76
+ if it.interaction_type not in exporter_classes:
77
+ raise SystemExit(
78
+ f"未知相互作用类型: '{it.interaction_type}'。可用: {', '.join(exporter_classes)}")
79
+ exporter = exporter_classes[it.interaction_type]()
80
+
81
+ # 空数据防护:0 对或 0 帧 → 只提示,跳过导出
82
+ if it.n_pairs == 0 or it.n_frames == 0:
83
+ print(f"[跳过] {it.interaction_type}: 无相互作用可导出"
84
+ f"(pairs={it.n_pairs}, frames={it.n_frames})")
85
+ continue
86
+
87
+ _print_overview(it, exporter)
88
+
89
+ seen_types[it.interaction_type] = seen_types.get(it.interaction_type, 0) + 1
90
+ n = seen_types[it.interaction_type]
91
+ prefix = f"{args.output}/{it.interaction_type}"
92
+ if n > 1:
93
+ prefix += f"_{n}"
94
+
95
+ # xvg: 每帧活跃数 + 数值 metric 时间序列
96
+ exporter.save_xvg_count(it, f"{prefix}_count.xvg")
97
+ for metric, arr in it.metrics.items():
98
+ if arr.dtype.kind in ('U', 'S', 'O'):
99
+ continue
100
+ exporter.save_xvg(it, metric, f"{prefix}_{metric}.xvg")
101
+
102
+ # xpm: existence 热力图;π-stacking 额外输出类型图
103
+ exporter.save_xpm(it, f"{prefix}_existence.xpm")
104
+ if it.interaction_type == "pi_stacking":
105
+ exporter.save_xpm_stacking_type(it, f"{prefix}_type.xpm")
106
+
107
+ # csv: 每对汇总
108
+ exporter.to_csv_summary(it, f"{prefix}_summary.csv")
109
+
110
+
111
+ def _print_overview(it, exporter) -> None:
112
+ """打印概览信息。"""
113
+ occ = it.occupancy()
114
+ order = np.argsort(occ)[::-1][:OVERVIEW_TOP_N]
115
+ print(f"\n===== {exporter.name} 概览 =====")
116
+ print(f"类型: {it.interaction_type}")
117
+ print(f"基团对数: {it.n_pairs}")
118
+ print(f"帧数: {it.n_frames}")
119
+ if it.n_frames > 0:
120
+ print(f"时间范围: {it.times[0]:.1f} ~ {it.times[-1]:.1f} ps")
121
+ print(f"\nTop {OVERVIEW_TOP_N} 占位率:")
122
+ for i, idx in enumerate(order, 1):
123
+ print(f" {i}. {exporter.get_pair_label(it, int(idx))} {occ[idx]:.1%}")
124
+
125
+
126
+ def main():
127
+ """命令行入口。"""
128
+ args = build_parser().parse_args()
129
+
130
+ if args.command == "run":
131
+ from .pipeline import Pipeline, ALL_INTERACTIONS
132
+ if args.interactions.lower() == "all":
133
+ interactions = None
134
+ else:
135
+ interactions = [s.strip().lower() for s in args.interactions.split(",")]
136
+ if "all" in interactions:
137
+ raise SystemExit("'all' 不能与其他类型混用")
138
+ for name in interactions:
139
+ if name not in ALL_INTERACTIONS:
140
+ raise SystemExit(
141
+ f"未知相互作用类型: '{name}'。可用: {', '.join(ALL_INTERACTIONS)}")
142
+ Pipeline(args.ff, args.strategy).run(
143
+ args.tpr, args.xtc, args.output, interactions)
144
+ elif args.command == "export":
145
+ _run_export(args)
146
+
147
+
148
+ if __name__ == "__main__":
149
+ main()
@@ -0,0 +1 @@
1
+ # DuIvyInteractions - 基于 MD 拓扑力场参数的相互作用判定工具
@@ -0,0 +1,25 @@
1
+ # -*- coding: utf-8 -*-
2
+ """core - 核心基础:数据类 + 接口定义 + 常量。"""
3
+
4
+ from .constants import GROUP_TYPES, BOND_TYPES
5
+ from .datas import (
6
+ Group, AtomData, BondData, ResidueData, InterResidueBond,
7
+ SystemData, Interaction, InteractionSparse
8
+ )
9
+ from .interfaces import (
10
+ Reader, GroupIdentifier,
11
+ InteractionDetectorPerTuple, InteractionDetectorPerFrame,
12
+ InteractionDetectorTwoPass,
13
+ )
14
+
15
+ __all__ = [
16
+ # 常量
17
+ "GROUP_TYPES", "BOND_TYPES",
18
+ # 数据类
19
+ "Group", "AtomData", "BondData", "ResidueData", "InterResidueBond",
20
+ "SystemData", "Interaction", "InteractionSparse",
21
+ # 接口
22
+ "Reader", "GroupIdentifier",
23
+ "InteractionDetectorPerTuple", "InteractionDetectorPerFrame",
24
+ "InteractionDetectorTwoPass",
25
+ ]
@@ -0,0 +1,46 @@
1
+ # -*- coding: utf-8 -*-
2
+ """核心常量定义。"""
3
+
4
+ # 基团类型
5
+ GROUP_TYPES = frozenset({
6
+ "H_donor", "H_acceptor", # H键
7
+ "aromatic_ring", # π 相关
8
+ "charged_positive", "charged_negative", # 电荷
9
+ "halogen_donor", "halogen_acceptor", # 卤键
10
+ "metal", "metal_binding", "water", "hydrophobic", # 其他
11
+ })
12
+
13
+ # 键类型
14
+ BOND_TYPES = frozenset({
15
+ "bond", # 未知键级(默认值)
16
+ "single", "double", "triple", "aromatic", # 化学键
17
+ "constrained", "settle", "virtual", # 特殊
18
+ })
19
+
20
+ # 原子序数到元素符号的映射(完整周期表)
21
+ ATOMIC_NUMBER_TO_ELEMENT = {
22
+ 1: "H", 2: "He", 3: "Li", 4: "Be", 5: "B",
23
+ 6: "C", 7: "N", 8: "O", 9: "F", 10: "Ne",
24
+ 11: "Na", 12: "Mg", 13: "Al", 14: "Si", 15: "P",
25
+ 16: "S", 17: "Cl", 18: "Ar", 19: "K", 20: "Ca",
26
+ 21: "Sc", 22: "Ti", 23: "V", 24: "Cr", 25: "Mn",
27
+ 26: "Fe", 27: "Co", 28: "Ni", 29: "Cu", 30: "Zn",
28
+ 31: "Ga", 32: "Ge", 33: "As", 34: "Se", 35: "Br",
29
+ 36: "Kr", 37: "Rb", 38: "Sr", 39: "Y", 40: "Zr",
30
+ 41: "Nb", 42: "Mo", 43: "Tc", 44: "Ru", 45: "Rh",
31
+ 46: "Pd", 47: "Ag", 48: "Cd", 49: "In", 50: "Sn",
32
+ 51: "Sb", 52: "Te", 53: "I", 54: "Xe", 55: "Cs",
33
+ 56: "Ba", 57: "La", 58: "Ce", 59: "Pr", 60: "Nd",
34
+ 61: "Pm", 62: "Sm", 63: "Eu", 64: "Gd", 65: "Tb",
35
+ 66: "Dy", 67: "Ho", 68: "Er", 69: "Tm", 70: "Yb",
36
+ 71: "Lu", 72: "Hf", 73: "Ta", 74: "W", 75: "Re",
37
+ 76: "Os", 77: "Ir", 78: "Pt", 79: "Au", 80: "Hg",
38
+ 81: "Tl", 82: "Pb", 83: "Bi", 84: "Po", 85: "At",
39
+ 86: "Rn", 87: "Fr", 88: "Ra", 89: "Ac", 90: "Th",
40
+ 91: "Pa", 92: "U", 93: "Np", 94: "Pu", 95: "Am",
41
+ 96: "Cm", 97: "Bk", 98: "Cf", 99: "Es", 100: "Fm",
42
+ 101: "Md", 102: "No", 103: "Lr", 104: "Rf", 105: "Db",
43
+ 106: "Sg", 107: "Bh", 108: "Hs", 109: "Mt", 110: "Ds",
44
+ 111: "Rg", 112: "Cn", 113: "Nh", 114: "Fl", 115: "Mc",
45
+ 116: "Lv", 117: "Ts", 118: "Og",
46
+ }
@@ -0,0 +1,265 @@
1
+ # -*- coding: utf-8 -*-
2
+ """核心数据结构定义:Group、Interaction、InteractionSparse、SystemData。"""
3
+
4
+ from dataclasses import dataclass, field
5
+ from typing import List, Tuple, Dict, Optional
6
+ import numpy as np
7
+
8
+ from .constants import GROUP_TYPES, BOND_TYPES
9
+
10
+
11
+ @dataclass
12
+ class Group:
13
+ """一个可参与相互作用的基团。
14
+
15
+ Attributes:
16
+ group_id: 唯一标识
17
+ group_type: 基团类型,必须是 GROUP_TYPES 中的值
18
+ molecule: 所属分子名
19
+ residue_name: 残基名
20
+ residue_id: 全局残基号
21
+ atoms: 基团内的原子列表
22
+ metadata: 附加信息字典(键必须是字符串,值只能是 JSON 支持的类型:str, int, float, bool, None, list, dict)
23
+ """
24
+
25
+ group_id: int
26
+ group_type: str
27
+ molecule: str
28
+ residue_name: str
29
+ residue_id: int
30
+ atoms: List["AtomData"]
31
+ metadata: Dict = field(default_factory=dict)
32
+
33
+ def __post_init__(self):
34
+ """验证数据完整性。"""
35
+ if self.group_type not in GROUP_TYPES:
36
+ raise ValueError(f"Invalid group_type: '{self.group_type}'")
37
+ if not self.atoms:
38
+ raise ValueError("Group must contain at least one atom")
39
+
40
+ @property
41
+ def num_atoms(self) -> int:
42
+ """基团包含的原子数量。"""
43
+ return len(self.atoms)
44
+
45
+ @property
46
+ def atom_indices(self) -> List[int]:
47
+ """全局原子索引列表。"""
48
+ return [a.atom_global_idx for a in self.atoms]
49
+
50
+ @property
51
+ def net_charge(self) -> float:
52
+ """基团的净电荷。"""
53
+ return sum(a.atom_charge for a in self.atoms)
54
+
55
+ def __repr__(self) -> str:
56
+ return (f"Group(id={self.group_id}, type='{self.group_type}', "
57
+ f"mol='{self.molecule}', res='{self.residue_name}{self.residue_id}', "
58
+ f"atoms={self.num_atoms})")
59
+
60
+
61
+ # ============================================================
62
+ # Interaction 相互作用数据结构(per-type,矩阵存储)
63
+ # ============================================================
64
+
65
+ @dataclass
66
+ class Interaction:
67
+ """一种相互作用类型的全部检测结果。
68
+
69
+ 按类型组织:一个 Interaction 对象包含该类型下所有基团对在全部帧上的结果。
70
+ groups[i] 对应 existence[i] 和 metrics 中各数组的第 i 行。
71
+
72
+ Attributes:
73
+ interaction_type: 相互作用类型(如 "salt_bridge", "hydrogen_bond")
74
+ groups: 基团对列表,每对是一个 tuple
75
+ existence: (n_pairs, n_frames) bool 数组
76
+ metrics: 几何指标字典,值为 (n_pairs, n_frames) 数组
77
+ """
78
+
79
+ interaction_type: str
80
+ groups: List[Tuple[Group, ...]]
81
+ existence: np.ndarray
82
+ metrics: Dict[str, np.ndarray]
83
+ times: np.ndarray
84
+
85
+ def __post_init__(self):
86
+ """验证数据完整性。"""
87
+ n_pairs = len(self.groups)
88
+ n_frames = self.existence.shape[1] if self.existence.ndim == 2 else 0
89
+ if self.existence.shape != (n_pairs, n_frames):
90
+ raise ValueError(
91
+ f"existence shape {self.existence.shape} != ({n_pairs}, {n_frames})"
92
+ )
93
+ for name, arr in self.metrics.items():
94
+ if arr.shape != (n_pairs, n_frames):
95
+ raise ValueError(
96
+ f"{name} shape {arr.shape} != ({n_pairs}, {n_frames})"
97
+ )
98
+ times = np.asarray(self.times, dtype=float)
99
+ if times.shape != (n_frames,):
100
+ raise ValueError(
101
+ f"times shape {times.shape} != n_frames {n_frames}"
102
+ )
103
+ self.times = times
104
+
105
+ @property
106
+ def n_pairs(self) -> int:
107
+ """基团对数量。"""
108
+ return len(self.groups)
109
+
110
+ @property
111
+ def n_frames(self) -> int:
112
+ """帧数。"""
113
+ return self.existence.shape[1]
114
+
115
+ def occupancy(self) -> np.ndarray:
116
+ """每对基团的存在比例,shape=(n_pairs,)。"""
117
+ return np.sum(self.existence, axis=1) / self.n_frames
118
+
119
+ def __repr__(self) -> str:
120
+ return (f"Interaction(type='{self.interaction_type}', "
121
+ f"pairs={self.n_pairs}, frames={self.n_frames})")
122
+
123
+
124
+ # ============================================================
125
+ # InteractionSparse 稀疏存储的相互作用检测结果(Pass1 输出)
126
+ # ============================================================
127
+
128
+ @dataclass
129
+ class InteractionSparse:
130
+ """稀疏存储的相互作用检测结果(Pass1 输出)。
131
+
132
+ 以 (group_id1, group_id2, ...) 为键,存储每个基团组在哪些帧存在相互作用。
133
+ 不依赖内部索引(pair_idx),直接用 group_id 标识基团组。
134
+
135
+ Attributes:
136
+ interaction_type: 相互作用类型(如 "salt_bridge", "hydrogen_bond")
137
+ data: 稀疏数据,格式:
138
+ {
139
+ (group_id1, group_id2): {
140
+ "groups": (Group1, Group2),
141
+ "frames": [0, 1, 5, ...],
142
+ "metrics": {"distance": [...], "angle": [...]}
143
+ }
144
+ }
145
+ """
146
+
147
+ interaction_type: str
148
+ data: Dict[Tuple[int, ...], dict]
149
+
150
+ def __post_init__(self):
151
+ """验证数据完整性。"""
152
+ if not self.interaction_type:
153
+ raise ValueError("interaction_type cannot be empty")
154
+
155
+ @property
156
+ def n_pairs(self) -> int:
157
+ """基团组数量。"""
158
+ return len(self.data)
159
+
160
+ def __repr__(self) -> str:
161
+ return (f"InteractionSparse(type='{self.interaction_type}', "
162
+ f"pairs={self.n_pairs})")
163
+
164
+
165
+ # ============================================================
166
+ # SystemData 体系分子数据结构
167
+ # ============================================================
168
+
169
+ @dataclass
170
+ class AtomData:
171
+ """单个原子的信息。"""
172
+ atom_global_idx: int # 全局原子索引(整个体系唯一)
173
+ atom_idx_in_residue: int # 残基内索引(用于残基内键连接)
174
+ atom_name: str # 原子名(如 "CG")
175
+ atom_type: str # 力场类型(如 "ca")
176
+ atom_element: str # 元素符号(如 "C")
177
+ atom_charge: float # 电荷
178
+ atom_mass: float # 原子质量(原子质量单位,-1.0 表示未设置)
179
+
180
+
181
+ @dataclass
182
+ class BondData:
183
+ """残基内的一个键。"""
184
+ atom1_idx_in_residue: int # 残基内索引
185
+ atom2_idx_in_residue: int # 残基内索引
186
+ bond_type: str # 键类型,见 BOND_TYPES
187
+
188
+ def __post_init__(self):
189
+ """验证键类型。"""
190
+ if self.bond_type not in BOND_TYPES:
191
+ raise ValueError(f"Invalid bond_type: '{self.bond_type}'")
192
+
193
+
194
+ @dataclass
195
+ class ResidueData:
196
+ """一个残基的数据。"""
197
+ residue_name: str # 残基名(如 "TYR")
198
+ residue_global_idx: int # 全局残基索引(整个体系唯一)
199
+ residue_idx_in_molecule: int # 分子内残基编号(PDB 编号)
200
+ molecule_name: str # 所属分子名(如 "RBD_pro")
201
+ atoms: List[AtomData] # 残基内的原子
202
+ bonds: List[BondData] # 残基内的键
203
+
204
+
205
+ @dataclass
206
+ class InterResidueBond:
207
+ """残基间的共价键(如肽键、二硫键)。"""
208
+ residue1_global_idx: int # 残基 1 的全局索引
209
+ atom_idx_in_residue1: int # 原子在残基 1 内的索引
210
+ residue2_global_idx: int # 残基 2 的全局索引
211
+ atom_idx_in_residue2: int # 原子在残基 2 内的索引
212
+ bond_type: str # 键类型
213
+
214
+ def __post_init__(self):
215
+ """验证键类型。"""
216
+ if self.bond_type not in BOND_TYPES:
217
+ raise ValueError(f"Invalid bond_type: '{self.bond_type}'")
218
+
219
+
220
+ @dataclass
221
+ class SystemData:
222
+ """体系数据,连接 Reader 和 Identifier。"""
223
+ system_name: str
224
+ residues: List[ResidueData]
225
+ inter_residue_bonds: List[InterResidueBond]
226
+
227
+ def __post_init__(self):
228
+ """验证数据完整性。"""
229
+ # 验证 residue_global_idx 唯一性
230
+ res_indices = [r.residue_global_idx for r in self.residues]
231
+ if len(res_indices) != len(set(res_indices)):
232
+ raise ValueError("Duplicate residue_global_idx found")
233
+
234
+ # 验证 atom_global_idx 唯一性
235
+ atom_indices = []
236
+ for r in self.residues:
237
+ for a in r.atoms:
238
+ atom_indices.append(a.atom_global_idx)
239
+ if len(atom_indices) != len(set(atom_indices)):
240
+ raise ValueError("Duplicate atom_global_idx found")
241
+
242
+ @property
243
+ def n_residues(self) -> int:
244
+ """残基数量。"""
245
+ return len(self.residues)
246
+
247
+ def get_residue_by_global_idx(self, idx: int) -> ResidueData:
248
+ """根据全局索引获取残基。"""
249
+ for r in self.residues:
250
+ if r.residue_global_idx == idx:
251
+ return r
252
+ raise KeyError(f"Residue with global_idx={idx} not found")
253
+
254
+ def get_atoms_by_molecule(self, molecule_name: str) -> List[AtomData]:
255
+ """获取指定分子的所有原子。"""
256
+ atoms = []
257
+ for r in self.residues:
258
+ if r.molecule_name == molecule_name:
259
+ atoms.extend(r.atoms)
260
+ return atoms
261
+
262
+ def __repr__(self) -> str:
263
+ return (f"SystemData(name='{self.system_name}', "
264
+ f"residues={self.n_residues}, "
265
+ f"inter_residue_bonds={len(self.inter_residue_bonds)})")