Пример #1
0
def test_angle_pbc_0():
    # Check that angles are calculated correctly accross periodic boxes
    random = np.random.RandomState(0)
    boxLengths = [1,2,3]
    N = 1000

    X = np.cumsum(0.1 * random.randn(N*3, 3), axis=0).reshape(N, 3, 3)

    center = X.mean(axis=1).reshape(N, 1, 3)
    cell = np.floor(center / boxLengths)
    X_cell = X - (cell * boxLengths)

    assert not np.all(X == X_cell)

    t0 = md.Trajectory(xyz=X, topology=None)
    t1 = md.Trajectory(xyz=X_cell, topology=None)
    t1.unitcell_vectors = np.tile(np.diag(boxLengths), [len(X), 1, 1])

    r0 = md.compute_angles(t0, [[0,1,2]], opt=False).reshape(-1)
    r1 = md.compute_angles(t1, [[0,1,2]], opt=False).reshape(-1)
    r2 = md.compute_angles(t0, [[0,1,2]], opt=True).reshape(-1)
    r3 = md.compute_angles(t1, [[0,1,2]], opt=True).reshape(-1)
    
    np.testing.assert_array_almost_equal(r0, r1, decimal=4)
    np.testing.assert_array_almost_equal(r2, r3, decimal=4)
    np.testing.assert_array_almost_equal(r0, r3, decimal=4)
Пример #2
0
def test_generator():
    N_FRAMES = 2
    N_ATOMS = 5
    xyz = np.asarray(np.random.randn(N_FRAMES, N_ATOMS, 3), dtype=np.float32)
    ptraj = md.Trajectory(xyz=xyz, topology=None)

    triplets = np.array(list(itertools.combinations(range(N_ATOMS), 3)), dtype=np.int32)
    triplets2 = itertools.combinations(range(N_ATOMS), 3)
    a = md.compute_angles(ptraj, triplets)
    b = md.compute_angles(ptraj, triplets2)
    eq(a, b)
    def water_nbr_orientations(self, traj, water, nbrs):
        """Calculates orientations of the neighboring water molecules of a given water molecule. The orientation is
        defined as the miniumum of four possible Donor-H-Acceptor angles.

        Parameters
        ----------
        traj : md.trajectory
            MDTraj trajectory object for which hydrogen bonds are to be calculates.
        water : int
            The index of water oxygen atom
        nbrs : np.ndarray, int, shape=(N^{ww}_nbr, )
            Indices of the water oxygen or solute atoms in the first solvation shell of the water molecule.

        Returns
        -------
        wat_orientations : np.ndarray
            Array of angles between the given and each one of its neighbors
        """

        angle_triplets = []
        for wat_nbr in nbrs:
            angle_triplets.extend([[water, wat_nbr, wat_nbr + 1],
                                   [water, wat_nbr, wat_nbr + 2],
                                   [wat_nbr, water, water + 1],
                                   [wat_nbr, water, water + 2]])
        angle_triplets = np.asarray(angle_triplets)
        angles = md.compute_angles(traj, angle_triplets)
        angles[np.isnan(angles)] = 0.0
        wat_orientations = [
            np.rad2deg(np.min(angles[0, i * 4:(i * 4) + 4]))
            for i in range(nbrs.shape[0])
        ]
        return wat_orientations
Пример #4
0
def extract_Q_indxd(frame, neighbors, idx_A, species_indx):
    """
    Handy for calculating the Q order parameter for
    a specific species in the simulation (e.g. for 
    HOD vs H2O oxygens.

    NOTE: species_indx is 1-indexed
          neighbors contains 0-indexed location in idx_A
          idx_A contains 0-indexed global index of the oxygen atoms
    """
    triplet_list = []
    neighbors = idx_A[neighbors]
    target_Os = species_indx - 1

    for i in range(len(neighbors)):
        tagged = idx_A[i]
    
        # Only want to calculate Qs for the target Os
        if tagged in target_Os:
            neighs = [O for O in neighbors[i] if not O == tagged]

            for j in range(3):
                for k in range(j+1,4):
                    trio = (neighs[j], tagged, neighs[k])
                    triplet_list.append(trio)

    triplet_list = np.array(triplet_list, dtype=int)
    angle_in_rad = md.compute_angles(frame, triplet_list, opt=True).reshape(-1, 6)
    sum_elements = np.sum(np.square(np.cos(angle_in_rad) + 1./3.), axis=1)
    Qs = (1. - 3./8. * sum_elements).reshape(-1, len(species_indx))
    return Qs
Пример #5
0
    def water_nbr_orientations(self, traj, water, nbrs):
        """Calculates hydrogen bonds made by a water molecule with its first shell
        water and solute neighbors.

        Parameters
        ----------
        traj : md.trajectory
            MDTraj trajectory object for which hydrogen bonds are to be calculates.
        water : int
            The index of water oxygen atom
        nbrs : np.ndarray, int, shape=(N^{ww}_nbr, )
            Indices of the water oxygen or solute atoms in the first solvation shell of the water molecule.
        water_water : bool
            Boolean for whether water-water or solute-water hbonds are desired

        Returns
        -------
        hbonds : np.ndarray
            Array of hydrogen bonds where each hydrogen bond is represented by an array of indices
            of three participating atoms [Donor, H, Acceptor]
        """
        angle_triplets = []
        for wat_nbr in nbrs:
            angle_triplets.extend(
                [[water, wat_nbr, wat_nbr + 1], [water, wat_nbr, wat_nbr + 2], [wat_nbr, water, water + 1],
                 [wat_nbr, water, water + 2]])
        angle_triplets = np.asarray(angle_triplets)
        angles = md.compute_angles(traj, angle_triplets)
        angles[np.isnan(angles)] = 0.0
        wat_orientations = [np.rad2deg(np.min(angles[0, i*4:(i*4)+4])) for i in range(nbrs.shape[0])]
        return wat_orientations
