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$')
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 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
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)
def test_von_mises_featurizer_2(): trajectories = MinimalFsPeptide().get_cached().trajectories # test to make sure results are being put in the right order feat = VonMisesFeaturizer(["phi", "psi"], n_bins=10) _, all_phi = compute_phi(trajectories[0]) X_all = feat.transform(trajectories) all_res = [] for frame in all_phi: for dihedral_value in frame: all_res.extend(vm.pdf(dihedral_value, loc=feat.loc, kappa=feat.kappa)) print(len(all_res)) # this checks 10 random dihedrals to make sure that they appear in the right columns # for the vonmises bins n_phi = all_phi.shape[1] for k in range(5): # pick a random phi dihedral rndint = np.random.choice(range(n_phi)) # figure out where we expect it to be in X_all indices_to_expect = [] for i in range(10): indices_to_expect += [n_phi * i + rndint] # we know the results in all_res are dihedral1(bin1-bin10) dihedral2(bin1 to bin10) # we are checking if X is alldihedrals(bin1) then all dihedrals(bin2) expected_res = all_res[rndint * 10:10 + rndint * 10] assert (np.array( [X_all[0][0, i] for i in indices_to_expect]) == expected_res).all()
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 ) )
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)
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=', ')
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
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
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
def test_von_mises_featurizer_2(): trajectories = MinimalFsPeptide().get_cached().trajectories # test to make sure results are being put in the right order feat = VonMisesFeaturizer(["phi", "psi"], n_bins=10) _, all_phi = compute_phi(trajectories[0]) X_all = feat.transform(trajectories) all_res = [] for frame in all_phi: for dihedral_value in frame: all_res.extend( vm.pdf(dihedral_value, loc=feat.loc, kappa=feat.kappa)) print(len(all_res)) # this checks 10 random dihedrals to make sure that they appear in the right columns # for the vonmises bins n_phi = all_phi.shape[1] for k in range(5): # pick a random phi dihedral rndint = np.random.choice(range(n_phi)) # figure out where we expect it to be in X_all indices_to_expect = [] for i in range(10): indices_to_expect += [n_phi * i + rndint] # we know the results in all_res are dihedral1(bin1-bin10) dihedral2(bin1 to bin10) # we are checking if X is alldihedrals(bin1) then all dihedrals(bin2) expected_res = all_res[rndint * 10:10 + rndint * 10] assert (np.array([X_all[0][0, i] for i in indices_to_expect]) == expected_res).all()
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 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')
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)
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]))
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
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
def test_von_mises_featurizer(): dataset = fetch_alanine_dipeptide() trajectories = dataset["trajectories"] featurizer = VonMisesFeaturizer(["phi"], n_bins=18) X_all = featurizer.transform(trajectories) n_frames = trajectories[0].n_frames assert X_all[0].shape == (n_frames, 18), ("unexpected shape returned: (%s, %s)" % X_all[0].shape) featurizer = VonMisesFeaturizer(["phi", "psi"], n_bins=18) X_all = featurizer.transform(trajectories) n_frames = trajectories[0].n_frames assert X_all[0].shape == (n_frames, 36), ("unexpected shape returned: (%s, %s)" % X_all[0].shape) featurizer = VonMisesFeaturizer(["phi", "psi"], n_bins=10) X_all = featurizer.transform(trajectories) assert X_all[0].shape == (n_frames, 20), ("unexpected shape returned: (%s, %s)" % X_all[0].shape) dataset = fetch_fs_peptide() trajectories = dataset["trajectories"][0] #test to make sure results are being put in the right order feat = VonMisesFeaturizer(["phi", "psi"], n_bins=10) _, all_phi = compute_phi(trajectories[0]) X_all = feat.transform([trajectories]) all_res = [] for frame in all_phi: for dihedral_value in frame: all_res.extend( vm.pdf(dihedral_value, loc=feat.loc, kappa=feat.kappa)) print(len(all_res)) #this checks 10 random dihedrals to make sure that they appear in the right columns #for the vonmises bins n_phi = all_phi.shape[1] for k in range(5): #pick a random phi dihedral rndint = np.random.choice(range(n_phi)) #figure out where we expect it to be in X_all indices_to_expect = [] for i in range(10): indices_to_expect += [n_phi * i + rndint] #we know the results in all_res are dihedral1(bin1-bin10) dihedral2(bin1 to bin10) # we are checking if X is alldihedrals(bin1) then all dihedrals(bin2) expected_res = all_res[rndint * 10:10 + rndint * 10] assert (np.array([X_all[0][0, i] for i in indices_to_expect]) == expected_res).all()
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
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)
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')
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'])
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 test_dihedral_2chains(get_fn): # make sure that comput_phi is finding dihedrals from all of the chains # in a multi-chain topology t = md.load_pdb(get_fn('4OH9.pdb')) # remove the water water_indices = [a.index for a in t.top.atoms if a.residue.name != 'HOH'] t.restrict_atoms(water_indices) # okay we've got two protein chains assert t.top.n_chains == 2 phi_indices, angles = md.compute_phi(t) for chain in t.top.chains: chain_indices = [a.index for a in chain.atoms] # assert that at least one of the phi_indices involves atoms in this chain assert any(i in chain_indices for i in np.concatenate(phi_indices))
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
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
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)
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)
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 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_))
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
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]
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)
def test_backbone_phi_dihedrals(): # Make sure backbone phi dihedrals are correct molecule = CGMolecule(names=names, resseq=resseq, resmap=resmap) traj = molecule.make_trajectory(data) _, mdtraj_phis = md.compute_phi(traj) mdtraj_phis = np.abs(mdtraj_phis) # manual calculation of phi angles phis = [] for frame_data in data: dihed_list = [] for i in range(residues): # we get the phi's by starting at the 'N', which is the first # bead for every residue a = frame_data[i * 3] b = frame_data[i * 3 + 1] c = frame_data[i * 3 + 2] # the last bead in the phi dihedral is the 'N' of the next residue d = frame_data[i * 3 + 3] 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)) phis.append(dihed_list) phis = np.abs(phis) np.testing.assert_allclose(mdtraj_phis, phis, rtol=1e-4)
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)
def compute_phi_psi(trj): #computes phi and psi phi=md.compute_phi(trj) psi=md.compute_psi(trj) return phi[1], psi[1]
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
def calc_phi(traj): # phi: 1 ~ nres-1 _, phi = md.compute_phi(traj) # phi in rand return phi[0] * 180 / np.pi
import mdtraj as md traj = md.load("frame0.h5") # From mdtraj/MDTraj/testing/reference/ indices, phi = md.compute_phi(traj) plot(phi) title("Phi Backbone Angle") xlabel("Timestep") ylabel("Phi [degrees]") savefig("./phi.png", bbox_inches=None)
parser.add_argument("-b","--opt",dest="opt",action="store_true",default=False,help="toggle bins optimization") # 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()
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))
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"])
def funcception(trj): return compute_phi(trj)[1]