ssRMSD 0.1.0__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.
- ssrmsd/__init__.py +26 -0
- ssrmsd/align.py +350 -0
- ssrmsd/cli.py +338 -0
- ssrmsd/format.py +128 -0
- ssrmsd/io.py +422 -0
- ssrmsd/kabsch.py +149 -0
- ssrmsd/score.py +154 -0
- ssrmsd/types.py +126 -0
- ssrmsd-0.1.0.dist-info/METADATA +144 -0
- ssrmsd-0.1.0.dist-info/RECORD +13 -0
- ssrmsd-0.1.0.dist-info/WHEEL +4 -0
- ssrmsd-0.1.0.dist-info/entry_points.txt +2 -0
- ssrmsd-0.1.0.dist-info/licenses/LICENSE +21 -0
ssrmsd/__init__.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from ssrmsd.score import score_batch, score_ensemble
|
|
4
|
+
from ssrmsd.types import (
|
|
5
|
+
ChainData,
|
|
6
|
+
EnsembleResult,
|
|
7
|
+
EnsembleSpec,
|
|
8
|
+
PairwiseDistance,
|
|
9
|
+
ScoringOptions,
|
|
10
|
+
SsrmsdError,
|
|
11
|
+
StructureData,
|
|
12
|
+
StructureInput,
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"ChainData",
|
|
17
|
+
"EnsembleResult",
|
|
18
|
+
"EnsembleSpec",
|
|
19
|
+
"PairwiseDistance",
|
|
20
|
+
"ScoringOptions",
|
|
21
|
+
"SsrmsdError",
|
|
22
|
+
"StructureData",
|
|
23
|
+
"StructureInput",
|
|
24
|
+
"score_batch",
|
|
25
|
+
"score_ensemble",
|
|
26
|
+
]
|
ssrmsd/align.py
ADDED
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
import string
|
|
5
|
+
from collections.abc import Sequence
|
|
6
|
+
from dataclasses import dataclass
|
|
7
|
+
|
|
8
|
+
import gemmi
|
|
9
|
+
import numpy as np
|
|
10
|
+
|
|
11
|
+
from ssrmsd.types import ChainData, ScoringOptions, SsrmsdError, StructureData
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
@dataclass(frozen=True)
|
|
15
|
+
class AlignedEnsemble:
|
|
16
|
+
"""Ensemble structures reduced to common aligned/scored C-alpha coordinates."""
|
|
17
|
+
|
|
18
|
+
names: tuple[str, ...]
|
|
19
|
+
sources: tuple[str | None, ...]
|
|
20
|
+
align_coords: tuple[np.ndarray, ...]
|
|
21
|
+
score_coords: tuple[np.ndarray, ...]
|
|
22
|
+
chain_mapping: tuple[dict[str, str], ...]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _synthetic_chain_id(index: int) -> str:
|
|
26
|
+
letters = string.ascii_uppercase
|
|
27
|
+
if index < len(letters):
|
|
28
|
+
return letters[index]
|
|
29
|
+
return f"C{index}"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _split_poly_g_linkers(
|
|
33
|
+
structures: Sequence[StructureData],
|
|
34
|
+
linker_min_len: int,
|
|
35
|
+
) -> list[StructureData]:
|
|
36
|
+
if linker_min_len <= 0 or not structures:
|
|
37
|
+
return list(structures)
|
|
38
|
+
|
|
39
|
+
max_chains = max(len(s.chains) for s in structures)
|
|
40
|
+
pattern = re.compile(f"G{{{linker_min_len},}}")
|
|
41
|
+
result: list[StructureData] = []
|
|
42
|
+
|
|
43
|
+
for s in structures:
|
|
44
|
+
if len(s.chains) >= max_chains:
|
|
45
|
+
result.append(s)
|
|
46
|
+
continue
|
|
47
|
+
|
|
48
|
+
new_chains: list[ChainData] = []
|
|
49
|
+
did_split = False
|
|
50
|
+
for chain in s.chains:
|
|
51
|
+
spans = [m.span() for m in pattern.finditer(chain.sequence)]
|
|
52
|
+
if not spans:
|
|
53
|
+
new_chains.append(chain)
|
|
54
|
+
continue
|
|
55
|
+
segments: list[tuple[int, int]] = []
|
|
56
|
+
cursor = 0
|
|
57
|
+
for start, end in spans:
|
|
58
|
+
if start > cursor:
|
|
59
|
+
segments.append((cursor, start))
|
|
60
|
+
cursor = end
|
|
61
|
+
if cursor < len(chain.sequence):
|
|
62
|
+
segments.append((cursor, len(chain.sequence)))
|
|
63
|
+
if len(segments) >= 2:
|
|
64
|
+
did_split = True
|
|
65
|
+
for seg_idx, (start, end) in enumerate(segments):
|
|
66
|
+
new_chains.append(
|
|
67
|
+
ChainData(
|
|
68
|
+
chain_id=f"{chain.chain_id}_{seg_idx}",
|
|
69
|
+
sequence=chain.sequence[start:end],
|
|
70
|
+
ca_coords=chain.ca_coords[start:end],
|
|
71
|
+
)
|
|
72
|
+
)
|
|
73
|
+
else:
|
|
74
|
+
new_chains.append(chain)
|
|
75
|
+
|
|
76
|
+
if did_split:
|
|
77
|
+
result.append(
|
|
78
|
+
StructureData(
|
|
79
|
+
name=s.name,
|
|
80
|
+
source=s.source,
|
|
81
|
+
chains=tuple(new_chains),
|
|
82
|
+
was_split=True,
|
|
83
|
+
)
|
|
84
|
+
)
|
|
85
|
+
else:
|
|
86
|
+
result.append(s)
|
|
87
|
+
|
|
88
|
+
return result
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _select_reference(
|
|
92
|
+
structures: Sequence[StructureData],
|
|
93
|
+
ref_source: str | None,
|
|
94
|
+
) -> tuple[int, StructureData]:
|
|
95
|
+
if ref_source is not None:
|
|
96
|
+
for idx, s in enumerate(structures):
|
|
97
|
+
if s.source == ref_source:
|
|
98
|
+
return idx, s
|
|
99
|
+
raise SsrmsdError(f"ref-source '{ref_source}' not present in ensemble")
|
|
100
|
+
|
|
101
|
+
for idx, s in enumerate(structures):
|
|
102
|
+
if not s.was_split:
|
|
103
|
+
return idx, s
|
|
104
|
+
|
|
105
|
+
# Fallback: all structures were linker-split -> normalize chain IDs to A, B, C, ...
|
|
106
|
+
first = structures[0]
|
|
107
|
+
normalized_chains = tuple(
|
|
108
|
+
ChainData(
|
|
109
|
+
chain_id=_synthetic_chain_id(i),
|
|
110
|
+
sequence=c.sequence,
|
|
111
|
+
ca_coords=c.ca_coords,
|
|
112
|
+
)
|
|
113
|
+
for i, c in enumerate(first.chains)
|
|
114
|
+
)
|
|
115
|
+
return 0, StructureData(
|
|
116
|
+
name=first.name,
|
|
117
|
+
source=first.source,
|
|
118
|
+
chains=normalized_chains,
|
|
119
|
+
was_split=first.was_split,
|
|
120
|
+
)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _make_alignment_scoring() -> gemmi.AlignmentScoring:
|
|
124
|
+
"""Affine-gap scoring that avoids scattering short peptides across long chains."""
|
|
125
|
+
scoring = gemmi.AlignmentScoring()
|
|
126
|
+
scoring.match = 2
|
|
127
|
+
scoring.mismatch = -2
|
|
128
|
+
scoring.gapo = -6
|
|
129
|
+
scoring.gape = -1
|
|
130
|
+
return scoring
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
_ALIGNMENT_SCORING = _make_alignment_scoring()
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _align_sequences(ref_seq: str, target_seq: str) -> tuple[float, float, dict[int, int]]:
|
|
137
|
+
"""Globally align two 1-letter sequences via gemmi; return overlap identity, coverage, map."""
|
|
138
|
+
if not ref_seq or not target_seq:
|
|
139
|
+
return 0.0, 0.0, {}
|
|
140
|
+
res = gemmi.align_string_sequences(list(ref_seq), list(target_seq), [], _ALIGNMENT_SCORING)
|
|
141
|
+
g1 = res.add_gaps(ref_seq, 1)
|
|
142
|
+
g2 = res.add_gaps(target_seq, 2)
|
|
143
|
+
i = 0
|
|
144
|
+
j = 0
|
|
145
|
+
matches = 0
|
|
146
|
+
aligned_pairs = 0
|
|
147
|
+
idx_map: dict[int, int] = {}
|
|
148
|
+
for c1, c2 in zip(g1, g2, strict=True):
|
|
149
|
+
if c1 != "-" and c2 != "-":
|
|
150
|
+
aligned_pairs += 1
|
|
151
|
+
if c1 == c2:
|
|
152
|
+
matches += 1
|
|
153
|
+
idx_map[i] = j
|
|
154
|
+
i += 1
|
|
155
|
+
j += 1
|
|
156
|
+
elif c1 != "-":
|
|
157
|
+
i += 1
|
|
158
|
+
elif c2 != "-":
|
|
159
|
+
j += 1
|
|
160
|
+
identity = (matches / aligned_pairs) if aligned_pairs > 0 else 0.0
|
|
161
|
+
coverage = aligned_pairs / max(len(ref_seq), len(target_seq))
|
|
162
|
+
return identity, coverage, idx_map
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _resolve_chain_sets(
|
|
166
|
+
ref: StructureData,
|
|
167
|
+
options: ScoringOptions,
|
|
168
|
+
) -> tuple[tuple[str, ...], tuple[str, ...], tuple[str, ...], bool]:
|
|
169
|
+
ref_ids = tuple(c.chain_id for c in ref.chains)
|
|
170
|
+
ref_id_set = set(ref_ids)
|
|
171
|
+
has_selection = options.align_chains is not None or options.score_chains is not None
|
|
172
|
+
|
|
173
|
+
if options.align_chains is not None:
|
|
174
|
+
missing = [cid for cid in options.align_chains if cid not in ref_id_set]
|
|
175
|
+
if missing:
|
|
176
|
+
raise SsrmsdError(
|
|
177
|
+
f"Unknown --align-chains ID(s) {missing} not in reference chains {list(ref_ids)}"
|
|
178
|
+
)
|
|
179
|
+
align_ids = tuple(dict.fromkeys(options.align_chains))
|
|
180
|
+
else:
|
|
181
|
+
align_ids = ref_ids
|
|
182
|
+
|
|
183
|
+
if options.score_chains is not None:
|
|
184
|
+
missing = [cid for cid in options.score_chains if cid not in ref_id_set]
|
|
185
|
+
if missing:
|
|
186
|
+
raise SsrmsdError(
|
|
187
|
+
f"Unknown --score-chains ID(s) {missing} not in reference chains {list(ref_ids)}"
|
|
188
|
+
)
|
|
189
|
+
score_ids = tuple(dict.fromkeys(options.score_chains))
|
|
190
|
+
else:
|
|
191
|
+
score_ids = ref_ids
|
|
192
|
+
|
|
193
|
+
required_set = set(align_ids) | set(score_ids)
|
|
194
|
+
required_ids = tuple(cid for cid in ref_ids if cid in required_set)
|
|
195
|
+
return align_ids, score_ids, required_ids, has_selection
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def align_ensemble(
|
|
199
|
+
structures: Sequence[StructureData],
|
|
200
|
+
options: ScoringOptions,
|
|
201
|
+
) -> AlignedEnsemble:
|
|
202
|
+
"""Match chains by sequence across structures and extract common C-alpha coordinates."""
|
|
203
|
+
if len(structures) < 2:
|
|
204
|
+
raise SsrmsdError("fewer than 2 structures")
|
|
205
|
+
|
|
206
|
+
prepped = _split_poly_g_linkers(structures, options.linker_min_len)
|
|
207
|
+
ref_idx, ref = _select_reference(prepped, options.ref_source)
|
|
208
|
+
if ref_idx == 0 and prepped[0] is not ref:
|
|
209
|
+
prepped[0] = ref
|
|
210
|
+
|
|
211
|
+
align_ids, score_ids, required_ids, has_selection = _resolve_chain_sets(ref, options)
|
|
212
|
+
ref_chains_by_id = {c.chain_id: c for c in ref.chains}
|
|
213
|
+
|
|
214
|
+
# Strict chain-count equality when no chain-selection flags are set.
|
|
215
|
+
if not has_selection:
|
|
216
|
+
expected_n = len(ref.chains)
|
|
217
|
+
for s in prepped:
|
|
218
|
+
if len(s.chains) != expected_n:
|
|
219
|
+
raise SsrmsdError(
|
|
220
|
+
f"Chain count mismatch: '{s.name}' has {len(s.chains)} chains, "
|
|
221
|
+
f"reference '{ref.name}' has {expected_n}"
|
|
222
|
+
)
|
|
223
|
+
|
|
224
|
+
# Homomer guard on reference required chains (gated on both identity and overlap coverage).
|
|
225
|
+
for i in range(len(required_ids)):
|
|
226
|
+
for j in range(i + 1, len(required_ids)):
|
|
227
|
+
c1 = ref_chains_by_id[required_ids[i]]
|
|
228
|
+
c2 = ref_chains_by_id[required_ids[j]]
|
|
229
|
+
ident, cov, _ = _align_sequences(c1.sequence, c2.sequence)
|
|
230
|
+
if ident >= options.min_chain_id and cov >= options.min_coverage:
|
|
231
|
+
raise SsrmsdError(
|
|
232
|
+
f"Ambiguous/homomeric chains detected in reference ('{c1.chain_id}' and "
|
|
233
|
+
f"'{c2.chain_id}', identity={ident:.2f}, coverage={cov:.2f}); "
|
|
234
|
+
"homomer symmetry matching is not enabled"
|
|
235
|
+
)
|
|
236
|
+
|
|
237
|
+
# Match each structure's chains to required reference chains and record residue alignments.
|
|
238
|
+
chain_mappings: list[dict[str, str]] = []
|
|
239
|
+
# per_chain_maps[ref_cid][struct_idx] = (target_chain, {ref_pos: target_pos})
|
|
240
|
+
per_chain_maps: dict[str, list[tuple[ChainData, dict[int, int]]]] = {
|
|
241
|
+
cid: [] for cid in required_ids
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
for s_idx, s in enumerate(prepped):
|
|
245
|
+
if s_idx == ref_idx:
|
|
246
|
+
mapping = {cid: cid for cid in required_ids}
|
|
247
|
+
chain_mappings.append(mapping)
|
|
248
|
+
for cid in required_ids:
|
|
249
|
+
rc = ref_chains_by_id[cid]
|
|
250
|
+
per_chain_maps[cid].append((rc, {k: k for k in range(len(rc.sequence))}))
|
|
251
|
+
continue
|
|
252
|
+
|
|
253
|
+
# Compute overlap identity & coverage matrices between ref chains and structure chains.
|
|
254
|
+
ident_mat: list[list[float]] = []
|
|
255
|
+
cov_mat: list[list[float]] = []
|
|
256
|
+
map_mat: list[list[dict[int, int]]] = []
|
|
257
|
+
for r_cid in required_ids:
|
|
258
|
+
r_seq = ref_chains_by_id[r_cid].sequence
|
|
259
|
+
row_id: list[float] = []
|
|
260
|
+
row_cov: list[float] = []
|
|
261
|
+
row_map: list[dict[int, int]] = []
|
|
262
|
+
for t_chain in s.chains:
|
|
263
|
+
ident, cov, idx_map = _align_sequences(r_seq, t_chain.sequence)
|
|
264
|
+
row_id.append(ident)
|
|
265
|
+
row_cov.append(cov)
|
|
266
|
+
row_map.append(idx_map)
|
|
267
|
+
ident_mat.append(row_id)
|
|
268
|
+
cov_mat.append(row_cov)
|
|
269
|
+
map_mat.append(row_map)
|
|
270
|
+
|
|
271
|
+
# Check row/column uniqueness above threshold (homomer/ambiguity guard).
|
|
272
|
+
mapping = {}
|
|
273
|
+
used_targets: set[int] = set()
|
|
274
|
+
for r_i, r_cid in enumerate(required_ids):
|
|
275
|
+
hits = [
|
|
276
|
+
t_j
|
|
277
|
+
for t_j, (val, cov) in enumerate(zip(ident_mat[r_i], cov_mat[r_i], strict=True))
|
|
278
|
+
if val >= options.min_chain_id and cov >= options.min_coverage
|
|
279
|
+
]
|
|
280
|
+
if len(hits) > 1:
|
|
281
|
+
hit_ids = [s.chains[t_j].chain_id for t_j in hits]
|
|
282
|
+
raise SsrmsdError(
|
|
283
|
+
f"Ambiguous/homomeric chains in '{s.name}': multiple chains {hit_ids} "
|
|
284
|
+
f"match reference chain '{r_cid}' above min-chain-id={options.min_chain_id}"
|
|
285
|
+
)
|
|
286
|
+
if not hits:
|
|
287
|
+
# If a chain matched on sequence identity alone (sub-coverage truncation), let
|
|
288
|
+
# the symmetric coverage guard below emit the clear coverage diagnostic.
|
|
289
|
+
id_only = [
|
|
290
|
+
t_j for t_j, val in enumerate(ident_mat[r_i]) if val >= options.min_chain_id
|
|
291
|
+
]
|
|
292
|
+
if len(id_only) == 1:
|
|
293
|
+
hits = id_only
|
|
294
|
+
else:
|
|
295
|
+
best = max(ident_mat[r_i]) if ident_mat[r_i] else 0.0
|
|
296
|
+
raise SsrmsdError(
|
|
297
|
+
f"No matching chain in '{s.name}' for reference chain '{r_cid}' "
|
|
298
|
+
f"(best identity={best:.2f} < {options.min_chain_id})"
|
|
299
|
+
)
|
|
300
|
+
t_j = hits[0]
|
|
301
|
+
if t_j in used_targets:
|
|
302
|
+
raise SsrmsdError(
|
|
303
|
+
f"Ambiguous/homomeric chain assignment in '{s.name}': "
|
|
304
|
+
f"chain '{s.chains[t_j].chain_id}' matches multiple reference chains"
|
|
305
|
+
)
|
|
306
|
+
used_targets.add(t_j)
|
|
307
|
+
t_chain = s.chains[t_j]
|
|
308
|
+
mapping[r_cid] = t_chain.chain_id
|
|
309
|
+
per_chain_maps[r_cid].append((t_chain, map_mat[r_i][t_j]))
|
|
310
|
+
|
|
311
|
+
chain_mappings.append(mapping)
|
|
312
|
+
|
|
313
|
+
# Compute ensemble-wide C-alpha intersection and symmetric coverage check per required chain.
|
|
314
|
+
common_coords_by_chain: dict[str, list[np.ndarray]] = {}
|
|
315
|
+
for cid in required_ids:
|
|
316
|
+
entries = per_chain_maps[cid]
|
|
317
|
+
common_positions: set[int] = set(entries[0][1].keys())
|
|
318
|
+
for _, idx_map in entries[1:]:
|
|
319
|
+
common_positions &= set(idx_map.keys())
|
|
320
|
+
sorted_pos = sorted(common_positions)
|
|
321
|
+
max_chain_len = max(len(chain.sequence) for chain, _ in entries)
|
|
322
|
+
coverage = (len(sorted_pos) / max_chain_len) if max_chain_len > 0 else 0.0
|
|
323
|
+
if coverage < options.min_coverage or len(sorted_pos) == 0:
|
|
324
|
+
raise SsrmsdError(
|
|
325
|
+
f"Aligned CA coverage for chain '{cid}' is {coverage:.2f} "
|
|
326
|
+
f"({len(sorted_pos)}/{max_chain_len}), below min-coverage={options.min_coverage}"
|
|
327
|
+
)
|
|
328
|
+
chain_coords_per_struct: list[np.ndarray] = []
|
|
329
|
+
for chain, idx_map in entries:
|
|
330
|
+
target_indices = [idx_map[p] for p in sorted_pos]
|
|
331
|
+
chain_coords_per_struct.append(chain.ca_coords[target_indices])
|
|
332
|
+
common_coords_by_chain[cid] = chain_coords_per_struct
|
|
333
|
+
|
|
334
|
+
# Assemble concatenated alignment and scoring coordinate arrays per structure.
|
|
335
|
+
n = len(prepped)
|
|
336
|
+
align_coords: list[np.ndarray] = []
|
|
337
|
+
score_coords: list[np.ndarray] = []
|
|
338
|
+
for s_idx in range(n):
|
|
339
|
+
a_arr = np.vstack([common_coords_by_chain[cid][s_idx] for cid in align_ids])
|
|
340
|
+
s_arr = np.vstack([common_coords_by_chain[cid][s_idx] for cid in score_ids])
|
|
341
|
+
align_coords.append(a_arr)
|
|
342
|
+
score_coords.append(s_arr)
|
|
343
|
+
|
|
344
|
+
return AlignedEnsemble(
|
|
345
|
+
names=tuple(s.name for s in prepped),
|
|
346
|
+
sources=tuple(s.source for s in prepped),
|
|
347
|
+
align_coords=tuple(align_coords),
|
|
348
|
+
score_coords=tuple(score_coords),
|
|
349
|
+
chain_mapping=tuple(chain_mappings),
|
|
350
|
+
)
|