Пример #6
0
def test_no_indices():
    for fn in ['2EQQ.pdb', '1bpi.pdb']:
        for opt in [True, False]:
            t = md.load(get_fn(fn))
            assert md.compute_distances(t, np.zeros((0,2), dtype=int), opt=opt).shape == (t.n_frames, 0)
            assert md.compute_angles(t, np.zeros((0,3), dtype=int), opt=opt).shape == (t.n_frames, 0)
            assert md.compute_dihedrals(t, np.zeros((0,4), dtype=int), opt=opt).shape == (t.n_frames, 0)
Пример #7
0
def test_angle_nan():
    t = md.Trajectory(topology=None, xyz=np.array([
        [0, 0, 0.2],
        [0, 0, 0.3],
        [0, 0, 0.0]
    ]))
    angles = md.compute_angles(t, [[0, 1, 2]], opt=True)
    np.testing.assert_array_almost_equal(angles, [[0]])
Пример #8
0
def hbond(traj,donor,acceptor,hydrogen,angle):
    #function that returns whether a hydrogen bond exists between a given set of 
    #candidates for the donor, the acceptor, and the hydrogen
    #assumes that the donor-acceptor distance is already within the correct limit
    #so simply checks the angle
    #angle should be in radians
    dhang = md.compute_angles(traj,np.array([[donor,hydrogen,acceptor]]))
    
    return (dhang[0,0] > angle)
Пример #9
0
 def transform(self, traj):
     rad = mdtraj.compute_angles(traj, self.angle_indexes, self.periodic)
     if self.cossin:
         rad = np.dstack((np.cos(rad), np.sin(rad)))
         rad = rad.reshape(rad.shape[0], rad.shape[1] * rad.shape[2])
     if self.deg and not self.cossin:
         return np.rad2deg(rad)
     else:
         return rad
    def compute_angles(self, angle_indices):
        """

        :param angle_indices: Each row gives the indices of three atoms which together make an angle (np.ndarray, shape=(num_angles, 3), dtype=int)
        :return: The angles are in radians (np.ndarray, shape=[n_frames, n_angles], dtype=float)

        """

        return md.compute_angles(self.traj, angle_indices)
 def calc_angles(self, triplets, range=None):
     quantity = md.compute_angles(self.traj, triplets)
     hist, edges = np.histogram(quantity,
                                density=True,
                                range=range,
                                bins=200)
     bins = (edges[1:] + edges[:-1]) * 0.5
     hist /= np.sin(bins)
     hist /= np.sum(hist) * (bins[1] - bins[0])
     return bins, hist
Пример #12
0
 def transform(self, traj):
     rad = mdtraj.compute_angles(traj, self.angle_indexes, self.periodic)
     if self.cossin:
         rad = np.dstack((np.cos(rad), np.sin(rad)))
         rad = rad.reshape(functools.reduce(lambda x, y: x * y,
                                            rad.shape), )
     if self.deg and not self.cossin:
         return np.rad2deg(rad)
     else:
         return rad
Пример #13
0
    def _add_sbm_angles(self, Model):
        structure = Model.mapping

        if hasattr(Model, "ref_traj"):
            ka = self._default_parameters["ka"]
            code = self._default_potentials["angle"]
            for atm1, atm2, atm3 in structure._angles:
                idxs = np.array([[atm1.index, atm2.index, atm3.index]])
                theta0 = md.compute_angles(Model.ref_traj, idxs)[0][0]
                self._add_angle(code, atm1, atm2, atm3, ka, theta0)
        else:
            util.missing_reference_warning()
Пример #14
0
    def partial_transform(self, traj):
        ca = [a.index for a in traj.top.atoms if a.name == 'CA']
        if len(ca) < 5:
            return np.zeros((len(traj), 0), dtype=np.float32)

        angle_indices = np.array(
            [(ca[i - 2], ca[i], ca[i + 2]) for i in range(2, len(ca) - 2)])
        result = md.compute_angles(traj, angle_indices)

        if self.cos:
            return np.cos(result)

        assert result.shape == (traj.n_frames, traj.n_residues - 4)
        return result
Пример #15
0
    def partial_transform(self, traj):
        ca = [a.index for a in traj.top.atoms if a.name == 'CA']
        if len(ca) < 5:
            return np.zeros((len(traj), 0), dtype=np.float32)

        angle_indices = np.array(
            [(ca[i - 2], ca[i], ca[i + 2]) for i in range(2, len(ca) - 2)])
        result = md.compute_angles(traj, angle_indices)

        if self.cos:
            return np.cos(result)

        assert result.shape == (traj.n_frames, traj.n_residues - 4)
        return result
