How to use the prody.atomic.AtomGroup function in ProDy

To help you get started, we’ve selected a few ProDy examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github prody / ProDy / prody / proteins / emdfile.py View on Github external
if cutoff is not None:
        cutoff = float(cutoff)

    n_nodes = int(kwargs.get('n_nodes', 1000))
    num_iter = int(kwargs.get('num_iter', 20))
    map = kwargs.get('map',True)
    make_nodes = kwargs.get('make_nodes',False)

    if map is False and make_nodes is False:
        LOGGER.warn('At least one of map and make_nodes should be True. '
                    'Setting map to False was an intentional change from the default '
                    'behaviour so make_nodes has been set to True.')
        make_nodes = True

    title_suffix = kwargs.get('title_suffix','')
    atomgroup = AtomGroup(str(kwargs.get('title', 'Unknown')) + title_suffix)
    atomgroup._n_atoms = n_nodes

    if make_nodes:
        LOGGER.info('Building coordinates from electron density map. This may take a while.')
        LOGGER.timeit()

        if map:
            emd, atomgroup = _parseEMDLines(atomgroup, stream, cutoff=cutoff, n_nodes=n_nodes, \
                                            num_iter=num_iter, map=map, make_nodes=make_nodes)
        else:
            atomgroup = _parseEMDLines(atomgroup, stream, cutoff=cutoff, n_nodes=n_nodes, \
                                       num_iter=num_iter, map=map, make_nodes=make_nodes)

        LOGGER.report('{0} atoms and {1} coordinate sets were '
                      'parsed in %.2fs.'.format(atomgroup.numAtoms(), atomgroup.numCoordsets()))
    else:
github prody / ProDy / prody / atomic.py View on Github external
def loadAtoms(filename):
    """Return :class:`AtomGroup` instance from *filename*.  This function makes
    use of :func:`numpy.load` function.  See also :func:`saveAtoms`.
    
    .. versionadded:: 0.7.1"""
    
    LOGGER.timeit()
    attr_dict = np.load(filename)
    files = set(attr_dict.files)
    # REMOVE support for _coordinates IN v1.0
    if not '_coordinates' in files and not 'n_atoms' in files:
        raise ValueError("'{0:s}' is not a valid atomic data file"
                         .format(filename))
    if '_coordinates' in files:
        ag = AtomGroup(str(attr_dict['_name']))
        for attr in attr_dict.files:
            if attr == '_name':
                continue
            elif attr == '_coordinates':
                data = attr_dict[attr]
                if data.ndim > 0:
                    ag.setCoords(data)
            elif attr in ATOMIC_ATTRIBUTES: 
                field = ATOMIC_ATTRIBUTES[attr]
                data = attr_dict[attr]
                if data.ndim > 0:
                   ag.__getattribute__('set' + field.meth_pl)(data)
                else:
                    ag.__getattribute__('set' + field.meth_pl)([data])
            else:            
                data = attr_dict[attr]
github prody / ProDy / prody / atomic.py View on Github external
def __contains__(self, item):
        """.. versionadded:: 0.5.3"""
        
        if isinstance(item, Atomic):
            if isinstance(item, AtomGroup) and self == item: 
                return True
            elif isinstance(self, AtomGroup) and self == item.getAtomGroup():
                return True
            elif len(item) <= len(self):
                if set(item.getIndices()).issubset(set(self.getIndices())):
                    return True
        return False
github prody / ProDy / prody / dynamics / gnm.py View on Github external
def calcGNM(pdb, selstr='calpha', cutoff=15., gamma=1., n_modes=20,
            zeros=False, hinges=True):
    """Returns a :class:`GNM` instance and atoms used for the calculations.
    By default only alpha carbons are considered, but selection string helps
    selecting a subset of it.  *pdb* can be :class:`.Atomic` instance."""

    if isinstance(pdb, str):
        ag = parsePDB(pdb)
        title = ag.getTitle()
    elif isinstance(pdb, Atomic):
        ag = pdb
        if isinstance(pdb, AtomGroup):
            title = ag.getTitle()
        else:
            title = ag.getAtomGroup().getTitle()
    else:
        raise TypeError('pdb must be an atom container, not {0}'
                        .format(type(pdb)))
    gnm = GNM(title)
    sel = ag.select(selstr)
    gnm.buildKirchhoff(sel, cutoff, gamma)
    gnm.calcModes(n_modes, zeros, hinges=hinges)
    return gnm, sel
