def plot_2ala_ramachandran(traj, ax=None, weights=None):
    import mdtraj as md
    if ax == None:
        ax = plt.gca()

    if isinstance(weights, np.ndarray):
        ax.hist2d(md.compute_phi(traj)[1].reshape(-1),
                  md.compute_psi(traj)[1].reshape(-1),
                  bins=[
                      np.linspace(-np.pi, np.pi, 64),
                      np.linspace(-np.pi, np.pi, 64)
                  ],
                  norm=mpl.colors.LogNorm(),
                  weights=weights)
    else:
        ax.hist2d(md.compute_phi(traj)[1].reshape(-1),
                  md.compute_psi(traj)[1].reshape(-1),
                  bins=[
                      np.linspace(-np.pi, np.pi, 64),
                      np.linspace(-np.pi, np.pi, 64)
                  ],
                  norm=mpl.colors.lognorm())

    ax.set_xlim(-np.pi, np.pi)
    ax.set_ylim(-np.pi, np.pi)
    ax.set_xlabel(r'$\phi$')
    ax.set_ylabel(r'$\psi$')
示例#2
0
文件: dmorph.py 项目: schilli/Tools
def ramachandran_angles(first, last):
    """
    Collect information on ramachandran dihedrals

    Parameters
    ----------
    first: string
        Filename of initial structure
    last: string
        Filename of final structure
    """
    dihedrals = []

    firsttrj = md.load(first)
    lasttrj  = md.load(last)

    phi_ndx, firstPhi = md.compute_phi(firsttrj)
    psi_ndx, firstPsi = md.compute_psi(firsttrj)
    phi_ndx,  lastPhi  = md.compute_phi(lasttrj)
    psi_ndx,  lastPsi  = md.compute_psi(lasttrj)

    for angle_idx in range(phi_ndx.shape[0]):
        resid       = firsttrj.top.atom(phi_ndx[angle_idx,1]).residue.index
        rotIndices  = list(firsttrj.top.select("resid {} and (sidechain or name C or name O) and not name H".format(resid)))
        rotIndices += list(firsttrj.top.select("resid > {}".format(resid)))
        dihedrals.append(Dihedral(firsttrj, phi_ndx[angle_idx,:], rotIndices, firstPhi[0,angle_idx], lastPhi[0,angle_idx]))

    for angle_idx in range(psi_ndx.shape[0]):
        resid       = firsttrj.top.atom(psi_ndx[angle_idx,1]).residue.index
        rotIndices  = list(firsttrj.top.select("resid {} and name O".format(resid)))
        rotIndices += list(firsttrj.top.select("resid > {}".format(resid)))
        dihedrals.append(Dihedral(firsttrj, psi_ndx[angle_idx,:], rotIndices, firstPsi[0,angle_idx], lastPsi[0,angle_idx]))
 
    return dihedrals
示例#3
0
    def discretize(self, method="rama", states=None, nbins=20):
        """ Discretize the simulation data.

        Parameters
        ----------
        method : str
            A method for doing the clustering. Options are
            "rama", "ramagrid"...
        states : list
            A list of states to be considered in the discretization.
            Only for method "rama".
        nbins : int
            Number of bins in the grid. Only for "ramagrid".

        Returns
        -------
        discrete : list
            A list with the set of discrete states visited.

        """
        if method == "rama":
            phi = md.compute_phi(self.mdt)
            psi = md.compute_psi(self.mdt)
            self.distraj = traj_lib.discrete_rama(phi, psi, states=states)
        elif method == "ramagrid":
            phi = md.compute_phi(self.mdt)
            psi = md.compute_psi(self.mdt)
            self.distraj = traj_lib.discrete_ramagrid(phi, psi, nbins)
def run_corr(args):
    print "reading trajectory"
    traj = md.load(args.input_traj, top=args.pdb_file)

    if args.feature_type == "positions":
        print "aligning frames"
        backbone = traj.topology.select_atom_indices("minimal")
        traj.superpose(traj, atom_indices=backbone)

        print "computing displacements"
        alpha_carbons = traj.topology.select_atom_indices("alpha")
        traj = traj.atom_slice(alpha_carbons)
        features = np.sqrt(
            np.sum((traj.xyz - np.mean(traj.xyz, axis=0))**2, axis=2))

    elif args.feature_type == "dihedrals":
        _, phi_angles = md.compute_phi(traj, periodic=False)
        _, psi_angles = md.compute_psi(traj, periodic=False)

        features = np.vstack([phi_angles, psi_angles])

    elif args.feature_type == "transformed-dihedrals":
        _, phi_angles = md.compute_phi(traj, periodic=False)
        _, psi_angles = md.compute_psi(traj, periodic=False)

        phi_sin = np.sin(phi_angles)
        phi_cos = np.cos(phi_angles)
        psi_sin = np.sin(psi_angles)
        psi_cos = np.cos(psi_angles)

        features = np.vstack([phi_sin, phi_cos, psi_sin, psi_cos])

    elif args.feature_type == "transformed-chi-dihedrals":
        _, chi_angles = md.compute_chi1(traj, periodic=False)
        chi_sin = np.sin(chi_angles)
        chi_cos = np.cos(chi_angles)
        features = np.vstack([chi_sin, chi_cos])

    print features.shape

    print "Computing correlation matrix"
    corr = np.corrcoef(features, rowvar=False)

    print "Plotting correlation matrix"
    if args.plot_type == "heatmap":
        plt.pcolor(corr, vmin=-1.0, vmax=1.0)
        plt.colorbar()
        plt.tight_layout()
    elif args.plot_type == "distribution":
        import seaborn as sns
        sns.distplot(np.ravel(corr), kde=False)
        plt.xlabel("Correlation", fontsize=16)
        plt.ylabel("Occurrences", fontsize=16)
    plt.savefig(args.figure_fl, DPI=300)
示例#5
0
文件: MCmin.py 项目: schilli/Tools
    def add_ramachandran_moves(self, philist=None, psilist=None, angle_std=120 * unit.degree, nrot=1, verbose=True):
        """
        Add dihedral rotation moves for the backbone phi/psi angles
        By default, ramachandran moves for all rotatable residues are added.

        Parameters:
        -----------
        philist:    residue IDs of phi angles to rotate (zero based residue numbering)
        psilist:    residue IDs of psi angles to rotate (zero based residue numbering)
        angle_std:  maximum rotation angle (with unit)
        nrot (int): number of rotations per step 
        """
        if philist is None:
            nphidihedrals = md.compute_phi(self[:1])[0].shape[0]
            philist = range(1, nphidihedrals)
        if psilist is None:
            npsidihedrals = md.compute_psi(self[:1])[0].shape[0]
            psilist = range(0, npsidihedrals)

        # add MC moves
        ndihedrals = len(philist) + len(psilist)
        frequency = max(min(1.0, 1.0 * nrot / ndihedrals), 0.0)
        for residue in philist:
            self.MC_moves.append(
                MC_ramachandran_move(
                    self, frequency=frequency, residue=residue, kind="phi", angle_std=angle_std, verbose=verbose
                )
            )
        for residue in psilist:
            self.MC_moves.append(
                MC_ramachandran_move(
                    self, frequency=frequency, residue=residue, kind="psi", angle_std=angle_std, verbose=verbose
                )
            )
