Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion package/CHANGELOG
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,16 @@ The rules for this file:


-------------------------------------------------------------------------------
??/??/?? IAlibay, sumitsaraswat362
??/??/?? IAlibay, sumitsaraswat362, BradyAJohnston

* 2.12.0

Fixes
* DSSP treats residues that start a chain (the first residue, and any
residue more than 2.5 Å from the C atom of the residue before it: another
chain or a gap) as DSSP does: they are no hydrogen bond donors and are
not checked for a single hydrogen with ``guess_hydrogens=False``, which
rejected every system with more than one chain (Issue #5505, PR #5506)

Enhancements
* InterRDF and InterRDF_s now expose computed average box volume and densities
Expand Down
120 changes: 78 additions & 42 deletions package/MDAnalysis/analysis/dssp/dssp.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,13 +145,13 @@
"""

import warnings
from typing import Optional, Union

import numpy as np

from MDAnalysis import AtomGroup, Universe

from ...due import Doi, due
from ...lib.distances import calc_bonds
from ..base import AnalysisBase, ResultsGroup

due.cite(
Expand All @@ -163,6 +163,10 @@

del Doi

# Longest C-N distance (in Å) between consecutive residues that still counts
# as a peptide bond; a longer one starts a new chain (the value used by DSSP)
MAX_PEPTIDE_BOND_LENGTH = 2.5


try: # pragma: no cover
from pydssp.pydssp_numpy import (
Expand Down Expand Up @@ -222,7 +226,7 @@ class DSSP(AnalysisBase):
atom makes, and a N-H bond length of 1.01 A.
If ``guess_hydrogens`` is False, hydrogen atom positions on N atoms
will be parsed from the trajectory, except for the "hydrogen" atom
positions on PRO residues, and an N-terminal residue.
positions on PRO residues, and the first residue of each chain.
heavyatom_names : tuple[str], default ("N", "CA", "C", "O O1 OT1")
selection names that will be used to select "N", "CA", "C" and "O"
atom coordinates for the secondary structure determination. The last
Expand Down Expand Up @@ -298,6 +302,15 @@ class DSSP(AnalysisBase):
Change treatment of proline and follow pydssp 0.9.1 (prolines are now explicitly
forbidden to participate in the hydrogen bond network). Previous version could yield
wrong assignment of prolines.

.. versionchanged:: 2.12.0
Residues that start a chain (the first residue, and every residue whose
N atom is more than 2.5 Å from the C atom of the residue before it, the
start of another chain or a gap) are no hydrogen bond donors, as in
DSSP, and are not checked for a single hydrogen with
``guess_hydrogens=False``. Before, systems with more than one chain
failed that check, and the hydrogen guessed for a residue after a gap
could form spurious hydrogen bonds.
"""

_analysis_algorithm_is_parallelizable = True
Expand All @@ -312,7 +325,7 @@ def get_supported_backends(cls):

def __init__(
self,
atoms: Union[Universe, AtomGroup],
atoms: Universe | AtomGroup,
guess_hydrogens: bool = True,
*,
heavyatom_names: tuple[str] = ("N", "CA", "C", "O O1 OT1"),
Expand All @@ -326,7 +339,7 @@ def __init__(
super().__init__(ag.universe.trajectory)

# define necessary selections
self._heavy_atoms: dict[str, "AtomGroup"] = {
self._heavy_atoms: dict[str, AtomGroup] = {
t: ag.atoms[
np.isin(
ag.names, t.split()
Expand All @@ -335,7 +348,6 @@ def __init__(
]
for t in heavyatom_names
}
self._donor_mask: Optional[np.ndarray] = ag.residues.resnames != "PRO"
self._box = self._trajectory.ts.dimensions
if self._box is not None and np.allclose(
self._box, [1, 1, 1, 90, 90, 90]
Expand All @@ -345,40 +357,64 @@ def __init__(
"Box dimensions are (1, 1, 1, 90, 90, 90), not using "
"periodic boundary conditions in DSSP calculations"
)
self._hydrogens: list["AtomGroup"] = [
res.atoms.select_atoms(f"name {hydrogen_name}")
for res in ag.residues
]
# can't do it the other way because I need missing values to exist
# so that I could fill them in later
if not self._guess_hydrogens:
# zip() assumes that _heavy_atoms and _hydrogens is ordered in the
# same way. This is true as long as the original AtomGroup ag is
# sorted. With the hard-coded protein selection for ag this is always
# true but if the code on L277 ever changes, make sure to sort first!
for calpha, hydrogen in zip(
self._heavy_atoms["CA"][1:], self._hydrogens[1:]
):
if (calpha.resname != "PRO" and len(hydrogen) != 1) or (
calpha.resname == "PRO" and hydrogen
):
raise ValueError(
(
f"Residue {calpha.residue} contains wrong number of hydrogens: "
"exactly 1 hydrogen is expected for non-PRO residues, and "
"zero hydrogens for PRO residues."
)
)

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

# chain starts: the first residue, and every residue whose N is not
# bonded to the C of the residue before it (the start of another
# chain, or a gap), judged on the current frame. As in DSSP, they do
# not donate hydrogen bonds: they have no peptide bond from which to
# guess the position of their hydrogen
n_positions, c_positions = positions[0], positions[2]
peptide_bonds = calc_bonds(
c_positions[:-1], n_positions[1:], box=self._box
)
self._chain_start: np.ndarray = np.concatenate(
[[True], peptide_bonds > MAX_PEPTIDE_BOND_LENGTH]
)
self._donor_mask: np.ndarray | None = (
ag.residues.resnames != "PRO"
) & ~self._chain_start

# hydrogens of each residue (among all of its atoms, not only those in
# ag), found with one selection: residue positions in ag.residues
# (sorted by resindex), then the number per residue and the first one
# of each residue that has any, in atom order
residues = ag.residues
hydrogens = residues.atoms.select_atoms(f"name {hydrogen_name}")
h_residue = np.searchsorted(residues.resindices, hydrogens.resindices)
n_hydrogens = np.bincount(h_residue, minlength=len(residues))
self._has_hydrogen: np.ndarray = n_hydrogens > 0
self._first_hydrogens: AtomGroup = hydrogens[
np.unique(h_residue, return_index=True)[1]
]
if not self._guess_hydrogens:
# pairs the k-th CA atom with the k-th residue. This assumes that
# both are ordered in the same way, which holds as long as ag is
# sorted (it is, from the hard-coded protein selection above).
# Chain starts are not checked: they do not donate hydrogen bonds,
# and N-terminal residues have several hydrogens on N.
calphas = self._heavy_atoms["CA"]
n = min(len(calphas), len(residues))
is_pro = calphas.resnames[:n] == "PRO"

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With definition of self._chain_start it makes sense to now not exclude the initial residue anymore. ✅

counts = n_hydrogens[:n]
wrong = np.flatnonzero(
np.where(is_pro, counts != 0, counts != 1)
& ~self._chain_start[:n]
)
if wrong.size:
residue = calphas[wrong[0]].residue
raise ValueError(
f"Residue {residue} contains wrong number of hydrogens: "
"exactly 1 hydrogen is expected for non-PRO residues, and "
"zero hydrogens for PRO residues."
)

if len(ag.residues) < 6:
raise ValueError(
"DSSP requires at least 6 residues for secondary structure analysis, "
Expand Down Expand Up @@ -413,14 +449,14 @@ def _get_coords(self) -> np.ndarray:
coords.swapaxes(0, 1)
)

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

coords = coords.swapaxes(0, 1)
return coords
Expand Down
98 changes: 96 additions & 2 deletions testsuite/MDAnalysisTests/analysis/test_dssp.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@
import numpy as np
import pytest
from MDAnalysis.analysis.dssp import DSSP, assign, translate
from MDAnalysis.analysis.dssp.pydssp_numpy import (
_get_hydrogen_atom_position,
get_hbond_map,
)
from MDAnalysis.coordinates.memory import MemoryReader

from MDAnalysisTests.datafiles import DSSP as DSSP_FOLDER
from MDAnalysisTests.datafiles import TPR, XTC
Expand Down Expand Up @@ -62,9 +67,11 @@ def test_donor_mask_proline_indices():
resnames = u.select_atoms("protein").residues.resnames
is_pro = resnames == "PRO"

# donor_mask should be False at proline positions and True at non-proline positions
# donor_mask should be False at proline positions and True at non-proline
# positions, except the first residue (a chain start)
assert np.all(~dssp._donor_mask[is_pro])
assert np.all(dssp._donor_mask[~is_pro])
assert np.all(dssp._donor_mask[1:][~is_pro[1:]])
assert not dssp._donor_mask[0]


def test_donor_mask_none():
Expand Down Expand Up @@ -171,3 +178,90 @@ def test_insufficient_residues_raises_error(client_DSSP):
dssp = DSSP(res6)
result = dssp.run(**client_DSSP, stop=1)
assert result.results.dssp.shape[1] == 6


def _hydrogens_per_residue(ag, hydrogen_name):
"""hydrogens selected one residue at a time (the selection DSSP made
before it was vectorised): the reference for the selection now"""
return [
res.atoms.select_atoms(f"name {hydrogen_name}")
for res in ag.select_atoms("protein").residues
]


@pytest.mark.parametrize(
"hydrogen_name", ["H HN HT1 HT2 HT3", "H HN H1", "H*"]
)
@pytest.mark.parametrize("selection", ["all", "protein and not name H HN"])
def test_hydrogens_match_per_residue_selection(hydrogen_name, selection):
# without H and HN in the selection, the hydrogens are still looked up
# among all atoms of each residue
ag = mda.Universe(TPR, XTC).select_atoms(selection)
dssp = DSSP(ag, hydrogen_name=hydrogen_name)
expected = _hydrogens_per_residue(ag, hydrogen_name)
np.testing.assert_equal(dssp._has_hydrogen, [bool(h) for h in expected])
np.testing.assert_equal(
dssp._first_hydrogens.ix, [h.ix[0] for h in expected if h]
)


def test_coords_with_hydrogens_match_per_residue_lookup():
# residues without a hydrogen (here the N-terminal MET, whose hydrogens
# are H1-H3, and prolines) take the guessed hydrogen of the same index
u = mda.Universe(TPR, XTC)
coords = DSSP(u, guess_hydrogens=False)._get_coords()
guessed = _get_hydrogen_atom_position(coords[:, :4])
hydrogens = _hydrogens_per_residue(u.atoms, "H HN HT1 HT2 HT3")
assert not all(hydrogens)
expected = [
h.positions[0] if h else guessed[k] for k, h in enumerate(hydrogens)
]
np.testing.assert_equal(coords[:, 4], expected)


def _protein_copies(copies, gap=100.0):
"""``copies`` of the TPR/XTC protein as one system without a box, each
shifted by ``gap`` A along x, with all frames of the trajectory (made
whole: the protein is split across the box)"""
protein = mda.Universe(TPR, XTC).select_atoms("protein")
u = mda.Merge(*[protein] * copies)
frames = np.array([protein.unwrap() for _ in protein.universe.trajectory])
coords = np.concatenate([frames] * copies, axis=1)
coords[:, :, 0] += np.repeat(np.arange(copies) * gap, protein.n_atoms)
u.load_new(coords.astype(np.float32), format=MemoryReader)
return u


@pytest.mark.parametrize("guess_hydrogens", [True, False])
def test_multiple_chains(guess_hydrogens, client_DSSP):
# the N-terminal residue of the second chain (MET, with hydrogens H1-H3)
# used to fail the check of one hydrogen per residue
single = DSSP(_protein_copies(1), guess_hydrogens=guess_hydrogens)
double = DSSP(_protein_copies(2), guess_hydrogens=guess_hydrogens)
n_residues = len(single._chain_start)
np.testing.assert_equal(
np.flatnonzero(double._chain_start), [0, n_residues]
)
expected = single.run(**client_DSSP).results.dssp
result = double.run(**client_DSSP).results.dssp
np.testing.assert_equal(result[:, :n_residues], expected)
np.testing.assert_equal(result[:, n_residues:], expected)
Comment on lines +247 to +248

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Did this test that both copies give the same results fail before this fix?



@pytest.mark.parametrize("guess_hydrogens", [True, False])
def test_chain_breaks_do_not_donate(guess_hydrogens):
# residues after a gap have no peptide bond to the residue before them,
# so they start a chain and are no hydrogen-bond donors
protein = mda.Universe(TPR, XTC).select_atoms("protein")
after_gaps = [30, 80, 133]
keep = np.setdiff1d(
np.arange(protein.n_residues),
np.concatenate([np.arange(r - 3, r) for r in after_gaps]),
)
dssp = DSSP(protein.residues[keep].atoms, guess_hydrogens=guess_hydrogens)
starts = [0] + [int(np.flatnonzero(keep == r)[0]) for r in after_gaps]
np.testing.assert_equal(np.flatnonzero(dssp._chain_start), starts)
assert not dssp._donor_mask[starts].any()
hbond_map = get_hbond_map(dssp._get_coords(), donor_mask=dssp._donor_mask)
# rows: donor residues (NH)
assert not hbond_map[starts].any()