Skip to content

Commit a7f7048

Browse files
improve constructing DSSP
1 parent 6cd1f7e commit a7f7048

3 files changed

Lines changed: 84 additions & 39 deletions

File tree

‎package/CHANGELOG‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,10 @@ Fixes
109109
DSSP by porting upstream PyDSSP 0.9.1 fix (Issue #4913)
110110

111111
Enhancements
112+
* DSSP finds the hydrogens of all residues with one selection instead of
113+
one per residue, so constructing DSSP is 30-50x faster, and fills in
114+
hydrogen positions without a loop over residues for
115+
``guess_hydrogens=False`` (PR #XXXX)
112116
* Add reading single-frame files from mmCIF, also known as PDBx format, using
113117
crystallographic library `gemmi` as a backend (Issue #2367 and extension of
114118
#4303, also solves #5089, PR #4712).

‎package/MDAnalysis/analysis/dssp/dssp.py‎

Lines changed: 40 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,6 @@
145145
"""
146146

147147
import warnings
148-
from typing import Optional, Union
149148

150149
import numpy as np
151150

@@ -312,7 +311,7 @@ def get_supported_backends(cls):
312311

313312
def __init__(
314313
self,
315-
atoms: Union[Universe, AtomGroup],
314+
atoms: Universe | AtomGroup,
316315
guess_hydrogens: bool = True,
317316
*,
318317
heavyatom_names: tuple[str] = ("N", "CA", "C", "O O1 OT1"),
@@ -326,7 +325,7 @@ def __init__(
326325
super().__init__(ag.universe.trajectory)
327326

328327
# define necessary selections
329-
self._heavy_atoms: dict[str, "AtomGroup"] = {
328+
self._heavy_atoms: dict[str, AtomGroup] = {
330329
t: ag.atoms[
331330
np.isin(
332331
ag.names, t.split()
@@ -335,7 +334,7 @@ def __init__(
335334
]
336335
for t in heavyatom_names
337336
}
338-
self._donor_mask: Optional[np.ndarray] = ag.residues.resnames != "PRO"
337+
self._donor_mask: np.ndarray | None = ag.residues.resnames != "PRO"
339338
self._box = self._trajectory.ts.dimensions
340339
if self._box is not None and np.allclose(
341340
self._box, [1, 1, 1, 90, 90, 90]
@@ -345,38 +344,40 @@ def __init__(
345344
"Box dimensions are (1, 1, 1, 90, 90, 90), not using "
346345
"periodic boundary conditions in DSSP calculations"
347346
)
348-
self._hydrogens: list["AtomGroup"] = [
349-
res.atoms.select_atoms(f"name {hydrogen_name}")
350-
for res in ag.residues
347+
# hydrogens of each residue (among all of its atoms, not only those in
348+
# ag), found with one selection: residue positions in ag.residues
349+
# (sorted by resindex), then the number per residue and the first one
350+
# of each residue that has any, in atom order
351+
residues = ag.residues
352+
hydrogens = residues.atoms.select_atoms(f"name {hydrogen_name}")
353+
h_residue = np.searchsorted(residues.resindices, hydrogens.resindices)
354+
n_hydrogens = np.bincount(h_residue, minlength=len(residues))
355+
self._has_hydrogen: np.ndarray = n_hydrogens > 0
356+
self._first_hydrogens: AtomGroup = hydrogens[
357+
np.unique(h_residue, return_index=True)[1]
351358
]
352-
# can't do it the other way because I need missing values to exist
353-
# so that I could fill them in later
354359
if not self._guess_hydrogens:
355-
# zip() assumes that _heavy_atoms and _hydrogens is ordered in the
356-
# same way. This is true as long as the original AtomGroup ag is
357-
# sorted. With the hard-coded protein selection for ag this is always
358-
# true but if the code on L277 ever changes, make sure to sort first!
359-
for calpha, hydrogen in zip(
360-
self._heavy_atoms["CA"][1:], self._hydrogens[1:]
361-
):
362-
if (calpha.resname != "PRO" and len(hydrogen) != 1) or (
363-
calpha.resname == "PRO" and hydrogen
364-
):
365-
raise ValueError(
366-
(
367-
f"Residue {calpha.residue} contains wrong number of hydrogens: "
368-
"exactly 1 hydrogen is expected for non-PRO residues, and "
369-
"zero hydrogens for PRO residues."
370-
)
371-
)
360+
# pairs the k-th CA atom with the k-th residue. This assumes that
361+
# both are ordered in the same way, which holds as long as ag is
362+
# sorted (it is, from the hard-coded protein selection above)
363+
calphas = self._heavy_atoms["CA"]
364+
n = min(len(calphas), len(residues))
365+
is_pro = calphas.resnames[1:n] == "PRO"
366+
counts = n_hydrogens[1:n]
367+
wrong = np.flatnonzero(np.where(is_pro, counts != 0, counts != 1))
368+
if wrong.size:
369+
residue = calphas[wrong[0] + 1].residue
370+
raise ValueError(
371+
f"Residue {residue} contains wrong number of hydrogens: "
372+
"exactly 1 hydrogen is expected for non-PRO residues, and "
373+
"zero hydrogens for PRO residues."
374+
)
372375

373376
positions = [group.positions for group in self._heavy_atoms.values()]
374-
if len(set(map(lambda arr: arr.shape[0], positions))) != 1:
377+
if len({arr.shape[0] for arr in positions}) != 1:
375378
raise ValueError(
376-
(
377-
"Universe contains unequal numbers of (N,CA,C,O) atoms ('name' field)."
378-
" Please select appropriate AtomGroup manually."
379-
)
379+
"Universe contains unequal numbers of (N,CA,C,O) atoms ('name' field)."
380+
" Please select appropriate AtomGroup manually."
380381
)
381382

382383
if len(ag.residues) < 6:
@@ -413,14 +414,14 @@ def _get_coords(self) -> np.ndarray:
413414
coords.swapaxes(0, 1)
414415
)
415416

416-
h_coords = np.array(
417-
[
418-
group.positions[0] if group else guessed_h_coords[idx]
419-
for idx, group in enumerate(self._hydrogens)
420-
]
421-
)
422-
h_coords = np.expand_dims(h_coords, axis=0)
423-
coords = np.vstack([coords, h_coords])
417+
# the first hydrogen of each residue that has one; a residue
418+
# without one takes the guessed hydrogen of the same index
419+
has = self._has_hydrogen
420+
h_coords = np.empty((len(has), 3), dtype=coords.dtype)
421+
h_coords[has] = self._first_hydrogens.positions
422+
missing = np.flatnonzero(~has)
423+
h_coords[missing] = guessed_h_coords[missing]
424+
coords = np.vstack([coords, h_coords[np.newaxis]])
424425

425426
coords = coords.swapaxes(0, 1)
426427
return coords

‎testsuite/MDAnalysisTests/analysis/test_dssp.py‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
import numpy as np
77
import pytest
88
from MDAnalysis.analysis.dssp import DSSP, assign, translate
9+
from MDAnalysis.analysis.dssp.pydssp_numpy import _get_hydrogen_atom_position
910

1011
from MDAnalysisTests.datafiles import DSSP as DSSP_FOLDER
1112
from MDAnalysisTests.datafiles import TPR, XTC
@@ -171,3 +172,42 @@ def test_insufficient_residues_raises_error(client_DSSP):
171172
dssp = DSSP(res6)
172173
result = dssp.run(**client_DSSP, stop=1)
173174
assert result.results.dssp.shape[1] == 6
175+
176+
177+
def _hydrogens_per_residue(ag, hydrogen_name):
178+
"""hydrogens selected one residue at a time (the selection DSSP made
179+
before it was vectorised): the reference for the selection now"""
180+
return [
181+
res.atoms.select_atoms(f"name {hydrogen_name}")
182+
for res in ag.select_atoms("protein").residues
183+
]
184+
185+
186+
@pytest.mark.parametrize(
187+
"hydrogen_name", ["H HN HT1 HT2 HT3", "H HN H1", "H*"]
188+
)
189+
@pytest.mark.parametrize("selection", ["all", "protein and not name H HN"])
190+
def test_hydrogens_match_per_residue_selection(hydrogen_name, selection):
191+
# without H and HN in the selection, the hydrogens are still looked up
192+
# among all atoms of each residue
193+
ag = mda.Universe(TPR, XTC).select_atoms(selection)
194+
dssp = DSSP(ag, hydrogen_name=hydrogen_name)
195+
expected = _hydrogens_per_residue(ag, hydrogen_name)
196+
np.testing.assert_equal(dssp._has_hydrogen, [bool(h) for h in expected])
197+
np.testing.assert_equal(
198+
dssp._first_hydrogens.ix, [h.ix[0] for h in expected if h]
199+
)
200+
201+
202+
def test_coords_with_hydrogens_match_per_residue_lookup():
203+
# residues without a hydrogen (here the N-terminal MET, whose hydrogens
204+
# are H1-H3, and prolines) take the guessed hydrogen of the same index
205+
u = mda.Universe(TPR, XTC)
206+
coords = DSSP(u, guess_hydrogens=False)._get_coords()
207+
guessed = _get_hydrogen_atom_position(coords[:, :4])
208+
hydrogens = _hydrogens_per_residue(u.atoms, "H HN HT1 HT2 HT3")
209+
assert not all(hydrogens)
210+
expected = [
211+
h.positions[0] if h else guessed[k] for k, h in enumerate(hydrogens)
212+
]
213+
np.testing.assert_equal(coords[:, 4], expected)

0 commit comments

Comments
 (0)