Пример #16
0
def dangling(frame, dictionary, sign, dist, distOSN, idx, idxOSN, normals):
    pair_ox = np.asarray(list(itertools.product(idx, idxOSN)))
    # remove pairs of same index
    pair_ox = pair_ox[np.std(pair_ox, axis=1) != 0]
    dist_ox = md.compute_distances(frame, pair_ox).reshape(idx.size, -1)
    h1o = np.c_[idx, idx + 1]
    h2o = np.c_[idx, idx + 2]
    # compute H-O vectors
    vec_h1o = md.compute_displacements(frame, h1o).reshape(-1, 3)
    vec_h2o = md.compute_displacements(frame, h2o).reshape(-1, 3)
    cosine_h1o = np.einsum('ij,ij->i', vec_h1o, normals) / np.linalg.norm(
        vec_h1o, axis=1)
    cosine_h2o = np.einsum('ij,ij->i', vec_h2o, normals) / np.linalg.norm(
        vec_h2o, axis=1)
    angle_h1o = np.arccos(np.clip(cosine_h1o, -1, 1)) / np.pi * 180
    angle_h2o = np.arccos(np.clip(cosine_h2o, -1, 1)) / np.pi * 180
    h1ox = np.c_[np.asarray(pair_ox)[:, 0] + 1,
                 np.asarray(pair_ox)[:, 0],
                 np.asarray(pair_ox)[:, 1]]
    h2ox = np.c_[np.asarray(pair_ox)[:, 0] + 2,
                 np.asarray(pair_ox)[:, 0],
                 np.asarray(pair_ox)[:, 1]]
    # compute H-O...O angles
    angle_h1ox = md.compute_angles(frame, h1ox).reshape(idx.size,
                                                        -1) / np.pi * 180
    angle_h2ox = md.compute_angles(frame, h2ox).reshape(idx.size,
                                                        -1) / np.pi * 180
    # selection of dangling OH based on R-beta definition (DOI: 10.1021/acs.jctc.7b00566)
    Rc = dist_ox <= .35
    beta1 = angle_h1ox <= 50
    beta2 = angle_h2ox <= 50
    angles_ho = np.append(angle_h1o[np.sum(beta1 * Rc, axis=1) == 0],
                          angle_h2o[np.sum(beta2 * Rc, axis=1) == 0])
    dictionary['ndang'] = np.append(dictionary['ndang'], angles_ho.size)
    dictionary['all'] = np.append(dictionary['all'], idx.size)
    hist, _ = np.histogram(angles_ho, bins=np.arange(0, 181, 2), density=False)
    dictionary['theta'] += hist
def gln_array(*args):
    if len(args) == 4:
        dihedral = np.array([[args[0], args[1], args[2], args[3]]])
        gln_dihedral_array = md.compute_dihedrals(traj, dihedral)
        return gln_dihedral_array

    elif len(args) == 3:
        angle = np.array([[args[0], args[1], args[2]]])
        gln_angle_array = md.compute_angles(traj, angle)
        return gln_angle_array

    else:
        print(
            'The amount of arguments (number of atoms) is not compatible with the selected light state'
        )
def angf(traj, residues, tol=15, ref=88):
    tol = float(tol)
    ref = float(ref)
    minimum = np.amin(residues)
    maximum = np.amax(residues)
    ca = traj.topology.select('name CA and protein and resid %i to %i' %
                              (minimum, maximum))
    indices = np.zeros([ca.shape[0] - 2, 3])
    for i in range(indices.shape[0]):
        indices[i] = ca[i:i + 3]
    angles = md.compute_angles(traj, indices)
    angles = angles / (2 * math.pi) * 360
    angf = np.zeros(angles.shape)
    angf[:, :] = 1 / (1 + (angles[:, :] - ref)**2 / tol**2)
    return angf
Пример #19
0
def calc_coord(traj, idxs):
    vals = np.zeros(traj.n_frames)
    idxs = np.array(idxs)
    NM_IN_ANG = 10.0
    RAD_IN_DEG = 180.0/np.pi
    if len(idxs) == 2:
        vals = md.compute_distances(traj, idxs.reshape(1, -1))
        vals *= NM_IN_ANG
    elif len(idxs) == 3:
        vals = md.compute_angles(traj, idxs.reshape(1, -1))
        vals *= RAD_IN_DEG
    elif len(idxs) == 4:
        vals = md.compute_dihedrals(traj, idxs.reshape(1, -1))
        vals *= RAD_IN_DEG
    return vals[:, 0]
    def calculate_hydrogen_bonds(self, traj, water, nbrs, water_water=True):
        """Calculates hydrogen bonds made by a water molecule with its first shell
        water and solute neighbors.

        Parameters
        ----------
        traj : md.trajectory
            MDTraj trajectory object for which hydrogen bonds are to be calculates.
        water : int
            The index of water oxygen atom
        nbrs : np.ndarray
            Indices of the water oxygen or solute atoms in the first solvation shell of the water molecule.
        water_water : bool
            Boolean for whether water-water or solute-water hbonds are desired

        Returns
        -------
        hbonds : np.ndarray
            Array of hydrogen bonds where each hydrogen bond is represented by an array of indices
            of three participating atoms [Donor, H, Acceptor]
        """
        hbond_data = []
        angle_triplets = []
        if water_water:
            for wat_nbr in nbrs:
                angle_triplets.extend([[water, wat_nbr, wat_nbr + 1],
                                       [water, wat_nbr, wat_nbr + 2],
                                       [wat_nbr, water, water + 1],
                                       [wat_nbr, water, water + 2]])
        else:
            for solute_nbr in nbrs:
                if self.prot_hb_types[solute_nbr] == 1 or self.prot_hb_types[
                        solute_nbr] == 3:
                    angle_triplets.extend([[solute_nbr, water, water + 1],
                                           [solute_nbr, water, water + 2]])
                if self.prot_hb_types[solute_nbr] == 2 or self.prot_hb_types[
                        solute_nbr] == 3:
                    for don_H_pair in self.don_H_pair_dict[solute_nbr]:
                        angle_triplets.extend(
                            [[water, solute_nbr, don_H_pair[1]]])

        angle_triplets = np.asarray(angle_triplets)
        angles = md.compute_angles(traj, angle_triplets)
        angles[np.isnan(angles)] = 0.0
        hbonds = angle_triplets[np.where(angles[0, :] <= ANGLE_CUTOFF_RAD)]
        return hbonds