示例#6
0
def test_dihedral_backbone_result(file_name):
    import mdtraj

    mmtf_file = mmtf.MMTFFile.read(file_name)
    array = mmtf.get_structure(mmtf_file, model=1)
    array = array[struc.filter_amino_acids(array)]
    if array.array_length() == 0:
        # Structure contains no protein
        # -> determination of backbone angles makes no sense
        return

    for chain in struc.chain_iter(array):
        print("Chain: ", chain.chain_id[0])
        if len(struc.check_res_id_continuity(chain)) != 0:
            # Do not test discontinuous chains
            return
        test_phi, test_psi, test_ome = struc.dihedral_backbone(chain)

        temp = NamedTemporaryFile("w+", suffix=".pdb")
        strucio.save_structure(temp.name, chain)
        traj = mdtraj.load(temp.name)
        temp.close()
        _, ref_phi = mdtraj.compute_phi(traj)
        _, ref_psi = mdtraj.compute_psi(traj)
        _, ref_ome = mdtraj.compute_omega(traj)
        ref_phi, ref_psi, ref_ome = ref_phi[0], ref_psi[0], ref_ome[0]

        assert test_phi[1:] == pytest.approx(ref_phi, abs=1e-5, rel=5e-3)
        assert test_psi[:-1] == pytest.approx(ref_psi, abs=1e-5, rel=5e-3)
        assert test_ome[:-1] == pytest.approx(ref_ome, abs=1e-5, rel=5e-3)
示例#7
0
def frame_op(trj, atom_info, basename, resfile):   #iterator over the frames 
    for i, frame in enumerate(trj):       #counter i and frame are now synced
	#We compute Rham Plot value 
	f=md.compute_phi(frame)
	p=md.compute_psi(frame)
        F=float(f[1][0][0])
	P=float(p[1][0][0])
	#We create the gromacs coord file 
	filename_g = '{}_{:04d}.gro'.format(basename, i)
	#filename="gromacs.gro"
	info=' phi={:8.3f} psi={:8.3f}'.format(F, P)
	#info='test'
	with open(filename_g, 'w') as f:
	    write_gro_frame(frame.xyz[0, ...], atom_info, f, info)
	
	#We also create the Amber coord file 
        filename_a = '{}_{:04d}.inpcrd'.format(basename, i)
	with open(filename_a,'w') as f:
	    write_amber_frame(frame.xyz[0, ...], f, info)
	
	#We compute the SEA and GB Energy
	Egb   = energy_GB(filename_a)
	Esea  = energy_SEA(filename_g)
        
	#And we write the output in a file 
	line='{:8.3f} {:8.3f} {:8.3f} {:8.3f} {:8.3f}'.format(F, P, Esea, Egb, np.exp(-(Esea-Egb)/0.59616123))
	print >>resfile, line
示例#8
0
def test_dihedral_backbone_result(file_name):
    import mdtraj

    mmtf_file = mmtf.MMTFFile()
    mmtf_file.read(file_name)
    array = mmtf.get_structure(mmtf_file, model=1)
    array = array[struc.filter_amino_acids(array)]
    for chain in struc.chain_iter(array):
        print("Chain: ", chain.chain_id[0])
        if len(struc.check_id_continuity(chain)) != 0:
            # Do not test discontinuous chains
            return
        test_phi, test_psi, test_ome = struc.dihedral_backbone(chain)

        temp_file_name = biotite.temp_file("pdb")
        strucio.save_structure(temp_file_name, chain)
        traj = mdtraj.load(temp_file_name)
        _, ref_phi = mdtraj.compute_phi(traj)
        _, ref_psi = mdtraj.compute_psi(traj)
        _, ref_ome = mdtraj.compute_omega(traj)
        ref_phi, ref_psi, ref_ome = ref_phi[0], ref_psi[0], ref_ome[0]

        assert test_phi[1:] == pytest.approx(ref_phi, abs=1e-5, rel=5e-3)
        assert test_psi[:-1] == pytest.approx(ref_psi, abs=1e-5, rel=5e-3)
        assert test_ome[:-1] == pytest.approx(ref_ome, abs=1e-5, rel=5e-3)
 def map_angles(self, trj):
         """
         trj:
               mdtraj pbject
         output:
               n_ec x n_frames
         """
         # map coordinate space to reaction coorinates space
         import mdtraj as md
         import numpy as np
         
         phi = md.compute_phi(trj)[1]
         z_phi = np.array([phi[i][0] for i in range(len(phi))]) # in rad
         psi = md.compute_psi(trj)[1]
         z_psi = np.array([psi[i][0] for i in range(len(psi))]) # in rad
         # (name CA or name N and resname ALA) or ((name C or name O) and resname ACE)
         #atom_indix_theta = trj.topology.select('name O or name C or name N or name CA')
         atom_indix_theta = trj.topology.select('(name O and resname ACE) or (name C and resname ACE) or (name N and resname ALA) or (name CA and resname ALA)')
         theta = md.compute_dihedrals(trj, [atom_indix_theta])
         z_theta = np.array([theta[i][0] for i in range(len(theta))])
         
         # (name CA) or ((name C and resname ALA) or ((name N or name H) and resname NME))
         #atom_indix_ksi = trj.topology.select('name CA or name C or name N or name H')
         atom_indix_ksi = trj.topology.select('(name CA and resname ALA) or (name C and resname ALA) or (name N and resname NME) or (name H and resname NME)')
         ksi = md.compute_dihedrals(trj, [atom_indix_ksi])
         z_ksi = np.array([ksi[i][0] for i in range(len(ksi))])
        
         trj_theta2 = []
         trj_theta2.append(z_phi)
         trj_theta2.append(z_psi)
         trj_theta2.append(z_theta)
         trj_theta2.append(z_ksi)
         return trj_theta2
示例#10
0
def main():
    parser = argparse.ArgumentParser()

    parser.add_argument('assignment', help='Path to an assignment file.')

    parser.add_argument(
        '-o',
        '--output',
        default='Data/conform.dat',
        help="output file for conformation file default is Data/conform.dat")

    parser.add_argument(
        '-t',
        '--trajectory',
        default='trajectory',
        help=
        'Path to the trajectory directory or project file (default=trajectory)'
    )

    parser.add_argument('-p',
                        '--percent',
                        help="conformation above percent to keep for Bayesian",
                        default=0.00,
                        type=float)

    parser.add_argument(
        '-d',
        '--angle',
        default='conform_angle.dat',
        help=
        "angle used to calculate Jcoupling default is conform_angle.dat (phi first, psi second)"
    )

    args = parser.parse_args()

    traj = md.load(os.path.join(os.getcwd(), args.trajectory, 'traj.h5'))

    phi = md.compute_phi(traj)[1] * 180.0 / np.pi
    psi = md.compute_psi(traj)[1] * 180.0 / np.pi

    if os.path.isfile(args.angle):
        angle = np.loadtxt(args.angle, dtype=int, unpack=True).reshape((2, -1))
        phi = np.hstack((phi[:, angle[0, :]], phi[:, [0]]))
        psi = np.hstack((psi[:, [0]], psi[:, angle[1, :]]))

    assignment = load_file(args.assignment)

    assignment = filter_assignment(assignment, args.percent)

    numstates = max(assignment) + 1

    with open(args.output, 'w') as output:
        for i in range(numstates):
            cluster = np.where(assignment == i)[0]
            conform = ''
            for i in range(len(phi[0, :]) - 1):
                conform = conform + '-' + detect_conf_print(
                    scipy.stats.mstats.mode(map(int, phi[cluster, i]))[0],
                    scipy.stats.mstats.mode(map(int, psi[cluster, i + 1]))[0])
            output.write(conform[1:] + '\n')
