def test_slice(self): traj1 = TrajectoryIterator(filename="data/Tc5b.x", top="./data/Tc5b.top") frame_indices = slice(9, 6, -1) traj0 = pt.load(filename="./data/Tc5b.x", top=pt.load_topology("./data/Tc5b.top"), frame_indices=frame_indices) aa_eq(traj0[0].xyz, traj1[9].xyz) aa_eq(traj0[1].xyz, traj1[8].xyz) aa_eq(traj0[2].xyz, traj1[7].xyz) assert traj0[0].rmsd(traj1[9]) < 1E-4 rmsdlist = [] ref = traj1[0].copy() for frame in traj1: rmsdlist.append(frame.rmsd(ref)) nparr = np.array(rmsdlist) # make sure we don't suport other frame_indices traj2 = Trajectory() traj2 = pt.load( filename="./data/Tc5b.x", top=pt.load_topology("./data/Tc5b.top"), frame_indices=list(range(4)) + list(range(9, 5, -1)) + [4, ]) aa_eq(traj2[-1].xyz, traj1[4].xyz)
def test_1(self): # status: OK from pytraj.compat import zip # note: use `load` instead of `iterload` traj = pt.load("./data/tz2.ortho.nc", "./data/tz2.ortho.parm7") traj.autoimage() traj.rmsfit(mask='@CA,C,N') saved_traj = pt.load('data/tz2.autoimage_with_rmsfit.nc', traj.top) # PASSED aa_eq(saved_traj.xyz, traj.xyz)
def test_0(self): # NOTE: no assert, just check for segfault traj = pt.load("./data/Tc5b.x", "./data/Tc5b.top") trajiter = pt.load("./data/Tc5b.x", "./data/Tc5b.top") atm = traj.top("@CA") f0 = traj[5] f0 = traj[0] f0.top = traj.top f0['@CA'] traj[0, '@CA'] f0 = traj[0, '@CA'] f1 = traj['@CA'][0] assert pt.tools.rmsd(f0.xyz, f1.xyz) == 0.0
def test_coordinates_meta(): from mdtraj.testing import get_fn fn, tn = [get_fn('frame0.pdb'),] * 2 trajs = [pt.load(fn, tn), md.load(fn, top=tn), pmd.load_file(tn, fn)] N_FRAMES = trajs[0].n_frames from MDAnalysis import Universe u = Universe(tn, fn) trajs.append(Universe(tn, fn)) views = [nv.show_pytraj(trajs[0]), nv.show_mdtraj(trajs[1]), nv.show_parmed(trajs[2])] views.append(nv.show_mdanalysis(trajs[3])) for index, (view, traj) in enumerate(zip(views, trajs)): view.frame = 3 nt.assert_equal(view.trajlist[0].n_frames, N_FRAMES) nt.assert_equal(len(view.trajlist[0].get_coordinates_dict().keys()), N_FRAMES) if index in [0, 1]: # pytraj, mdtraj if index == 0: aa_eq(view.coordinates[0], traj.xyz[3], decimal=4) else: aa_eq(view.coordinates[0],10*traj.xyz[3], decimal=4) view.coordinates = traj.xyz[2]
def test_real_box(self): traj = pt.load("./data/tz2.ortho.nc", "data/tz2.ortho.parm7") trajiter = pt.iterload("./data/tz2.ortho.nc", "data/tz2.ortho.parm7") saved_box = Box([3.94559740E+01, 4.68215170E+01, 4.04695410E+01, 90., 90., 90.]) aa_eq(traj.top.box.values, saved_box.values) for frame in traj: assert frame.box.type == 'ortho' aa_eq(frame.box.values, [ 35.2627796623, 41.8455476799, 36.168629529, 90.0, 90.0, 90.0 ], decimal=1) arr0 = traj.unitcells arr1 = trajiter.unitcells for b0, b1, frame in zip(arr0, arr1, trajiter): box = frame.box # FIXME: # python3) b2 = box.values aa_eq(b0, b1) aa_eq(b0, b2) # test assign Box with list/tuple b = Box(saved_box.values) b2 = Box((t for t in saved_box.values)) aa_eq(b.values, saved_box.values, decimal=7) aa_eq(b2.values, saved_box.values, decimal=7) # assign frame.box with list/tuple frame.box = b.values b3 = frame.box aa_eq(b3.values, saved_box.values, decimal=7)
def test_rmsfit_with_autoimage_compared_to_cpptraj(self): # assert to cpptraj: need to set mass traj = self.traj.copy() txt = ''' parm {0} trajin {1} autoimage rms first {2} mass trajout tmp.nc '''.format(traj.top.filename, traj.filename, self.mask) with tempfolder(): state = pt.datafiles.load_cpptraj_output(txt, dtype='state') state.run() # need to load to memory (not iterload) saved_traj = pt.load('tmp.nc', traj.top) fa1 = traj[:] fa1.autoimage() pt.superpose(fa1, ref=0, mask=self.mask, mass=True) aa_eq(fa1.xyz, saved_traj.xyz) fa_saved_nowat = saved_traj['!:WAT'] fa1_nowat = fa1['!:WAT'] aa_eq(fa_saved_nowat.xyz, fa1_nowat.xyz)
def test_add_trajectory(): view = nv.NGLWidget() def update_coords(view=view): view.frame = 1000 view.frame = 0 p_traj = pt.load(nv.datafiles.TRR, nv.datafiles.PDB) view.add_trajectory(p_traj) m_traj = md.load(nv.datafiles.XTC, top=nv.datafiles.PDB) view.add_trajectory(m_traj) # trigger updating coordinates update_coords() assert len(view.coordinates_dict.keys()) == 2 if has_MDAnalysis: from MDAnalysis import Universe mda_traj = Universe(nv.datafiles.PDB, nv.datafiles.TRR) view.add_trajectory(mda_traj) update_coords() assert len(view.coordinates_dict.keys()) == 3 if has_HTMD: from htmd import Molecule htmd_traj = Molecule(nv.datafiles.PDB) htmd_traj.filter('protein') view.add_trajectory(htmd_traj) update_coords() if has_MDAnalysis: assert len(view.coordinates_dict.keys()) == 4 else: assert len(view.coordinates_dict.keys()) == 3
def test_projection_for_pca(self): traj = pt.load("./data/tz2.nc", "./data/tz2.parm7") state = pt.load_cpptraj_state(command) state.run() cpp_modes = state.data['MyEvecs'] cpp_arr_crd = np.array(cpp_modes._get_avg_crd()) cpp_arr_crd = cpp_arr_crd.reshape(117, 3) mask = '!@H=' pt.superpose(traj, mask=mask) avg = pt.mean_structure(traj) atom_indices = traj.top(mask).indices strip_avg_coords = avg.xyz[atom_indices] pt.superpose(traj, mask=mask, ref=avg) avg2 = pt.mean_structure(traj, mask=mask) mat = pt.matrix.covar(traj, mask) modes = pt.matrix.diagonalize(mat, n_vecs=2, dtype='dataset')[0] aa_eq(cpp_arr_crd, avg2.xyz) aa_eq(np.abs(modes.eigenvalues), np.abs(state.data['MyEvecs'].eigenvalues)) aa_eq(np.abs(modes.eigenvectors), np.abs(state.data['MyEvecs'].eigenvectors)) projection_data = pt.all_actions.projection(traj, mask=mask, average_coords=avg2.xyz, eigenvalues=modes.eigenvalues, eigenvectors=modes.eigenvectors, scalar_type='covar') aa_eq(np.abs(projection_data), np.abs(state.data[-2:].values), decimal=3)
def test_GB_QMMM(self): # compare to saved test: GB + QMMM topfile = os.path.join(amberhome, "test/qmmm2/lysine_PM3_qmgb2/prmtop") rstfile = os.path.join(amberhome, "test/qmmm2/lysine_PM3_qmgb2/lysine.crd") traj = pt.load(rstfile, topfile) options = sander.gas_input(1) options.cut = 99.0 options.ifqnt = 1 qm_options = sander.qm_input() qm_options.iqmatoms[:3] = [8, 9, 10] qm_options.qm_theory = "PM3" qm_options.qmcharge = 0 qm_options.qmgb = 2 qm_options.adjust_q = 0 edict = pt.energy_decomposition(traj=traj, mm_options=options, qm_options=qm_options) assert_close(edict['bond'][0], 0.0016, tol=3E-4) assert_close(edict['vdw'][0], 0.1908, tol=3E-4) assert_close(edict['vdw_14'][0], 3.7051, tol=3E-4) assert_close(edict['elec'][0], -4.1241, tol=3E-4) assert_close(edict['elec_14'][0], 65.9137, tol=3E-4) assert_close(edict['gb'][0], -80.1406, tol=3E-4) assert_close(edict['scf'][0], -11.9100, tol=3E-4)
def test_component_for_duck_typing(): view = NGLWidget() traj = pt.load(nv.datafiles.PDB) view.add_component(get_fn('tz2.pdb')) view.add_component(get_fn('tz2_2.pdb.gz')) view.add_trajectory(nv.PyTrajTrajectory(traj)) view.component_0.add_representation('cartoon') c0 = view[0] c1 = view[1] assert hasattr(view, 'component_0') assert hasattr(view, 'component_1') assert hasattr(view, 'trajectory_0') assert hasattr(view.trajectory_0, 'n_frames') assert hasattr(view.trajectory_0, 'get_coordinates') assert hasattr(view.trajectory_0, 'get_structure_string') c0.show() c0.hide() view.remove_component(c0.id) assert not hasattr(view, 'component_2') # negative indexing assert view[-1]._index == c1._index
def test_0(self): # TrajectoryIterrator # status: failed from pytraj.compat import zip traj = pt.iterload("./data/tz2.ortho.nc", "./data/tz2.ortho.parm7") pt.write_traj("./output/tz2.autoimage_with_rmsfit.nc", traj(autoimage=True, rmsfit=(0, '@CA,C,N')), overwrite=True) saved_traj = pt.load('data/tz2.autoimage_with_rmsfit.nc', traj.top) p_traj = pt.load('./output/tz2.autoimage_with_rmsfit.nc', traj.top) aa_eq(saved_traj.xyz, p_traj.xyz) for f1, f2 in zip(p_traj, saved_traj): pass
def test_PME_QMMM(self): # compare to saved test: PME + QMMM topfile = os.path.join(amberhome, "test/qmmm2/MechEm_nma-spcfwbox/prmtop") rstfile = os.path.join(amberhome, "test/qmmm2/MechEm_nma-spcfwbox/inpcrd") traj = pt.load(rstfile, topfile) options = sander.pme_input() options.cut = 8.0 options.ifqnt = 1 options.jfastw = 4 qm_options = sander.QmInputOptions() qm_options.qm_theory = "PDDG-PM3" qm_options.qmmask = ":1-2" qm_options.qmcharge = 0 qm_options.scfconv = 1e-10 qmmm_tight_p_conv = 1 qm_options.qmmm_int = 5 edict = pt.energy_decomposition(traj=traj, mm_options=options, qm_options=qm_options) assert_close(edict['bond'][0], 605.7349, tol=3E-4) assert_close(edict['vdw_14'][0], 0.0000, tol=3E-4) assert_close(edict['elec_14'][0], 0.0000, tol=3E-4) assert_close(edict['elec'][0], -7409.7167, tol=3E-1) assert_close(edict['scf'][0], -37.1277, tol=3E-4)
def test_constructor_from_command_list_Trajectory(self): '''mutable Trajectory''' # use `load` method rather `iterload` traj = pt.load("data/tz2.ortho.nc", "data/tz2.ortho.parm7") # make sure no space-sensitivity # make the code (commands) ugly is my intention. commands = [ 'autoimage ', 'autoimage', 'rmsd @CA', 'distance :3 :7', 'distance :3 :7', 'vector :2 :3', ' distance :3 :7', 'rms @C,N,O', ] dslist = CpptrajDatasetList() actlist = ActionList(commands, traj.top, dslist=dslist) for frame in traj: actlist.compute(frame) aa_eq(pt.rmsd(traj, mask='@CA'), dslist[0]) aa_eq(pt.distance(traj, ':3 :7'), dslist[1]) aa_eq(pt.distance(traj, ':3 :7'), dslist[2]) # do not need to perform rmsfit again. aa_eq(pt.vector.vector_mask(traj, ':2 :3'), dslist[3].values) aa_eq(pt.distance(traj, ':3 :7'), dslist[4]) aa_eq(pt.rmsd(traj, mask='@C,N,O'), dslist[5])
def test_buffer_not_c_contiguous(self): # source code was lightly adapted from jmborr # https://github.com/Amber-MD/pytraj/issues/991 traj = pt.load('data/issue991/short.dcd', 'data/issue991/pdb.gz', mask='(!:1-256)&(@H1,@H2,@H3,@H4,@H5)') # Trajectory of the center of mass of the first two residues minitraj = np.empty((2, traj.n_frames, 3)) minitraj[0] = pt.center_of_mass(traj, mask=':1') minitraj[1] = pt.center_of_mass(traj, mask=':2') minitraj = minitraj.transpose((1, 0, 2)) # "topology" using the first two atoms minitop = traj.top['@1,2'] # Save trajectory # make sure there is no ValueError # something is wrong with pdb, crd extension when loading with # minitop (poor topology?) # make issue in cpptraj too? for ext in ['nc', 'dcd', 'mdcrd', 'crd', 'pdb', 'trr']: fn = 'output/junk.' + ext pt.write_traj(filename=fn, traj=minitraj, top=minitop, overwrite=True) # load coord back to make sure we correctly write it new_traj = pt.iterload(fn, minitop) # mdcrd, crd, pdb has only 3 digits after decimal decimal = 5 if ext in ['nc', 'dcd', 'trr'] else 3 aa_eq(minitraj, new_traj.xyz, decimal=decimal)
def __init__(self, top=None, restart=None, reference=None): self.top = top assert os.path.exists(restart), '{} must exists'.format(restart) assert os.path.exists(reference), '{} must exists'.format(reference) self.restart = restart self.reference_traj = pt.load(reference, top=self.top) self.thread = None self.event = None
def test_pca_with_ref_with_different_mask_from_matrix(self): '''has reference. Use !@H= for ref_mask and use * for covariance matrix and projection from drroe: "You should be able to supply separate masks for fitting and creating the covariance matrix It is common enough for example to only perform rms-fitting on heavy atoms while still wanting all atoms in eigenvectors." pytraj: pt.pca(traj, mask=mask_matrix, n_vecs=2, ref=ref, ref_mask=mask_ref) ''' command_ref_provided = ''' parm data/tz2.parm7 trajin data/tz2.nc reference data/tz2.rst7 # only perform fitting on heavy atoms rms reference !@H= # all atoms matrix covar name MyMatrix * createcrd CRD1 run # Step three. Diagonalize matrix. runanalysis diagmatrix MyMatrix vecs 2 name MyEvecs # Step four. Project saved fit coordinates along eigenvectors 1 and 2 # all atoms crdaction CRD1 projection evecs MyEvecs * out project.dat beg 1 end 2 ''' traj = pt.load("data/tz2.nc", "data/tz2.parm7") ref = pt.load('data/tz2.rst7', traj.top) state = pt.load_cpptraj_state(command_ref_provided) state.run() mask_ref = '!@H=' mask_matrix = '*' data = pt.pca(traj, mask=mask_matrix, n_vecs=2, ref=ref, ref_mask=mask_ref) cpp_data = state.data[-2:].values # use absolute values aa_eq(np.abs(data[0]), np.abs(cpp_data), decimal=3)
def test_center(self): traj = pt.iterload("./data/tz2.ortho.nc", "./data/tz2.ortho.parm7") saved_traj = pt.load("./data/tz2.center_mass.nc", traj.top) fa = traj[:] pt.center(fa, mask=':1', mass=True) aa_eq(fa.xyz, fa.xyz, decimal=5) # raise if center not in 'origin', 'box' self.assertRaises(ValueError, lambda: pt.center(fa, center='oh'))
def test_run_0(self): # load traj farray = pt.load(filename="./data/tz2.truncoct.nc", top="./data/tz2.truncoct.parm7")[:2] fold = farray.copy() act = allactions.Action_Image() ptrajin = """ center :2-11 image center familiar com :6 """ # create 'strip' action stripact = allactions.Action_Strip() # creat datasetlist to hold distance data dsetlist = CpptrajDatasetList() dflist = DataFileList() # creat ActionList to hold actions alist = ActionList() top = farray.top # add two actions: Action_Strip and Action_Distance alist.add(allactions.Action_Center(), ArgList(":2-11"), top=top) alist.add(allactions.Action_Image(), ArgList("center familiar com :6"), top=top) # do checking alist.check_topology(top) farray2 = Trajectory() frame0 = Frame() # testing how fast to do the actions # loop all frames # use iterator to make faster loop # don't use "for i in range(farray.n_frames)" for frame in farray: # perform actions for each frame # we make a copy since we want to keep orginal Frame frame0 = frame.copy() alist.compute(frame0) # we need to keep the modified frame in farray2 farray2.append(frame0) # make sure that Action_Strip does its job in stripping assert farray2.n_frames == farray.n_frames fsaved = pt.iterload(cpptraj_test_dir + "/Test_Image/image4.crd.save", "data/tz2.truncoct.parm7") assert fsaved.n_frames == 2
def _update(event): start = time.time() while time.time() - start <= timeout and not event.is_set(): time.sleep(every) traj = pt.load(self.restart, top=self.top) if callback is not None: callback(traj) else: mask = '@C,N,O,CA,P' pt.superpose(traj, mask=mask, ref=self.reference_traj) self._update_coordinates(traj[0].xyz)
def test_ComparetoMDtraj(self): import mdtraj as md traj = pt.load(filename="./data/Tc5b.x", top="./data/Tc5b.top") m_top = md.load_prmtop("./data/Tc5b.top") m_traj = md.load_mdcrd("./data/Tc5b.x", m_top) m_traj.xyz = m_traj.xyz * 10 # convert `nm` to `Angstrom` unit arr0 = pt.rmsd(traj, ref=0) arr1 = pt.rmsd(traj, ref=0) arr2 = pt.rmsd(traj, ) a_md0 = md.rmsd(m_traj, m_traj, 0) aa_eq(arr0, arr1) aa_eq(arr0, arr2) aa_eq(arr0, a_md0) arr0 = pt.rmsd(traj, ref=-1) arr1 = pt.rmsd(traj, ref=-1) a_md = md.rmsd(m_traj, m_traj, -1) aa_eq(arr0, arr1) aa_eq(arr0, a_md) mask = ":3-18@CA,C" atm = traj.top(mask) arr0 = pt.rmsd(traj, ref=-1, mask=mask) arr1 = pt.rmsd(traj, mask=atm.indices, ref=-1) arr2 = pt.rmsd(traj, mask=list(atm.indices), ref=-1) arr3 = pt.rmsd(traj, mask=tuple(atm.indices), ref=-1) a_md = md.rmsd(m_traj, m_traj, -1, atm.indices) aa_eq(arr0, a_md) aa_eq(arr1, a_md) aa_eq(arr2, a_md) aa_eq(arr3, a_md) fa = Trajectory(traj) arr0 = pt.rmsd(fa, ref=-1, mask=mask) arr1 = pt.rmsd(fa, mask=atm.indices, ref=-1) arr2 = pt.rmsd(fa, mask=list(atm.indices), ref=-1) arr3 = pt.rmsd(fa, mask=tuple(atm.indices), ref=-1) a_md = md.rmsd(m_traj, m_traj, -1, atm.indices) aa_eq(arr0, a_md) aa_eq(arr1, a_md) aa_eq(arr2, a_md) aa_eq(arr3, a_md) fa = Trajectory(traj) mask = "!@H=" atm = fa.top(mask) arr0 = pt.rmsd(fa, ref=4, mask=mask) a_md = md.rmsd(m_traj, m_traj, 4, atm.indices) # exclude 0-th frame for ref aa_eq(arr0, a_md)
def test_load_frame_indices_from_io(self): traj0 = pt.load(filename="data/Tc5b.x", top="./data/Tc5b.top", frame_indices=(1, 3, 7)) trajCA = pt.load(filename="data/Tc5b.x", top="./data/Tc5b.top", frame_indices=(1, 3, 7), mask='@CA') trajreadonly = pt.iterload(filename="data/Tc5b.x", top="./data/Tc5b.top") trajCA_10frames = trajreadonly['@CA'] assert isinstance(traj0, Trajectory) aa_eq(traj0[0].xyz, trajreadonly[1].xyz) aa_eq(traj0[1].xyz, trajreadonly[3].xyz) aa_eq(traj0[2].xyz, trajreadonly[7].xyz) # @CA aa_eq(trajCA[0].xyz, trajCA_10frames[1].xyz) aa_eq(trajCA[1].xyz, trajCA_10frames[3].xyz) aa_eq(trajCA[2].xyz, trajCA_10frames[7].xyz)
def test_handling_n_components_changed(): view = nv.NGLWidget() n_traj = nv.PyTrajTrajectory(pt.load(nv.datafiles.PDB)) view.add_trajectory(n_traj) # fake updating n_components and _repr_dict from front-end view._repr_dict = REPR_DICT view.n_components = 1 view.player.widget_repr = view.player._make_widget_repr() view.remove_component(n_traj.id) # fake updating n_components from front-end view._repr_dict = {'c0': {}} view.n_components = 0
def test_coordinates_dict(): traj = pt.load(nv.datafiles.TRR, nv.datafiles.PDB) view = nv.show_pytraj(traj) view.frame = 1 coords = view.coordinates_dict[0] aa_eq(coords, traj[1].xyz) # dummy view._send_binary = False view.coordinates_dict = {0: coords} # increase coverage for IndexError: make index=1000 (which is larger than n_frames) view._set_coordinates(1000)
def test_pca_with_ref(self): '''has reference from drroe: "If the user provides their own reference structure, do not create an average structure" pytraj: pt.pca(traj, mask, n_vecs=2, ref=ref) ''' command_ref_provided = ''' parm data/tz2.parm7 trajin data/tz2.nc reference data/tz2.rst7 rms reference !@H= matrix covar name MyMatrix !@H= createcrd CRD1 run # Step three. Diagonalize matrix. runanalysis diagmatrix MyMatrix vecs 2 name MyEvecs # Step four. Project saved fit coordinates along eigenvectors 1 and 2 crdaction CRD1 projection evecs MyEvecs !@H= out project.dat beg 1 end 2 ''' traj = pt.load("data/tz2.nc", "data/tz2.parm7") ref = pt.load('data/tz2.rst7', traj.top) state = pt.load_cpptraj_state(command_ref_provided) state.run() mask = '!@H=' data = pt.pca(traj, mask, n_vecs=2, ref=ref) cpp_data = state.data[-2:].values # use absolute values aa_eq(np.abs(data[0]), np.abs(cpp_data), decimal=3)
def test_gbneck2nu(self): # compare to saved test: GBneck2nu topfile = os.path.join(amberhome, "test/gbneck2nu/1hji/prmtop") rstfile = os.path.join(amberhome, "test/gbneck2nu/1hji/min.r") traj = pt.load(rstfile, topfile) options = sander.gas_input(8) options.cut = 9999.0 edict = pt.energy_decomposition(traj=traj, mm_options=options, prmtop=topfile) assert_close(edict['gb'][0], -2287.6880, tol=3E-4) assert_close(edict['gb'][0], -2287.6880, tol=3E-4) assert_close(edict['elec'][0], -1659.5740, tol=3E-4) assert_close(edict['vdw'][0], 384.2512, tol=3E-4)
def test_0(self): farray = pt.load("data/Tc5b.x", "./data/Tc5b.top", frame_indices=list(range(10))) frame0 = farray[0] trajout = TrajectoryWriter() trajout.open(filename="./output/test.x", top=farray.top, overwrite=True) trajout.write(frame0) # add more frames for i in range(5, 8): trajout.write(farray[i]) trajout.close()
def test_calc_atomicfluct_with_unitcell(self): # use iterload for load_batch traj = pt.iterload("./data/tz2.ortho.nc", "./data/tz2.ortho.parm7") state = pt.load_cpptraj_state(''' distance :3 :7 atomicfluct @CA out output/test.agr distance :3 :7''', traj) state.run() # use `load` method t0 = pt.load("./data/tz2.ortho.nc", "./data/tz2.ortho.parm7") data = pt.atomicfluct(traj, '@CA') aa_eq(data, state.data[-2].values) # make sure that traj's coordinates were not altered # https://github.com/Amber-MD/pytraj/issues/1166 aa_eq(pt.distance(t0, ':3 :7'), state.data[-1]) aa_eq(traj.xyz, t0.xyz)
def test_coordinates_meta(): from mdtraj.testing import get_fn fn, tn = [get_fn('frame0.pdb'),] * 2 trajs = [pt.load(fn, tn), md.load(fn, top=tn), pmd.load_file(tn, fn)] N_FRAMES = trajs[0].n_frames from MDAnalysis import Universe u = Universe(tn, fn) trajs.append(Universe(tn, fn)) views = [nv.show_pytraj(trajs[0]), nv.show_mdtraj(trajs[1]), nv.show_parmed(trajs[2])] views.append(nv.show_mdanalysis(trajs[3])) for index, (view, traj) in enumerate(zip(views, trajs)): view.frame = 3 nt.assert_equal(view._trajlist[0].n_frames, N_FRAMES)
def test_GB(self): # compare to saved test: GB topfile = os.path.join(amberhome, "test/gb7_trx/prmtop_an") rstfile = os.path.join(amberhome, "test/gb7_trx/trxox.2.4ns.x") traj = pt.load(rstfile, topfile) options = sander.gas_input(7) options.cut = 9999.0 options.saltcon = 0.2 options.gbsa = 1 edict = pt.energy_decomposition(traj=traj, mm_options=options, prmtop=topfile) assert_close(edict['bond'][0], 631.8993, tol=3E-4) assert_close(edict['angle'][0], 898.2543, tol=3E-4) assert_close(edict['surf'][0], 33.8338, tol=3E-4) assert_close(edict['gb'][0], -1943.0838, tol=3E-4) # dummy test to make sure `energy_decomposition` can work with list edict2 = pt.energy_decomposition(traj=[traj, ], mm_options=options, prmtop=topfile, top=traj.top) edict3 = pt.energy_decomposition(traj=traj(), mm_options=options, prmtop=topfile, top=traj.top) edict4 = pt.energy_decomposition(traj=[traj[:5], traj[5:]], mm_options=options, prmtop=topfile, top=traj.top) edict5 = pt.energy_decomposition(traj=[traj[:5], traj(start=5)], mm_options=options, prmtop=topfile, top=traj.top) # test dtype dslist = pt.energy_decomposition(traj=[traj, ], mm_options=options, prmtop=topfile, top=traj.top, dtype='dataset') assert edict == edict2 assert edict == edict3 assert edict == edict4 assert sorted(dslist.to_dict()) == sorted(edict)
def test_regular(self): traj = self.traj.copy() assert traj[0].has_box() == True with tempfolder(): # write traj with nobox info fname = "traj_nobox.nc" pt.write_traj(fname, traj, options='nobox') t = pt.load(fname, traj.top) assert t[0].has_box() == False aa_eq(t.xyz, traj.xyz) # write from frame_iter, need to provide top fname = "traj_frame_iter.nc" # raise ValueError if there is no Topology pt.write_traj(fname, traj(), top=traj.top, overwrite=True) t = pt.iterload(fname, traj.top) aa_eq(t.xyz, traj.xyz)
# May need to add positional restraints to dummy atoms ''' # Create Positional Restraints pos_rest = mm.CustomExternalForce("k*((x-x0)^2+(y-y0)^2+(z-z0)^2)") pos_rest.addGlobalParameter("k",50.0*kilocalories_per_mole/angstroms**2) pos_rest.addPerParticleParameter("x0") pos_rest.addPerParticleParameter("y0") pos_rest.addPerParticleParameter("z0") for i, atom in enumerate(structure.positions): if structure.atoms[i].name == 'DUM': pos_rest.addParticle(i, atom.value_in_unit(nanometers)) ''' # Distance restraint # Use original prmtop and coordinates. Pytraj does not give correct distance to dummy atoms otherwise traj = pt.load(struct_dir + '/' + old_coordinates, struct_dir + '/' + old_topology) static_distance_rest = [D[0], H[0]] static_init_dist = pt.distance(traj, D[0] + ' ' + H[0])[0] dist_restraint = mm.CustomBondForce('k * (r - r_0)^2') dist_restraint.addPerBondParameter('k') dist_restraint.addPerBondParameter('r_0') r_0 = static_init_dist * angstroms k = 5 * kilojoules_per_mole / angstroms**2 dist_restraint.addBond(D_i[0], H_i[0], [k, r_0]) # Angle restraint 1 static_angle_rest1 = [D[1], D[0], H[0]] static_init_angle1 = pt.angle(traj, D[1] + ' ' + D[0] + ' ' + H[0])[0]
import pytraj as pt fn = "../tests/data/Test_NAstruct/adh026.3.pdb" traj = pt.load(fn, fn) d = pt.nastruct(traj) print(d) # get major groove print(d.major) # get minor groove print(d.minor) print(d.minor[1].mean(axis=0)) # get inclination print(d.incl) # get all supported keys print(d.keys())
import pytraj as pt traj = pt.load('../tests/data/tz2.nc', '../tests/data/tz2.parm7') data = pt.pca(traj, mask='@CA', n_vecs=3) print(pt.pca.__doc__) print('##################') print('output') print(data)
def test_in_memory_trajectory(self): traj = pt.load(fn('tz2.ortho.nc'), fn('tz2.ortho.parm7')) traj.autoimage() traj.rmsfit(mask='@CA,C,N') saved_traj = pt.load(fn('tz2.autoimage_with_rmsfit.nc'), traj.top) aa_eq(saved_traj.xyz, traj.xyz)
def test_pbc(self): traj = pt.load(fn('small_pbc.pdb')) aa_eq(traj.unitcells[0], [51.263, 51.263, 51.263, 90.00, 90.00, 90.00]) assert traj.top.has_box() == True, 'Topology must has box' assert traj.top.box.type == 'ortho', 'must be ortho box'
import pytraj as pt # use load method to load all frames to memory traj = pt.load("../tests/data/Tc5b.x", "../tests/data/Tc5b.top") # compute center of geometry for residue 1, use all atoms mask0 = ':1' cog_0 = pt.center_of_geometry(traj, mask=mask0) # should be ndarray, shape=(n_frames, 3) print(cog_0) # compute center of geometry for residue 1, exclude H atoms mask1 = ':1&!:1@H=' print(set(atom.name for atom in traj.top[mask1] .atoms)) # should get {'OD1', 'CA', 'ND2', 'CB', 'O', 'C', 'N', 'CG' cog_1 = pt.center_of_geometry(traj, mask=mask1) print(cog_1) # compute center of geometry for residue 1, 3, 5 and use all atoms mask2 = ':1,3,5' print(set(atom.name for atom in traj.top[mask2].atoms)) cog_2 = pt.center_of_geometry(traj, mask=mask2) print(cog_2) # compute center of geometry for residue 1, 3, 5 and use only CA atoms mask3 = ':1,3,5@CA' print(set(atom.name for atom in traj.top[mask3].atoms)) # should get {'@CA'} cog_3 = pt.center_of_geometry(traj, mask=mask3) print(cog_3)
"""calculate RMSD for two proteins with different topologies""" import pytraj as pt # create trajectory objects (having frames) traj_0 = pt.load("../tests/data/Tc5b.crd", "../tests/data/Tc5b.top") traj_1 = pt.load("../tests/data/ala3.dcd", "../tests/data/ala3.psf") # get new traj objects with given mask traj_0_new = traj_0[":8-10@CA"] traj_1_new = traj_1[":1-3@CA"] # calculate rmsd between 1st frame of traj_1_new and 1st frame of traj_0_new # best fit, no mass print(traj_1_new[0].rmsd(traj_0_new[0]))
import pytraj as pt traj = pt.load("../tests/data/Tc5b.x", "../tests/data/Tc5b.top") # etract first 10 frames and write to CHARMM format subtraj = traj[:10] pt.write_traj(filename="./output/subtraj_0_CHARMM.dcd", traj=subtraj, top=traj.top, overwrite=True) # make sure we can load the traj, # use AMBER top is fine charmm_traj = pt.load("./output/subtraj_0_CHARMM.dcd", "../tests/data/Tc5b.top") # calculate rmsd between old and saved traj for 1st frame print(charmm_traj[0].rmsd(subtraj[0])) assert charmm_traj[0].rmsd(subtraj[0]) < 1E-6 # another way subtraj.save("./output/subtraj_1_CHARMM.dcd", overwrite=True) charmm_traj_1 = pt.load("./output/subtraj_1_CHARMM.dcd", "../tests/data/Tc5b.top") print(charmm_traj_1[0].rmsd(subtraj[0])) assert charmm_traj_1[0].rmsd(subtraj[0]) < 1E-6
import pytraj as pt from pytraj.testing import aa_eq, tempfolder from pytraj import * # local from utils import fn farray = pt.load(fn("Tc5b.x"), fn("Tc5b.top"), frame_indices=list(range(10))) def test_trajectory_writer_open_close(): farray = pt.load(fn("Tc5b.x"), fn("Tc5b.top"), frame_indices=list(range(10))) frame0 = farray[0] with tempfolder(): trajout = TrajectoryWriter() trajout.open(filename="test.x", top=farray.top, overwrite=True) trajout.write(frame0) # add more frames for i in range(5, 8): trajout.write(farray[i]) trajout.close() farray = Trajectory() farray.top = pt.load_topology(fn('Tc5b.top')) farray.load("test.x")
def main(args): parser = argparse.ArgumentParser(description='Prepare config files for umbrella sampling run.') parser.add_argument('raf', help='list like: "residues_1,angle_1_fromp,angle_1_to,force_1:residues_2,angle_2_from,' 'angle_2_to,force_2:..."') parser.add_argument('umbrellas', help='how many umbrella do we want to span?') parser.add_argument('init', help='names of initial topologies and trajectories, ' 'e.g. "WT.prmtop,rel_3.rst:WT.prmtop,prod_1.rst"') parser.add_argument('sim_config_path', help='here can MD settings be found') parser.add_argument('init_value', help='initial value that should be started with', nargs='?', default=False) parser.add_argument('-s', action='store_true', help='define weather the last frame of each simulation is used for the next one as a start. ' 'In this case there should be only one init file.') args = parser.parse_args() umbrellas = int(args.umbrellas) configs_directory = "umbrella_config/" try: mkdir(configs_directory) except OSError: pass # initial/template configuration files sim_configuration_path = args.sim_config_path sim_configuration_files = [join(sim_configuration_path, 'min_1.umbin'), join(sim_configuration_path, 'rel_1.umbin'), join(sim_configuration_path, 'rel_2_25C.umbin'), join(sim_configuration_path, 'rel_3_25C.umbin'), join(sim_configuration_path, 'prod_25C.umbin')] # there is possibly more than one angle that gets transformed residues_angles_force = args.raf.split('|') init_files = args.init.split(':') if len(init_files) != len(residues_angles_force): print('Error: Number of input file tuples has to be same as sets of "residue angles force")') print('init_files:', init_files, 'length', len(init_files)) print('residue_angles_force:', residues_angles_force, 'length', len(residues_angles_force)) exit() init_prmtop = init_files[0].split(",")[0] init_traj = init_files[0].split(",")[1] print('Input file tuples: {}'.format(init_files)) # angle increments contains the step size for every configuration angle_increments = [] # contains [[atom1,atom2,...][angle1,angle2][force]] umbrella_configs = [] # read input arguments into variables for raf, i_file in zip(residues_angles_force, init_files): raf = re.sub('\'|\"', '', raf) residues, angles, force = raf.split(':') angles = angles.split(',') angles = list(map(float, angles)) print(residues) top, traj = i_file.split(',') pdb = pt.load(traj, top) atoms = [str(pt.select_atoms(':' + k + '@CA', pdb.top)[0] + 1) for k in residues.split(',')] print(atoms) umbrella_config = [] umbrella_config.append(atoms) umbrella_config.append(angles) umbrella_config.append(force) umbrella_configs.append(umbrella_config) angle_increments.append(abs(umbrella_config[1][0] - umbrella_config[1][1]) / umbrellas) umbrella_constraint_files = [] n_cnfgs = len(umbrella_configs) # create dictionary to hold meta files meta_files = {} range_n_confgs = range(n_cnfgs) for n in range_n_confgs: meta_files[n] = "" init_value = args.init_value if init_value: init_value = float(init_value) if init_value < angles[0] or init_value > angles[1]: print('Error: init value must lie between min and max angle value') exit() else: angle = init_value c = 0 meta_out = "" next_traj = init_traj init_relaxed = "" run_script = "" # !!! only implemented for one init file for i in range_n_confgs: min = np.min(umbrella_configs[i][1]) max = np.max(umbrella_configs[i][1]) # go down to min while angle >= min: angle_low = angle - 180 angle_high = angle + 180 force = umbrella_configs[i][2] out, meta_out_temp = generate_umb_config(angle, angle_low, angle_high, force, c, atoms) # write constraint file umbrella_constraint_file_name = '{}umb_out_{}.dat'.format(configs_directory, c) with open(umbrella_constraint_file_name, 'w') as f: f.write(out) meta_out += meta_out_temp md_configs = generate_sim_configs(configs_directory, sim_configuration_files, umbrella_constraint_file_name, c) # old_traj old_traj = next_traj run_temp, next_traj = generate_run_script(md_configs, init_prmtop, next_traj) run_script += "#{}\n".format(c) run_script += run_temp if old_traj == init_traj: init_relaxed = next_traj # increment angle -= angle_increments[i] c -= 1 # reset to init value angle = init_value + angle_increments[i] c = 0 next_traj = init_relaxed # go up while angle <= max: angle_low = angle - 180 angle_high = angle + 180 out, meta_out_temp = generate_umb_config(angle, angle_low, angle_high, force, c, atoms) # write constraint file umbrella_constraint_file_name = '{}umb_out_{}.dat'.format(configs_directory, c) with open(umbrella_constraint_file_name, 'w') as f: f.write(out) meta_out += meta_out_temp md_configs = generate_sim_configs(configs_directory, sim_configuration_files, umbrella_constraint_file_name, c) md_configs = generate_sim_configs(configs_directory, sim_configuration_files, umbrella_constraint_file_name, c) run_temp, next_traj = generate_run_script(md_configs, init_prmtop, next_traj) run_script += "#{}\n".format(c) run_script += run_temp # increment angle += angle_increments[i] c += 1 # write meta file with open(configs_directory + 'meta_file', 'w') as mf: mf.write(meta_out) with open("run.sh", "w") as o: o.write("#!/bin/bash\n\n") o.write(run_script) else: # generate meta files and umbrella contstraint files umb_out_...dat meta_out = "" for c in range(umbrellas + 1): out = "Harmonic restraints\n" for i in range_n_confgs: out += " &rst\n" residues = umbrella_configs[i][0] out += " iat=" + ','.join(atoms) + ",\n" angle_low_bound = umbrella_configs[i][1][0] - 180 angle = umbrella_configs[i][1][0] angle_high_bound = umbrella_configs[i][1][0] + 180 out += " r1={}, r2={}, r3={}, r4={}\n".format(angle_low_bound, angle, angle, angle_high_bound) force = umbrella_configs[i][2] out += " rk2={}, rk3={}\n/\n".format(force, force) meta_out += '../umbrella_productions/prod_25C_{}.dat {} 0.12184\n'.format(c, angle) if angles[0] > angles[1]: umbrella_configs[i][1][0] -= angle_increments[i] else: umbrella_configs[i][1][0] += angle_increments[i] umbrella_constraint_file_name = '{}umb_out_{}.dat'.format(configs_directory, c) with open(umbrella_constraint_file_name, 'w') as f: f.write(out) umbrella_constraint_files.append(umbrella_constraint_file_name) # write meta file print(meta_out) with open(configs_directory + 'meta_file', 'w') as mf: mf.write(meta_out) ## generate run scripts if args.s and len(init_files) > 1: print("too many input files for option s. Exiting.") exit() runs_per_script = umbrellas // len(init_files) umbrellas = umbrellas + 1 idx = 0 for init_f in init_files: top, traj = init_f.split(',') traj_temp = traj out = "" while idx <= runs_per_script and idx <= umbrellas and idx + umbrellas * 4 < len(md_files): b_name_min = basename(md_files[idx]).split('.')[0] run_min = \ "pmemd -O " \ "-i {} " \ "-o umbrella_productions/{}.out " \ "-p {} " \ "-c {} " \ "-r umbrella_productions/{}.rst " \ "-inf umbrella_productions/{}.mdinfo \n" \ .format(md_files[idx], b_name_min, top, traj_temp, b_name_min, b_name_min) b_name_rel_1 = basename(md_files[idx + umbrellas]).split('.')[0] run_rel_1 = \ "pmemd.cuda -O " \ "-i {} " \ "-o umbrella_productions/{}.out " \ "-p {} " \ "-c umbrella_productions/{}.rst " \ "-r umbrella_productions/{}.rst " \ "-inf umbrella_productions/{}.mdinfo " \ "-ref umbrella_productions/{}.rst \n" \ .format(md_files[idx + umbrellas], b_name_rel_1, top, b_name_min, b_name_rel_1, b_name_rel_1, \ b_name_min) b_name_rel_2 = basename(md_files[idx + umbrellas * 2]).split('.')[0] run_rel_2 = \ "pmemd.cuda -O " \ "-i {} " \ "-o umbrella_productions/{}.out " \ "-p {} " \ "-c umbrella_productions/{}.rst " \ "-r umbrella_productions/{}.rst " \ "-inf umbrella_productions/{}.mdinfo " \ "-ref umbrella_productions/{}.rst \n" \ .format(md_files[idx + umbrellas * 2], b_name_rel_2, top, b_name_rel_1, b_name_rel_2, b_name_rel_2, b_name_rel_1) b_name_rel_3 = basename(md_files[idx + umbrellas * 3]).split('.')[0] run_rel_3 = \ "pmemd.cuda -O " \ "-i {} " \ "-o umbrella_productions/{}.out " \ "-p {} " \ "-c umbrella_productions/{}.rst " \ "-r umbrella_productions/{}.rst " \ "-inf umbrella_productions/{}.mdinfo " \ "-ref umbrella_productions/{}.rst \n" \ .format(md_files[idx + umbrellas * 3], b_name_rel_3, top, b_name_rel_2, b_name_rel_3, b_name_rel_3, b_name_rel_2) b_name_prod = basename(md_files[idx + umbrellas * 4]).split('.')[0] run_prod = \ "pmemd.cuda -O " \ "-i {} " \ "-o umbrella_productions/{}.out " \ "-p {} " \ "-c umbrella_productions/{}.rst " \ "-r umbrella_productions/{}.rst " \ "-inf umbrella_productions/{}.mdinfo " \ "-x umbrella_productions/{}.nc " \ "-ref umbrella_productions/{}.rst \n" \ .format(md_files[idx + umbrellas * 4], b_name_prod, top, b_name_rel_3, b_name_prod, b_name_prod, b_name_prod, \ b_name_rel_3) out += "#{}\n".format(idx) idx += 1 out += run_min + "\n" + run_rel_1 + "\n" + run_rel_2 + "\n" + run_rel_3 + "\n" + run_prod + "\n" if args.s: traj_temp = "umbrella_productions/" + b_name_prod + ".rst" # write run script if args.s: script_file_name = 'init_WT_run_s_' + str(idx - 1) + ".sh" else: script_file_name = 'init_' + basename(init_f).split('.')[0] + "_run_" + str(idx - 1) + ".sh" print(script_file_name) with open(script_file_name, "w") as o: o.write("#!/bin/bash\n\n") o.write(out) print(runs_per_script) runs_per_script *= 2 with open('umbrella_config/umb_out_0.dat','r') as f: print(f.readlines())
def default_view(): traj = pt.load(nv.datafiles.TRR, nv.datafiles.PDB) return nv.show_pytraj(traj)
[dummy_anchors[1], dummy_anchors[0], guest_anchors[0]], [dummy_anchors[0], guest_anchors[0], guest_anchors[1]], ] attach_fractions = [float(i) / 100 for i in attach_string.split()] windows = [len(attach_fractions), len(pull_string.split()), 0] paths = glob.glob( os.path.normpath( os.path.join('./OA-G3-0', 'AMBER', 'APR', 'windows', '*'))) window_list = [os.path.basename(i) for i in paths] # Setup the fractions for SAMPLing convergence... fractions = np.arange(0.01, 1.01, 0.01) traj = pt.load( os.path.join(complx, 'AMBER', 'solvate.rst7'), os.path.join(complx, 'AMBER', 'solvate.prmtop')) pull_initial = pt.distance(traj, ' '.join([dummy_anchors[0], guest_anchors[0]]))[0] pull_distances = [float(i) + pull_initial for i in pull_string.split()] guest_restraint_targets = [pull_initial, 180.0, 180.0] guest_restraint_target_final = [pull_distances[-1], 180.0, 180.0] guest_restraint_distance_fc = 5.0 # kcal/mol-A**2 guest_restraint_angle_fc = 100.0 # kcal/mol-rad**2 hg = pmd.load_file( os.path.join(complx, 'AMBER', 'solvate.prmtop'), os.path.join(complx, 'AMBER', 'solvate.rst7'),
import os import sys import logging logging.basicConfig(level=logging.INFO) logging.getLogger().setLevel(logging.DEBUG) logging.info('Started logging...') sim_type = sys.argv[1] window_dir = "windows_apr" topology = "cb6-but/cb6-but-dum.prmtop" coordinates = "cb6-but/cb6-but-dum.rst7" structure = pt.load(coordinates, topology) rests = rjson.load_restraints() phases = ["attach", "pull", "release"] guest_restraints = rests[-3:] analyze = fe_calc() analyze.prmtop = structure.topology analyze.trajectory = sim_type + "_prod.nc" analyze.path = window_dir analyze.restraint_list = guest_restraints analyze.collect_data() method = ["ti-block", "mbar-block"] m = method[1]
def test_load_url(): url = 'https://raw.githubusercontent.com/Amber-MD/pytraj/master/tests/data/1L2Y.pdb' local_traj = pt.load(fn('1L2Y.pdb')) github_traj = pt.io.load_url(url) aa_eq(local_traj.xyz, github_traj.xyz)
def gb_minimize( tleapfile='tleap.in', pdbfile=None, restraintfile='restraints.in', ntrmask=None, saveprefix='vac'): """ Minimize system in implicit solvent, initially with non-bonded off, then gradually non-bondeds turned on. """ # Read tleapfile (mostly duplicated from solvate.py) tleaplines = [] with open(tleapfile, 'r') as f: for line in f.readlines(): if re.search('loadpdb', line): words = line.rstrip().replace('=', ' ').split() if pdbfile is None: pdbfile = words[2] unit = words[0] tleaplines.append( "{} = loadpdb {}\n".format(unit, pdbfile)) if not re.search(r"^\s*addions|^\s*addions2|^\s*addionsrand|^\s*desc|" r"^\s*quit|^\s*solvate|loadpdb|^\s*save", line, re.IGNORECASE): tleaplines.append(line) tleaplines.append("saveamberparm {0} {1}.prmtop {1}.rst7\n".format(unit,saveprefix)) tleaplines.append("quit\n") # Write tleap file and run with open('tleap_gb_minimize.in', 'w') as f: for line in tleaplines: f.write(line) sp.call('tleap -s -f tleap_gb_minimize.in >& log.tleap_gb_minimize', shell=True) # Write pmemd input file if ntrmask: ntrstring="\n ntr = 1,\n restraint_wt = 10.0,\n restraintmask = '{}',".format(ntrmask) else: ntrstring="" with open('gb_minimize.in', 'w') as f: f.write(""" ********************************* ***** gb_minimize.in ************ ********************************* Minimizing in GB. &cntrl imin = 1, ntx = 1, ntpr = 100, maxcyc = 1000, ncyc = 100, ntxo = 1, irest = 0, ntf = 1, ntc = 1, ntb = 0, igb = 1, cut = 999.0, nmropt = 1, pencut = -1,{} / &wt type = 'NB', istep1=0, istep2=500, value1 = 0.000, value2=0.000, IINC=50, / &wt type = 'NB', istep1=500, istep2=750, value1 = 0.000, value2=1.000, IINC=50, / &wt type = 'END', / DISANG={} LISTOUT=POUT """.format(ntrstring,restraintfile)) # Run pmemd sp.call("pmemd -O -p {0}.prmtop -c {0}.rst7 -ref {0}.rst7 -i gb_minimize.in -o gb_minimize.out -r gb_minimize.rst7 -inf /dev/null".format(saveprefix), shell=True) # Any problems with /dev/null here? gbmin = pt.load('gb_minimize.rst7', top=saveprefix+'.prmtop') return gbmin
host = ":CB6" guest = ":BUT" H = [host + "@C7", host + "@C31", host + "@C19"] G = [guest + "@C", guest + "@C3"] D = [":DM1", ":DM2", ":DM3"] struct_dir = "cb6-but" topology_file = "cb6-but-dum.prmtop" coordinate_file = "cb6-but-dum.rst7" structure = pmd.load_file(struct_dir + '/' + topology_file, struct_dir + '/' + coordinate_file, structure=True) traj = pt.load(struct_dir + '/' + coordinate_file, struct_dir + '/' + topology_file) guest_init_dist = pt.distance(traj, D[0] + ' ' + G[0])[0] attach_string = "0.00 0.40 0.80 1.60 2.40 4.00 5.50 8.65 11.80 18.10 24.40 37.00 49.60 74.80 100.00" attach_fractions = [float(i) / 100 for i in attach_string.split()] pull_distances = np.arange(0.0 + guest_init_dist, 18.0 + guest_init_dist, 1.0) release_fractions = attach_fractions[::-1] windows = [len(attach_fractions), len(pull_distances), len(release_fractions)] # Static Restraints static_distance_rest = [D[0], H[0]] static_angle_rest1 = [D[1], D[0], H[0]]
import unittest import pytraj as pt import numpy as np from pytraj.base import * from pytraj import io as mdio from pytraj.testing import aa_eq farray = pt.load("data/Tc5b.x", "./data/Tc5b.top", frame_indices=list(range(10))) class TestTrajectoryWriter(unittest.TestCase): def test_0(self): farray = pt.load("data/Tc5b.x", "./data/Tc5b.top", frame_indices=list(range(10))) frame0 = farray[0] trajout = TrajectoryWriter() trajout.open(filename="./output/test.x", top=farray.top, overwrite=True) trajout.write(frame0) # add more frames for i in range(5, 8): trajout.write(farray[i]) trajout.close() def test_1_with_statement(self):
def test_ClusteringDataset(): traj = pt.load(tz2_trajin, tz2_top) x = pt.cluster.kmeans(traj, n_clusters=5, metric='rms', mask='@CA') assert x.n_frames == 101 assert list(x.centroids) == [24, 101, 76, 13, 9] aa_eq(x.fraction, [0.485, 0.238, 0.139, 0.079, 0.059], decimal=3)
import pytraj as pt traj = pt.load("../../naf_apo.nc", top="../../dry_naf_apo_154.prmtop") for x in range(0, 599): pdb = "snapshot" pdb += str(x) pdb += ".pdb" pt.write_traj(pdb, traj, frame_indices=[x], overwrite=False)
def test_rotdif(self): traj = pt.load(trajin, parm) ref = pt.load(reference, parm) mat = pt.rotation_matrix(traj, ref=ref, mask='@CA,C,N,O') data = pt.all_actions.rotdif(mat, short_cm)
def setup_restraints(): struct_dir = "cb6-but" topology_file = "cb6-but-dum.prmtop" coordinate_file = "cb6-but-dum.rst7" structure = pmd.load_file(struct_dir+'/'+topology_file, struct_dir+'/'+coordinate_file, structure=True) host = ":CB6" guest = ":BUT" H = [host+"@C7", host+"@C31", host+"@C19"] G = [guest+"@C", guest+"@C3"] D = [":DM1", ":DM2", ":DM3"] # Get distance of dummy atom to guest with pytraj traj = pt.load(struct_dir+'/'+coordinate_file,struct_dir+'/'+topology_file) guest_init_dist = pt.distance(traj,D[0]+' '+G[0])[0] attach_fractions = [1.0] pull_distances = [guest_init_dist,5.0+guest_init_dist,18.0+guest_init_dist] windows = [len(attach_fractions), len(pull_distances)] # Guest Restraints guest_distance_rest = [D[0], G[0]] #guest_angle_rest = [D[1], D[0], G[0]] guest_restraint_atoms = [ guest_distance_rest, #guest_angle_rest ] guest_restraint_targets = [guest_init_dist] guest_restraint_target_final = [18.0+guest_init_dist] guest_restraint_distance_fc = 5.0 guest_restraint_angle_fc = 100.0 guest_restraints = [] for index, atoms in enumerate(guest_restraint_atoms): if len(atoms) > 2: angle = True else: angle = False this = restraints.DAT_restraint() this.auto_apr = True this.amber_index = True this.topology = structure this.mask1 = atoms[0] this.mask2 = atoms[1] if angle: this.mask3 = atoms[2] this.attach['fc_final'] = guest_restraint_angle_fc else: this.attach['fc_final'] = guest_restraint_distance_fc this.attach['target'] = guest_restraint_targets[index] this.attach['fraction_list'] = attach_fractions this.pull['target_final'] = guest_restraint_target_final[index] this.pull['num_windows'] = windows[1] this.initialize() guest_restraints.append(this) return guest_restraints
def main(): X = pt.load(args.traj, args.parm, stride=args.stride) if args.pca == "no": X = X[args.mask].xyz[args.start:] shape = X.shape X = X.reshape((shape[0], shape[1] * 3)) else: n_vecs = 3 * X[args.mask].xyz[args.start:].shape[1] - 6 pca_data, eigen = pt.pca(X[args.start:], n_vecs=n_vecs, mask=args.mask) eigen_val = eigen[0] eigen_vec = eigen[1] np.savetxt("%s_eigen_vec.dat" % args.prefix, np.c_[eigen_vec[0], eigen_vec[1], eigen_vec[2]]) pairs = list() #make pairs for n_i in range(3): for n_j in range(3): if n_i < n_j: pairs.append((n_i, n_j)) # Plot PCA for pc_i, pc_j in pairs: plt.scatter(pca_data[pc_i], pca_data[pc_j], marker='o', c="r", alpha=0.5) plt.xlabel("PC%d [$\AA$]" % pc_i) plt.ylabel("PC%d [$\AA$]" % pc_j) plt.title("PCA PC%d vs. PC%d" % (pc_i, pc_j)) plt.savefig("PC%d-vs-PC%s_%s.png" % (pc_i, pc_j, args.prefix), dpi=1000) plt.close('all') # Plot atom contritbuion for pc_i in range(3): l = eigen_vec[pc_i].shape[0] c = np.linalg.norm(eigen_vec[pc_i].reshape((l / 3, 3)), axis=1) a = np.arange(l / 3) + 1 plt.plot(a, c, label="PC%s" % pc_i, alpha=0.5) plt.legend() plt.xlim(0, l / 3 + 1) plt.xlabel("Atom ID") plt.ylabel("Eigenvector components") plt.title("Eigenvectors") plt.savefig("Eigenvectors_%s.png" % args.prefix, dpi=1000) plt.close('all') total_var = np.sum(eigen_val) plt.scatter(range(1, n_vecs + 1), (np.cumsum(eigen_val) / total_var) * 100, label="Cumulative Variance") plt.plot(range(1, n_vecs + 1), (eigen_val / total_var) * 100, "g--", label="Eigenvector Variance") plt.legend() #plt.xticks(range(1, n_vecs+1, 2)) plt.xlabel("Eigenvector #") plt.ylabel("Fractional of Variance explained [%]") plt.title("Explained total variance explained by PCA") plt.savefig("Variance_%s.png" % args.prefix, dpi=1000) plt.close('all') X = pca_data range_n_clusters = range(2, 20) for n_clusters in range_n_clusters: # Create a subplot with 1 row and 2 columns if args.pca == "yes": fig, (ax1, ax2) = plt.subplots(1, 2) fig.set_size_inches(18, 7) else: fig, (ax1, ax2) = plt.subplots(1, 1) # The 1st subplot is the silhouette plot # The silhouette coefficient can range from -1, 1 but in this example all # lie within [-0.1, 1] ax1.set_xlim([-0.1, 1]) # The (n_clusters+1)*10 is for inserting blank space between silhouette # plots of individual clusters, to demarcate them clearly. ax1.set_ylim([0, len(X) + (n_clusters + 1) * 10]) # Initialize the clusterer with n_clusters value and a random generator # seed of rand for reproducibility. rand = np.random.randint(99999) print("Random seed is %d." % rand) clusterer = KMeans(n_clusters=n_clusters, random_state=rand) cluster_labels = clusterer.fit_predict(X) # The silhouette_score gives the average value for all the samples. # This gives a perspective into the density and separation of the formed # clusters silhouette_avg = silhouette_score(X, cluster_labels) print("For n_clusters =", n_clusters, "The average silhouette_score is :", silhouette_avg) # Compute the silhouette scores for each sample sample_silhouette_values = silhouette_samples(X, cluster_labels) y_lower = 10 for i in range(n_clusters): # Aggregate the silhouette scores for samples belonging to # cluster i, and sort them ith_cluster_silhouette_values = \ sample_silhouette_values[cluster_labels == i] ith_cluster_silhouette_values.sort() size_cluster_i = ith_cluster_silhouette_values.shape[0] y_upper = y_lower + size_cluster_i color = cm.spectral(float(i) / n_clusters) ax1.fill_betweenx(np.arange(y_lower, y_upper), 0, ith_cluster_silhouette_values, facecolor=color, edgecolor=color, alpha=0.7) # Label the silhouette plots with their cluster numbers at the middle ax1.text(-0.05, y_lower + 0.5 * size_cluster_i, str(i)) # Compute the new y_lower for next plot y_lower = y_upper + 10 # 10 for the 0 samples ax1.set_title("The silhouette plot for the various clusters.") ax1.set_xlabel("The silhouette coefficient values") ax1.set_ylabel("Cluster label") # The vertical line for average silhouette score of all the values ax1.axvline(x=silhouette_avg, color="red", linestyle="--") ax1.set_yticks([]) # Clear the yaxis labels / ticks ax1.set_xticks([-0.1, 0, 0.2, 0.4, 0.6, 0.8, 1]) if args.pca == "yes": # 2nd Plot showing the actual clusters formed colors = cm.spectral(cluster_labels.astype(float) / n_clusters) ax2.scatter(X[:, 0], X[:, 1], marker='.', s=30, lw=0, alpha=0.7, c=colors) # Labeling the clusters centers = clusterer.cluster_centers_ # Draw white circles at cluster centers ax2.scatter(centers[:, 0], centers[:, 1], marker='o', c="white", alpha=1, s=200) for i, c in enumerate(centers): ax2.scatter(c[0], c[1], marker='$%d$' % i, alpha=1, s=50) ax2.set_title("The visualization of the clustered data.") ax2.set_xlabel("Feature space for the 1st feature") ax2.set_ylabel("Feature space for the 2nd feature") plt.suptitle( ("Silhouette analysis for KMeans clustering on sample data " "with n_clusters = %d" % n_clusters), fontsize=14, fontweight='bold') plt.savefig("%s_silhouette_n=%d.png" % (args.prefix, n_clusters), dpi=1000) plt.close('all')
# james robertson testing new eco analysis tool built w/ networkx and pytraj import pytraj as pt import networkx as nx import os from itertools import izip # check if edge_list_out.dat exists if (os.path.isfile('edge_list_out.dat')): print "Warning: edge_list_out.dat already exists" exit(1) # load protein #top = pt.load_topology('1ubq.parm7') # load as pdb (single structure) top = pt.load_topology('1nd9.parm7') # load as pdb (single structure) traj = pt.load('1nd9.rst7', '1nd9.parm7') # if loading traj simp_p = top.simplify() # return simplified topology # do some counting and indexing rescount = len(simp_p.residues) # length of protein chain numbonds = rescount - 1 # number of bonds in protein backbone residues = range(1, rescount + 1) # indexing from 1 (or should it be 0?) print "The number of residues(nodes) that should be in the graph: %s" % rescount print "The number of backbone bonds(edges) that should be in the graph: %s" % numbonds print "These are the residue indices in the graph:\n%s" % residues # set up and check graph G = nx.Graph() # initiate empty graph G.add_nodes_from(residues) # add nodes, which are all residues in protein numnodes = G.number_of_nodes( ) # check that number of residues matches expected number
# datafiles and this test.py were provided by jmborr # issue #991: # Error "ValueError: Buffer not C contiguous" # https://github.com/Amber-MD/pytraj/issues/991 import os import argparse import numpy import pytraj from pdb import set_trace as tr traj = pytraj.load('short.dcd', 'pdb', mask='(!:1-256)&(@H1,@H2,@H3,@H4,@H5)') # Trajectory of the center of mass of the first two residues minitraj = numpy.empty((2, traj.n_frames, 3)) minitraj[0] = pytraj.center_of_mass(traj, mask=':1') minitraj[1] = pytraj.center_of_mass(traj, mask=':2') minitraj = minitraj.transpose((1, 0, 2)) # "topology" using the first two atoms minitop = traj.top['@1,2'] # Save trajectory pytraj.write_traj(filename='/tmp/junk.crd', traj=minitraj, top=minitop, overwrite=True)