Пример #21
0
def test_KappaFeaturizer_describe_features():
    feat = KappaAngleFeaturizer()
    rnd_traj = np.random.randint(len(trajectories))
    features = feat.transform([trajectories[rnd_traj]])
    df = pd.DataFrame(feat.describe_features(trajectories[rnd_traj]))

    for f in range(25):
        f_index = np.random.choice(len(df))

        atom_inds = df.iloc[f_index].atominds

        feature_value = md.compute_angles(trajectories[rnd_traj], [atom_inds])
        if feat.cos:
            func = getattr(np, '%s' % df.iloc[f_index].otherinfo)
            feature_value = func(feature_value)

        assert (features[0][:, f_index] == feature_value.flatten()).all()
def test_KappaFeaturizer_describe_features():
    feat = KappaAngleFeaturizer()
    rnd_traj = np.random.randint(len(trajectories))
    features = feat.transform([trajectories[rnd_traj]])
    df = pd.DataFrame(feat.describe_features(trajectories[rnd_traj]))

    for f in range(25):
        f_index = np.random.choice(len(df))

        atom_inds = df.iloc[f_index].atominds

        feature_value = md.compute_angles(trajectories[rnd_traj], [atom_inds])
        if feat.cos:
            func = getattr(np, '%s' % df.iloc[f_index].otherinfo)
            feature_value = func(feature_value)

        assert (features[0][:, f_index] == feature_value.flatten()).all()
Пример #23
0
def extract_Q(frame, neighbors, idx_A):
    triplet_list = []
    neighbors = idx_A[neighbors]
    
    for i in range(len(neighbors)):
        tagged = idx_A[i]
        neighs = [O for O in neighbors[i] if not O == tagged]
        
        for j in range(3):
            for k in range(j+1,4):
                trio = (neighs[j], tagged, neighs[k])
                triplet_list.append(trio)

    triplet_list = np.array(triplet_list, dtype=int)
    angle_in_rad = md.compute_angles(frame, triplet_list, opt=True).reshape(-1, 6)
    sum_elements = np.sum(np.square(np.cos(angle_in_rad) + 1./3.), axis=1)
    Qs = (1. - 3./8. * sum_elements).reshape(-1, len(idx_A)) 
    return Qs
Пример #24
0
    def calculate_hydrogen_bonds2(self, traj, water, water_nbrs, solute_nbrs):
        """Calculates hydrogen bonds made by a water molecule with its first shell
        water and solute neighbors.

        Parameters
        ----------
        traj : md.trajectory
            MDTraj trajectory object for which hydrogen bonds are to be calculates.
        water : int
            The index of water oxygen atom
        water_nbrs : np.ndarray, int, shape=(N^{ww}_nbr, )
            Indices of the water oxygen atoms in the first solvation shell of the water molecule.
        solute_nbrs : np.ndarray, int, shape=(N^{sw}_nbr, )
            Indices of thesolute atoms in the first solvation shell of the water molecule.

        Returns
        -------
        (hbonds_ww, hbonds_sw) : tuple
            A tuple consisting of two np.ndarray objects for water-water and solute-water
            hydrogen bonds. A hydrogen bond is represented by an array of indices
            of three atom particpating in the hydrogen bond, [Donor, H, Acceptor]
        """
        hbond_data = []
        angle_triplets = []
        for wat_nbr in water_nbrs:
            angle_triplets.extend(
                [[water, wat_nbr, wat_nbr + 1], [water, wat_nbr, wat_nbr + 2], [wat_nbr, water, water + 1],
                 [wat_nbr, water, water + 2]])
        for solute_nbr in solute_nbrs:
            if self.prot_hb_types[solute_nbr] == 1 or self.prot_hb_types[solute_nbr] == 3:
                angle_triplets.extend([[solute_nbr, water, water + 1], [solute_nbr, water, water + 2]])
            if self.prot_hb_types[solute_nbr] == 2 or self.prot_hb_types[solute_nbr] == 3:
                for don_H_pair in self.don_H_pair_dict[solute_nbr]:
                    angle_triplets.extend([[water, solute_nbr, don_H_pair[1]]])
        angle_triplets = np.asarray(angle_triplets)
        angles = md.compute_angles(traj, np.asarray(angle_triplets))
        angles[np.isnan(angles)] = 0.0
        angles_ww = angles[0, 0:water_nbrs.shape[0] * 4]
        angles_sw = angles[0, water_nbrs.shape[0] * 4:]
        angle_triplets_ww = angle_triplets[:water_nbrs.shape[0] * 4]
        angle_triplets_sw = angle_triplets[water_nbrs.shape[0] * 4:]
        hbonds_ww = angle_triplets_ww[np.where(angles_ww <= ANGLE_CUTOFF_RAD)]
        hbonds_sw = angle_triplets_sw[np.where(angles_sw <= ANGLE_CUTOFF_RAD)]
        return (hbonds_ww, hbonds_sw)