示例#11
0
def run_dihedral_extraction(CP, outdir):
    MEGA_PHI = []
    MEGA_PSI = []
    MEGA_OMEGA = []
    for residue_index in range(1, CP.n_residues - 3):
        print(residue_index)
        PHI = np.degrees(
            np.transpose(md.compute_phi(CP.traj)[1])[residue_index])
        PSI = np.degrees(
            np.transpose(md.compute_psi(CP.traj)[1])[residue_index])
        OMEGA = np.degrees(
            np.transpose(md.compute_omega(CP.traj)[1])[residue_index])

        MEGA_PHI.append(PHI)
        MEGA_PSI.append(PSI)
        MEGA_OMEGA.append(OMEGA)

    np.savetxt('%s/PSI_matrix.csv' % (outdir),
               np.array(MEGA_PSI),
               delimiter=', ')
    np.savetxt('%s/PHI_matrix.csv' % (outdir),
               np.array(MEGA_PHI),
               delimiter=', ')
    np.savetxt('%s/OMEGA_matrix.csv' % (outdir),
               np.array(MEGA_OMEGA),
               delimiter=', ')
示例#12
0
    def map_angles(self, trj):
        """
                trj:
                      mdtraj pbject
                output:
                      n_ec x n_frames
                """
        # map coordinate space to reaction coorinates space
        import mdtraj as md
        import numpy as np

        phi = md.compute_phi(trj)[1]
        z_phi = np.rad2deg([phi[i][0] for i in range(len(phi))])
        #z_phi = np.array([phi[i][0] for i in range(len(phi))])
        psi = md.compute_psi(trj)[1]
        #z_psi = np.array([psi[i][0] for i in range(len(psi))])
        z_psi = np.rad2deg([psi[i][0] for i in range(len(psi))])

        trj_theta2 = []
        trj_theta2.append(z_phi)
        trj_theta2.append(z_psi)
        #trj_theta.append(np.sin(z_phi)) # sin's input is in Radian
        #trj_theta.append(np.cos(z_phi))
        #trj_theta.append(np.sin(z_psi))
        #trj_theta.append(np.cos(z_psi))
        return trj_theta2
示例#13
0
def get_dihedrals(hdf_file, trajectory, structure,
                  chunk=1000, atoms=None, start=0, stride=1):
    """ Evaluate the dihedral angles and store it as HDF5 dataset """
    trj_iterator = mdtraj.iterload(
        trajectory, top=structure, chunk=chunk, atom_indices=atoms, skip=start,
        stride=stride)
    first_trj_chunk = next(trj_iterator)
    print(f'Calculating dihedrals for trajectory between '
          f'{first_trj_chunk.time[0]} and {first_trj_chunk.time[-1]} ps')
    phi_indices, phi = mdtraj.compute_phi(first_trj_chunk)
    psi_indices, psi = mdtraj.compute_psi(first_trj_chunk)
    omega_indices, omega = mdtraj.compute_omega(first_trj_chunk)

    time = [first_trj_chunk.time]
    phi_array = [phi]
    psi_array = [psi]
    omega_array = [omega]
    for trj_chunk in trj_iterator:
        print(f'Calculating dihedrals for trajectory between '
              f'{trj_chunk.time[0]} and {trj_chunk.time[-1]} ps')
        time.append(trj_chunk.time)
        phi_array.append(mdtraj.compute_phi(trj_chunk)[1])
        psi_array.append(mdtraj.compute_psi(trj_chunk)[1])
        omega_array.append(mdtraj.compute_omega(trj_chunk)[1])

    group = hdf_file.require_group('dihedrals')
    phi_data = numpy.vstack(phi_array)
    phi_dset = group.require_dataset('phi',
                                     data=phi_data,
                                     shape=phi_data.shape,
                                     dtype=phi_data.dtype)
    psi_data = numpy.vstack(psi_array)
    psi_dset = group.require_dataset('psi',
                                     data=psi_data,
                                     shape=psi_data.shape,
                                     dtype=psi_data.dtype)
    omega_data = numpy.vstack(omega_array)
    omega_dset = group.require_dataset('omega',
                                       data=omega_data,
                                       shape=omega_data.shape,
                                       dtype=omega_data.dtype)
    phi_dset.attrs['indices'] = phi_indices.astype(numpy.int32)
    psi_dset.attrs['indices'] = psi_indices.astype(numpy.int32)
    omega_dset.attrs['indices'] = omega_indices.astype(numpy.int32)
    return numpy.hstack(time)
示例#14
0
def compute_phipsi(struc):
	"""
	compute dihedrals for Ramachandran plot

	"""
	phi = md.compute_phi(struc)[1][0]
	psi = md.compute_psi(struc)[1][0]
	dihedrals = np.array([phi,psi]).T
	return dihedrals
示例#15
0
def dataset_phi_psi_omega(traj):
    dataset = []
    indices, angles1 = md.compute_phi(traj)
    indices, angles2 = md.compute_psi(traj)
    indices, angles3 = md.compute_omega(traj)
    angles = np.concatenate((angles1, angles2, angles3), axis=1)
    dataset.append(angles)
    print("Done constructing dataset using Phi angles")
    return dataset
示例#16
0
def test_shape_when_none():
    t = md.load(get_fn('frame0.h5'))
    np.hstack((md.compute_phi(t)[1],
               md.compute_psi(t)[1],
               md.compute_chi1(t)[1],
               md.compute_chi2(t)[1],
               md.compute_chi3(t)[1],
               md.compute_chi1(t)[1],
               md.compute_omega(t)[1]))
示例#17
0
def test_shape_when_none():
    t = md.load(get_fn('frame0.h5'))
    np.hstack((md.compute_phi(t)[1],
               md.compute_psi(t)[1],
               md.compute_chi1(t)[1],
               md.compute_chi2(t)[1],
               md.compute_chi3(t)[1],
               md.compute_chi1(t)[1],
               md.compute_omega(t)[1]))
示例#18
0
    def test_discreteramagrid(self):
        mdt_test = self.tr.mdt

        phi = md.compute_phi(mdt_test)
        psi = md.compute_psi(mdt_test)
        discrete = traj_lib.discrete_ramagrid(phi, psi, nbins=20)
        min_ibin = min(discrete)
        max_ibin = max(discrete)
        self.assertLess(max_ibin,400)
        self.assertGreaterEqual(min_ibin,0)
示例#19
0
def ramachandran_plot(t):
    l, phi = md.compute_phi(t)
    n, psi = md.compute_psi(t)
    phi = np.rad2deg(phi)
    psi = np.rad2deg(psi)
    plt.plot(phi, psi, 'go', markersize=1)
    plt.axis([-180, 180, -180, 180])
    plt.grid(True)
    plt.show()
    return phi, psi
示例#20
0
def main():
    parser = argparse.ArgumentParser()

    parser.add_argument('assignment',
        help = 'Path to an assignment file.')

    parser.add_argument('-o',
        '--output',
        default = 'Data/conform.dat',
        help = "output file for conformation file default is Data/conform.dat")
    
    parser.add_argument('-t',
        '--trajectory',
        default='trajectory',
        help ='Path to the trajectory directory or project file (default=trajectory)'
        )

    parser.add_argument('-p',
        '--percent',
        help = "conformation above percent to keep for Bayesian",
        default = 0.00,
        type = float
        )

    parser.add_argument('-d',
        '--angle',
        default = 'conform_angle.dat',
        help = "angle used to calculate Jcoupling default is conform_angle.dat (phi first, psi second)")

    args = parser.parse_args()

    traj = md.load(os.path.join(os.getcwd(),args.trajectory,'traj.h5'))
    
    phi = md.compute_phi(traj)[1] * 180.0 / np.pi
    psi = md.compute_psi(traj)[1] * 180.0 / np.pi

    if os.path.isfile(args.angle):
        angle = np.loadtxt(args.angle,dtype = int,unpack=True).reshape((2,-1))
        phi = np.hstack((phi[:,angle[0,:]],phi[:,[0]]))
        psi = np.hstack((psi[:,[0]],psi[:,angle[1,:]]))


    assignment = load_file(args.assignment)

    assignment = filter_assignment(assignment,args.percent)

    numstates = max(assignment) + 1

    with open(args.output, 'w') as output:
        for i in range(numstates):
            cluster = np.where(assignment == i)[0]
            conform = ''
            for i in range(len(phi[0,:])-1):
                conform = conform +'-'+detect_conf_print(scipy.stats.mstats.mode(map(int,phi[cluster,i]))[0],scipy.stats.mstats.mode(map(int,psi[cluster,i+1]))[0])
            output.write(conform[1:]+'\n')
