def test_split_and_write_traj(self): fn = "data/Tc5b.x" traj = pt.iterload([fn, fn], "./data/Tc5b.top") # duplcate assert traj.n_frames == 20 top = traj.top # test TrajectoryIterator object pt.tools.split_and_write_traj(traj, n_chunks=4, root_name='./output/trajiterx', overwrite=True) flist = sorted(glob("./output/trajiterx*")) traj4 = pt.iterload(flist, top) aa_eq(traj4.xyz, traj.xyz) # dcd ext pt.tools.split_and_write_traj(traj, 4, root_name='./output/ts', ext='dcd', overwrite=True) flist = sorted(glob("./output/ts.*.dcd")) traj4 = pt.iterload(flist, top) aa_eq(traj4.xyz, traj.xyz)
def test_1(self): # load frames to immutable traj traj = pt.iterload("./data/Tc5b.x", "./data/Tc5b.top") trajsaved = pt.iterload("./data/fit_to_1stframe.Tc5b.x", "./data/Tc5b.top") for _f1 in trajsaved: pass f0saved = traj[0].copy() first = traj[0].copy() # make mutable traj farray = traj[:] aa_eq(farray[0].xyz, first.xyz) farray.rmsfit(ref=first, mask="*", mass=False) farray2 = traj[:] farray2.superpose(ref=first, mask="*", mass=False) for i, _f0 in enumerate(farray): _f1 = trajsaved[i] aa_eq(_f0.xyz, _f1.xyz, decimal=3) for i, _f0 in enumerate(farray2): _f1 = trajsaved[i] aa_eq(_f0.xyz, _f1.xyz, decimal=3)
def test_frame_indices(self): traj = pt.iterload("data/tz2.truncoct.nc", "data/tz2.truncoct.parm7") traj2 = pt.iterload("data/tz2.truncoct.nc", "data/tz2.truncoct.parm7", frame_slice=(2, 8)) txt = ''' reference ./data/tz2.truncoct.nc 2 2 rmsd :2-11 refindex 0 perres perresout center.agr range 1 perrescenter ''' state = pt.load_batch(traj2, txt) state.run() frame_indices = range(2, 8) rmsd0 = pt.rmsd(traj, ref=1, mask=':2-11', frame_indices=frame_indices) rmsdperres = pt.rmsd_perres(traj, ref=1, mask=':2-11', perres_mask='*', resrange='1', perres_center=True, frame_indices=frame_indices) aa_eq(rmsd0, state.data[2]) aa_eq(rmsdperres[1], state.data[3].values)
def test_frame_fit(self): traj = pt.iterload("./data/Tc5b.x", "./data/Tc5b.top") f0 = traj[0] f1 = traj[1] arr0 = list(f0[0]) arr1 = list(f1[0]) f0.rmsd(f1) aa_eq(arr0, f0[0]) aa_eq(arr1, f1[0]) f1.rmsfit(ref=f0) # expect reference `f0` xyz are not changed aa_eq(arr0, f0[0]) trajsaved = pt.iterload("./data/fit_to_1stframe.Tc5b.x", "./data/Tc5b.top") f1saved = trajsaved[1] # make sure we reproduce cpptraj output aa_eq(f1.xyz, f1saved.xyz, decimal=3) farray = traj[:] farray.rmsfit(ref=traj[0]) aa_eq(farray[1].xyz, f1saved.xyz, decimal=3)
def test_0(self): traj = pt.iterload("./data/tz2.ortho.nc", "./data/tz2.ortho.parm7") trajectory_traj = traj[:] # test xyz aa_eq(trajectory_traj.xyz, traj.xyz) # test object lifetime aa_eq(trajectory_traj[0].xyz, trajectory_traj.xyz[0]) # test Box assert (trajectory_traj.top.has_box() == True) boxes = traj.unitcells for i, frame in enumerate(trajectory_traj): assert (frame.has_box() == True) f_blist = frame.box.tolist() aa_eq(f_blist, boxes[i].tolist()) # test autoimage # make Trajectory from TrajectoryIterator fa = traj[:] fa.autoimage() saved_traj = pt.iterload("./data/tz2.autoimage.nc", "./data/tz2.ortho.parm7") # make sure to reproduce cpptraj's output too aa_eq(saved_traj.xyz, fa.xyz)
def test_fancy_save(self): traj = pt.iterload("./data/Tc5b.x", "./data/Tc5b.top") traj[1:8].save("./output/test_fancy_save_frame1_7.x", overwrite=True) fanew = pt.iterload("./output/test_fancy_save_frame1_7.x", traj.top) for idx, f0 in enumerate(traj[1:8]): f0new = fanew[idx] aa_eq(f0.xyz, f0new.xyz)
def test_1(self): traj = pt.iterload("./data/tz2.truncoct.nc", "./data/tz2.truncoct.parm7") f0 = traj[0] f0cp = f0.copy() adict['autoimage']("", f0, traj.top) fsaved = pt.iterload("./data/tz2.truncoct.autoiamge.save.r", "./data/tz2.truncoct.parm7")[0] aa_eq(fsaved.xyz, f0.xyz, decimal=3)
def test_volmap(self): traj = pt.iterload("./data/tz2.ortho.nc", "./data/tz2.ortho.parm7")[:1] size = '' center = '' state = pt.load_cpptraj_state(txt.format(cm, size, center)) state.run() cpp_data = state.data[-1].values traj = traj.superpose(mask=':1-13').center(':1-13 mass origin') ds = pt.volmap(traj, mask=':WAT@O', grid_spacing=(0.5, 0.5, 0.5), buffer=2.0, centermask='!:1-13', radscale=1.36) aa_eq(cpp_data, ds) # assert self.assertRaises(AssertionError, lambda: pt.volmap(traj, mask=':WAT@O', grid_spacing='0.5 0.5 0.5')) self.assertRaises(AssertionError, lambda: pt.volmap(traj, mask=':WAT@O', grid_spacing=(0.5, 0.5))) self.assertRaises(ValueError, lambda: pt.volmap(traj, mask=':WAT@O', grid_spacing=(0.5, 0.5, 0.5), size='20 20 20')) # test size cm_no_buffer = cm.replace('buffer 2.0', '') state = pt.load_cpptraj_state(txt.format(cm_no_buffer, 'size 20,20,20', '')) state.run() cpp_data = state.data[-1].values ds = volmap(traj, mask=':WAT@O', grid_spacing=(0.5, 0.5, 0.5), size=(20, 20, 20), buffer=2.0, centermask='!:1-13', radscale=1.36) aa_eq(cpp_data, ds) # test center state = pt.load_cpptraj_state(txt.format(cm_no_buffer, 'size 20,20,20', 'center 0.5,0.5,0.5')) state.run() cpp_data = state.data[-1].values ds = volmap(traj, mask=':WAT@O', grid_spacing=(0.5, 0.5, 0.5), size=(20, 20, 20), center=(0.5, 0.5, 0.5), buffer=2.0, centermask='!:1-13', radscale=1.36) aa_eq(cpp_data, ds) # raise RuntimeError dry_traj = pt.iterload('data/tz2.nc', 'data/tz2.parm7') self.assertRaises(RuntimeError, lambda: pt.volmap(dry_traj, mask=':WAT@O', grid_spacing=(0.5, 0.5, 0.5)))
def test_randomize_ions(self): fn = os.path.join(cpptraj_test_dir, 'Test_RandomizeIons', 'adh206.tip3p.rst7.gz') tn = os.path.join(cpptraj_test_dir, 'Test_RandomizeIons', 'adh206.ff10.tip3p.parm7.gz') saved_traj_name = os.path.join(cpptraj_test_dir, 'Test_RandomizeIons', 'random.crd.save') traj = pt.iterload(fn, tn) traj_mut = traj[:] saved_traj = pt.iterload(saved_traj_name, traj.top) pt.randomize_ions(traj_mut, mask='@Na+', around=':1-16', by=5.0, overlap=3.0, seed=113698) aa_eq(traj_mut.xyz, saved_traj.xyz, decimal=2)
def test_load_from_list(self): from glob import glob pattern = "./data/Test_RemdTraj/rem.nc.*" flist = sorted(glob(pattern)) top = glob("./data/Test_RemdTraj/ala*parm7")[0] traj0 = pt.iterload(flist, top) traj1 = pt.iterload(pattern, top) aa_eq(traj0.xyz, traj1.xyz) # raise if not find files self.assertRaises(ValueError, lambda: pt.iterload("./data/xyz_cool*.x", traj0.top))
def test_2(self): from pytraj.all_actions import do_autoimage # test do_autoimage traj = pt.iterload("./data/tz2.truncoct.nc", "./data/tz2.truncoct.parm7") f0 = traj[0] f0cp = f0.copy() do_autoimage(traj=f0, top=traj.top) fsaved = pt.iterload("./data/tz2.truncoct.autoiamge.save.r", "./data/tz2.truncoct.parm7")[0] aa_eq(fsaved.xyz, f0.xyz, decimal=3)
def test_comprehensive(self): traj = pt.iterload("./data/Tc5b.x", "./data/Tc5b.top") # make sure we DO reproducing cpptraj output f_saved = pt.iterload("./data/avg.Tc5b.pdb", traj.top)[0] # shorter frame2 = mean_structure(traj) aa_eq(frame2.xyz, f_saved.xyz, decimal=3) frame3 = mean_structure(traj=traj) aa_eq(frame3.xyz, f_saved.xyz, decimal=3) # test list frame4 = mean_structure(traj=[traj, traj[:3]], top=traj.top) # test iter frame5 = mean_structure(traj=traj(1, 8, 2), top=traj.top) f5_saved = pt.iterload("./data/avg.Tc5b.frame_2_to_8_skip_2.pdb", traj.top)[0] aa_eq(frame5.xyz, f5_saved.xyz, decimal=3) # test iter CA frame5 = mean_structure(traj[[0, 3, 7]], '@CA', top=traj.top) # use atom_indices ca_indices = pt.select('@CA', traj.top) frame5_1 = mean_structure(traj[[0, 3, 7]], ca_indices, top=traj.top) # test frame_indices frame6 = mean_structure(traj, mask='@CA', frame_indices=[0, 3, 7]) aa_eq(frame5.xyz, frame6.xyz, decimal=3) aa_eq(frame5_1.xyz, frame6.xyz, decimal=3) xyz_0 = pt.get_coordinates(traj(1, 8, 2)) xyz_1 = np.array([frame.xyz.copy( ) for frame in traj.iterframe(frame_indices=range(1, 8, 2))]) aa_eq(xyz_0, xyz_1, decimal=3) # test as traj out_traj = mean_structure(traj, mask='@CA', frame_indices=[0, 3, 7], dtype='traj') assert isinstance(out_traj, Trajectory), 'must be Trajectory' aa_eq(out_traj.xyz, frame6.xyz, decimal=3) # raise if not trajectory, traj or frame self.assertRaises(ValueError, lambda: pt.mean_structure(traj, dtype='trajxyz'))
def main(argv): args = sys.argv scorefile = 'AmberScores.sc' decoy_list = glob( "{base}/5.AmberMinimize/min*.rst7".format( base=BASE_DIR ) ) decoy_list = [] for d in decoy_list_long: decoy_list.append(d.strip()) print("Decoy List: " + str(len(decoy_list))) parmfile = "{base}/5.AmberMinimize/decoy.parm7".format( base=BASE_DIR ) print("Making Traj.") traj = pt.iterload( decoy_list, parmfile ) print("Getting energies...") energy_data = pt.pmap_mpi(pt.energy_decomposition, traj, igb=8) print("done!") if energy_data: ekeys = energy_data.keys() ekeys.sort() print('Scorefile: ' + scorefile) with open(scorefile,'w') as myscorefile: header = 'description\t' for key in ekeys: header += key + '\t' myscorefile.write(header +"\n") for decoy in range(len(decoy_list)): scoreline = decoy_list[decoy]+'\t' for key in ekeys: scoreline += "%s\t" % str(energy_data[key][decoy]) myscorefile.write(scoreline+"\n")
def test_check_valid_command(self): from pytraj.parallel.base import check_valid_command assert check_valid_command(['rms', ]) == (['rms refindex 0 '], True) assert check_valid_command(['distrmsd', ]) == (['distrmsd refindex 0 '], True) assert check_valid_command(['nativecontacts', ]) == (['nativecontacts refindex 0 '], True) assert check_valid_command(['nastruct', ]) == (['nastruct refindex 0 '], True) assert check_valid_command(['symmetricrmsd', ]) == (['symmetricrmsd refindex 0 '], True) traj = pt.iterload("data/tz2.nc", "data/tz2.parm7") aa_eq(pt.tools.dict_to_ndarray( pt.pmap(['rmsd'], traj, ref=traj[3], n_cores=3)), pt.rmsd(traj, ref=traj[3])) # provide refindex aa_eq(pt.tools.dict_to_ndarray( pt.pmap(['rmsd refindex 0'], traj, ref=traj[3], n_cores=3)), pt.rmsd(traj, ref=traj[3])) aa_eq(pt.tools.dict_to_ndarray( pt.pmap(['rmsd refindex 0'], traj, ref=[traj[3], traj[0]], n_cores=3)), pt.rmsd(traj, ref=traj[3])) # if user does not provide reference, need to give it to them aa_eq(pt.tools.dict_to_ndarray( pt.pmap(['rmsd'], traj, n_cores=3)), pt.rmsd(traj, ref=traj[0])) # does not support matrix self.assertRaises(ValueError, lambda: pt.pmap(['matrix'], traj, n_cores=2)) # do not accept any c analysis command for word in c_commands.analysis_commands: self.assertRaises(ValueError, lambda: pt.pmap(word, traj, n_cores=2))
def test_nosegfault_for_force(self): fn = cpptraj_test_dir + '/Test_systemVF/systemVF.nc' tn = cpptraj_test_dir + '/Test_systemVF/systemVF.parm7' traj = pt.iterload(fn, tn) for f in traj: assert f.has_force(), 'must have force'
def test_general(self): traj = pt.iterload("./data/Tc5b.x", "./data/Tc5b.top") # with mask saved_data = pt.radgyr(traj, '@CA') data = pt.pmap(pt.radgyr, traj, '@CA') data = pt.tools.dict_to_ndarray(data) aa_eq(saved_data, data) # with a series of functions func_list = [pt.radgyr, pt.molsurf, pt.rmsd] ref = traj[-3] for n_cores in [2, 3]: for func in func_list: if func in [pt.rmsd, ]: pout = pt.tools.dict_to_ndarray(pt.pmap(func=func, traj=traj, ref=ref, n_cores=n_cores)) serial_out = flatten(func(traj, ref=ref)) else: pout = pt.tools.dict_to_ndarray(pt.pmap(n_cores=n_cores, func=func, traj=traj)) serial_out = flatten(func(traj)) aa_eq(pout[0], serial_out) # test worker # need to test this since coverages seems not recognize partial func from pytraj.parallel.multiprocessing_ import worker_byfunc data = worker_byfunc(rank=2, n_cores=8, func=pt.radgyr, traj=traj, args=(), kwd={'mask': '@CA'}, iter_options={}) assert data[0] == 2, 'rank must be 2' assert data[2] == 1, 'n_frames for rank=2 should be 1 (only 10 frames in total)'
def test_1(self): # merge_frames import numpy as np # load 2 frames traj = pt.iterload("./data/Tc5b.x", "./data/Tc5b.top", frame_slice=(0, 2)) # test mutable traj t0 = traj[:] frame = pt.tools.merge_frames(t0) r0 = pt.tools.rmsd(frame.xyz, pt.get_coordinates(traj), True) assert r0 == 0. # test immutable traj assert np.any(pt.tools.merge_frames(traj).xyz.flatten() == pt.get_coordinates(traj).flatten()) # tuple assert np.any(pt.tools.merge_frames(( frame for frame in traj)).xyz.flatten() == pt.get_coordinates( traj).flatten()) # list assert np.any(pt.tools.merge_frames( [frame for frame in traj]).xyz.flatten() == pt.get_coordinates( traj).flatten()) # frame_iter: all atoms assert np.any(pt.tools.merge_frames(traj()).xyz.flatten() == pt.get_coordinates(traj()).flatten())
def test_vs_list_tuple(self): traj = pt.iterload("./data/tz2.ortho.nc", "./data/tz2.ortho.parm7") traj0 = pt.replicate_cell(traj, direction='dir 001 dir 0-10') traj1 = pt.replicate_cell(traj, direction=('001', '0-10')) aa_eq(traj0.xyz, traj1.xyz) self.assertRaises(ValueError, lambda: pt.replicate_cell(traj, direction=traj[0]))
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 test_nh_paramters(self): parmfile = cpptraj_test_dir + '/Test_IRED/1IEE_A_prot.prmtop' trajfile = cpptraj_test_dir + '/Test_IRED/1IEE_A_test.mdcrd' traj = pt.iterload(trajfile, parmfile) h_indices = pt.select_atoms('@H', traj.top) n_indices = h_indices - 1 nh_indices = list(zip(n_indices, h_indices)) # single core orders = pt.NH_order_parameters(traj, nh_indices, tcorr=8000.) saved_S2 = np.loadtxt(cpptraj_test_dir + '/Test_IRED/orderparam.save').T[-1] aa_eq(orders, saved_S2) # multiple core # default 2 orders = pt.pmap(pt.NH_order_parameters, traj, nh_indices, tcorr=8000.) aa_eq(orders, saved_S2) for n_cores in [1, 2, 3, 4, -1]: orders = pt.NH_order_parameters(traj, nh_indices, tcorr=8000., n_cores=n_cores) aa_eq(orders, saved_S2) orders = pt.pmap(pt.NH_order_parameters, traj, nh_indices, tcorr=8000., n_cores=n_cores) aa_eq(orders, saved_S2)
def test_frame_indices(self): # load frames to immutable traj traj = pt.iterload("data/tz2.nc", "data/tz2.parm7") # convert to numpy traj frame_indices = [0, 3, 5] t00 = traj[:] t01 = traj[:] t10 = traj[frame_indices] t11 = traj[frame_indices] aa_eq(t00[frame_indices].xyz, t11.xyz) ref = traj[-1] t00.superpose(ref=ref, frame_indices=frame_indices) ref = traj[-1] pt.superpose(t01, ref=ref, frame_indices=frame_indices) ref = traj[-1] t10.superpose(ref=ref) ref = traj[-1] pt.superpose(t11, ref=ref, frame_indices=frame_indices) aa_eq(t00.xyz, t01.xyz) aa_eq(t10.xyz, t11.xyz) aa_eq(t00[frame_indices].xyz, t10.xyz)
def test_0(self): import numpy as np # load 2 frames traj = pt.iterload("./data/Tc5b.x", "./data/Tc5b.top", frame_slice=(0, 2)) # test mutable traj big_frame = pt.tools.merge_frames(traj[:]) assert pt.tools.rmsd(big_frame.xyz.flatten(), pt.get_coordinates(traj).flatten()) < 1E-5 # test immutable traj big_frame = pt.tools.merge_frames(traj) assert pt.tools.rmsd(big_frame.xyz.flatten(), pt.get_coordinates(traj).flatten()) < 1E-5 # test tuple big_frame = pt.tools.merge_frames((frame for frame in traj)) assert pt.tools.rmsd(big_frame.xyz.flatten(), pt.get_coordinates(traj).flatten()) < 1E-5 # test list big_frame = pt.tools.merge_frames([frame.copy() for frame in traj]) assert pt.tools.rmsd(big_frame.xyz.flatten(), pt.get_coordinates(traj).flatten()) < 1E-5
def test_radgyr_dispatch(self): traj = pt.iterload("./data/tz2.ortho.nc", "./data/tz2.ortho.parm7") # mask is an array-like aa_eq(sb._toy_radgyr(traj, [0, 3]), pt.radgyr(traj, '@1,4')) # frame_indices aa_eq( sb._toy_radgyr(traj, '@CA', frame_indices=[0, 3]), pt.radgyr(traj, '@CA')[[0, 3]]) # frame_indices, mask in kwd aa_eq( sb._toy_radgyr(traj, mask='@CA', frame_indices=[0, 3]), pt.radgyr(traj, '@CA')[[0, 3]]) # frame iterator aa_eq( sb._toy_radgyr( traj(0, 3), mask='@CA'), pt.radgyr(traj, '@CA')[[0, 1, 2]])
def test_2(self): traj = pt.iterload("./data/Tc5b.nat.crd", "./data/Tc5b.top") t0 = traj[:1] pt.set_dihedral(t0, resid='4', dihedral_type='phi', deg=120) dih = pt.calc_phi(t0, resrange='4').values[0] assert abs(dih - 120) < 1E-3 t0.save('test.pdb', options='model', overwrite=True)
def test_0(self): traj = pt.iterload("./data/Tc5b.x", "./data/Tc5b.top") traj(0, 8, 2, mask='@CA').save('output/test0.nc', overwrite=True) pt.write_traj('./output/test1.nc', traj(0, 8, 2, mask='@CA'), overwrite=True) new_top = traj.top._get_new_from_mask('@CA') t0 = pt.iterload('./output/test0.nc', new_top) t1 = pt.iterload('./output/test1.nc', new_top) aa_eq(t0.xyz, t1.xyz)
def test_pipe(self): traj = pt.iterload("data/tz2.ortho.nc", "data/tz2.ortho.parm7") # from TrajectoryIterator fi = pt.pipe(traj, ['autoimage', 'rms']) xyz = np.array([frame.xyz.copy() for frame in fi]) t0 = traj[:].autoimage().superpose() aa_eq(xyz, t0.xyz) # from FrameIterator fi = pt.pipe(traj(), ['autoimage', 'rms']) xyz = np.array([frame.xyz.copy() for frame in fi]) t0 = traj[:].autoimage().superpose() aa_eq(xyz, t0.xyz) # from FrameIterator with indices fi = pt.pipe(traj(0, 8, 2), ['autoimage', 'rms']) xyz = np.array([frame.xyz.copy() for frame in fi]) t0 = traj[:8:2].autoimage().superpose() aa_eq(xyz, t0.xyz) # from TrajectoryIterator, cpptraj's command style fi = pt.pipe(traj, ''' autoimage rms''') xyz = np.array([frame.xyz.copy() for frame in fi]) t0 = traj[:].autoimage().superpose() aa_eq(xyz, t0.xyz)
def test_comprehensive(self): traj = pt.iterload("data/Test_RemdTraj/rem.nc.000", "data/Test_RemdTraj/ala2.99sb.mbondi2.parm7") # temperature aa_eq(traj.temperatures, [300., 630.5, 630.5, 630.5, 630.5, 630.5, 630.5, 630.5, 492.2, 384.3]) # iterframe (already in doctest), just throwing raise to increase coverage score self.assertRaises(ValueError, lambda: traj.iterframe(rmsfit='crazy')) # raise # memory error if load larger than 1GB for xyz traj = pt.datafiles.load_tz2_ortho() for _ in range(11): traj._load(traj.filelist) self.assertRaises(MemoryError, lambda: traj.xyz) # can not find filename self.assertRaises(ValueError, lambda: traj._load(None)) # has filename but does not have Topology self.assertRaises( ValueError, lambda: pt.TrajectoryIterator("data/Test_RemdTraj/rem.nc.000", top=None)) self.assertRaises( ValueError, lambda: pt.TrajectoryIterator("data/Test_RemdTraj/rem.nc.000")) # empty Topology self.assertRaises( ValueError, lambda: pt.TrajectoryIterator("data/Test_RemdTraj/rem.nc.000", top=pt.Topology())) # weird Topology self.assertRaises( ValueError, lambda: pt.TrajectoryIterator("data/Test_RemdTraj/rem.nc.000", top=pt.Frame))
def test_matrix_module(self): traj = pt.iterload("data/tz2.nc", "data/tz2.parm7") for n_cores in [2, 3]: for func in [matrix.dist, matrix.idea]: x = pt.pmap(func, traj, '@CA', n_cores=n_cores) aa_eq(x, func(traj, '@CA'))
def test_general(self): traj = pt.iterload("./data/tz2.crd", "./data/tz2.parm7") for (mask, delta) in [('*', 0.1), ('@CA', '0.2')]: data = pt.pairdist(traj, delta=delta, mask=mask, dtype='ndarray') data0 = data[0].T data1 = data[1].T txt = ''' parm ./data/tz2.parm7 trajin ./data/tz2.crd pairdist out test.out mask {0} delta {1} '''.format(mask, delta) # take data, skip DatasetTopology cpp_data = pt.datafiles.load_cpptraj_output(txt)[1:].values cpp_distance, cpp_Pr = cpp_data[0].T _, cpp_std = cpp_data[1].T aa_eq(data0[0], cpp_distance) # distance aa_eq(data1[0], cpp_distance) # distance aa_eq(data0[1], cpp_Pr, decimal=2) # Pr aa_eq(data1[1], cpp_std, decimal=2) # std
def test_0(self): # merge_coordinates import numpy as np # load 2 frames traj = pt.iterload("./data/Tc5b.x", "./data/Tc5b.top", frame_slice=(0, 2)) # test mutable traj coords = pt.tools.merge_coordinates(traj[:]) r0 = pt.tools.rmsd(coords, pt.get_coordinates(traj)) assert r0 == 0. # test immutable traj coords = pt.tools.merge_coordinates(traj) r0 = pt.tools.rmsd(coords, pt.get_coordinates(traj), True) assert r0 == 0. # test tuple coords = pt.tools.merge_coordinates((frame for frame in traj)) r0 = pt.tools.rmsd(coords, pt.get_coordinates(traj), True) assert r0 == 0. coords = pt.tools.merge_coordinates([f.copy() for f in traj]) r0 = pt.tools.rmsd(coords, pt.get_coordinates(traj), True) assert r0 == 0.
def test_reference(self): traj = pt.iterload(fn('tz2.nc'), fn('tz2.parm7')) for n_cores in [2, 3]: # use 4-th Frame for reference data = pt.pmap(['rms @CA refindex 0'], traj, ref=traj[3], n_cores=n_cores) # another way to get reference data2 = pt.pmap(['rms @CA reference'], traj, ref=traj[3], n_cores=n_cores) # use int for ref data3 = pt.pmap(pt.rmsd, traj, ref=3, mask='@CA', n_cores=n_cores) # use int for ref: use cpptraj's commmand style data4 = pt.pmap(['rms @CA reference'], traj, ref=3, n_cores=n_cores) arr = pt.tools.dict_to_ndarray(data)[0] arr2 = pt.tools.dict_to_ndarray(data2)[0] arr3 = pt.tools.dict_to_ndarray(data3)[0] arr4 = pt.tools.dict_to_ndarray(data4)[0] aa_eq(arr, pt.rmsd(traj, ref=3, mask='@CA')) aa_eq(arr2, pt.rmsd(traj, ref=3, mask='@CA')) aa_eq(arr3, pt.rmsd(traj, ref=3, mask='@CA')) aa_eq(arr4, pt.rmsd(traj, ref=3, mask='@CA')) # use 4-th and 5-th Frame for reference data = pt.pmap(['rms @CA refindex 0', 'rms @CB refindex 1'], traj, ref=[traj[3], traj[4]], n_cores=n_cores) arr = pt.tools.dict_to_ndarray(data)[0] aa_eq(arr, pt.rmsd(traj, '@CA', 3)) arr1 = pt.tools.dict_to_ndarray(data)[1] aa_eq(arr1, pt.rmsd(traj, ref=4, mask='@CB')) # no ref data = pt.pmap([ 'radgyr', ], traj, n_cores=n_cores) arr = pt.tools.dict_to_ndarray(data)[0] aa_eq(arr, pt.radgyr(traj))
def test_iter(self): traj = pt.iterload(fn('Tc5b.x'), fn('Tc5b.top')) fa = traj[:] iter_me(traj, traj.n_frames) iter_me(fa, traj.n_frames) iter_me(traj(), traj.n_frames) iter_me(fa(), traj.n_frames) iter_me(traj(mask='@CA'), traj.n_frames) iter_me(fa(mask='@CA'), traj.n_frames) iter_me([traj, fa], 2 * traj.n_frames) iter_me((traj, fa), 2 * traj.n_frames) iter_me((traj, (fa[0], )), traj.n_frames + 1) for frame in iterframe_master(traj[0]): assert frame.n_atoms == traj.top.n_atoms i = 0 for frame in iterframe_master([traj, traj[:1]]): i += 1 assert frame.n_atoms == traj.top.n_atoms assert i == traj.n_frames + 1 i = 0 for frame in iterframe_master(traj.iterchunk()): i += 1 assert isinstance(frame, Frame) assert i == traj.n_frames i = 0 for frame in iterframe_master([ traj.iterchunk(), ]): i += 1 assert isinstance(frame, Frame) assert i == traj.n_frames # raise if wrong type def test_raise(): for frame in pt.iterframe_master([0, 3]): pass with pytest.raises(TypeError): test_raise()
def __init__(self, Traj, Parm, HS, start=0, stop=-1, step=1, mask=":WAT@O", radius=1.5, dt=1.0): __doc__ = """ Traj : Path to trajectory file Parm : Path to parameter file HS : Path to cluster center (hydration sites) file start : Start frame trajectory, default 0 stop : Stop frame trajectory, default -1 (last) step : Stride every step frame, default 1 mask : selection mask used for water calculation, default \":WAT@O\" radius: radius of cluster center dt : integration step for autocorrelation in pico seconds """ self.traj_path = Traj self.parm_path = Parm self.hs_path = HS self.mask = mask self.radius = radius self.dt = dt self.traj = pt.iterload(self.traj_path, self.parm_path, frame_slice=(start, stop, step), mask=self.mask) self.hs = pt.load(self.hs_path) ### This contains all data of the time series ### rows contain frames, columns contain different hydration sites self.series = np.zeros((self.traj.n_frames, self.hs.n_atoms), dtype=np.int_) self.autocorr = np.zeros((self.traj.n_frames, self.hs.n_atoms)) self.crosscorr = np.zeros( (self.traj.n_frames, self.hs.n_atoms, self.hs.n_atoms)) self.__get_data()
def test_rotation_matrix_in_rmsd_calculation(self): traj = pt.iterload("data/tz2.nc", "data/tz2.parm7") saved_mat = pt.rotation_matrix(traj, ref=traj[3], mask='@CA') saved_rmsd = pt.rmsd(traj, ref=traj[3], mask='@CA') for n_cores in [2, 3]: out = pt.pmap(pt.rotation_matrix, traj, ref=traj[3], mask='@CA') out_with_rmsd = pt.pmap(pt.rotation_matrix, traj, ref=traj[3], mask='@CA', with_rmsd=True) mat = out[list(out.keys())[0]] mat2, rmsd_ = out_with_rmsd[list(out_with_rmsd.keys())[0]] aa_eq(saved_mat, mat) aa_eq(saved_mat, mat2) aa_eq(saved_rmsd, rmsd_)
def test_iter_options(self): traj = pt.iterload("data/tz2.ortho.nc", "data/tz2.ortho.parm7") t0 = traj[:].autoimage().rmsfit(ref=0) saved_avg = pt.mean_structure(t0) saved_radgyr = pt.radgyr(traj, '@CA') # perform autoimage, then rms fit to 1st frame, then compute mean structure iter_options = {'autoimage': True, 'rmsfit': 0} for n_cores in [2, 3]: avg = pt.pmap(pt.mean_structure, traj, iter_options=iter_options, n_cores=n_cores) aa_eq(saved_avg.xyz, avg.xyz) radgyr_ = pt.tools.dict_to_ndarray( pt.pmap(pt.radgyr, traj, iter_options={'mask': '@CA'})) aa_eq(radgyr_[0], saved_radgyr)
def test_vector_principal(self): traj = pt.iterload(fn('Tc5b.x'), fn('Tc5b.top')) pdata = pt.vector.principal(traj) assert pdata.shape == (10, 3) np.testing.assert_almost_equal( pt.vector.principal(traj), [[-0.16903813783287722, 0.36316033000258224, 0.9162645265808389], [-0.3199676454090604, 0.8725925204063159, -0.36905690512756323], [ 0.9845639960055733, -0.1655283170881773, -0.056869271241093346 ], [0.806423302456264, 0.35877569174107243, -0.47006537872007553], [0.06177153699316464, 0.9689358562119692, 0.23947355545922028], [-0.1977750666117889, 0.10362572565059913, 0.9747547035075487], [ 0.8122317492961045, -0.032170512063985766, 0.5824471165598908 ], [ 0.30670002856835077, 0.22464432292840247, -0.9249162235857972 ], [0.7710019864344335, -0.04553437498669517, 0.6352027688925233], [-0.17181943718191456, 0.7403546691757756, 0.6498869477348488]])
def test_issue807(self): # files are provided by Chris Lee traj = pt.iterload("./data/issue807/trunc.nc", "./data/issue807/system.prmtop") traj[0] for frame in traj: pass traj[::2] pt.radgyr(traj[[0, 3]]) pt.radgyr(traj, frame_indices=[0, 3]) pt.radgyr(traj()) traj[:3, '@O'].xyz pt.get_coordinates((traj.iterframe(mask='@O'))) pt.radgyr(traj(mask='@O')) for c in pt.iterchunk(traj, 4): assert c[0].n_atoms == traj.top.n_atoms
def test_pytraj_do(): traj = pt.iterload(fn("tz2.nc"), fn("tz2.parm7")) ref0 = pt.autoimage(traj[0], top=traj.top) ref1 = pt.autoimage(traj[1], top=traj.top) data = pt.tools.dict_to_ndarray(pt.compute( ['autoimage', 'radgyr nomax @CA', 'rms refindex 0', 'rms refindex 1'], traj, ref=[ref0, ref1])) t0 = pt.autoimage(traj[:]) aa_eq(pt.radgyr(t0, '@CA'), data[0]) aa_eq(pt.rmsd(t0, ref=ref0), data[1]) aa_eq(pt.rmsd(t0, ref=ref1), data[2]) aa_eq(pt.compute(pt.radgyr, t0, '@CA'), data[0])
def test_atom_distance(self): traj = pt.iterload(tz2_trajin, tz2_top) top = traj.top ref = traj[0] # test for 1st frame top.set_reference(ref) ref.top = top # all atoms within 5 Angtrom from :3@CA indices = top.select(":3@CA <@5.0") saved_indices = np.loadtxt( fn("mask.tz2.dat"), skiprows=1, usecols=(1, )) neighbors_smaller = pt.search_neighbors( traj, mask=':3@CA <@5.0', frame_indices=[ 0, ]) # subtract by '1' since cpptraj uses "1" as starting index for output saved_indices = saved_indices - 1 aa_eq(indices, saved_indices) aa_eq(neighbors_smaller.values, indices) # re-calculate the distance ca_indices = pt.select_atoms(':3@CA', traj.top) all_pairs = list(product(ca_indices, indices)) distances = pt.tools.flatten(pt.distance(ref, all_pairs)) for dist in distances: assert dist < 5.0, 'all distances must be smaller than 5.0 Angstrom' # test larger # why do we need to set reference frame again? top.set_reference(ref) indices_larger = top.select(":3@CA >@5.0") all_pairs_larger = list(product(ca_indices, indices_larger)) distances = pt.tools.flatten(pt.distance(ref, all_pairs_larger)) for dist in distances: assert dist > 5.0, 'all distances must be larger than 5.0 Angstrom' # search_neighbors neighbors_larger = pt.search_neighbors( traj, mask=':3@CA >@5.0', frame_indices=[ 0, ]) aa_eq(neighbors_larger.values, indices_larger)
def test_RMSF(self): traj = pt.iterload(fn('tz2.nc'), fn('tz2.parm7')) state = pt.load_batch(traj, ''' rms first average crdset MyAvg run rms ref MyAvg atomicfluct out fluct.agr''') state.run() t0 = traj[:] pt.superpose(t0, ref=0) avg = pt.mean_structure(t0) pt.superpose(t0, ref=avg) data = pt.rmsf(t0) aa_eq(data, state.data[-1].values)
def test_calc_atomicfluct_with_unitcell(self): # use iterload for load_batch traj = pt.iterload(fn('tz2.ortho.nc'), fn('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(fn('tz2.ortho.nc'), fn('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_autoimage_with_rmsfit(self): traj = pt.iterload(fn('tz2.ortho.nc'), fn('tz2.ortho.parm7')) t0 = traj[:] pt.autoimage(t0).superpose() avg_0 = pt.mean_structure(t0, '@CA') avg_1 = pt.mean_structure(traj(autoimage=True, rmsfit=0), '@CA') aa_eq(avg_0.xyz, avg_1.xyz) # 3rd frame # assign traj again t0 = traj[:] pt.autoimage(t0).superpose(ref=3) avg_0 = pt.mean_structure(t0, '@CA') avg_1 = pt.mean_structure(traj(autoimage=True, rmsfit=3), '@CA') avg_2 = pt.mean_structure(traj, autoimage=True, rmsfit=3, mask='@CA') aa_eq(avg_0.xyz, avg_1.xyz) aa_eq(avg_0.xyz, avg_2.xyz) # 3rd frame, frame_indices # assign traj again frame_indices = [0, 8, 5] t0 = traj[frame_indices] t1 = traj[frame_indices] t0.autoimage().superpose(ref=-1) avg_0 = pt.mean_structure(t0, '@CA') # use ref=5 which correspond to original index # try with pytraj.TrajectoryIterator avg_1 = pt.mean_structure(traj, autoimage=True, rmsfit=5, mask='@CA', frame_indices=frame_indices) # try with pytraj.Trajectory avg_2 = pt.mean_structure(t1, autoimage=True, rmsfit=-1, mask='@CA') avg_3 = pt.mean_structure(traj[:], autoimage=True, rmsfit=5, mask='@CA', frame_indices=frame_indices) aa_eq(avg_0.xyz, avg_1.xyz) aa_eq(avg_0.xyz, avg_2.xyz) aa_eq(avg_0.xyz, avg_3.xyz)
def test_frame_indices(self): traj = pt.iterload(fn('tz2.nc'), fn('tz2.parm7')) # frame_indices could be a list, range frame_indices_list = [[0, 8, 9, 3, 2, 5], range(6)] for frame_indices in frame_indices_list: for n_cores in [2, 3]: serial_out = pt.radgyr( traj, '@CA', frame_indices=frame_indices) parallel_out = pt.pmap( pt.radgyr, traj, '@CA', frame_indices=frame_indices) parallel_out_c_style = pt.pmap( ['radgyr @CA nomax'], traj, frame_indices=frame_indices) aa_eq([serial_out], pt.tools.dict_to_ndarray(parallel_out)) aa_eq([serial_out], pt.tools.dict_to_ndarray(parallel_out_c_style))
def test_diagmatrix_mwcovar(self): traj = pt.iterload(fn('tz2.nc'), fn('tz2.parm7')) state = pt.load_batch(traj, ''' matrix mwcovar @CA name mymat diagmatrix mymat vecs 6 name mydiag''') state.run() mat = pt.matrix.mwcovar(traj, '@CA') ca_indices = traj.top.select('@CA') eigenvectors, eigenvalues = pt.matrix.diagonalize( mat, n_vecs=6, scalar_type='mwcovar', mass=traj.top.mass[ca_indices]) aa_eq(np.abs(state.data['mydiag'].eigenvalues), np.abs(eigenvalues)) aa_eq(np.abs(state.data['mydiag'].eigenvectors), np.abs(eigenvectors))
def test_comprehensive(self): traj = pt.iterload(fn('Test_RemdTraj/rem.nc.000'), fn('Test_RemdTraj/ala2.99sb.mbondi2.parm7')) # temperature aa_eq(traj.temperatures, [ 300., 630.5, 630.5, 630.5, 630.5, 630.5, 630.5, 630.5, 492.2, 384.3 ]) # iterframe (already in doctest), just throwing raise to increase coverage score self.assertRaises(ValueError, lambda: traj.iterframe(rmsfit='crazy')) # raise # memory error if load larger than 1GB for xyz traj = pt.datafiles.load_tz2_ortho() for _ in range(2): traj._load(traj.filelist) with patch('pytraj.trajectory.trajectory_iterator.TrajectoryIterator._estimated_GB') as \ mem: def mock_get(*args, **kwargs): return 10000000 mem.__get__ = mock_get self.assertRaises(MemoryError, lambda: traj.xyz) # can not find filename self.assertRaises(ValueError, lambda: traj._load(None)) # has filename but does not have Topology self.assertRaises( ValueError, lambda: pt.TrajectoryIterator(fn('Test_RemdTraj/rem.nc.000'), top=None)) self.assertRaises( ValueError, lambda: pt.TrajectoryIterator(fn('Test_RemdTraj/rem.nc.000'))) # empty Topology self.assertRaises( ValueError, lambda: pt.TrajectoryIterator(fn('Test_RemdTraj/rem.nc.000'), top=pt.Topology())) # weird Topology self.assertRaises( ValueError, lambda: pt.TrajectoryIterator(fn('Test_RemdTraj/rem.nc.000'), top=pt.Frame))
def test_cluster_hieragglo(): command = """ parm {} trajin {} createcrd crd1 cluster crdset crd1 C0 !@H hieragglo epsilon 0.8 averagelinkage """.format(tz2_top, tz2_trajin) with tempfolder(): state = pt.load_cpptraj_state(command) with capture_stdout() as (cpp_out, _): state.run() traj = pt.iterload(tz2_trajin, tz2_top) data = pt.cluster.hieragglo(traj, mask='!@H=', options='epsilon 0.8 averagelinkage') aa_eq(state.data[-2], data.cluster_index)
def test_cluster_dbscan(): command = """ parm {} trajin {} createcrd crd1 cluster crdset crd1 C0 @CA dbscan epsilon 1.7 minpoints 5 """.format(tz2_top, tz2_trajin) with tempfolder(): state = pt.load_cpptraj_state(command) with capture_stdout() as (out, _): state.run() traj = pt.iterload(tz2_trajin, tz2_top) data = pt.cluster.dbscan(traj, mask='@CA', options='epsilon 1.7 minpoints 5') aa_eq(state.data[-2], data.cluster_index)
def test_reference(self): traj = pt.iterload("data/tz2.ortho.nc", "data/tz2.ortho.parm7") # store reference dslist = CpptrajDatasetList() ref = dslist.add_new('reference') ref.top = traj.top ref.append(traj[3]) fi = pt.pipe(traj, ['autoimage', 'rms refindex 0 @CA'], dslist=dslist) xyz = np.array([frame.xyz.copy() for frame in fi]) t0 = (traj[:].autoimage().superpose(ref=traj[3], mask='@CA')) print('ok') aa_eq(xyz, t0.xyz) t1 = traj[:].autoimage() aa_eq(pt.rmsd(t1, ref=traj[3], mask='@CA'), dslist[-1].values)
def testsuper_dispatch(self): traj = pt.iterload(fn('tz2.nc'), fn('tz2.parm7')) funclist = [pt.radgyr, pt.molsurf] for func in funclist: mask = '@CA' atom_indices = pt.select_atoms(mask, traj.top) # mask aa_eq(func(traj, mask=mask), func(traj, mask=atom_indices)) # specify traj=traj aa_eq(func(traj=traj, mask=mask), func(traj, mask=atom_indices)) # frame_indices with mask frame_indices = [0, 5, 8] aa_eq( func(traj[frame_indices], mask=mask), func(traj, mask=atom_indices, frame_indices=frame_indices))
def test_radgyr(self): traj = pt.iterload( top="./data/Tc5b.top", filename='data/Tc5b.x', ) txt = ''' parm ./data/Tc5b.top trajin ./data/Tc5b.x radgyr @CA nomax radgyr nomax radgyr !@H= nomax ''' # exclude DatasetTopology data = pt.datafiles.load_cpptraj_output(txt)[1:] for mask, out in zip(['@CA', '', '!@H='], data): aa_eq(pt.radgyr(traj, mask), out)
def test_matrix(self): import numpy as np from pytraj import ArgList from pytraj import matrix as ma from pytraj.externals.six import iteritems matrix_test_dir = cpptraj_test_dir + "/Test_Matrix/" top_file = matrix_test_dir + "/1rrb_vac.prmtop" crd_file = matrix_test_dir + "/1rrb_vac.mdcrd" traj = pt.iterload(crd_file, top_file) with tempfolder(): state = pt.load_cpptraj_state(all_commands, traj) state.run() state_byres = pt.load_batch(traj, byres_cm) state_byres.run() byres_matlist = [] # no byres keyword for idx, line in enumerate(command_list): arg = ArgList(line) # get function act_key = arg.get_string_key("matrix") slist = arg.get_string_key('out').split(".") mask = arg.get_next_mask() fname = ".".join((slist[0], slist[-1], slist[1])) # get correct name func = ma.__dict__[act_key] # get command command = line.split(act_key)[1] matout = func(traj, command, dtype='ndarray') # cpptraj output has only 3 digits after decimal if 'byres' not in command: aa_eq(matout.flatten(), state.data[idx + 1].values) else: # save data for asserting later byres_matlist.append(matout) byres_arr = np.array(byres_matlist, dtype='f8') # only take byres datasets saved_matbyres = state_byres.data[[1, 3]].values aa_eq(byres_arr, saved_matbyres)
def test_radgyr_dispatch(self): traj = pt.iterload(fn('tz2.ortho.nc'), fn('tz2.ortho.parm7')) # mask is an array-like aa_eq(sb._toy_radgyr(traj, [0, 3]), pt.radgyr(traj, '@1,4')) # frame_indices aa_eq(sb._toy_radgyr(traj, '@CA', frame_indices=[0, 3]), pt.radgyr(traj, '@CA')[[0, 3]]) # frame_indices, mask in kwd aa_eq(sb._toy_radgyr(traj, mask='@CA', frame_indices=[0, 3]), pt.radgyr(traj, '@CA')[[0, 3]]) # frame iterator aa_eq(sb._toy_radgyr(traj(0, 3), mask='@CA'), pt.radgyr(traj, '@CA')[[0, 1, 2]])
def test_iter_with_a_list_of_frame_and_trajectory_and_FrameIterator(self): traj = pt.iterload("./data/Tc5b.x", "./data/Tc5b.top") ref = traj[0] for idx, frame in enumerate(iterframe_master([traj[0], traj])): assert isinstance(frame, Frame), 'must a a Frame' assert idx == traj.n_frames # FrameIterator: traj() for idx, frame in enumerate(iterframe_master([traj[0], traj()])): assert isinstance(frame, Frame), 'must a a Frame' assert idx == traj.n_frames # FrameIterator: traj() fi = traj.iterframe(frame_indices=[0, 3]) for idx, frame in enumerate(iterframe_master([traj[0], fi])): assert isinstance(frame, Frame), 'must a a Frame'
def test_append_trajectory(self): # test append traj = pt.Trajectory() t = pt.iterload(fn('Tc5b.x'), fn('Tc5b.top')) traj.top = t.top # append single Frame traj.append(t[0]) assert traj.n_frames == 1 # append xyz traj.append(t.xyz[:]) assert traj.n_frames == t.n_frames + 1 # append TrajectoryIterator traj.append(t) assert traj.n_frames == t.n_frames * 2 + 1 # append frame_iter traj.append(t.iterframe()) assert traj.n_frames == t.n_frames * 3 + 1 # append pt.iterframe_master traj.append(pt.iterframe_master(t)) assert traj.n_frames == t.n_frames * 4 + 1 # append itself NFrames = traj.n_frames traj.append(traj) assert traj.n_frames == NFrames * 2 # append itself frame_iter traj.append(traj.iterframe(stop=2)) assert traj.n_frames == NFrames * 2 + 2 # append pt.iterframe_master for itself NFrames = traj.n_frames traj.append(pt.iterframe_master(traj)) assert traj.n_frames == NFrames * 2 # append pt.iterframe_master for itself + other n0 = traj.n_frames n1 = t.n_frames traj.append(pt.iterframe_master([traj, t])) assert traj.n_frames == 2 * n0 + n1
def test_ired_lapack_in_numpy(self): parmfile = parm_dir trajfile = traj_dir # load to TrajectoryIterator traj = pt.iterload(trajfile, parmfile) # create N-H vectors h_indices = pt.select_atoms('@H', traj.top) n_indices = pt.select_atoms('@H', traj.top) - 1 nh_indices = list(zip(n_indices, h_indices)) # compute N-H vectors and ired matrix vecs_and_mat = pt.ired_vector_and_matrix(traj, mask=nh_indices, order=2) state_vecs = vecs_and_mat[:-1].values mat_ired = vecs_and_mat[-1] mat_ired /= mat_ired[0, 0] # cpptraj data_cpp = pt.matrix.diagonalize(mat_ired, n_vecs=len(state_vecs))[0] print(data_cpp.eigenvectors) # numpy data_np = pt.matrix._diag_np(mat_ired, n_vecs=len(state_vecs)) def order_(modes): data = _ired(state_vecs, modes=modes) order_s2_v0 = data['IRED_00127[S2]'] # make sure the S2 values is 1st array # load cpptraj's output and compare to pytraj' values for S2 order paramters cpp_order_s2 = np.loadtxt(os.path.join( cpptraj_test_dir, 'Test_IRED', 'orderparam.save')).T[-1] aa_eq(order_s2_v0.values, cpp_order_s2, decimal=4) order_(data_cpp.values) def plot_(x, y): import seaborn as sb sb.heatmap(x - y) pt.show() print((data_cpp.values[1] - data_np[1]).shape)
def test_run_3(self): dslist = CpptrajDatasetList() actlist = ActionList() traj = pt.iterload(tc5b_trajin, tc5b_top) mask_list = ['@CB @CA @N', '@CA @H @N'] for mask in mask_list: actlist.add(CA.Action_Angle(), mask, traj.top, dslist=dslist) actlist.compute(traj) pt.calc_angle(traj, mask_list) dslist3_0 = pt.calc_angle(traj, mask_list[0]) dslist3_1 = pt.calc_angle(traj, mask_list[1]) aa_eq(dslist3_0, dslist[0].to_ndarray()) aa_eq(dslist3_1, dslist[1].to_ndarray()) aa_eq(dslist3_0, dslist[0].to_ndarray()) aa_eq(dslist3_1, dslist[1].to_ndarray())
def test_hbonds_solvent_bridge(self): traj = pt.iterload(fn('tz2.ortho.nc'), fn('tz2.ortho.parm7')) # find solvent bridge between residue 10 and 11. hb = pt.hbond(traj, ':10,11', solvent_donor=':WAT', solvent_acceptor=':WAT') assert hb._get_bridge() == \ [[('WAT208', 'THR10', 'TRP11')], [('WAT208', 'THR10', 'TRP11')], [('WAT208', 'THR10', 'TRP11')], [('WAT208', 'THR10', 'TRP11')], [], [], [], [], [], [('WAT266', 'THR10', 'TRP11')]]
def calcS2(self, s='phi', stride=2): print('calculating order parameters of ' + s + ' angles....') S2 = dict() for tt, t in enumerate(self.trajs): traj = pt.iterload(t, self.top, stride=stride) #read dihedral angles dih = pt.multidihedral(traj, s) #get residues labels = dih.keys() residues = sorted([int(l[len(s) + 1:]) for l in labels]) S2[tt] = dict() for r in residues: lab = s + ':' + str(r) vals = np.array(dih[lab]) S2[tt][r] = (np.sum(np.cos(vals * np.pi / 180.))**2 + np.sum( np.sin(vals * np.pi / 180.))**2) / len(vals)**2 return S2
def test_hbond_general(self): traj = pt.iterload("./data/DPDP.nc", "./data/DPDP.parm7") dslist = pt.search_hbonds(traj, dtype='dataset') for key in dslist.keys(): if 'UU' not in key: assert len(dslist[key].values) == traj.n_frames mydict = dslist.to_dict() mydict_np = dslist.to_dict() assert len(mydict.keys()) == dslist.size assert len(mydict_np.keys()) == dslist.size for key in mydict.keys(): mydict[key] = np.asarray(mydict[key]) aa_eq(mydict[key], mydict_np[key]) # raise if dtype='hbond' and series=False self.assertRaises(ValueError, lambda: pt.hbond(traj, series=False, dtype='hbond'))
def test_0(self): traj = pt.iterload(fn('Tc5b.x'), fn('Tc5b.top')) # rmsd flist = [ pt.rmsd, pt.radgyr, pt.molsurf, pt.calc_atomicfluct, pt.bfactors, # pt.calc_rmsd_with_rotation_matrices, pt.calc_pairwise_rmsd, ] for func in flist: aa_eq(pt.tools.flatten(func(traj, mask=range(7))), pt.tools.flatten(func(traj, mask="@1,2,3,4,5,6,7"))) aa_eq(pt.tools.flatten(func(traj, mask=range(0, 7, 2))), pt.tools.flatten(func(traj, mask="@1,3,5,7")))