Пример #25
0
    def get_angles(self, angle_index):
        """calculate angles between three atoms for a trajectory

        Parameters
        ----------
        angle_index: list, shape=[n, 3]
            the atom indices for angle calculations

        Returns
        -------
        angles: ndarray, shape=[N, M]
            angles, N is number of frames, M is the number
            of the angles per frame

        """

        angles = mt.compute_angles(self.traj, angle_indices=angle_index)

        return angles
Пример #26
0
def get_internal_coordinates(top, coordinate_type, pca_traj, atom_indices):
    'get the different types of internal coordinates as per user selections'
    calpha_idx = top.select_atom_indices(atom_indices)
    if coordinate_type == 'distance':
        print('Pair wise atomic distance selected\n ')
        atom_pairs = list(combinations(calpha_idx,
                                       2))  # all unique pairs of elements
        pairwise_distances = md.geometry.compute_distances(
            pca_traj, atom_pairs)
        int_cord = pairwise_distances

    if coordinate_type == 'phi':
        print('phi torsions  selected\n')
        atom_pairs = list(combinations(calpha_idx, 3))
        angle = md.compute_phi(pca_traj)

        int_cord = angle[
            1]  ## apparently compute_phi returns tupple of atoms indices and phi angles, index 1 has phi angles

    if coordinate_type == 'psi':
        print('psi torsions  selected\n')
        atom_pairs = list(combinations(calpha_idx, 3))
        angle = md.compute_psi(pca_traj)

        int_cord = angle[
            1]  ## apparently compute_psi returns tupple of atoms indices and psi angles, index 1 has psi angles

    if coordinate_type == 'angle':
        print('1-3 angle selected between N,CA and C')
        nrow = len(top.select(
            "name CA"))  # to get the number of amino acid ignoring ligand etc.
        ncol = 3
        # make a matrix of N,CA, C index, each row index making bond
        B = np.ones((nrow, ncol))
        B[:, 0] = top.select('backbone and name N')
        B[:, 1] = top.select('backbone and name CA')
        B[:, 2] = top.select('backbone and name C')

        # compute angle between N,CA, C
        angle = md.compute_angles(pca_traj, B)
        int_cord = angle
    return int_cord
Пример #27
0
def tetra_struct_Q(frame, neighbors):
    print('Computing tetrahedrality...')
    Qs = []
   
    for cluster in neighbors:
        doub_sum = 0.
        
        for i in range(3):
            for j in range(i+1,4):
                trio = (cluster[1][i], cluster[0], cluster[1][j])
                ang_in_rad = md.compute_angles(frame, [trio])[0][0] 
                doub_sum += (math.cos(ang_in_rad) + 1./3.)**2
                
        Q = 1. - (3./8.) * doub_sum        
        Qs.append(Q)  

    print('Done.')
    print('')

    return Qs
Пример #28
0
def test_equality_with_cgnet_angles():
    # Make sure CA distances caluclated internally are consistent with mdtraj.
    # This test appears here because it requires an mdtraj dependency.
    molecule = CGMolecule(names=names, resseq=resseq, resmap=resmap)
    traj = molecule.make_trajectory(data)

    # Grab the CA inds only to get the backbone angles and compute them
    # with mdtraj
    CA_inds = [i for i, name in enumerate(names) if name == 'CA']
    backbone_angles = [(CA_inds[i], CA_inds[i + 1], CA_inds[i + 2])
                       for i in range(len(CA_inds) - 2)]
    mdtraj_angles = md.compute_angles(traj, backbone_angles)

    # Get the GeometryFeature for just the
    geom_feature = GeometryFeature(feature_tuples=backbone_angles)
    out = geom_feature.forward(data_tensor)

    cgnet_angles = geom_feature.angles

    np.testing.assert_allclose(mdtraj_angles, cgnet_angles, rtol=1e-4)
Пример #29
0
    def calc_angle_energy(self, traj, sum=True):
        """Energy for angle interactions

        Parameters
        ----------
        traj : mdtraj.Trajectory

        sum : bool (opt.)
            If sum=True return the total energy.
        """
        theta = md.compute_angles(traj, self._angle_idxs)
        if sum:
            Eangle = np.zeros(traj.n_frames, float)
        else:
            Eangle = np.zeros((traj.n_frames, self.n_angles), float)

        for i in range(self.n_angles):
            if sum:
                Eangle += self._angles[i].V(theta[:,i])
            else:
                Eangle[:,i] = self._angles[i].V(theta[:,i])
        return Eangle
Пример #30
0
chunk_size = 100
indexes = np.array([np.arange(len(apairs)) for _ in range(chunk_size)])

index_all = np.array([], dtype=int)
ha_all = np.array([], dtype=float)
da_all = np.array([], dtype=float)