示例#21
0
    def test_discreterama(self):
        mdt_test = self.tr.mdt

        phi = md.compute_phi(mdt_test)
        psi = md.compute_psi(mdt_test)
        # print(psi)
        # psi = ([ 6,  8, 14, 16], [-30, 0, -40, 90, 140, 180])
        # phi = ([ 4,  6,  8, 14],[60., 0, -90, -90, -90, -180])
        states = ['L','A','E']
        discrete = traj_lib.discrete_rama(phi, psi, states=states)
        unique_st = set(discrete)
        for state in unique_st:
            self.assertIn(state, ['O', 'A', 'E', 'L'])
示例#22
0
def main():
	parser = argparse.ArgumentParser()

	parser.add_argument('-o',
	    '--output',
	    default = 'Data/J_coup_kalplus.dat',
	    help = "output file name for trajectory (default = Data/J_coup_kalplus.dat)"
	    )

	parser.add_argument('-t',
	    '--trajectory',
	    default='trajectory',
	    help ='Path to the trajectory directory or project file (default=trajectory)'
	    )

	parser.add_argument('-f',
		'--function',
		default = 'karp_function.dat',
		help = "Function used to calculate Jcoupling default is karp_function.dat")

	parser.add_argument('-d',
		'--angle',
		default = 'karp_angle.dat',
		help = "angle used to calculate Jcoupling default is karp_angle.dat (phi first, psi second)")

	args = parser.parse_args()
	traj = md.load(os.path.join(os.getcwd(),args.trajectory,'traj.h5'))

	function = np.loadtxt(args.function,dtype = str)
	dispatcher = {'J3HNHa':J3HNHa,'J3HNC':J3HNC,'J3HaC':J3HaC,'J3CC':J3CC,'J3HNCb':J3HNCb,'J1NCa':J1NCa,'J2NCa':J2NCa,'J3HNCa':J3HNCa}

	angles = np.loadtxt(args.angle,dtype = int)

	phi = md.compute_phi(traj)[1] * 180.0 / np.pi
	psi = md.compute_psi(traj)[1] * 180.0 / np.pi

	snap=traj.n_frames
	nj=len(function)

	print 'There are '+str(nj)+' jcoupling and totally '+str(snap)+' snapshot'

	J = np.zeros((snap, nj))

	for i in range(nj):
		print i
		J[:,i] = map(dispatcher[function[i]],phi[:,angles[i,0]],psi[:,angles[i,1]])

	if not os.path.isdir(os.path.dirname(args.output)):
		os.mkdir(os.path.dirname(args.output))
		
	np.savetxt(args.output,J,newline='\n',fmt='%f')
 def map_angles(self, trj):
         """
         trj:
               mdtraj pbject
         output:
               n_ec x n_frames
         """
         # map coordinate space to reaction coorinates space
         import mdtraj as md
         import numpy as np
         
         phi = md.compute_phi(trj)[1]
         z_phi = np.array([phi[i][0] for i in range(len(phi))]) # in rad
         psi = md.compute_psi(trj)[1]
         z_psi = np.array([psi[i][0] for i in range(len(psi))]) # in rad
         trj_theta2 = []
         trj_theta2.append(z_phi)
         trj_theta2.append(z_psi)
         return trj_theta2
示例#24
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
示例#25
0
def test_equality_with_cgnet_dihedrals():
    # Make sure dihedrals are consistent with GeometryFeature

    geom_feature = GeometryFeature(feature_tuples='all_backbone',
                                   n_beads=beads)
    out = geom_feature.forward(data_tensor)

    molecule = CGMolecule(names=names, resseq=resseq, resmap=resmap)
    traj = molecule.make_trajectory(data)

    mdtraj_phis = md.compute_phi(traj)[1]
    mdtraj_psis = md.compute_psi(traj)[1]

    mdtraj_phi_cosines = np.cos(mdtraj_phis)
    mdtraj_phi_sines = np.sin(mdtraj_phis)

    mdtraj_psi_cosines = np.cos(mdtraj_psis)
    mdtraj_psi_sines = np.sin(mdtraj_psis)

    # To get phi's and psi's out of cgnet, we need to specify which
    # indices they correspond to along the backbone
    # ['N', 'CA', 'C', 'N'] dihedrals
    phi_inds = [i * 3 for i in range(residues)]
    # ['CA', 'C', 'N', 'CA'] dihedrals
    psi_inds = [i * 3 + 1 for i in range(residues)]

    cgnet_phi_cosines = geom_feature.dihedral_cosines.numpy()[:, phi_inds]
    cgnet_phi_sines = geom_feature.dihedral_sines.numpy()[:, phi_inds]

    cgnet_psi_cosines = geom_feature.dihedral_cosines.numpy()[:, psi_inds]
    cgnet_psi_sines = geom_feature.dihedral_sines.numpy()[:, psi_inds]

    np.testing.assert_allclose(mdtraj_phi_cosines,
                               cgnet_phi_cosines,
                               rtol=1e-4)
    np.testing.assert_allclose(mdtraj_phi_sines, cgnet_phi_sines, rtol=1e-4)
    np.testing.assert_allclose(mdtraj_psi_cosines,
                               cgnet_psi_cosines,
                               rtol=1e-4)
    np.testing.assert_allclose(mdtraj_psi_sines, cgnet_psi_sines, rtol=1e-4)
示例#26
0
    def discretize(self, method="rama", states=None):
        """ Discretize the simulation data.

        Parameters
        ----------
        method : str
            A method for doing the clustering.
        states : list
            A list of states to be considered in the discretization.

        Returns
        -------
        discrete : class
            A Discrete class object.

        """

        if method == "rama":
            phi = md.compute_phi(self.mdt)
            psi = md.compute_psi(self.mdt)
            res = [x for x in self.mdt.topology.residues]
            self.distraj = traj_lib.discrete_rama(phi, psi, states=states)
def conformational_entropy(traj, bins=45, weights=None, density=True):
    #####################
    # calculate entropy #
    #####################
    phi = md.compute_phi(traj)
    psi = md.compute_psi(traj)

    ramachandrans = []
    for idx in range(phi[1].shape[1] - 1):
        x = phi[1][:, idx]
        y = psi[1][:, idx + 1]
        hist, _, _ = np.histogram2d(
            x,
            y,
            bins=bins,
            weights=weights,
            density=density,
        )
        s_j = -hist * np.ma.log(hist)
        ramachandrans.append(s_j.sum())
    # return residue-wise backbone conformational entropy
    return np.array(ramachandrans)
示例#28
0
    def calculate_dihedrals(self, save=True):
	""" 
	Calculates dihedral angles using mdtraj functions given omega, psi, or phi

	Parameters:
	    save: Saves to dihedrals_(angle).npy if True (default True)
	
	Returns:
	    indices: The indices that dihedrals are being calculated for
	    dihedrals: The calculated dihedral angles 	
	"""
	print('Calculating dihedrals for angle %s...' % self.angle) 
	if self.angle == 'phi':
	    indices, dihedrals = md.compute_phi(self.traj)
	elif self.angle == 'psi':
	    indices, dihedrals = md.compute_psi(self.traj)
	else:
	    indices, dihedrals = md.compute_omega(self.traj)
	if save:
	    load_and_save(self, dihedrals)
	    print('Dihedrals saved for index [%d][%d][%d]' % (self.run_num, self.clone_num, self.gen_num))
	return indices, dihedrals