github prody / ProDy / prody / dynamics / signature.py View on Github external
if isinstance(matched, np.ndarray):
        matched = matched.tolist()

    if isinstance(reweighted, np.ndarray):
        reweighted = reweighted.tolist()

    modeens = ModeEnsemble(title=title)
    modeens._weights = weights
    modeens._labels = labels
    modeens._matched = matched
    modeens._reweighted = reweighted
    modeens._modesets = modesets

    if atoms is not None:
        if isinstance(atoms, AtomGroup):
            data = atoms._data
        else:
            data = atoms._ag._data
            
        for key in data:
            arr = data[key]
            char = arr.dtype.char
            if char in 'SU' and char != DTYPE:
                arr = arr.astype(str)
                data[key] = arr

    modeens._atoms = atoms

    return modeens
github prody / ProDy / prody / dynamics / editing.py View on Github external
:type model: :class:`.ANM`, :class:`.GNM`, or :class:`.PCA`

    :arg atoms: atoms that were used to build the model
    :type atoms: :class:`.Atomic`

    :arg select: an atom selection or a selection string
    :type select: :class:`.Selection`, str

    :returns: (:class:`.NMA`, :class:`.Selection`)"""

    linalg = importLA()

    if not isinstance(model, NMA):
        raise TypeError('model must be an NMA instance, not {0}'
                        .format(type(model)))
    if not isinstance(atoms, (AtomGroup, AtomSubset, AtomMap)):
        raise TypeError('atoms type is not valid')
    if len(atoms) <= 1:
        raise TypeError('atoms must contain more than 1 atoms')

    if isinstance(model, GNM):
        matrix = model._kirchhoff
    elif isinstance(model, ANM):
        matrix = model._hessian
    elif isinstance(model, PCA):
        matrix = model._cov
    else:
        raise TypeError('model does not have a valid type derived from NMA')
    if matrix is None:
        raise ValueError('model matrix (Hessian/Kirchhoff/Covariance) is not '
                         'built')
github prody / ProDy / prody / dynamics / sampling.py View on Github external
def deformAtoms(atoms, mode, rmsd=None):
    """Generate a new coordinate set for *atoms* along the *mode*.  *atoms*
    must be a :class:`.AtomGroup` instance.  New coordinate set will be
    appended to *atoms*. If *rmsd* is provided, *mode* will be scaled to
    generate a coordinate set with given RMSD distance to the active coordinate
    set."""

    if not isinstance(atoms, AtomGroup):
        raise TypeError('atoms must be an AtomGroup, not {0}'
                        .format(type(atoms)))
    if not isinstance(mode, VectorBase):
        raise TypeError('mode must be a Mode or Vector instance, '
                        'not {0}'.format(type(mode)))
    if not mode.is3d():
        raise ValueError('mode must be from a 3-dimensional model.')
    if atoms.numAtoms() != mode.numAtoms():
        raise ValueError('number of atoms do not match')

    array = mode.getArrayNx3()

    if rmsd is not None:
        rmsd = float(rmsd)
        # rmsd = ( ((scalar * array)**2).sum() / n_atoms )**0.5
        scalar = (atoms.numAtoms() * rmsd**2 / (array**2).sum())**0.5
github prody / ProDy / prody / atomic.py View on Github external
def __add__(self, other):
        """.. versionadded:: 0.5"""
        
        if isinstance(other, AtomGroup):
            if self == other:
                raise ValueError('an atom group cannot be added to itself')
            
            new = AtomGroup(self._title + ' + ' + other._title)
            n_coordsets = self._n_csets
            if n_coordsets != other._n_csets:
                LOGGER.warning('AtomGroups {0:s} and {1:s} do not have same '
                               'number of coordinate sets.  First from both '
                               'AtomGroups will be merged.'
                  .format(str(self._title), str(other._title), n_coordsets))
                n_coordsets = 1
            coordset_range = range(n_coordsets)
            new.setCoords(np.concatenate((self._coordinates[coordset_range],
                                        other._coordinates[coordset_range]), 1))
            for field in ATOMIC_DATA_FIELDS.values():
                var = field.var
                this = self._data[var]
                that = other._data[var]
                if this is not None and that is not None:
                    new._data[var] = np.concatenate((this, that))