# variable to sum up total frames
tt = 0
for chunk_index, traj in enumerate(
        md.iterload(filename, chunk=chunk_size, top='begin.gro')):
    print('Reading chunk %d of %d frames' % (chunk_index, chunk_size))
    tt += len(traj)
    dists = md.compute_distances(traj, apairs[:, [0, 2]])
    ha_dists = md.compute_distances(traj, apairs[:, [1, 2]])
    angles = md.compute_angles(traj, apairs)
    # Using this way we could also obtain the info for the distance distribution
    #remaining = angles[np.where(dists <= cutoff)]
    #final = remaining[np.where(remaining > acri)]
    locs = np.where(angles > acri)
    da = dists[locs]
    ha = ha_dists[locs]
    ind_temp = indexes[locs]
    locs = np.where(da <= cutoff)
    da_all = np.append(da_all, da[locs])
    ha_all = np.append(ha_all, ha[locs])
    index_all = np.append(index_all, ind_temp[locs])

## Compare the sequence pair indexes to determine each frame.
## Most cases should be fine, but there could be cases that the starting index
## of next frame is higher than the ending index of previous frame.
Пример #31
0
#for i in range(3):
#    temp.append(topology.select_pairs(topology.select("name %s" %donor_name[i]), topology.select("name =~ 'F.*'")))
#pdb.set_trace()
dists = md.compute_distances(traj, pairs)
dist_all = []
hdist_all = []
print(time.time() - start)
for i, frame in enumerate(traj):
    if i % 10 == 0:
        print(i)
    remaining = []
    for j, item in enumerate(dists[i]):
        if item <= cutoff:
            remaining.append(j)
    temp = apairs[remaining, :]
    angles = md.compute_angles(frame, temp)[0]
    final = []
    ind = []
    for j, item in enumerate(angles):
        if item >= acri:
            ind.append(remaining[j])
    for item in ind:
        outfile.write('%d ' % item)
    outfile.write('\n')
    dist_all.extend(dists[i][ind])
    hdist_all.extend(md.compute_distances(frame, apairs[ind, :][:, [1, 2]])[0])
print('Average distance:', np.mean(dist_all))
print('Hydrogen bonds per frame:', len(dist_all) / float(len(traj)))
print(time.time() - start)
outfile.close()
np.savetxt('hbond_da_dist_acn.txt', dist_all)
for i in range(ndimers):
    #pdbin=inputstr[intcode]+str(i)+'.pdb'
    #traj=md.load(pdbin,top=pdbin)
    #topology=traj.topology
    xyzin = inputstr[intcode] + str(i) + '.xyz'
    traj = md.load_xyz(xyzin, top="sample_Urea_Chol.pdb")
    #if intcode==2:
    #be careful. if chol cl order swapped(due to residue index), need to change calculation
    #  if 'Cl' in str(topology.atom(0)): #first atom is Cl -> chol cl swapped
    #    list_distc1=np.array([mother_list_dist[4]])
    #    list_angle=np.array([mother_list_angle[4]])
    #    list_dih1=np.array([mother_list_dih1[4]])

    sub_distc1 = (md.compute_distances(traj, list_distc1)).flatten()[0]
    sub_distc2 = 10000000
    sub_ang1 = (md.compute_angles(traj, list_angle)).flatten()[0]
    if intcode == 1 or intcode == 3 or intcode == 5:
        sub_distc2 = (md.compute_distances(traj, list_distc2)).flatten()[0]
    #if intcode==0:
    #elif intcode==1:
    #chHuN distance: choose closer one
    #elif intcode==2:
    #be careful. if chol cl order swapped(due to residue index), need to change calculation
    #elif intcode==3:
    #chHuN distance: choose closer one
    sub_dist1 = np.minimum(sub_distc1, sub_distc2)
    main_dih = (md.compute_dihedrals(traj, list_dih1)).flatten()[0]
    maindist = (md.compute_distances(traj, list_maindist)).flatten()[0]
    #sub_dih2=(md.compute_dihedrals(traj,list_dih2)).flatten()[0]
    #main_dih,sub_dih2,sub_ang1=main_dih*180.0/math.pi,sub_dih2*180.0/math.pi,sub_ang1*180.0/math.pi
    main_dih, sub_ang1 = main_dih * 180.0 / math.pi, sub_ang1 * 180.0 / math.pi
Пример #33
0
cs83 = topo.select('resSeq 83 and name SG')
cs87 = topo.select('resSeq 87 and name SG')
cs93 = topo.select('resSeq 93 and name SG')
cc83 = topo.select('resSeq 83 and name CB')
cc87 = topo.select('resSeq 87 and name CB')
cc93 = topo.select('resSeq 93 and name CB')
# cysteines for ZN248
cs185 = topo.select('resSeq 185 and name SG')
cs232 = topo.select('resSeq 232 and name SG')
cs234 = topo.select('resSeq 234 and name SG')
cs239 = topo.select('resSeq 239 and name SG')
cc185 = topo.select('resSeq 185 and name CB')
cc232 = topo.select('resSeq 232 and name CB')
cc234 = topo.select('resSeq 234 and name CB')
cc239 = topo.select('resSeq 239 and name CB')
# make arrays of trios
list246 = [[int(zn246), int(cs53), int(cc53)], [int(zn246), int(cs55), int(cc55)], [int(zn246), int(cs70), int(cc70)], [int(zn246), int(cs74), int(cc74)]]
list247 = [[int(zn247), int(cs70), int(cc70)], [int(zn247), int(cs83), int(cc83)], [int(zn247), int(cs87), int(cc87)], [int(zn247), int(cs93), int(cc93)]]
list248 = [[int(zn248), int(cs185), int(cc185)], [int(zn248), int(cs232), int(cc232)], [int(zn248), int(cs234), int(cc234)], [int(zn248), int(cs239), int(cc239)]]
array246 = np.asarray(list246)
array247 = np.asarray(list247)
array248 = np.asarray(list248)
# calc angles
angles246 = md.compute_angles(traj, array246)
angles247 = md.compute_angles(traj, array247)
angles248 = md.compute_angles(traj, array248)
# save results
np.savetxt('angles246.txt', angles246)
np.savetxt('angles247.txt', angles247)
np.savetxt('angles248.txt', angles248)
Пример #34
0
def angles(traj, indices=None):
    x = []
    y = md.compute_angles(traj, angle_indices=indices, periodic=True)
    x.extend([np.sin(y), np.cos(y)])
    return np.hstack(x)