示例#29
0
def plot_rmsf(args):
    print "reading trajectory"
    traj = md.load(args.input_traj, top=args.pdb_file)

    print "computing dihedrals"
    _, phi_angles = md.compute_phi(traj, periodic=False)
    _, psi_angles = md.compute_psi(traj, periodic=False)

    # first residue has no phi angle
    # last residue has no psi angle
    # so we only have pairs for residues 1 to n - 2
    angles = np.stack([phi_angles[:, :-1], psi_angles[:, 1:]], axis=2)

    print "computing RMSF"
    vectors = np.exp(1.j * angles)
    avg_angle = np.angle(np.mean(vectors, axis=0))

    angle_diff = avg_angle - angles
    rounded_diff = np.arctan2(np.sin(angle_diff), np.cos(angle_diff))
    rmsf = np.sqrt(2 * np.mean(rounded_diff**2, axis=(0, 2)))

    # 1-based indexing
    resids = range(2, rmsf.shape[0] + 2)

    if args.figure_fl:
        plt.clf()
        plt.plot(resids, rmsf)

        plt.xlabel("Residue", fontsize=16)
        plt.ylabel("RMSF (radians)", fontsize=16)
        plt.ylim([0, np.pi])
        plt.xlim([1, traj.n_residues])
        plt.savefig(args.figure_fl, DPI=300)

    if args.output_tsv:
        with open(args.output_tsv, "w") as fl:
            fl.write("residue_id\tangular_rmsf\n")
            for resid_, rmsf_ in zip(resids, rmsf):
                fl.write("%s\t%s\n" % (resid_, rmsf_))
示例#30
0
 def calculate_phi_psi(self, chain, t, resseq_pos, n_res):
   indices1, angles1 = md.compute_phi(t)
   indices2, angles2 = md.compute_psi(t)
   restricted_residues = list(chain.residues)
   indices1 = [t.topology.atom(indice[0]).residue for indice in indices1]
   indices2 = [t.topology.atom(indice[0]).residue for indice in indices2]
   
   phi = [angles1[0, i] for i in range(len(angles1[0])) if indices1[i] in restricted_residues]
   phi_inds = np.array([indice.resSeq for indice in indices1 if indice in restricted_residues]) - resseq_pos
   psi = [angles2[0, i] for i in range(len(angles2[0])) if indices2[i] in restricted_residues]
   psi_inds = np.array([indice.resSeq for indice in indices2 if indice in restricted_residues]) - resseq_pos
   
   out = np.zeros((n_res, 2)) # phi, psi
   weight1 = np.zeros((n_res, 1))
   weight2 = np.zeros((n_res, 1))
   for i, ind in enumerate(phi_inds):
     out[ind, 0] = phi[i]
     weight1[ind] -= 1
   for i, ind in enumerate(psi_inds):
     out[ind, 1] = psi[i]
     weight2[ind] -= 1
   return out[:, 0], out[:, 1], (weight1*weight2)[:, 0]
示例#31
0
def test_backbone_psi_dihedrals():
    # Make sure backbone psi dihedrals are correct

    molecule = CGMolecule(names=names, resseq=resseq, resmap=resmap)
    traj = molecule.make_trajectory(data)
    _, mdtraj_psis = md.compute_psi(traj)
    mdtraj_psis = np.abs(mdtraj_psis)

    # manual calculation of psi angles
    psis = []
    for frame_data in data:
        dihed_list = []
        for i in range(residues):
            # we get the psi's by starting at the 'CA', which is the second
            # bead for every residue
            a = frame_data[i * 3 + 1]
            b = frame_data[i * 3 + 2]
            # the last two beads in the psi dihedral are the 'N' and 'CA'
            # of the next residue
            c = frame_data[i * 3 + 3]
            d = frame_data[i * 3 + 4]

            ba = b - a
            cb = c - b
            dc = d - c

            c1 = np.cross(ba, cb)
            c2 = np.cross(cb, dc)
            temp = np.cross(c2, c1)
            term1 = np.dot(temp, cb) / np.sqrt(np.dot(cb, cb))
            term2 = np.dot(c2, c1)
            dihed_list.append(np.arctan2(term1, term2))
        psis.append(dihed_list)

    psis = np.abs(psis)

    np.testing.assert_allclose(mdtraj_psis, psis, rtol=1e-4)
示例#32
0
    def __init__(self, mdtraj_trajectory):
        WrappedPose.__init__(self)
        if md is None:
            print(
                "MDTrajPoseWrapper requires the mdtraj library to be installed"
            )
            raise ImportError

        assert isinstance(mdtraj_trajectory, md.Trajectory)
        assert mdtraj_trajectory.n_frames == 1
        self.trajectory = mdtraj_trajectory

        # RADIANS:
        self.phi_atoms, self.phis = md.compute_phi(self.trajectory)
        self.psi_atoms, self.psis = md.compute_psi(self.trajectory)

        self.chis = [None, None, None, None,
                     None]  # Adding zero element just to make indexing easier
        self.chi_atoms = [None, None, None, None, None]

        self.chi_atoms[1], self.chis[1] = md.compute_chi1(self.trajectory)
        self.chi_atoms[2], self.chis[2] = md.compute_chi2(self.trajectory)
        self.chi_atoms[3], self.chis[3] = md.compute_chi3(self.trajectory)
        self.chi_atoms[4], self.chis[4] = md.compute_chi4(self.trajectory)
示例#33
0
def calc_psi(traj):
    # psi: 0 ~ nres-2
    _, psi = md.compute_psi(traj)
    return psi[0] * 180 / np.pi
示例#34
0
import scipy as sp
from scipy import stats
import numpy as np
import matplotlib.pyplot as plt
import mdtraj as md
import sys
from sys import argv
import math

script, parmfile, trajfile = argv

top = md.load_prmtop(parmfile)
traj = md.load(trajfile, top=top)
print(traj)

psi_list = md.compute_psi(traj)
#phi_list = md.compute_phi(traj)
#chi1_list = md.compute_chi1(traj)
#chi2_list = md.compute_chi2(traj)

for i in xrange(psi_list[1].shape[1]):
    dihedral_traj = psi_list[1][:, i]
    dihedral_traj_deg = (dihedral_traj * 180) / math.pi
    index = np.linspace(1, len(dihedral_traj),
                        len(dihedral_traj)).astype('int')
    (n, bins, patches) = plt.hist(dihedral_traj_deg,
                                  bins=300,
                                  range=(-180.00, 180.00),
                                  normed=True)
    # data = np.vstack((index,dihedral_traj_deg)).T
    #    np.savetxt('dihedrals/psi_%d.xvg' %i, data, fmt=['%d', '%.4f'])
