Source code for BioSimSpace._SireWrappers._residue
####################################################################### BioSimSpace: Making biomolecular simulation a breeze!## Copyright: 2017-2024## Authors: Lester Hedges <lester.hedges@gmail.com>## BioSimSpace is free software: you can redistribute it and/or modify# it under the terms of the GNU General Public License as published by# the Free Software Foundation, either version 3 of the License, or# (at your option) any later version.## BioSimSpace is distributed in the hope that it will be useful,# but WITHOUT ANY WARRANTY; without even the implied warranty of# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the# GNU General Public License for more details.## You should have received a copy of the GNU General Public License# along with BioSimSpace. If not, see <http://www.gnu.org/licenses/>.#####################################################################"""A thin wrapper around Sire.Mol.Residue. This is an internal package and shouldnot be directly exposed to the user."""__author__="Lester Hedges"__email__="lester.hedges@gmail.com"__all__=["Residue"]fromsire.legacyimportMolas_SireMolfrom..import_isVerbosefrom._sire_wrapperimportSireWrapperas_SireWrapper
[docs]classResidue(_SireWrapper):"""A class for storing a residue."""
[docs]def__init__(self,residue):""" Constructor. Parameters ---------- residue : Sire.Mol.Residue, :class:`Residue <BioSimSpace._SireWrappers.Residue>` A Sire or BioSimSpace Residue object. """# Check that the residue is valid.# A Sire Residue object.ifisinstance(residue,_SireMol._Mol.Residue):sire_object=residue# Another BioSimSpace Residue object.elifisinstance(residue,Residue):sire_object=residue._sire_object# Invalid type.else:raiseTypeError("'residue' must be of type 'Sire.Mol.Residue' ""or 'BioSimSpace._SireWrappers.Residue'.")# Call the base class constructor.super().__init__(sire_object)# Flag that this object holds multiple atoms.self._is_multi_atom=True# Store the number of atoms in the residue.self._num_atoms=self._sire_object.nAtoms()# Store the atom indices in the residue.self._atom_idxs=self._sire_object.atomIdxs()# Initialise the iterator count.self._iter_count=0
def__str__(self):"""Return a human readable string representation of the object."""return"<BioSimSpace.Residue: name=%r, molecule=%d, index=%d, nAtoms=%d>"%(self.name(),self.moleculeNumber(),self.index(),self.nAtoms(),)def__repr__(self):"""Return a string showing how to instantiate the object."""return"<BioSimSpace.Residue: name=%r, molecule=%d, index=%d, nAtoms=%d>"%(self.name(),self.moleculeNumber(),self.index(),self.nAtoms(),)def__contains__(self,other):"""Return whether other is in self."""ifnotisinstance(other,_Atom):raiseTypeError("'other' must be of type 'BioSimSpace._SireWrappers.Atom'.")# Return whether the residue contains the atom.returnself._sire_object.contains(other._sire_object.atom().number())def__getitem__(self,key):"""Get an atom from the residue."""# Slice.ifisinstance(key,slice):# Create a list to hold the atoms.atoms=[]# Iterate over the slice.forxinrange(*key.indices(self._num_atoms)):atoms.append(_Atom(self[x]))# Return the list of atoms.returnatoms# Index.else:try:key=int(key)except:raiseTypeError("'key' must be of type 'int'")ifkey<-self._num_atomsorkey>self._num_atoms-1:raiseIndexError("Residue index is out of range.")ifkey<0:key=key+self._num_atoms# Extract and return the corresponding atom.return_Atom(self._sire_object.atom(self._atom_idxs[key]))def__setitem__(self,key,value):"""Set an atom in the residue."""raiseTypeError("'Residue' object does not support assignment.")def__iter__(self):"""An iterator for the object."""# Reset the iterator counter and return the object.self._iter_count=0returnselfdef__next__(self):"""An iterator for the object."""# Stop if we've reached the end of the residue.ifself._iter_count==self._num_atoms:raiseStopIteration# Extract the next atom in the residue.atom=self[self._iter_count]# Update the iterator counter.self._iter_count+=1# Return the atom.returnatomdef__len__(self):"""Return the number of atoms in the residue."""returnself._num_atoms
[docs]defname(self):""" Return the name of the residue. Returns ------- name : str The name of the residue. """returnself._sire_object.name().value()
[docs]defindex(self):""" Return the index of the residue. Returns ------- index : int The index of the residue. """returnself._sire_object.index().value()
[docs]defmoleculeNumber(self):""" Return the number of the molecule to which this residue belongs. Returns ------- number : int The number of the molecule to which the residue belongs. """returnself._sire_object.molecule().number().value()
[docs]defcoordinates(self,property_map={}):""" Return the coordinates of the atoms in the residue. Parameters ---------- property_map : dict A dictionary that maps system "properties" to their user defined values. This allows the user to refer to properties with their own naming scheme, e.g. { "charge" : "my-charge" } Returns ------- [coordinates] : [class:`Coordinate <BioSimSpace.Types.Coordinate>`] The coordinates of the atoms in the residue. """# Get the "coordinates" property for each atom in the residue.try:coordinates=[]foratominself.getAtoms():coordinates.append(atom.coordinates(property_map))except:returnNone# Return the coordinates.returncoordinates
[docs]defnAtoms(self):""" Return the number of atoms in the residue. Returns ------- num_atoms : int The number of atoms in the system. """returnself._num_atoms
[docs]defgetAtoms(self):""" Return a list containing all of the atoms in the residue. Parameters ---------- Returns ------- atoms : [:class:`Atoms <BioSimSpace._SireWrappers.Atom>`] The list of atoms in the residue. """atoms=[]foratominself._sire_object.atoms():atoms.append(_Atom(atom))returnatoms
[docs]deftoMolecule(self):""" Convert a single Residue to a Molecule. Returns ------- system : :class:`Molecule <BioSimSpace._SireWrappers.Molecule>` """return_Molecule(_SireMol.PartialMolecule(self._sire_object).extract().molecule())
[docs]defsearch(self,query,property_map={}):""" Search the residue for atoms and residues. Parameters ---------- query : str The search query. property_map : dict A dictionary that maps system "properties" to their user defined values. This allows the user to refer to properties with their own naming scheme, e.g. { "charge" : "my-charge" } Returns ------- results : [:class:`Atom <BioSimSpace._SireWrappers.Atom>`] A list of objects matching the search query. Examples -------- Search for all oxygen or hydrogen atoms. >>> result = residue.search("element oxygen or element hydrogen") Search for atom index 23. >>> result = residue.search("atomidx 23") """ifnotisinstance(query,str):raiseTypeError("'query' must be of type 'str'")ifnotisinstance(property_map,dict):raiseTypeError("'property_map' must be of type 'dict'")# Initialise a list to hold the search results.results=[]try:# Query the Sire residue.search_result=_SireMol.Select(query)(self._sire_object,property_map)exceptExceptionase:msg="'Invalid search query: %r"%queryif_isVerbose():raiseValueError(msg)fromeelse:raiseValueError(msg)fromNonereturn_SearchResult(search_result)
# Import at bottom of module to avoid circular dependency.from._atomimportAtomas_Atomfrom._moleculeimportMoleculeas_Moleculefrom._search_resultimportSearchResultas_SearchResult