Пример #35
0
 def map(self, traj):
     rad = mdtraj.compute_angles(traj, self.angle_indexes)
     if self.deg:
         return np.rad2deg(rad)
     else:
         return rad
Пример #36
0
def main():
    #Part to load coordinate file
    topfile = sys.argv[1]
    trjfile = sys.argv[2]
    outfile = open(sys.argv[3], 'w')

    aname1 = input("atom names for donors? ex) OW \n")
    aname2 = input("atom names for hydrogens? ex) HW1 HW2 \n")
    aname3 = input("atom names for acceptors? ex) UO \n")
    rrange = input(
        "minimum, maximum D-A distance in angstroms? ex) 1.00 5.00 \n")
    rsplit = rrange.split()
    rmin, rmax = float(rsplit[0]) * angtonm, float(rsplit[1]) * angtonm
    rbin = float(input("r bin size in angstrom? ex) 0.02 \n")) * angtonm
    abin = float(input("cosine(theta) bin size? ex) 0.02 \n"))
    rnbin, anbin = int((rmax - rmin) / rbin), int(2 / abin)
    hbrcut = float(
        input(
            "cutoff distance(D-A) for hydrogen bond in angstroms? ex) 3.5 ? \n"
        )) * angtonm
    #In the donor-H -- acceptor triplet, D - A RDF r_min should be considered.
    hbacut = float(
        input(
            "cutoff angle in degree width from 180, for hydrogen bond? ex) 30 \n"
        ))
    hbamin, hbamax = (180.0 - hbacut) * degtorad, (
        180.0 + hbacut) * degtorad  #in radian.
    tskip = int(
        input("Once in how many frames do you want to take? ex) 10 \n"))
    teq = int(
        input(
            "How many initial frames do you want to cut as equilibration? ex) 5000 \n"
        ))

    start_time = timeit.default_timer()

    #input 1 : load surf traj. (big file)
    traj = md.load(trjfile, top=topfile)
    traj = traj[teq::tskip]
    topology = traj.topology
    nstep = traj.n_frames
    nmon = topology.n_residues
    if nstep >= 100:  #if there're many frames..
        nfrag = 200
    else:
        nfrag = 1

    elapsed = timeit.default_timer() - start_time
    print('finished trajectory loading {}'.format(elapsed))
    print(nstep, nmon)

    #prepare 2dbins for hydrogen-acceptor distance and H-bond angle
    #sdbin,count=numpy.zeros(nstep),numpy.zeros(nstep) #bin & stat weight of dr^2(t) ave

    #make atom indices list (before filtering too far pairs)
    #should avoid intramolecular atomic pair
    asplit1, asplit2, asplit3 = aname1.split(), aname2.split(), aname3.split()
    text1, text2, text3 = '', '', ''
    for word in asplit1:
        text1 += 'name ' + word + ' or '
    for word in asplit2:
        text2 += 'name ' + word + ' or '
    for word in asplit3:
        text3 += 'name ' + word + ' or '
    text1, text2, text3 = text1[:-4], text2[:-4], text3[:-4]
    seld = topology.select(text1)
    selh = topology.select(text2)
    sela = topology.select(text3)
    n_atomd, n_atomh, n_atoma = len(seld), len(selh), len(sela)
    print(n_atomd, n_atomh, n_atoma)
    dhpairs = []
    for j in topology.bonds:
        if j[0].index in selh and j[1].index in seld:
            dhpairs.append([j[1].index, j[0].index])
        elif j[0].index in seld and j[1].index in selh:
            dhpairs.append([j[0].index, j[1].index])
    fulllist_angles = []
    for row in dhpairs:
        for i in sela:
            if topology.atom(row[1]).residue != topology.atom(i).residue:
                extrow = row.copy()
                extrow.append(i)
                fulllist_angles.append(extrow)
    #list_dist=numpy.array(list_dist)
    fulllist_angles = numpy.array(fulllist_angles)
    n_angles_full = len(fulllist_angles)
    print("dhpairs # = {}, full list # angles = {} ".format(
        len(dhpairs), n_angles_full))

    hbtot = 0
    for ifrag in range(
            nfrag):  #loop of fragmental calculation, to save memory.
        blength = int(nstep / nfrag)
        bstart, bend = ifrag * blength, (ifrag + 1) * blength
        fragtraj = traj[bstart:bend]
        #calculate distances between donors and acceptors, angle
        dist = (md.compute_distances(fragtraj,
                                     fulllist_angles[:, [0, 2]])).flatten()
        #index_thres=numpy.where(full_dist<=rmax)[0]
        #dist=numpy.array(full_dist[index_thres])
        #print(dist)
        #list_angles=fulllist_angles[index_thres,:]
        ## calculate angles and distances
        angl = (md.compute_angles(fragtraj, fulllist_angles)).flatten()
        #n_angles=len(list_angles)
        #print(" list # distances(within threshold) = {}".format(len(dist)))
        #print(" list # angles = {}".format(n_angles))
        i_thresd, i_thresa = numpy.where(dist <= hbrcut), numpy.where(
            numpy.logical_and(hbamin <= angl, angl <= hbamax))
        hbtot += len(numpy.intersect1d(i_thresd[0], i_thresa[0]))
        # recalculate NaN values of angles
        import copy
        for nan_item in numpy.argwhere(numpy.isnan(angl)).reshape(-1):
            i_frame = int(nan_item / n_angles_full)
            i_angle = nan_item % n_angles_full
            #print(" Nan at {} th frame and {} th angle".format(i_frame,i_angle))
            #print(" <-- {} th atoms".format(list_angles[i_angle]))
            i_abc = fulllist_angles[i_angle]
            a = traj.xyz[i_frame][i_abc[0]]
            b = traj.xyz[i_frame][i_abc[1]]
            c = traj.xyz[i_frame][i_abc[2]]
            print(" <-- position: \n {} \n {} \n {}".format(a, b, c))
            ba = a - b
            bc = c - b
            cosine_angle = numpy.dot(
                ba, bc) / (numpy.linalg.norm(ba) * numpy.linalg.norm(bc))
            print(" distance= {}".format(numpy.linalg.norm(bc)))
            angle = numpy.arccos(cosine_angle)
            print(" get correct value from NaN, {} (rad) {} (deg)".format(
                angle, angle * 180.0 / numpy.pi))
            angl[nan_item] = copy.copy(angle)

        cosangl = numpy.cos(angl)
        #print(cosangl)
        #printing section - should regard gnuplot pm3d-compatible format.
        #hold x. increment y. when a full cycle of y range ends, make an empty line.
        #histogram
        counts_2d, edge_r, edge_cosa = numpy.histogram2d(dist,
                                                         cosangl,
                                                         bins=[rnbin, anbin],
                                                         range=[[rmin, rmax],
                                                                [-1.0, 1.0]])
        #volume in each radial shell
        vol = numpy.power(edge_r[1:], 3) - numpy.power(edge_r[:-1], 3)
        vol *= 4 / 3.0 * numpy.pi
        # Average number density
        box_vol = numpy.average(fragtraj.unitcell_volumes)
        density = n_angles_full / box_vol
        rdf_2d = (counts_2d * anbin / nstep) / (density * vol[:, None])
        if ifrag == 0:
            totrdf_2d = numpy.copy(rdf_2d)
        else:
            totrdf_2d += rdf_2d
        elapsed = timeit.default_timer() - start_time
        print('finished fragment {} time {}'.format(ifrag, elapsed))

    for i in range(rnbin):
        for j in range(anbin):
            xval, yval = (rmin + rbin * i) / angtonm, -1.0 + abin * j
            outfile.write('{:11.4f} {:11.4f} {:11.4f}\n'.format(
                xval, yval, totrdf_2d[i][j]))
        outfile.write('\n')
    #average number of H-bonds normalization : when D-H -- A exist, number of A atoms satisfies criterion, per one D-H.
    #therefore, (Total count in the whole trajectory)/((# of frames)*(total# of D-H pairs in 1 system))
    hbavg = hbtot / (nstep * len(dhpairs))
    print(
        'Detected H-bond rcut {:8.3f} A angcut {:8.3f} deg totcount {} avg {:11.4f}'
        .format(hbrcut / angtonm, hbacut, hbtot, hbavg))
    elapsed = timeit.default_timer() - start_time
    print('finished job {}'.format(elapsed))
    #numpy.savetxt(outfile,numpy.transpose(rdf_2d), \
    #header='x = distance [{},{}], y= cos angle [{},{}]' \
    #.format(rmin,rmax,-1.0,1.0),fmt='%f',comments='# ')
    #numpy.save(outfile,numpy.transpose(rdf_2d))
    #print(rdf_2d)
    outfile.close()