示例#35
0
文件: dmorph.py 项目: schilli/Tools
def dmorph(first, last, nframes, outfile, mode="linear"):
    """
    Linearly interpolate the dihedral angels from firststructure to laststructure.

    Parameters
    ----------
    first: string
        Starting structure for morph. PDB filename
    last: string
        Last structure for morph. PDB filename. 
    nframes: int
        Number of frames for morph.
    outfile: string
        Path and filename for the output trajectory
    mode: string
        Sets the interpolation mode between first and last.
        Mode is one of:
            {"linear", "cycle", "sin2"}
    """

    trj  = allocate_trj(first, nframes)
    xyz4 = np.ones([trj.n_frames, trj.n_atoms, 4], dtype=np.float64)
    xyz4[:,:,:3] = trj.xyz

    dihedrals = ramachandran_angles(first, last)

    phi_ndx, targetPhi = md.compute_phi(md.load(last))
    psi_ndx, targetPsi = md.compute_psi(md.load(last))

    rottime = 0.0
    start_t = time.time()

    error = np.zeros([nframes])
    for nf in range(1, nframes):
        print("\r", 100*" ", "\r", end="")
        print("frame {:5d} / {:5d}".format(nf+1, nframes), end="")
        rottime += rotate_dihedrals(xyz4[nf,:,:], 1.0*nf/nframes, dihedrals, mode=mode)
        sys.stdout.flush()

        trj.xyz = xyz4[:,:,:3]

        phi_ndx, phi = md.compute_phi(trj)
        psi_ndx, psi = md.compute_psi(trj)

        e = (((psi[nf,:] - targetPsi[0,:])**2).sum()/psi.shape[1])**0.5
        error[nf] = e
        print(" ", e)

    trj.superpose(trj)

    tottime = time.time() - start_t

    print()
    print("Runtime: {:6.2f} sec.".format(tottime))
#    print("rottime: {:6.2f}%".format(100*rottime/tottime))

#    lasttrj = md.load(last)
#    phi_ndx, targetPhi = md.compute_phi(lasttrj)
#    phi_ndx, targetPsi = md.compute_psi(lasttrj)
#    phi_ndx, phi = md.compute_phi(trj)
#    psi_ndx, psi = md.compute_phi(trj)
#
#    for nf in range(phi.shape[0]):
#        error[nf]  = 0.0
#        error[nf] += ((phi[nf,:] - targetPhi[0,:])**2).sum()
#        error[nf] += ((psi[nf,:] - targetPsi[0,:])**2).sum()
#        error[nf] /= 2*phi.shape[1]
#        error[nf]  = error[nf]**0.5
#    error = error

    trj.save(outfile)

    return error
import pandas as pd
import nmrpystar
import mdtraj as md

#t = md.load("./1am7_fixed.pdb")
t = md.load(["./Trajectories/1am7_%d.dcd" % i for i in range(15)], top="./1am7_fixed.pdb")[::50]
psi = md.compute_psi(t)[1][:, 48]  * 180 / pi


#full_prediction = md.nmr.chemical_shifts_shiftx2(t)
#full_prediction = md.nmr.chemical_shifts_spartaplus(t)
full_prediction = md.nmr.chemical_shifts_ppm(t)


parsed = nmrpystar.parse(open("./16664.str").read())
print(parsed.status)

q = parsed.value.saves["assigned_chem_shift_list_1"].loops[1]
x = pd.DataFrame(q.rows, columns=q.keys)
x = x[["Atom_chem_shift.Seq_ID", "Atom_chem_shift.Atom_ID", "Atom_chem_shift.Val"]]
x.rename(columns={"Atom_chem_shift.Seq_ID":"resSeq", "Atom_chem_shift.Atom_ID":"name", "Atom_chem_shift.Val":"value"}, inplace=True)

# Need to make dtypes match to do eventual comparison.
x["resSeq"] = x["resSeq"].astype('int')
x["value"] = x["value"].astype('float')
expt = x.set_index(["resSeq", "name"]).value


cond = psi > 50
prediction0 = full_prediction[where(cond)[0]].mean(1)  # Average over time dimensions
prediction0.name = "value"
#
options = parser.parse_args()

f_traj = options.traj
f_top = options.top
f_out = options.out
stride = options.stride

t = md.load(f_traj,top=f_top,stride=stride)

Ca = t.top.select('name CA')
aver_str = np.average(t.xyz[:,Ca], axis=0)
dat1  = np.swapaxes(t.xyz[:,Ca] - aver_str,1,2)

phi_ndx , phi = md.compute_phi(t)
psi_ndx , psi = md.compute_psi(t)
nres,n_fr = phi.transpose()[:-1].shape
dat2 = np.zeros([nres,2,n_fr]) 

dat2[:,0,:] = phi.transpose()[:-1]
dat2[:,1,:] = psi.transpose()[1:]

del(t)
DATA1= ts.TimeSer(dat1,n_fr,dim=3,nbins=options.nbins,reshape=False)
DATA2= ts.TimeSer(dat2,n_fr,dim=2,nbins=options.nbins,frame_row=False,reshape=False)

DATA1.calc_bins(opt=options.opt)
DATA2.calc_bins(opt=options.opt)

M1,E1 = DATA1.mutual_info_omp()
M2,E2 = DATA2.mutual_info_omp()
示例#38
0
import pandas as pd
import mdtraj as md
from dipeptide_parameters import *
import scalar_couplings

reference = pd.read_csv(
    "./experimental_data/baldwin_table1_2006_couplings.csv", index_col=0)
reference = reference["coupling"]

data = []
for (ff, water, seq) in products:
    try:
        aa = seq.split("_")[1]
        t = md.load("./dcd/%s_%s_%s.dcd" % (ff, water, seq),
                    top="./pdbs/%s.pdb" % (seq))
    except:
        continue
    phi = md.compute_phi(t)[1][:, 0] * 180 / np.pi
    psi = md.compute_psi(t)[1][:, 0] * 180 / np.pi
    J = scalar_couplings.J3_HN_HA(phi).mean()
    data.append([ff, water, aa, J])

data = pd.DataFrame(data, columns=["ff", "water", "AA", "J"])

X = data.pivot_table(values="J", cols=["AA"], rows=["ff", "water"])
delta = X - reference
Z = (delta / 0.36)
rms_by_model = (Z**2.).mean(1)**0.5
rms_by_model
示例#39
0
def compute_phi_psi(trj):                                #computes phi and psi 
    phi=md.compute_phi(trj)
    psi=md.compute_psi(trj)
    return phi[1], psi[1]
