145145"""
146146
147147import warnings
148- from typing import Optional , Union
149148
150149import 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
0 commit comments