Пример #37
0
            print_frequency=print_frequency,
            output_data=output_data)
    else:
        replica_energies, replica_positions, replica_states = read_replica_exchange_data(
            system=cgmodel.system,
            topology=cgmodel.topology,
            temperature_list=temperature_list,
            output_data=output_data,
            print_frequency=print_frequency)

    bond_angles = []
    make_replica_pdb_files(cgmodel.topology, replica_positions)
    for replica_index in range(len(replica_positions)):
        trajectory = md.load(str("replica_" + str(replica_index + 1) + ".pdb"))
        for angle in angle_list:
            traj_angles = md.compute_angles(trajectory, [angle])
            for sample in traj_angles:
                bond_angles.append(sample)

    bond_angles = np.array([float(angle) for angle in bond_angles])

    n_bond_angle_bins = 100
    bond_angle_bin_counts = np.zeros((n_bond_angle_bins + 1), dtype=int)
    min_bond_angle = bond_angles[np.argmin(bond_angles)]
    max_bond_angle = bond_angles[np.argmax(bond_angles)]
    bond_angle_step = (max_bond_angle - min_bond_angle) / (n_bond_angle_bins +
                                                           1)
    bond_angle_ranges = [[
        min_bond_angle + bond_angle_step * i,
        min_bond_angle + bond_angle_step * (i + 1)
    ] for i in range(n_bond_angle_bins + 1)]