示例#40
0
def dihedral_rmsd(trj, ca_atoms, refframe = None, mode = 1):
    if refframe is None:
        refframe = trj[0]

    if len(refframe.xyz[0]) != len(trj.xyz[0]):
        raise Exception('Refframe has not the same amount of atoms as trj!')



    phi_indices, phi_angles = md.compute_phi(trj)
    psi_indices, psi_angles = md.compute_psi(trj)
    ref_phi_indices, ref_phi_angles = md.compute_phi(refframe)
    ref_psi_indices, ref_psi_angles = md.compute_psi(refframe)


    phi_indexlist = []
    psi_indexlist = []
    ref_phi_indexlist = []
    ref_psi_indexlist = []
    for i in ca_atoms:
        phi_itemindex, dump = np.where(phi_indices == i)
        phi_indexlist.append(phi_itemindex[0])
        psi_itemindex, dump = np.where(psi_indices == i)
        psi_indexlist.append(psi_itemindex[0])
        ref_phi_itemindex, dump = np.where(ref_phi_indices == i)
        ref_phi_indexlist.append(phi_itemindex[0])
        ref_psi_itemindex, dump = np.where(ref_psi_indices == i)
        ref_psi_indexlist.append(psi_itemindex[0])

    if mode == 1 or mode == 3:

        rmsd_data = np.zeros(shape=[len(phi_indexlist)+len(psi_indexlist),
                                    len(phi_angles)])
        ref_rmsd_data = np.zeros(shape=[len(phi_indexlist)+len(psi_indexlist),
                                    len(phi_angles)])


        for i, j in enumerate(phi_indexlist):
            rmsd_data[i*2, :] = phi_angles[:, j]
        for i, j in enumerate(psi_indexlist):
            rmsd_data[(i*2+1), :] = psi_angles[:, j]
        for i, j in enumerate(ref_phi_indexlist):
            ref_rmsd_data[i*2, :] = ref_phi_angles[:, j]
        for i, j in enumerate(ref_psi_indexlist):
            ref_rmsd_data[(i*2+1), :] = ref_psi_angles[:, j]

        temp_array = np.zeros(shape=[len(rmsd_data), len(rmsd_data[0])])
        for i in range(temp_array.shape[1]):
            temp_array[:, i] = ref_rmsd_data[:, 0]

        rmsd_data_dif = rmsd_data - temp_array
        rmsd_data_abs = np.absolute(rmsd_data_dif)
        over_pi = np.where(rmsd_data_abs > np.pi)
        for i, j in enumerate(over_pi[0]):
            rmsd_data_abs[j, over_pi[1][i]] -= np.pi

        rmsd = np.zeros(shape=[len(rmsd_data_abs[0])])
        rmsd = np.sum(rmsd_data_abs, axis=0)
        rmsd = rmsd/len(rmsd_data_abs)

    if mode == 2 or  mode == 3:
        rmsd_data_phi = np.zeros(shape=[len(phi_indexlist), len(phi_angles)])
        rmsd_data_psi = np.zeros(shape=[len(psi_indexlist), len(psi_angles)])
        ref_rmsd_data_phi = np.zeros(shape=[len(ref_phi_indexlist),
                                            len(ref_phi_angles)])
        ref_rmsd_data_psi = np.zeros(shape=[len(ref_psi_indexlist),
                                            len(ref_psi_angles)])

        for i, j in enumerate(phi_indexlist):
            rmsd_data_phi[i, :] = phi_angles[:, j]
        for i, j in enumerate(psi_indexlist):
            rmsd_data_psi[i, :] = psi_angles[:, j]

        for i, j in enumerate(ref_phi_indexlist):
            ref_rmsd_data_phi[i, :] = ref_phi_angles[:, j]
        for i, j in enumerate(ref_psi_indexlist):
            ref_rmsd_data_psi[i, :] = ref_psi_angles[:, j]

        temp_array_phi = np.zeros(shape=[len(rmsd_data_phi),
                                         len(rmsd_data_phi[0])])
        temp_array_psi = np.zeros(shape=[len(rmsd_data_psi),
                                         len(rmsd_data_psi[0])])

        for i in range(temp_array_phi.shape[1]):
            temp_array_phi[:, i] = ref_rmsd_data_phi[:, 0]
        for i in range(temp_array_psi.shape[1]):
            temp_array_psi[:, i] = ref_rmsd_data_psi[:, 0]

        rmsd_data_dif_psi = rmsd_data_psi - temp_array_psi
        rmsd_data_dif_phi = rmsd_data_phi - temp_array_phi
        rmsd_data_abs_psi = np.absolute(rmsd_data_dif_psi)
        rmsd_data_abs_phi = np.absolute(rmsd_data_dif_phi)

        over_pi_psi = np.where(rmsd_data_abs_psi > np.pi)
        over_pi_phi = np.where(rmsd_data_abs_phi > np.pi)


        for i, j in enumerate(over_pi_psi[0]):
            rmsd_data_abs_psi[j, over_pi_psi[1][i]] -= np.pi
        for i, j in enumerate(over_pi_phi[0]):
            rmsd_data_abs_phi[j, over_pi_phi[1][i]] -= np.pi

        rmsd_phi = np.zeros(shape=[len(rmsd_data_abs_phi[0])])
        rmsd_psi = np.zeros(shape=[len(rmsd_data_abs_psi[0])])
        rmsd_phi = np.sum(rmsd_data_abs_phi, axis=0)
        rmsd_psi = np.sum(rmsd_data_abs_psi, axis=0)

        rmsd_phi = rmsd_phi/len(rmsd_data_abs_phi)
        rmsd_psi = rmsd_psi/len(rmsd_data_abs_psi)
    if mode == 1:
        return(rmsd)
    if mode == 2:
        return(rmsd_phi,rmsd_psi)
    if mode == 3:
        return(rmsd, rmsd_phi, rmsd_psi)
示例#41
0
def extract_features(args):
    print "reading trajectory"
    traj = md.load(args.input_traj,
                   top=args.pdb_file)

    if args.select_residues:
        selections = []
        ranges = args.select_residues.split(",")
        for range_ in args.select_residues.split(","):
            if "-" in range_:
                left, right = map(int, range_.split("-"))
                selections.append("(residue %s to %s)" % (left, right))
            else:
                singleton = int(range_)
                selections.append("(residue %s)" % singleton)

        selection_str = " or ".join(selections)
        selected_atoms = traj.topology.select(selection_str)
        traj = traj.atom_slice(selected_atoms)

    if args.feature_type == "positions":
        print "aligning frames"
        traj.superpose(traj)

        features = traj.xyz.reshape(traj.n_frames,
                                    traj.n_atoms * 3)

    elif args.feature_type == "transformed-dihedrals":
        print "computing dihedrals"
        _, phi_angles = md.compute_phi(traj,
                                       periodic=False)
        _, psi_angles = md.compute_psi(traj,
                                       periodic=False)

        phi_sin = np.sin(phi_angles)
        phi_cos = np.cos(phi_angles)
        psi_sin = np.sin(psi_angles)
        psi_cos = np.cos(psi_angles)

        features = np.hstack([phi_sin,
                              phi_cos,
                              psi_sin,
                              psi_cos])

    elif args.feature_type == "transformed-dihedrals-chi":
        print "computing dihedrals"
        _, phi_angles = md.compute_phi(traj,
                                       periodic=False)
        _, psi_angles = md.compute_psi(traj,
                                       periodic=False)
        _, chi_angles = md.compute_chi1(traj,
                                        periodic=False)

        phi_sin = np.sin(phi_angles)
        phi_cos = np.cos(phi_angles)
        psi_sin = np.sin(psi_angles)
        psi_cos = np.cos(psi_angles)
        chi_sin = np.sin(chi_angles)
        chi_cos = np.cos(chi_angles)

        features = np.hstack([phi_sin,
                              phi_cos,
                              psi_sin,
                              psi_cos,
                              chi_sin,
                              chi_cos])

    elif args.feature_type == "residue-residue-distances":
        print "computing residue-residue distances"
        features, _ = md.compute_contacts(traj,
                                          scheme="ca",
                                          periodic=False)

    elif args.feature_type == "inverse-residue-residue-distances":
        print "computing inverse residue-residue distances"
        features, _ = md.compute_contacts(traj,
                                          scheme="ca",
                                          periodic=False)
        features = np.reciprocal(features)
        
    else:
        raise Exception, "Unknown feature type '%s'", args.features

    return features, args.feature_type
