def _add_sbm_dihedrals(self, Model): structure = Model.mapping if hasattr(Model, "ref_traj"): kd = self._default_parameters["kd"] code = self._default_potentials["dihedral"] for atm1, atm2, atm3, atm4 in structure._dihedrals: idxs = np.array( [[atm1.index, atm2.index, atm3.index, atm4.index]]) phi0 = md.compute_dihedrals(Model.ref_traj, idxs)[0][0] #if temp_phi > 0: # phi0 = 2.*np.pi - temp_phi #else: # phi0 = -temp_phi self._add_dihedral(code, atm1, atm2, atm3, atm4, kd, phi0, 1) self._add_dihedral(code, atm1, atm2, atm3, atm4, 0.5 * kd, phi0, 3) kd = self._default_parameters["ka"] code = self._default_potentials["improper_dihedral"] for atm1, atm2, atm3, atm4 in structure._improper_dihedrals: # How does mdtraj angle correspond to gromacs? idxs = np.array( [[atm1.index, atm2.index, atm3.index, atm4.index]]) phi0 = md.compute_dihedrals(Model.ref_traj, idxs)[0][0] self._add_dihedral(code, atm1, atm2, atm3, atm4, kd, phi0) else: util.missing_reference_warning()
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 main(): parser = argparse.ArgumentParser() parser.add_argument('assignments', default='Macro4/MacroAssignments.h5', help='Path to an assignments file. (default=Macro4/MacroAssignments.h5)') parser.add_argument('--project', default='ProjectInfo.yaml', help='Path to ProjectInfo.yaml file. (default=ProjectInfo.yaml)') args = parser.parse_args() project = Project.load_from(args.project) t = reduce(operator.add, (project.load_traj(i) for i in range(project.n_trajs))) phi_angles = md.compute_dihedrals(t, [PHI_INDICES]) * 180.0 / np.pi psi_angles = md.compute_dihedrals(t, [PSI_INDICES]) * 180.0 / np.pi state_index = np.hstack(io.loadh(args.assignments)['arr_0']) for i in np.unique(state_index): pp.plot(phi_angles[np.where(state_index == i)], psi_angles[np.where(state_index == i)], 'x', label='State %d' % i) pp.title("Alanine Dipeptide Macrostates") pp.xlabel(r"$\phi$") pp.ylabel(r"$\psi$") annotate() pp.legend(loc=1, labelspacing=0.075, prop={'size': 8.0}, scatterpoints=1, markerscale=0.5, numpoints=1) pp.xlim([-180, 180]) pp.ylim([-180, 180]) pp.show()
def test_generator(): N_FRAMES = 2 N_ATOMS = 5 xyz = np.asarray(np.random.randn(N_FRAMES, N_ATOMS, 3), dtype=np.float32) ptraj = md.Trajectory(xyz=xyz, topology=None) quartets = np.array(list(itertools.combinations(range(N_ATOMS), 4)), dtype=np.int32) quartets2 = itertools.combinations(range(N_ATOMS), 4) a = md.compute_dihedrals(ptraj, quartets) b = md.compute_dihedrals(ptraj, quartets2) eq(a, b)
def test_dihedral_1(pymol, tmpdir): xyz = '''MODEL 0 ATOM 1 A ACE 1 4.300 13.100 8.600 1.00 0.00 ATOM 2 B ACE 1 5.200 13.600 8.800 1.00 0.00 ATOM 3 C ACE 1 4.900 14.300 9.600 1.00 0.00 ATOM 4 D ACE 1 5.600 14.200 7.900 1.00 0.00 ''' script = ''' from pymol import cmd with open('output.txt', 'w') as f: f.write('%f' % cmd.get_dihedral('1/A', '1/B', '1/C', '1/D')) ''' prevdir = os.path.abspath('.') try: os.chdir(tmpdir) with open('xyz.pdb', 'w') as f: f.write(xyz) with open('pymolscript.py', 'w') as f: f.write(script) os.system('%s %s -cr %s' % (pymol, 'xyz.pdb', 'pymolscript.py')) with open('output.txt') as f: pymol_value = np.deg2rad(float(f.read())) t = md.load('xyz.pdb') finally: os.chdir(prevdir) mdtraj_value = md.compute_dihedrals(t, [[0, 1, 2, 3]])[0, 0] np.testing.assert_array_almost_equal(pymol_value, mdtraj_value)
def test_VonMisesFeaturizer_describe_features(): feat = VonMisesFeaturizer() rnd_traj = np.random.randint(len(trajectories)) features = feat.transform([trajectories[rnd_traj]]) df = pd.DataFrame(feat.describe_features(trajectories[rnd_traj])) for f in range(25): f_index = np.random.choice(len(df)) atom_inds = df.iloc[f_index].atominds bin_index = int(df.iloc[f_index].otherinfo.strip('bin-')) dihedral_value = md.compute_dihedrals(trajectories[rnd_traj], [atom_inds]) feature_value = [ vm.pdf(i, loc=feat.loc, kappa=feat.kappa)[bin_index] for i in dihedral_value ] assert (features[0][:, f_index] == feature_value).all()
def fix_dihedral(molecule, system, dihedrals): """ Author: Simon Boothroyd impose a dihedral angle constraint so that bonds and angles can change during optimization """ mdtraj_trajectory = mdtraj.Trajectory( xyz=molecule.conformers[0], topology=mdtraj.Topology.from_openmm(molecule.topology.to_openmm()), ) dihedral_angle = mdtraj.compute_dihedrals(mdtraj_trajectory, np.array([dihedrals]))[ 0 ][0].item() dihedral_restraint = openmm.CustomTorsionForce( f"k * min(min(abs(theta - theta_0), abs(theta - theta_0 + 2 * " f"{np.pi})), abs(theta - theta_0 - 2 * {np.pi}))^2" ) dihedral_restraint.addPerTorsionParameter("k") dihedral_restraint.addPerTorsionParameter("theta_0") theta_0 = dihedral_angle k = 1.0 * unit.kilocalories_per_mole / unit.radian ** 2 dihedral_restraint.addTorsion( dihedrals[0], dihedrals[1], dihedrals[2], dihedrals[3], [k, theta_0], ) system.addForce(dihedral_restraint)
def calc_dihedral_energy(self, traj, improper=False, sum=True): """Energy for dihedral interactions Parameters ---------- traj : mdtraj.Trajectory sum : bool (opt.) If sum=True return the total energy. """ phi = md.compute_dihedrals(traj, self._dihedral_idxs) #if improper: # phi = np.pi + md.compute_dihedrals(traj, self._dihedral_idxs) # ? #else: # phi = -temp_phi.copy() # phi[temp_phi > 0] = 2.*np.pi - temp_phi[temp_phi > 0] if sum: Edihedral = np.zeros(traj.n_frames, float) else: Edihedral = np.zeros((traj.n_frames, self.n_dihedrals), float) for i in range(self.n_dihedrals): if sum: Edihedral += self._dihedrals[i].V(phi[:,i]) else: Edihedral[:,i] = self._dihedrals[i].V(phi[:,i]) return Edihedral
def get_phipsi(self, trajs, phi, psi): #phi = [6, 8, 14, 16] #psi = [4, 6, 8, 14] PHI_INDICES = [] PSI_INDICES = [] for i in range(len(phi)): PHI_INDICES.append(self.atom_indices.index(phi[i])) PSI_INDICES.append(self.atom_indices.index(psi[i])) #len_trajs = len(trajs) print("PSI:", PSI_INDICES) print("PHI:", PHI_INDICES) phi_angles = md.compute_dihedrals(trajs, [PHI_INDICES]) * 180.0 / np.pi psi_angles = md.compute_dihedrals(trajs, [PSI_INDICES]) * 180.0 / np.pi #phi_psi=np.column_stack((phi_angles, psi_angles)) #return phi_psi return phi_angles, psi_angles
def partial_transform(self, traj): """Featurize an MD trajectory into a vector space via calculation of dihedral (torsion) angles of alpha carbon backbone Parameters ---------- traj : mdtraj.Trajectory A molecular dynamics trajectory to featurize. Returns ------- features : np.ndarray, dtype=float, shape=(n_samples, n_features) A featurized trajectory is a 2D array of shape `(length_of_trajectory x n_features)` where each `features[i]` vector is computed by applying the featurization function to the `i`th snapshot of the input trajectory. """ ca = [a.index for a in traj.top.atoms if a.name == 'CA'] if len(ca) < 4: return np.zeros((len(traj), 0), dtype=np.float32) alpha_indices = np.array( [(ca[i - 1], ca[i], ca[i+1], ca[i + 2]) for i in range(1, len(ca) - 2)]) result = md.compute_dihedrals(traj, alpha_indices) x = [] if self.atom_indices is None: self.atom_indices = np.vstack(alpha_indices) if self.sincos: x.extend([np.cos(result), np.sin(result)]) else: x.append(result) return np.hstack(x)
def test_no_indices(): for fn in ['2EQQ.pdb', '1bpi.pdb']: for opt in [True, False]: t = md.load(get_fn(fn)) assert md.compute_distances(t, np.zeros((0,2), dtype=int), opt=opt).shape == (t.n_frames, 0) assert md.compute_angles(t, np.zeros((0,3), dtype=int), opt=opt).shape == (t.n_frames, 0) assert md.compute_dihedrals(t, np.zeros((0,4), dtype=int), opt=opt).shape == (t.n_frames, 0)
def DFG_dihedral_byrun(project, runs, def_DFG): dihedral = [] dihedral_combinetrajs = [] print "Working on project %s." % project for run in range(runs): trajectories = dataset.MDTrajDataset( "/cbio/jclab/projects/fah/fah-data/munged2/no-solvent/%d/run%d-clone*.h5" % (project, run)) print "Run %s has %s trajectories." % (run, len(trajectories)) for traj in trajectories: dihedral_combinetrajs.append(md.compute_dihedrals(traj, [def_DFG])) # flatten dihedral_combinetrajs = [ val for sublist in dihedral_combinetrajs for val in sublist ] dihedral.append(dihedral_combinetrajs) dihedral_combinetrajs = [] dihedral = np.asarray([dihedral]) return [dihedral]
def Get_Dihedral(self, atom_indices, periodic=True, newchunk=100, unit='degrees'): ''' Uses MDTraj compute_dihedrals to compute the dihedrals formed by input atom indices in each frame. Input: atom_indices-> An array of shape (num_dihedrals,4) with each row giving indices of four atoms to compute dihedrals for. The angle is between the planes spanned by the first 3 atoms and the last 3 atoms, a torsion around the bond between the middle two atoms. periodic-> If periodic is True and the trajectory contains unitcell information, minimum image convention will be used for dihedrls crossing periodic boundary. unit -> MDTraj default unit is radian. Here by default, angles are returned in degrees. Returns: an array of shape (num_frames, num_dihedrals). ''' dihed_angles = numpy.empty((0, numpy.shape(atom_indices)[0])) #Return array #Reload Trajectory in case user already worked with few/all chunks, working with newchunk frames at a time self.Reload(newchunk=newchunk) s_time = time.clock() for partial_traj in self.traj_iter: partial_dihed = md.compute_dihedrals(partial_traj, atom_indices, periodic=periodic) dihed_angles = numpy.vstack((dihed_angles,partial_dihed)) e_time = time.clock() print "Dihedral Calculation Finished! \nTotal time spent: \n\t%0.2f seconds process time\ \n\tOn average, %0.4f seconds per trajectory frame" % (e_time-s_time, (e_time-s_time)/numpy.array(dihed_angles).shape[0]) if unit.lower() == 'degrees': return numpy.degrees(dihed_angles) else: return dihed_angles
def get_phipsi(self, trajs, phi, psi): #phi = [6, 8, 14, 16] #psi = [4, 6, 8, 14] PHI_INDICES = [] PSI_INDICES = [] for i in xrange(len(phi)): PHI_INDICES.append(self.atom_indices.index(phi[i])) PSI_INDICES.append(self.atom_indices.index(psi[i])) len_trajs = len(trajs) print "PSI:", PSI_INDICES print "PHI:", PHI_INDICES phi_angles = md.compute_dihedrals(trajs, [PHI_INDICES]) * 180.0 / np.pi psi_angles = md.compute_dihedrals(trajs, [PSI_INDICES]) * 180.0 / np.pi #phi_psi=np.column_stack((phi_angles, psi_angles)) #return phi_psi return phi_angles, psi_angles
def test_dihedral_1(): pymol = find_executable('pymol') if pymol is None: raise SkipTest("pymol executable not found") xyz = '''MODEL 0 ATOM 1 A ACE 1 4.300 13.100 8.600 1.00 0.00 ATOM 2 B ACE 1 5.200 13.600 8.800 1.00 0.00 ATOM 3 C ACE 1 4.900 14.300 9.600 1.00 0.00 ATOM 4 D ACE 1 5.600 14.200 7.900 1.00 0.00 ''' script = ''' with open('output.txt', 'w') as f: f.write('%f' % cmd.get_dihedral('1/A', '1/B', '1/C', '1/D')) ''' with enter_temp_directory(): with open('xyz.pdb', 'w') as f: f.write(xyz) with open('pymolscript.py', 'w') as f: f.write(script) os.system('%s %s -cr %s' % (pymol, 'xyz.pdb', 'pymolscript.py')) with open('output.txt') as f: pymol_value = np.deg2rad(float(f.read())) t = md.load('xyz.pdb') mdtraj_value = md.compute_dihedrals(t, [[0,1,2,3]])[0,0] np.testing.assert_array_almost_equal(pymol_value, mdtraj_value)
def check_chirality(traj, threshold=0): """Check whether each chiral amino acid is in the L-configuration at each frame in the trajectory. Parameters ---------- traj : mdtraj.trajectory threshold : angle (in degrees) angles below this threshold will be taken as errors Returns ------- chiral_atoms : list of 4-tuples errors : numpy.ndarray, shape=(len(traj), len(chiral_atoms)), dtype=bool errors[i,j] means there is a chirality error in frame i, quartet j References ---------- [1] Stereochemical errors and their implications for molecular dynamics simulations. Schriener et al., 2011. BMC Bioinformatics. DOI: 10.1186/1471-2105-12-190 http://bmcbioinformatics.biomedcentral.com/articles/10.1186/1471-2105-12-190 """ chiral_atoms = get_chiral_atoms(traj.top) dihedrals = md.compute_dihedrals(traj, chiral_atoms) print(dihedrals) in_degrees = dihedrals * 180 / np.pi errors = in_degrees < threshold return chiral_atoms, errors
def chi1_feat(traj, res): chi1 = traj.topology.select('resid %i and (name C or name CA or name CB or name CG or name SG or name CG1 or name OG or name OG1)' %res) if chi1.shape[0] != 4: return None chi1 = chi1.reshape([1,4]) traj_chi1 = md.compute_dihedrals(traj, chi1) return traj_chi1
def check_cispeptide_bond(traj, dihedral_cutoff=85): """Given a trajectory, check every peptide bond in every frame. Return a boolean array of shape=(len(traj), n_peptide_bonds) Print a warning if any cis-peptide bonds are found Parameters ---------- traj : mdtraj.Trajectory dihedral_cutoff : default 85 Dihedral angle cutoff, in degrees Returns ------- problems : boolean array problems[i,j] means that, in frame i, peptide bond j is cis References ---------- [1] Stereochemical errors and their implications for molecular dynamics simulations. Schriener et al., 2011. BMC Bioinformatics. DOI: 10.1186/1471-2105-12-190 http://bmcbioinformatics.biomedcentral.com/articles/10.1186/1471-2105-12-190 """ indices, residues = find_peptide_bonds(traj.top) angles = md.compute_dihedrals(traj, indices) in_degrees = angles * 180 / np.pi problems = in_degrees > dihedral_cutoff if np.sum(problems) > 0: print('Problems in {0} frames!'.format(sum(problems.sum(1) != 0))) print('Problems in {0} bonds!'.format(sum(problems.sum(0) != 0))) return problems
def sugar_angles_traj(traj, residues=None, angles=None): top = traj.topology # initialize nucleic class nn = nucleic.Nucleic(top) all_idx, rr = nn.get_sugar_torsion_idx(residues) if (angles == None): idx_angles = np.arange(all_idx.shape[1]) else: # find indeces corresponding to angles idx_angles = [] for i in range(len(angles)): if (angles[i] in definitions.sugar_angles): idx_angles.append(definitions.sugar_angles.index(angles[i])) else: msg = "# Fatal error. requested angle \"%s\" not available.\n" % angles[ i] msg += "# Choose from: %s \n" % (definitions.sugar_angles) sys.stderr.write(msg) sys.exit(1) idxs = (all_idx[:, idx_angles, :]).reshape(-1, 4) missing = np.where(np.sum(idxs, axis=1) == 0) torsions = md.compute_dihedrals(traj, idxs, opt=True) # set to NaN where atoms are missing torsions[:, missing[0]] = np.nan torsions = torsions.reshape( (traj.n_frames, all_idx.shape[0], len(idx_angles))) return torsions, rr
def sidechain_example(yaml_file): # Parse a YAML configuration, return as Dict cfg = Settings(yaml_file).asDict() structure = cfg['Structure'] #Select move type sidechain = SideChainMove(structure, [1]) #Iniitialize object that selects movestep sidechain_mover = MoveEngine(sidechain) #Generate the openmm.Systems outside SimulationFactory to allow modifications systems = SystemFactory(structure, sidechain.atom_indices, cfg['system']) #Generate the OpenMM Simulations simulations = SimulationFactory(systems, sidechain_mover, cfg['simulation'], cfg['md_reporters'], cfg['ncmc_reporters']) # Run BLUES Simulation blues = BLUESSimulation(simulations, cfg['simulation']) blues.run() #Analysis import mdtraj as md import numpy as np traj = md.load_netcdf('vacDivaline-test/vacDivaline.nc', top='tests/data/vacDivaline.prmtop') indicies = np.array([[0, 4, 6, 8]]) dihedraldata = md.compute_dihedrals(traj, indicies) with open("vacDivaline-test/dihedrals.txt", 'w') as output: for value in dihedraldata: output.write("%s\n" % str(value)[1:-1])
def DFG_dihedral_states(trajectories,def_DFG): dihedral = [] for traj in trajectories: dihedral.append(md.compute_dihedrals(traj,[def_DFG])) return [dihedral]
def DFG_dihedral_states(trajectories, def_DFG): dihedral = [] for traj in trajectories: dihedral.append(md.compute_dihedrals(traj, [def_DFG])) return [dihedral]
def load_data(self): load_time_start = time.time() data = [] for tfn in self.filenames: kwargs = {} if tfn.endswith('h5') else {'top': self.top} for t in md.iterload(tfn, chunk=self.args.split, **kwargs): item = np.asarray(md.compute_dihedrals(t, self.indices), np.double) data.append(item) return data
def test_dihedral_op(self): """ Create a dihedral order parameter """ psi_atoms = [6,8,14,16] dihedral_op = op.CV_MDTraj_Function("psi", md.compute_dihedrals, indices= [psi_atoms]) md_dihed = md.compute_dihedrals(self.mdtraj, indices=[psi_atoms]) my_dihed = dihedral_op(self.traj) np.testing.assert_allclose(md_dihed.reshape(md_dihed.shape[:-1]), my_dihed, rtol=10**-6, atol=10**-10)
def compute_dihedrals(self, indices): """ :param indices: Each row gives the indices of four atoms which together make a dihedral angle (np.ndarray, shape=(n_dihedrals, 4), dtype=int) :return: dihedrals : np.ndarray, shape=(n_frames, n_dihedrals), dtype=float. The output array gives, in each frame from the trajectory, each of the n_dihedrals torsion angles. The angles are measured in radians """ return md.compute_dihedrals(self.traj, indices)
def calculate_dihedrals(): print("Calculating dihedrals...") traj_files = sorted(glob.glob("traj*xtc")) traj = [ md.load(filename, top='structure.gro') for filename in traj_files ] indices = list(traj[0].topology.select('backbone')) dihedral_quartets = np.array([indices[i:i+4] for i in range(len(indices)-4)]) for i in range(len(traj)): thetas = md.compute_dihedrals(traj[i], dihedral_quartets) cos_sin_dihedrals = np.hstack([np.cos(thetas), np.sin(thetas)]) np.save('out_' + str(i) + '.npy', thetas)
def calculate_rama_energy(self, traj, total=True): """Calculate the one-body burial potential Parameters ---------- traj : mdtraj.Trajectory Trajectory to calculate energy over. sum : opt, bool If true (default) return the sum of the burial potentials. If false, return the burial energy of each individual residue. """ rama = self.potential_forms["RAMA"] pro_rama = self.potential_forms["RAMA_PROLINE"] bb_traj = self.backbone_mapping.map_traj(traj) # where does AWSEM define 0. phi = md.compute_dihedrals(bb_traj, self._phi_idxs) psi = md.compute_dihedrals(bb_traj, self._psi_idxs) if total: Vrama = np.zeros(bb_traj.n_frames, float) else: Vrama = np.zeros((bb_traj.n_frames, self.n_phi + self.n_pro_phi), float) for i in range(self.n_phi): if total: Vrama += rama.V(phi[:, i], psi[:, i]) else: Vrama[:, i] = rama.V(phi[:, i], psi[:, i]) if self.n_pro_phi > 0: pro_phi = md.compute_dihedrals(bb_traj, self._pro_phi_idxs) pro_psi = md.compute_dihedrals(bb_traj, self._pro_psi_idxs) for i in range(self.n_pro_phi): if total: Vrama += pro_rama.V(pro_phi[:, i], pro_psi[:, i]) else: Vrama[:, self.n_phi + i] = pro_rama.V(pro_phi[:, i], pro_psi[:, i]) return Vrama
def transform(self, traj): rad = mdtraj.compute_dihedrals(traj, self.angle_indexes, self.periodic) if self.cossin: rad = np.dstack((np.cos(rad), np.sin(rad))) rad = rad.reshape(rad.shape[0], rad.shape[1] * rad.shape[2]) # convert to degrees if self.deg and not self.cossin: rad = np.rad2deg(rad) return rad
def DFG_dihedral(trajectories,def_DFG): dihedral = [] for traj in trajectories: dihedral.append(md.compute_dihedrals(traj,[def_DFG])) flattened_dihedral = np.asarray([val for sublist in dihedral for val in sublist]) return [flattened_dihedral]
def transform(self, traj): # compute dihedral energy phi = md.compute_dihedrals(traj, self.dihedrals) Edih = np.array(map(lambda x,y: x(y), self.Vdih, phi.T)).T # compute pair energy r = md.compute_distances(traj, self.pairs) Epair = np.array(map(lambda x,y: x(y), self.Vpair, r.T)).T return np.hstack((Edih, Epair))
def DFG_dihedral(trajectories, def_DFG): dihedral = [] for traj in trajectories: dihedral.append(md.compute_dihedrals(traj, [def_DFG])) flattened_dihedral = np.asarray([val for sublist in dihedral for val in sublist]) return [flattened_dihedral]
def compute_torsion(traj, *args): """ Compute the specified torsion. """ indices = [get_atom_index(traj, selection) for selection in args] min_frame = 400 end_frame = len(traj) short_traj = traj.slice(range(min_frame, end_frame), copy=False) # Compute torsion in degrees torsions = md.compute_dihedrals(short_traj, [indices]).squeeze() * (180.0 / np.pi) return torsions
def calculate_rama_energy(self, traj, total=True): """Calculate the one-body burial potential Parameters ---------- traj : mdtraj.Trajectory Trajectory to calculate energy over. sum : opt, bool If true (default) return the sum of the burial potentials. If false, return the burial energy of each individual residue. """ rama = self.potential_forms["RAMA"] pro_rama = self.potential_forms["RAMA_PROLINE"] bb_traj = self.backbone_mapping.map_traj(traj) # where does AWSEM define 0. phi = md.compute_dihedrals(bb_traj, self._phi_idxs) psi = md.compute_dihedrals(bb_traj, self._psi_idxs) if total: Vrama = np.zeros(bb_traj.n_frames, float) else: Vrama = np.zeros((bb_traj.n_frames, self.n_phi + self.n_pro_phi), float) for i in range(self.n_phi): if total: Vrama += rama.V(phi[:,i], psi[:,i]) else: Vrama[:, i] = rama.V(phi[:,i], psi[:,i]) if self.n_pro_phi > 0: pro_phi = md.compute_dihedrals(bb_traj, self._pro_phi_idxs) pro_psi = md.compute_dihedrals(bb_traj, self._pro_psi_idxs) for i in range(self.n_pro_phi): if total: Vrama += pro_rama.V(pro_phi[:,i], pro_psi[:,i]) else: Vrama[:,self.n_phi + i] = pro_rama.V(pro_phi[:,i], pro_psi[:,i]) return Vrama
def test_dihedral_op(self): """ Create a dihedral order parameter """ psi_atoms = [6,8,14,16] dihedral_op = op.CV_MD_Function("psi", md.compute_dihedrals, indices=[psi_atoms]) mdtraj_version = self.storage.trajectories.load(0).md() md_dihed = md.compute_dihedrals(mdtraj_version, indices=[psi_atoms]) traj = self.storage.trajectories.load(0) my_dihed = dihedral_op( traj ) np.testing.assert_allclose(md_dihed, my_dihed)
def test_build_mdtraj_function_cv(self): if not HAS_OPENMM: pytest.skip("Requires OpenMM for ops_load_trajectory") yml = self.yml.format(kwargs=self.kwargs, func="compute_dihedrals") dct = yaml.load(yml, Loader=yaml.FullLoader) cv = MDTRAJ_CV_PLUGIN(dct) assert isinstance(cv, MDTrajFunctionCV) assert cv.func == md.compute_dihedrals md_trj = md.load(self.ad_pdb) ops_trj = paths.engines.openmm.tools.ops_load_trajectory(self.ad_pdb) expected = md.compute_dihedrals(md_trj, indices=[[4, 6, 8, 14]]) npt.assert_array_almost_equal( cv(ops_trj).reshape(expected.shape), expected)
def test_dihedral_op(self): """ Create a dihedral order parameter """ psi_atoms = [6, 8, 14, 16] dihedral_op = op.MDTrajFunctionCV( "psi", md.compute_dihedrals, topology=self.topology, indices=[psi_atoms]) md_dihed = md.compute_dihedrals(self.mdtraj, indices=[psi_atoms]) my_dihed = dihedral_op(self.traj_topology) np.testing.assert_allclose( md_dihed.reshape(md_dihed.shape[:-1]), my_dihed, rtol=10 ** -6, atol=10 ** -10)
def calc_coord(traj, idxs): vals = np.zeros(traj.n_frames) idxs = np.array(idxs) NM_IN_ANG = 10.0 RAD_IN_DEG = 180.0/np.pi if len(idxs) == 2: vals = md.compute_distances(traj, idxs.reshape(1, -1)) vals *= NM_IN_ANG elif len(idxs) == 3: vals = md.compute_angles(traj, idxs.reshape(1, -1)) vals *= RAD_IN_DEG elif len(idxs) == 4: vals = md.compute_dihedrals(traj, idxs.reshape(1, -1)) vals *= RAD_IN_DEG return vals[:, 0]
def parseDihedFile(file, traj): # Get topology top = traj.topology diheds = [] with open(file) as f: for line in f: # for each line from the input file select atoms and # calculate dihed for the trajectory ai = top.select("name " + line) ai = np.array(np.split(ai, ai.shape[0] // 4)) dihed = np.concatenate(md.compute_dihedrals(traj, ai), axis=None) # Append calculated dihedrals to the diheds diheds.append(dihed) diheds = np.array(diheds) np.savetxt("diheds.txt", diheds)
def gln_array(*args): if len(args) == 4: dihedral = np.array([[args[0], args[1], args[2], args[3]]]) gln_dihedral_array = md.compute_dihedrals(traj, dihedral) return gln_dihedral_array elif len(args) == 3: angle = np.array([[args[0], args[1], args[2]]]) gln_angle_array = md.compute_angles(traj, angle) return gln_angle_array else: print( 'The amount of arguments (number of atoms) is not compatible with the selected light state' )
def load_data(self): load_time_start = time.time() data = [] for tfn in self.filenames: kwargs = {} if tfn.endswith('h5') else {'top': self.top} for t in md.iterload(tfn, chunk=self.args.split, **kwargs): item = np.asarray(md.compute_dihedrals(t, self.indices), np.double) data.append(item) print('Loading data into memory + vectorization: %f s' % (time.time() - load_time_start)) print('''Fitting with %s timeseries from %d trajectories with %d total observations''' % (len(data), len(self.filenames), sum(len(e) for e in data))) return data
def label_alanine(traj): ''' use dihedral angles to cluster and label alanine dipeptide ''' # calculating psi and phi angles psi_atoms = [6,8,14,16] phi_atoms = [4,6,8,14] indices = np.asarray([phi_atoms,psi_atoms]) dihedrals = md.compute_dihedrals(traj,indices) # print(dihedrals) trans_di = np.transpose(dihedrals) # print(trans_di) plt.scatter(trans_di[0],trans_di[1]) plt.xlabel('phi') plt.ylabel('psi') plt.savefig("/output/tempplot") # deal with the periodical condition: manually put same cluster together def shift_phi(x): if x>2.2: return -2*np.pi+x else: return x def shift_psi(x): if x<-2.2: return 2*np.pi+x else: return x dihedrals_shift = np.asarray( [np.vectorize(shift_phi)(trans_di[0]), np.vectorize(shift_psi)(trans_di[1])]) # print(trans_di) plt.figure() plt.scatter(dihedrals_shift[0],dihedrals_shift[1]) plt.xlabel('phi') plt.ylabel('psi') plt.savefig("/output/tempplot1") print(dihedrals.shape) print(dihedrals_shift.shape) # do clustering with given initial centers centers = np.array([[55,48],[-77,138],[-77, -39],[60, -72]])*np.pi/180.0 clu = kmeans(n_clusters=4,init=centers) # labels = clu.fit_predict(dihedrals) labels = clu.fit_predict(np.transpose(dihedrals_shift)) labels = print("centers:") print(clu.cluster_centers_*180.0/np.pi) return labels
def dihedral_making(trajectories, dihedral_indices): dihedral = [] for traj in trajectories: dihedral.append(md.compute_dihedrals(traj, [dihedral_indices])) flattened_dihedral = np.asarray([val for sublist in dihedral for val in sublist]) # import math # flattened_dihedral_rotate = [A-(2*math.pi) if A >= 1.9 else A for A in flattened_dihedral] flattened_dihedral = [A for A in flattened_dihedral] # return flattened_dihedral_rotate return flattened_dihedral
def test_DihedralFeaturizer_describe_features_nosincos(): feat = DihedralFeaturizer(sincos=False) rnd_traj = np.random.randint(len(trajectories)) features = feat.transform([trajectories[rnd_traj]]) df = pd.DataFrame(feat.describe_features(trajectories[rnd_traj])) for f in range(25): f_index = np.random.choice(len(df)) atom_inds = df.iloc[f_index].atominds feature_value = md.compute_dihedrals(trajectories[rnd_traj], [atom_inds]) if feat.sincos: func = getattr(np, '%s' % df.iloc[f_index].otherinfo) feature_value = func(feature_value) assert (features[0][:, f_index] == feature_value.flatten()).all()
def test_VonMisesFeaturizer_describe_features(): feat = VonMisesFeaturizer() rnd_traj = np.random.randint(len(trajectories)) features = feat.transform([trajectories[rnd_traj]]) df = pd.DataFrame(feat.describe_features(trajectories[rnd_traj])) for f in range(25): f_index = np.random.choice(len(df)) atom_inds = df.iloc[f_index].atominds bin_index = int(df.iloc[f_index].otherinfo.strip('bin-')) dihedral_value = md.compute_dihedrals(trajectories[rnd_traj], [atom_inds]) feature_value = [vm.pdf(i, loc=feat.loc, kappa=feat.kappa)[bin_index] for i in dihedral_value] assert (features[0][:, f_index] == feature_value).all()
def DFG_dihedral_byrun(files,def_DFG): # Since we are going to sort files by where they are in first frame of clone0 # we can only analyze trajectories with a clone0 present. path_base = files.split('*')[0] clone0_files = "%s/*clone0.h5" % path_base globfiles = glob(clone0_files) runs_list = [] for filename in globfiles: run_string = re.search('run([^-]+)',filename).group(1) run = int(run_string) if run not in runs_list: runs_list.append(run) runs_list.sort() dihedral = [] dihedral_combinetrajs = [] for run in runs_list: trajectories = dataset.MDTrajDataset("%s/run%d-*.h5" % (path_base,run)) print "Run %s has %s trajectories." % (run,len(trajectories)) for traj in trajectories: dihedral_combinetrajs.append(md.compute_dihedrals(traj,[def_DFG])) # flatten dihedral_combinetrajs = [val for sublist in dihedral_combinetrajs for val in sublist] dihedral.append(dihedral_combinetrajs) dihedral_combinetrajs = [] dihedral = np.asarray([dihedral]) return [dihedral]
def DFG_dihedral_byrun(project,runs,def_DFG): dihedral = [] dihedral_combinetrajs = [] print "Working on project %s." % project for run in range(runs): trajectories = dataset.MDTrajDataset("/cbio/jclab/projects/fah/fah-data/munged2/no-solvent/%d/run%d-clone*.h5" % (project,run)) print "Run %s has %s trajectories." % (run,len(trajectories)) for traj in trajectories: dihedral_combinetrajs.append(md.compute_dihedrals(traj,[def_DFG])) # flatten dihedral_combinetrajs = [val for sublist in dihedral_combinetrajs for val in sublist] dihedral.append(dihedral_combinetrajs) dihedral_combinetrajs = [] dihedral = np.asarray([dihedral]) return [dihedral]
x = [eps[i][2] for i in range(len(eps))] plt.scatter(x , np.absolute(deltaDist)) plt.savefig('fig1.png') plt.show() #################################################################################################################### # calculating dihedrals #################################################################################################################### top1 = md.load('3SN6-R.pdb').topology top2 = md.load('2RH1.pdb').topology dhdrls101 = [] dhdrls102 = [] dhdrls201 = [] dhdrls202 = [] for i in range(len(eps)): atoms101 = top1.select("type == C and resid " + str(eps[i][0])) atoms102 = top1.select("type == C and resid " + str(eps[i][1])) atoms201 = top2.select("type == C and resid " + str(eps[i][0])) atoms202 = top2.select("type == C and resid " + str(eps[i][1])) dhdrl101 = md.compute_dihedrals(t1, atoms101) dhdrl102 = md.compute_dihedrals(t1, atoms102) dhdrl201 = md.compute_dihedrals(t2, atoms201) dhdrl202 = md.compute_dihedrals(t2, atoms202) dhdrls101.append(dhdrl101) dhdrls102.append(dhdrl102) dhdrls201.append(dhdrl201) dhdrls202.append(dhdrl202)
def psi_feat(traj, res): psi = traj.topology.select('(resid %i and (name N or name CA or name C)) or (resid %i and name N)' %(res, res + 1)) psi = psi.reshape([1,4]) traj_psi = md.compute_dihedrals(traj, psi) return traj_psi
with open('reweight.txt') as file: lines = file.readlines() for i in range(len(lines)): lines[i] = lines[i].strip() lines[i] = lines[i].split() lines[i][0] = int(lines[i][0]) lines[i][1] = float(lines[i][1]) x_ticks = [''.join(choices[i][0]) for i in range(len(choices))] dihedrals = [] for i in range(len(traj)): dihedrals.append(md.compute_dihedrals(traj[i], np.asarray(indices))) best_dihedrals = [] results = [0]*len(choices) for i in range(len(dihedrals)): # each trajectory for j in range(len(dihedrals[i])): # each frame best_dihedrals = [] for k in range(len(dihedrals[i][j])): # each angle if dihedrals[i][j][k] >= -1.57 and dihedrals[i][j][k] < 1.57: best_dihedrals.append("c") elif dihedrals[i][j][k] < -1.57 or dihedrals[i][j][k] >= 1.57: best_dihedrals.append("t") for k in range(len(choices)): if best_dihedrals in choices[k]: results[k] += 1000**lines[i][1]
# Parse a YAML configuration, return as Dict cfg = Settings('sidechain_cuda.yaml').asDict() structure = cfg['Structure'] #Select move type sidechain = SideChainMove(structure, [1]) #Iniitialize object that selects movestep sidechain_mover = MoveEngine(sidechain) #Generate the openmm.Systems outside SimulationFactory to allow modifications systems = SystemFactory(structure, sidechain.atom_indices, cfg['system']) #Generate the OpenMM Simulations simulations = SimulationFactory(systems, sidechain_mover, cfg['simulation'], cfg['md_reporters'], cfg['ncmc_reporters']) # Run BLUES Simulation blues = BLUESSimulation(simulations, cfg['simulation']) blues.run() #Analysis import mdtraj as md import numpy as np traj = md.load_netcdf('vacDivaline-test/vacDivaline.nc', top='tests/data/vacDivaline.prmtop') indicies = np.array([[0, 4, 6, 8]]) dihedraldata = md.compute_dihedrals(traj, indicies) with open("vacDivaline-test/dihedrals.txt", 'w') as output: for value in dihedraldata: output.write("%s\n" % str(value)[1:-1])
def map(self, traj): rad = mdtraj.compute_dihedrals(traj, self.dih_indexes) if self.deg: return np.rad2deg(rad) else: return rad