Exemple #1
0
    def inner(*args, **kwd):
        args = list(args)
        traj = kwd.get('traj', args[0])
        frame_indices = kwd.get('frame_indices')
        ref = kwd.get('ref')
        top = kwd.get('top')

        if 'mask' in kwd.keys():
            mask = kwd.get('mask')
        else:
            mask = args[1]

        # overwrite
        kwd['top'] = get_topology(traj, top)
        if ref is not None:
            kwd['ref'] = get_reference(traj, ref)
        if 'traj' in kwd.keys():
            kwd['traj'] = get_fiterator(traj, frame_indices)
        else:
            args[0] = get_fiterator(traj, frame_indices)
        if not isinstance(mask, string_types):
            mask = array_to_cpptraj_atommask(mask)
        if 'mask' in kwd.keys():
            kwd['mask'] = mask
        else:
            args[1] = mask
        return f(*args, **kwd)
Exemple #2
0
def vector(traj=None,
           command="",
           frame_indices=None,
           dtype='ndarray',
           top=None):
    """perform vector calculation. See example below. Same as 'vector' command in cpptraj.

    Parameters
    ----------
    traj : Trajectory-like or iterable that produces :class:`pytraj.Frame`
    command : str or a list of strings, cpptraj command
    frame_indices : array-like, optional, default None
        only perform calculation for given frame indices
    dtype : output's dtype, default 'ndarray'
    top : Topology, optional, default None

    Returns
    -------
    out : numpy ndarray, shape (n_frames, 3) if command is a string
          numpy ndarray, shape (n_vectors, n_frames, 3) if command is a list of strings

    Examples
    --------
    >>> import pytraj as pt
    >>> traj = pt.datafiles.load_tz2_ortho()
    >>> data = pt.vector.vector(traj, "@CA @CB")
    >>> data = pt.vector.vector(traj, [("@CA @CB"),])
    >>> data = pt.vector.vector(traj, "principal z")
    >>> data = pt.vector.vector(traj, "principal x")
    >>> data = pt.vector.vector(traj, "ucellx")
    >>> data = pt.vector.vector(traj, "boxcenter")
    >>> data = pt.vector.vector(traj, "box")

    Notes
    -----
    It's faster to calculate with a list of commands.
    For example, if you need to perform 3 calculations for 'ucellx', 'boxcenter', 'box'
    like below:

    >>> data = pt.vector.vector(traj, "ucellx")
    >>> data = pt.vector.vector(traj, "boxcenter")
    >>> data = pt.vector.vector(traj, "box")

    You should use a list of commands for faster calculation.
    >>> comlist = ['ucellx', 'boxcenter', 'box']
    >>> data = pt.vector.vector(traj, comlist)
    """
    c_dslist = CpptrajDatasetList()
    top_ = get_topology(traj, top)
    list_of_commands = get_list_of_commands(command)
    fi = get_fiterator(traj, frame_indices)
    actlist = ActionList()

    for command in list_of_commands:
        act = c_action.Action_Vector()
        actlist.add(act, command, top_, dslist=c_dslist)
    actlist.compute(fi)

    return get_data_from_dtype(c_dslist, dtype=dtype)
Exemple #3
0
    def __init__(self,
                 filename=None,
                 top=None,
                 xyz=None,
                 velocity=None,
                 force=None,
                 time=None):
        self._top = get_topology(filename, top)
        if velocity is not None:
            velocity = np.asarray(velocity, dtype='f8')
        if force is not None:
            force = np.asarray(force, dtype='f8')
        if time is not None:
            time = np.asarray(time, dtype='f8')
        self.velocities = velocity
        self.forces = force
        self.time = time

        if self._top is None:
            self._top = Topology()

        self._xyz = None
        self._boxes = None

        # use those to keep lifetime of Frame
        self._life_holder = None
        self._frame_holder = None

        if filename is None or filename == "":
            if xyz is not None:
                if self.top.is_empty():
                    raise ValueError("must have a non-empty Topology")
                else:
                    assert self.top.n_atoms == xyz.shape[
                        1], "must have the same n_atoms"
                self._xyz = np.asarray(xyz)
            else:
                self._xyz = None
        elif hasattr(filename, 'xyz'):
            # make sure to use `float64`
            self._xyz = filename.xyz.astype(np.float64)
        elif isinstance(filename, (string_types, list, tuple)):
            self.load(filename)
        else:
            raise ValueError('filename must be None, a Trajectory or a string')

        if hasattr(self._xyz, 'shape'):
            assert self.top.n_atoms == self._xyz.shape[
                1], "must have the same n_atoms"

        if hasattr(filename, 'unitcells'):
            self._boxes = filename.unitcells