示例#42
0
文件: MCmin.py 项目: schilli/Tools
    def __init__(
        self,
        trajectory,
        frequency=1.0,
        angle_ndx=None,
        residue=None,
        resid=None,
        kind="phi",
        angle_std=1.0 * unit.degree,
        verbose=False,
    ):

        assert frequency >= 0.0 and frequency <= 1.0, "frequency must be in interval [0,1]"
        assert kind in ["phi", "psi"], "kind must be 'phi' or 'psi'"
        assert type(angle_std) == unit.quantity.Quantity, "angle_std must be of unit.degree or unit.radian"
        assert (
            sum([i is not None for i in [angle_ndx, residue, resid]]) > 0
        ), "One of [angle_ndx, residue, resid] must be an integer"

        # parent class initializer
        super(MC_ramachandran_move, self).__init__(trajectory.topology, frequency)

        self.verbose = verbose
        self.kind = kind
        self.angle_std = angle_std

        # get list of all ramachandran atom indices
        if self.kind == "phi":
            dihedral_atom_indices = md.compute_phi(trajectory[:1])[0]
        elif self.kind == "psi":
            dihedral_atom_indices = md.compute_psi(trajectory[:1])[0]
        ndihedrals = dihedral_atom_indices.shape[0]  # number of dihedral angles

        # determine index of this dihedral angle
        if angle_ndx is not None:
            self.angle_ndx = angle_ndx
        elif residue is not None:
            residue_indices = [self.topology.atom(a).residue.index for a in dihedral_atom_indices[:, 1]]
            self.angle_ndx = residue_indices.index(residue)
        elif resid is not None:
            residue_ids = [self.topology.atom(a).residue.resSeq for a in dihedral_atom_indices[:, 1]]
            if residue_ids.count(resid) != 1:
                self.angle_ndx = residue_ids.index(resid)
            else:
                print("{} angle not (unambiguoulsy) found for resid {}".format(self.kind, resid), file=sys.stderr)
                sys.exit(1)

        assert self.angle_ndx in range(ndihedrals), "dihedral angle index out of range"

        # determine indices of atoms spanning the rotation vector
        if self.kind == "phi":
            atom1_name = "N"
            atom2_name = "CA"
        elif self.kind == "psi":
            atom1_name = "CA"
            atom2_name = "C"
        self.atom1 = dihedral_atom_indices[
            self.angle_ndx,
            [self.topology.atom(a).name for a in dihedral_atom_indices[self.angle_ndx, :]].index(atom1_name),
        ]
        self.atom2 = dihedral_atom_indices[
            self.angle_ndx,
            [self.topology.atom(a).name for a in dihedral_atom_indices[self.angle_ndx, :]].index(atom2_name),
        ]

        self.residue = self.topology.atom(self.atom1).residue
        chainid = self.residue.chain.index

        # determine atoms to rotate
        selection_texts = []
        if self.kind == "phi":
            selection_texts.append(
                "resid {} and (sidechain or name C or name O) and not name H and chainid {}".format(
                    self.residue.index, chainid
                )
            )
            selection_texts.append("resid > {} and chainid {}".format(self.residue.index, chainid))
        elif self.kind == "psi":
            selection_texts.append("resid {} and name O and chainid {}".format(self.residue.index, chainid))
            selection_texts.append("resid > {} and chainid".format(self.residue.index))

        self.rotation_atoms = []
        for text in selection_texts:
            self.rotation_atoms += list(self.topology.select(text))

        self.symmetry_partners = []

        # report
        if self.verbose:
            print("MC move: {:3s} {:4d} {:3s} dihedral".format(self.residue.name, self.residue.resSeq, self.kind))
示例#43
0
def traj_dihedral_classes(trajin, dihedral_classes):
    #
    dihedrals_temp = None
    dihedral_ids_temp = None

    for dihedral_class in dihedral_classes:
        #
        #print("Loading {:s} angles...".format(dihedral_class))

        if re.match("phi", dihedral_class):
            #
            phi_atoms, phi = md.compute_phi(trajin)

            if dihedrals_temp is None:
                #
                dihedrals_temp = np.cos(phi)

                dihedral_ids_temp = extract_res_info(trajin.top, phi_atoms,
                                                     "phi")
            #
            else:
                #
                dihedrals_temp = np.append(dihedrals_temp, np.cos(phi), axis=1)

                dihedral_ids_temp = np.append(dihedral_ids_temp,
                                              extract_res_info(
                                                  trajin.top, phi_atoms,
                                                  "phi"),
                                              axis=0)
            #
        #

        if re.match("psi", dihedral_class):
            #
            psi_atoms, psi = md.compute_psi(trajin)

            if dihedrals_temp is None:
                #
                dihedrals_temp = np.sin(psi)

                dihedral_ids_temp = extract_res_info(trajin.top, psi_atoms,
                                                     "psi")
            #
            else:
                #
                dihedrals_temp = np.append(dihedrals_temp, np.sin(psi), axis=1)

                dihedral_ids_temp = np.append(dihedral_ids_temp,
                                              extract_res_info(
                                                  trajin.top, psi_atoms,
                                                  "psi"),
                                              axis=0)
            #
        #

        if re.match("chi1", dihedral_class):
            #
            chi1_atoms, chi1 = md.compute_chi1(trajin)

            if dihedrals_temp is None:
                #
                dihedrals_temp = np.sin(chi1)

                dihedral_ids_temp = extract_res_info(trajin.top, chi1_atoms,
                                                     "chi1")
            #
            else:
                #
                dihedrals_temp = np.append(dihedrals_temp,
                                           np.sin(chi1),
                                           axis=1)

                dihedral_ids_temp = np.append(dihedral_ids_temp,
                                              extract_res_info(
                                                  trajin.top, chi1_atoms,
                                                  "chi1"),
                                              axis=0)
            #
        #

        if re.match("chi2", dihedral_class):
            #
            chi2_atoms, chi2 = md.compute_chi2(trajin)

            if dihedrals_temp is None:
                #
                dihedrals_temp = np.sin(chi2)

                dihedral_ids_temp = extract_res_info(trajin.top, chi2_atoms,
                                                     "chi2")
            #
            else:
                #
                dihedrals_temp = np.append(dihedrals_temp,
                                           np.sin(chi2),
                                           axis=1)

                dihedral_ids_temp = np.append(dihedral_ids_temp,
                                              extract_res_info(
                                                  trajin.top, chi2_atoms,
                                                  "chi2"),
                                              axis=0)
            #
        #

        if re.match("chi3", dihedral_class):
            #
            chi3_atoms, chi3 = md.compute_chi3(trajin)

            if dihedrals_temp is None:
                #
                dihedrals_temp = np.sin(chi3)

                dihedral_ids_temp = extract_res_info(trajin.top, chi3_atoms,
                                                     "chi3")
            #
            else:
                #
                dihedrals_temp = np.append(dihedrals_temp,
                                           np.sin(chi3),
                                           axis=1)

                dihedral_ids_temp = np.append(dihedral_ids_temp,
                                              extract_res_info(
                                                  trajin.top, chi3_atoms,
                                                  "chi3"),
                                              axis=0)
            #
        #

        if re.match("chi4", dihedral_class):
            #
            chi4_atoms, chi4 = md.compute_chi4(trajin)

            if dihedrals_temp is None:
                #
                dihedrals_temp = np.sin(chi4)

                dihedral_ids_temp = extract_res_info(trajin.top, chi4_atoms,
                                                     "chi4")
            #
            else:
                #
                dihedrals_temp = np.append(dihedrals_temp,
                                           np.sin(chi4),
                                           axis=1)

                dihedral_ids_temp = np.append(dihedral_ids_temp,
                                              extract_res_info(
                                                  trajin.top, chi4_atoms,
                                                  "chi4"),
                                              axis=0)
            #
        #

        if dihedral_class is None:
            #
            raise Exception(
                "Feature format \"{:s}\" is invalid in a dihedral class measurement context."
                .format(dihedral_class))
        #
    #

    return (dihedrals_temp, dihedral_ids_temp)
import pandas as pd
import mdtraj as md
from dipeptide_parameters import *

reference = pd.read_csv("./experimental_data/baldwin_table1_populations.csv", index_col=0)

data = []
for (ff, water, seq) in products:
    try:
        aa = seq.split("_")[1]
        t = md.load("./dcd/%s_%s_%s.dcd" % (ff, water, seq), top="./pdbs/%s.pdb" % (seq))
    except:
        continue
    phi = md.compute_phi(t)[1][:, 0] * 180 / np.pi
    psi = md.compute_psi(t)[1][:, 0] * 180 / np.pi
    ass = assign(phi, psi)
    populations = pd.Series({"PPII":0.0, "beta":0.0, "alpha":0.0, "other":0.0})
    populations += ass.value_counts(normalize=True)
    data.append([ff, water, aa, populations["PPII"], populations["beta"], populations["alpha"]])

data = pd.DataFrame(data, columns=["ff", "water", "aa", "PPII", "beta", "alpha"])