Exemple #4
0
def _dbscan(traj=None,
            mask='*',
            minpoints=None,
            epsilon=0.,
            sievetoframe=False,
            random_sieveseed=1,
            kdist=None,
            kfile=None,
            sieve=1,
            metric='rms',
            top=None,
            options=''):
    '''perform clustering and return cluster index for each frame

    Parameters
    ----------
    traj : Trajectory-like or iterable that produces Frame
    mask : str, default: * (all atoms)
    n_clusters: int, default: 10
    random_point : bool, default: True
    maxit : int, default: 100
        max iterations
    metric : str, {'rms', 'dme'}
        distance metric
    top : Topology, optional, default: None
        only need to provide this Topology if ``traj`` does not have one
    options : option to save data to files.


    Returns
    -------
    1D numpy array of frame indices
    '''

    # don't need to get_topology
    _top = get_topology(traj, top)
    _clusters = 'dbscan minpoints ' + str(minpoints)
    _mask = mask
    _epsilon = 'epsilon ' + str(epsilon)
    _sievetoframe = 'sievetoframe' if sievetoframe else ''
    _kdist = 'kdist' + str(kdist) if kdist is not None else ''
    _kfile = kfile if kfile is not None else ''
    _sieve = 'sieve ' + str(sieve)
    _metric = metric
    _random_sieveseed = 'random ' + str(random_sieveseed)
    _output = options
    command = ' '.join((_clusters, _epsilon, _sievetoframe, _kdist, _sieve,
                        _kfile, _metric, _random_sieveseed, _mask, _output))
    return _cluster(traj, command, top=_top, dtype='ndarray')
Exemple #5
0
def read_gaussian_output(filename=None, top=None):
    """return a `pytraj.trajectory.Trajectory` object

    Parameters
    ----------
    fname : str, filename
    top : {str, Topology}, optional, default None
        pytraj.Topology or a filename or None
        if None, use `antechamber` to generate mol2 file, need set $AMBERHOME env

    Requires
    --------
    cclib (``pip install cclib``)

    >>> import pytraj as pt
    >>> pt.tools.read_gaussian_output("gau.out", "mytest.pdb") # doctest: +SKIP
    """
    import cclib
    from pytraj.trajectory.trajectory import Trajectory
    from pytraj.utils.context import tempfolder
    from pytraj.utils.get_common_objects import get_topology

    _top = get_topology(None, top)
    gau = cclib.parser.Gaussian(filename)
    go = gau.parse()

    if _top is None:  # pragma: no cover
        try:
            amberhome = os.environ['AMBERHOME']
        except KeyError:
            raise KeyError("must set AMBERHOME")

        fpath = os.path.abspath(filename)

        with tempfolder():
            at = amberhome + "/bin/antechamber"
            out = "-i %s -fi gout -o tmp.mol2 -fo mol2 -at amber" % fpath
            cm = " ".join((at, out))
            os.system(cm)

            return Trajectory(xyz=go.atomcoords, top="tmp.mol2")
    else:
        return Trajectory(xyz=go.atomcoords, top=_top)
Exemple #6
0
def vector_mask(traj=None,
                mask="",
                frame_indices=None,
                dtype='ndarray',
                top=None):
    """compute vector between two maskes

    Parameters
    ----------
    traj : Trajectory-like or iterable that produces Frame
    mask: str or array of string or array of intergers, shape (n_vectors, 2)
        vector maskes
    frame_indices : array-like or iterable that produces integer number
        frame indices
    dtype : str, default 'ndarray'
        output dtype
    top : Topology, optional, default None

    Returns
    -------
    if mask is a string, return 2D ndarray, shape (n_frames, 3)
    if mask is a list of strings or a 2D ndarray, return 3D ndarray, shape (n_vectors, n_frames, 3)

    Examples
    --------
    >>> # calcualte N-H vector
    >>> import pytraj as pt
    >>> import numpy as np
    >>> traj = pt.load_sample_data('tz2')
    >>> from pytraj import vector as va
    >>> n_indices = pt.select_atoms('@N', traj.top)
    >>> h_indices = n_indices + 1

    >>> # create n-h pair for vector calculation
    >>> n_h_pairs = np.array(list(zip(n_indices, h_indices)))
    >>> data_vec = va.vector_mask(traj, n_h_pairs, dtype='ndarray')

    >>> # compute vectors for specific frame indices (0, 4)
    >>> data_vec = va.vector_mask(traj, n_h_pairs, frame_indices=[0, 4], dtype='ndarray')
    """
    from pytraj.utils.get_common_objects import get_topology, get_data_from_dtype, get_fiterator
    from pytraj.utils.get_common_objects import get_list_of_commands
    from pytraj.datasets.c_datasetlist import DatasetList as CpptrajDatasetList
    from pytraj.analysis.c_action.c_action import Action_Vector
    from pytraj.analysis.c_action.actionlist import ActionList

    fi = get_fiterator(traj, frame_indices)
    _top = get_topology(fi, top)
    dslist = CpptrajDatasetList()
    template_command = ' mask '

    cm_arr = np.asarray(mask)
    if cm_arr.dtype.kind != 'i':
        list_of_commands = get_list_of_commands(mask)
    else:
        if cm_arr.ndim != 2:
            raise ValueError(
                'if mask is a numpy.ndarray, it must have ndim = 2')
        list_of_commands = _2darray_to_atommask_groups(cm_arr)

    actlist = ActionList()

    for command in list_of_commands:
        act = Action_Vector()
        _command = command + template_command
        actlist.add(act, _command, _top, dslist=dslist)
    actlist.compute(fi)
    return get_data_from_dtype(dslist, dtype=dtype)