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 testsuperpose_alias(self): '''testsuperpose_alias''' t0 = self.traj[:] t1 = self.traj[:] pt.transform(t0, ['superpose']) pt.transform(t1, ['rms']) aa_eq(t0.xyz, t1.xyz)
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_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_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_fit_and_then_nofit(self): traj = pt.iterload("data/Tc5b.x", "data/Tc5b.top") t0 = traj[:] pt.superpose(t0, ref=traj[3], mask='@CA') rmsd_0 = pt.rmsd_nofit(traj, ref=traj[3], mask='@CB') rmsd_1 = pt.rmsd(traj, ref=traj[3], mask='@CB', nofit=True) aa_eq(rmsd_1, rmsd_0)
def main(): # require 'sanderapi' and 'parmed' packages in AmberTools15 # http://ambermd.org/#AmberTools # more info about `sanderapi` in Amber15 manual # http://ambermd.org/doc12/Amber15.pdf (page 341) traj = io.iterload("../tests/data/Tc5b.x", "../tests/data/Tc5b.top") print(traj) edict0 = pyca.energy_decomposition(parm="../tests/data/Tc5b.top", traj=traj, igb=8, input_options=None) print(edict0) # edict1: use default igb=8 edict1 = pyca.energy_decomposition(traj=traj) print(edict1) aa_eq(edict0['tot'], edict1['tot']) # update `input` and get minimal output import sander inp = sander.gas_input(6) edict2 = pyca.energy_decomposition(traj, input_options=inp, mode='minimal') print(edict2)
def testsuperpose_vs_rmsd(self): # load frames to immutable traj traj = pt.iterload("data/tz2.nc", "data/tz2.parm7") t0 = traj[:] t1 = traj[:] pt.rmsd(t0, ref=traj[0], mask='@CA') pt.superpose(t1, ref=traj[0], mask='@CA') aa_eq(t0.xyz, t1.xyz)
def test_autoimage(self): traj = pt.iterload("data/tz2.ortho.nc", "data/tz2.ortho.parm7") t0 = traj[:] t0.autoimage() avg_0 = pt.mean_structure(t0, '@CA') avg_1 = pt.mean_structure(traj(autoimage=True), '@CA') aa_eq(avg_0.xyz, avg_1.xyz)
def test_vs_cpptraj(self): data = pt.dssp(self.traj, "*", dtype='cpptraj_dataset') data_int = np.array( [d0.values for d0 in data if d0.dtype == 'integer'], dtype='i4') # load cpptraj output cpp_data = np.loadtxt("./data/dssp.Tc5b.dat", skiprows=1)[:, 1:].T aa_eq(data_int.flatten(), cpp_data.flatten())
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 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)
def test_not_update_coordinates(self): traj = self.traj[:] data = pt.rmsd(traj, ref=3, update_coordinate=False) # make sure coordinates are not updated aa_eq(traj.xyz, self.traj.xyz) # make sure give the same rmsd values aa_eq(pt.rmsd(traj, ref=3), data)
def test_0(self): traj = pt.iterload("./data/tz2.ortho.nc", "./data/tz2.ortho.parm7") cout = pt.datafiles.load_cpptraj_output(""" parm ./data/tz2.ortho.parm7 trajin ./data/tz2.ortho.nc rms first nofit rms first mass """) aa_eq(pt.rmsd(traj, nofit=True), cout[1]) aa_eq(pt.rmsd(traj, mass=True), cout[2])
def test_0(self): trajcpp = pt.iterload("./data/Tc5b.x", "./data/Tc5b.top") farray = trajcpp[:] # bugs: trajcpp[0, 0, 0] != farray[0, 0, 0] (must be equal) assert farray[0][0, 0] == trajcpp[0][0, 0] farray[0, 0, 0] = 100.10 assert farray[0, 0, 0] == 100.10 farray[0, 0, :] = [100.10, 101.1, 102.1] aa_eq(farray[0, 0, :], [100.10, 101.1, 102.1])
def test_load_samples(self): traj = pt.load_sample_data()[:] assert isinstance(traj, pt.Trajectory) == True assert traj.top.n_atoms == 34 assert traj.shape == (1, 34, 3) traj2 = pt.load_sample_data() assert isinstance(traj2, pt.TrajectoryIterator) == True assert traj2.top.n_atoms == 34 assert traj2.shape == (1, 34, 3) aa_eq(traj.xyz, traj2.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_noreference(self): from pytraj.datafiles import load_cpptraj_output, tz2_ortho_trajin traj = pt.iterload("./data/tz2.ortho.nc", "./data/tz2.ortho.parm7") cout = load_cpptraj_output(tz2_ortho_trajin + """ rmsd first @CA perres range 2-7""") d = pt.rmsd_perres(traj, ref=0, mask='@CA', resrange='2-7', dtype='ndarray') aa_eq(cout[1:].values, d)
def test_watershell(self): traj = pt.iterload("data/tz2.truncoct.nc", "data/tz2.truncoct.parm7") state = pt.load_batch(traj, ''' watershell :1-7 ''') d0 = pt.watershell(traj, solute_mask=':1-7') state.run() aa_eq(d0.values, state.data[[1, 2]].values) # need to provide solute_mask self.assertRaises(ValueError, lambda: pt.watershell(traj))
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_2(self): import numpy as np box = Box() arr0 = np.arange(6).astype(np.float64) box.data[:] = arr0 for idx, x in enumerate(arr0): assert box.data[idx] == x # set Box for Frame f1 = Frame() f1.box = box aa_eq(f1.box.values, box.values, decimal=7)
def test_0(self): traj = mdio.iterload("./data/Tc5b.x", "./data/Tc5b.top") if has_("numpy"): import numpy as np from numpy.testing import assert_almost_equal arr0 = traj.xyz aa_eq(arr0, traj[:, :, :].xyz) # create Trajectory farray = traj[:] aa_eq(arr0, farray[:, :, :].xyz) else: pass
def test_combine_nofit_mass_nomod(self): cm = ''' parm data/tz2.parm7 trajin data/tz2.nc rms @CA nofit mass nomod ''' state = pt.load_cpptraj_state(cm) state.run() unmut_traj = pt.iterload('data/tz2.nc', 'data/tz2.parm7') mut_traj = unmut_traj[:] data = pt.rmsd(mut_traj, mask='@CA', mass=True, nofit=True, update_coordinate=False) aa_eq(data, state.data[-1])
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_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_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_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_frame_indices(self): traj = pt.iterload('data/tz2.nc', 'data/tz2.parm7') frame_indices = [0, 6, 7, 4, 5] data_without_frame_indices = pt.energy_decomposition(traj, igb=8) data_with_frame_indices = pt.energy_decomposition( traj, igb=8, frame_indices=frame_indices) data_with_frame_indices_2 = pt.energy_decomposition( traj[frame_indices], igb=8) for key in data_without_frame_indices: aa_eq(data_without_frame_indices[key][frame_indices], data_with_frame_indices[key]) aa_eq(data_without_frame_indices[key][frame_indices], data_with_frame_indices_2[key])
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_buffer1d(self): FRAME._buffer1d[0] = 199. assert FRAME[0, 0] == 199. FRAME[0] = 0.1 assert FRAME[0, 0] == 0.1 assert FRAME._buffer1d[-1] == FRAME[-1, 2] FRAME._buffer1d[:3] = array('d', [1, 2.3, 3.4]) aa_eq(FRAME.xyz[0], array('d', [1, 2.3, 3.4])) arr0 = np.asarray(FRAME._buffer1d) arr1 = arr0.reshape(10, 3) arr1[1] = [100., 200., 300.] start = 0 stop = 10 strip = 2 arr = np.asarray(FRAME[start:stop:strip])
def test_principal_axes_and_lign_principal_axis(self): traj = pt.iterload(fn('Tc5b.x'), fn('Tc5b.top')) cm = ''' principal * dorotation mass name pout createcrd myname ''' state = pt.load_cpptraj_state(cm, traj) state.run() mut_traj_0 = traj[:] mut_traj_1 = traj[:] data = pt.principal_axes(mut_traj_0, mask='*', dorotation=True, mass=True) pt.align_principal_axis(mut_traj_1, mask='*', mass=True) aa_eq(data[0], state.data[1].values) aa_eq(data[1], state.data[2].values) aa_eq(state.data[-1].xyz, mut_traj_0.xyz) aa_eq(state.data[-1].xyz, mut_traj_1.xyz)
def test_projection_for_pca(self): traj = pt.load(fn('tz2.nc'), fn('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 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_1(self): # TODO: get absolute path so we can use `tempfolder` # if not: wrong dir if using TrajectoryIterator traj = mdio.iterload("./data/Tc5b.x", "./data/Tc5b.top")[:] trajout = TrajectoryWriter() # multiple pdb in multiple files, using `save` method in traj with tempfolder(): basename = "test_pdb_files.pdb" traj.save(basename, overwrite=True, options="multi") for i in range(10): fname = basename + "." + str(i + 1) # cpptraj use `1` frame = mdio.iterload(fname, traj.top)[0] aa_eq(frame.xyz, traj[i].xyz) # multiple pdb in multiple files, using `mdio.write_traj` with tempfolder(): basename = "test_pdb_files_mdio_write_traj.pdb" mdio.write_traj(basename, traj, overwrite=True, options="multi") for i in range(10): fname = basename + "." + str(i + 1) # cpptraj use `1` frame = pt.iterload(fname, traj.top)[0] aa_eq(frame.xyz, traj[i].xyz) # multiple pdb in SINGLE file with tempfolder(): basename = "test_pdb_files.pdb" traj.save(basename, overwrite=True) traj2 = mdio.load(basename, traj.top) aa_eq(traj.xyz, traj2.xyz) # multiple pdb in SINGLE file with `model` keyword # write to output so we can manually check basename = "./output/test_pdb_files_model.pdb" traj.save(basename, overwrite=True, options='model') traj3 = mdio.load(basename, traj.top) aa_eq(traj.xyz, traj3.xyz)
def test_rotation_matrix_in_rmsd_calculation(self): traj = pt.iterload(fn('tz2.nc'), fn('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_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_0(self): # create Trajectory from Trajing_Single traj = pt.iterload("./data/Tc5b.x", "./data/Tc5b.top")[:] aa_eq(traj[3, 3], traj[3][3, :]) frame1 = traj[1] aa_eq(frame1[0], traj[1][:, :][0]) assert traj[0, 0, 0] == -16.492 assert traj[:, :, 0][0, 0] == traj[0, 0, 0] f0 = traj[0] farr0 = traj[:2] fa = traj[2:4] # we don't support traj[:, idx] or traj[:, idx, idy] since this give wrong answer # got ~0.0 value aa_eq(traj[:, 0, 0], np.asarray(traj[0][0])) for i in range(traj[0]._buffer2d.shape[0]): aa_eq(traj[:, :, 0][i], traj[0]._buffer2d[i]) # slicing with mask atm = traj.top("@CA") traj[atm] traj[:, atm]
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_len_on_disk(self): N = ts.n_frames old_xyz_5_10 = ts[5].xyz[:10].copy() assert ts[:3].n_frames == 3 assert ts[1:3].n_frames == 2 assert ts[3:1].n_frames == 0 assert ts[3:1:-1].n_frames == 2 assert ts[-1:-3].n_frames == 0 assert ts[-1:-3:-1].n_frames == 2 # need to store xyz xyz = ts[-1].xyz.copy() aa_eq(xyz, ts[N - 1].xyz) # need to create a temp farray subfarray = ts[5:1:-1] aa_eq(subfarray[0].xyz, ts[5].xyz) aa_eq(old_xyz_5_10, ts[5].xyz[:10])
def test_3(self): traj = pt.iterload(fn('Tc5b.x'), fn('Tc5b.top')) count = 0 for frame in traj.iterframe(): count += 1 aa_eq(frame.xyz, traj[-1].xyz) count = 0 for frame in traj.iterframe(2, 8, 2): count += 1 assert count == 3 aa_eq(frame.xyz, traj[6].xyz) count = 0 for frame in traj[:].iterframe(): count += 1 aa_eq(frame.xyz, traj[-1].xyz)
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 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_0(self): import numpy as np traj = pt.iterload(fn('Tc5b.x'), fn('Tc5b.top')) traj2 = traj[:] d1 = pt.calc_center_of_mass(traj, dtype='dataset') d2 = pt.calc_center_of_mass(traj2, dtype='dataset') for frame in traj: pass saved_d0 = np.loadtxt(fn('vec.out'), skiprows=1, usecols=(1, 2, 3)) aa_eq(d1.to_ndarray().flatten(), saved_d0.flatten()) aa_eq(d2.to_ndarray().flatten(), saved_d0.flatten()) aa_eq(pt.center_of_geometry(traj, dtype='ndarray'), pt.center_of_geometry(traj2, dtype='ndarray'))
def test_len_in_memory(self): N = 10 farray = FARRAY[:N].copy() assert farray.n_frames == N old_xyz_5_10 = farray[5].xyz[:10] assert farray[:3].n_frames == 3 assert farray[1:3].n_frames == 2 assert farray[3:1].n_frames == 0 assert farray[3:1:-1].n_frames == 2 assert farray[-1:-3].n_frames == 0 assert farray[-1:-3:-1].n_frames == 2 aa_eq(farray[-1].xyz, farray[N - 1].xyz) # need to create a temp farray subfarray = farray[5:1:-1] aa_eq(subfarray[0].xyz, farray[5].xyz) aa_eq(old_xyz_5_10, farray[5].xyz[:10]) f_last = farray[-3:-1][-1]
def test_iterframe_indices(self): traj = pt.iterload(fn('Tc5b.x'), fn('Tc5b.top')) t0 = traj[:] indices = range(3) d1 = pt.radgyr(traj[indices]) d2 = pt.radgyr(traj, frame_indices=indices) aa_eq(d2, d1) n_frames = traj.n_frames aa_eq( np.array([frame.xyz.copy() for frame in traj._iterframe_indices([-2, -1])]), traj[[n_frames-2, n_frames-1]].xyz) # yapf: disable aa_eq( traj[[-2, -1]].xyz, traj[[n_frames-2, n_frames-1]].xyz) # yapf: disable
def test_len_TrajectoryIterator(self): # create alias of `ts` (TrajectoryIterator instance created above) farray = ts N = ts.n_frames assert farray.n_frames == N old_xyz_5_10 = farray[5].xyz[:10].copy() assert farray[:3].n_frames == 3 assert farray[1:3].n_frames == 2 assert farray[3:1].n_frames == 0 assert farray[3:1:-1].n_frames == 2 assert farray[-1:-3].n_frames == 0 assert farray[-1:-3:-1].n_frames == 2 # need to store xyz xyz = farray[-1].xyz.copy() aa_eq(xyz, farray[N - 1].xyz) # need to create a temp farray subfarray = farray[5:1:-1] aa_eq(subfarray[0].xyz, farray[5].xyz) aa_eq(old_xyz_5_10, farray[5].xyz[:10])
def test_molsurf(self): traj = self.traj text = ''' parm {0} trajin {1} molsurf @CA molsurf @CA probe 1.2 molsurf @CA probe 1.2 offset 0.3 '''.format(traj.top.filename, traj.filename) state = pt.load_cpptraj_state(text) state.run() cpp_data = state.data[1:].values atom_indices = traj.top.select("@CA") for mask in [atom_indices, '@CA']: aa_eq(pt.molsurf(traj, mask), cpp_data[0]) aa_eq(pt.molsurf(traj, mask, probe=1.2), cpp_data[1]) aa_eq(pt.molsurf(traj, mask, probe=1.2, offset=0.3), cpp_data[2])
def test_distances(self): traj = pt.iterload(tc5b_trajin, tc5b_top)[:] trajin = """ parm {} trajin {} distance @CB @CA distance @CA @H """.format(fn('Tc5b.parm7'), fn('Tc5b.x')) cout = pt.datafiles.load_cpptraj_output(trajin)[1:] mask_list = ('@CB @CA', '@CA @H') dslist = pt.calc_distance(traj, mask_list) dslist3_0 = pt.calc_distance(traj, mask_list[0]) dslist3_1 = pt.calc_distance(traj, mask_list[1]) # compare to cpptraj output aa_eq(dslist.flatten(), cout.values.flatten()) aa_eq(dslist3_0, dslist[0]) aa_eq(dslist3_1, dslist[1])
def test_simple_for_coverage(self): ''' ''' traj = pt.iterload(traj_dir, parm_dir) 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)) vecs_and_mat = pt.ired_vector_and_matrix(traj, nh_indices, dtype='tuple') vecs_and_mat = pt.ired_vector_and_matrix(traj, nh_indices, dtype='tuple') state_vecs = vecs_and_mat[0] mat_ired = vecs_and_mat[1] # get eigenvalues and eigenvectors modes = pt.matrix.diagonalize(mat_ired, n_vecs=len(state_vecs)) evals, evecs = modes data_0 = _ired(state_vecs, modes=(evals, evecs), NHbond=True, tcorr=10000, tstep=1.) data_1 = _ired(state_vecs, modes=modes, NHbond=True, tcorr=10000, tstep=1) for d0, d1 in zip(data_0, data_1): if d0.dtype not in ['modes', ]: aa_eq(d0.values, d1.values) else: # modes # values: tuple aa_eq(d0.values[0], d1.values[0]) aa_eq(d0.values[1], d1.values[1]) # try different dtype out_try_new_dtype = pt.ired_vector_and_matrix(traj, nh_indices, dtype='cpptraj_dataset')
def test_multivector(self): traj = pt.iterload(fn('tz2.nc'), fn('tz2.parm7')) state = pt.load_batch( traj, ''' multivector resrange 3-7 name1 C name2 N ''') state.run() cpp_data = state.data[1:].values aa_eq( pt.multivector(traj, resrange='3-7', names=('C', 'N'), dtype='ndarray'), cpp_data) aa_eq( pt.multivector(traj, resrange='3-7', names='C N', dtype='ndarray'), cpp_data) aa_eq( pt.multivector(traj, resrange='3-7', names='name1 C name2 N', dtype='ndarray'), cpp_data)
def testTwoTrajTypes(self): '''test different metrics with different traj objects ''' funclist = [pt.iterload, pt.load] txt = ''' parm ./data/Tc5b.top trajin ./data/Tc5b.x rms2d @CA metric_holder rmsout tmp.out ''' for func in funclist: traj = func("./data/Tc5b.x", "./data/Tc5b.top") for metric in ['rms', 'nofit', 'dme']: d0 = pt.pairwise_rmsd(traj(mask='@CA'), metric=metric) d1 = pt.pairwise_rmsd(traj, mask='@CA', metric=metric) d2 = pt.pairwise_rmsd(traj(), mask='@CA', metric=metric) txt0 = txt.replace('metric_holder', metric) state = pt.datafiles.load_cpptraj_output(txt0, dtype='state') d3 = state.datasetlist[-1].values aa_eq(d0, d1) aa_eq(d0, d2) aa_eq(d0, d3)
def test_superpose_trajectory_iterator_pytraj_method(self): traj_on_disk = pt.iterload(fn('Tc5b.x'), fn('Tc5b.top')) traj_on_disk2 = pt.iterload(fn('Tc5b.x'), fn('Tc5b.top')) traj_on_mem = pt.load(fn('Tc5b.x'), fn('Tc5b.top')) ref = pt.iterload(fn("Tc5b.crd"), fn('Tc5b.top'))[0] pt.superpose(traj_on_mem, ref=ref, mask='@CA') pt.superpose(traj_on_disk, ref=ref, mask='@CA') assert traj_on_disk._being_transformed == True, '_being_transformed must be True' aa_eq(traj_on_mem.xyz, traj_on_disk.xyz) # test saving with tempfolder(): traj_on_mem.save('t0.nc', overwrite=True) traj_on_disk.save('t1.nc', overwrite=True) aa_eq( pt.load('t0.nc', traj_on_mem.top).xyz, pt.load('t1.nc', traj_on_disk.top).xyz) # turn off superpose traj_on_disk._being_transformed = False aa_eq(traj_on_disk.xyz, traj_on_disk2.xyz)
def test_assert(self): traj = pt.iterload("./data/Tc5b.x", "./data/Tc5b.top") fa = Trajectory.from_iterable(iterframe_master(traj), top=traj.top) for f0, f1 in zip(fa, traj): aa_eq(f0.xyz, f1.xyz)
def test_ired_vector(self): '''test mask as a list of strings or as a 2D array of integers ''' parm_dir = os.path.join(cpptraj_test_dir, 'Test_IRED', '1IEE_A_prot.prmtop') trajin_dir = os.path.join(cpptraj_test_dir, 'Test_IRED', '1IEE_A_test.mdcrd') traj = pt.iterload(trajin_dir, parm_dir) # get a list of mask from cpptraj input maskes = [] lines = None n_indices_cpp = [] with open('data/ired.in', 'r') as fh: lines = fh.readlines() for line in lines: if 'vector' in line and 'ired' in line: # example: vector v100 @1541 ired @1542 sline = line.split() mask = ' '.join((sline[2], sline[4])) n_indices_cpp.append(int(sline[2][1:]) - 1) maskes.append(mask) h_indices_cpp = [i + 1 for i in n_indices_cpp] # calcuate vector from a list of strings data_vec = va.vector_mask(traj, maskes) # calcuate vector from a 2d array of integers nh_indices = np.array(list(zip(n_indices_cpp, h_indices_cpp))) data_vec_2 = va.vector_mask(traj, nh_indices) # re-create cpptraj input to run cpptraj txt = ''.join(lines) # add parm and trajin lines txt = 'parm ' + parm_dir + '\n' + \ 'trajin ' + trajin_dir + '\n' + \ txt state = pt.datafiles.load_cpptraj_output(txt, dtype='state') state.run() cpp_data = state.datasetlist cpp_vectors = cpp_data.grep('vector', mode='dtype').values cpp_matired = cpp_data.grep('matrix', mode='dtype')['matired'] # assert between pytraj's data_vec and cpptraj's cpp_vectors aa_eq(data_vec, cpp_vectors) # from a 2D array of integers aa_eq(data_vec_2, cpp_vectors) # test ired vector with ired matrix # open file with open('data/ired_reduced.in', 'r') as fh: text = ''.join(fh.readlines()) state2 = pt.load_batch(traj, text) state2.run() data = pt.ired_vector_and_matrix(traj, nh_indices, order=2) data_vec_3 = data[0] assert len(data_vec_3) == 126, 'must have 126 vectors' matired = data[1] # TODO: know why?? matired /= matired[0, 0] aa_eq(data_vec_3, cpp_vectors) assert pt.tools.rmsd(matired.flatten(), cpp_matired.values) < 1E-6, 'matired'
def test_iterframe_from_array(self): traj = pt.iterload("./data/Tc5b.x", "./data/Tc5b.top") # no mass fi = pt.iterframe_from_array(traj.xyz, traj.n_atoms, range(traj.n_frames)) for f_traj, f_fi in zip(traj, fi): aa_eq(f_traj.xyz, f_fi.xyz) # f_fi mass must be [1.0, ...] aa_eq(f_fi.mass, [1.0 for _ in range(traj.n_atoms)]) # mass from Topology fi = pt.iterframe_from_array(traj.xyz, traj.n_atoms, range(traj.n_frames), traj.top) for f_traj, f_fi in zip(traj, fi): aa_eq(f_traj.xyz, f_fi.xyz) aa_eq(f_fi.mass, f_traj.mass) aa_eq(f_fi.mass, traj.top.mass) # mass from array fi = pt.iterframe_from_array(traj.xyz, traj.n_atoms, range(traj.n_frames), mass=traj.top.mass) for f_traj, f_fi in zip(traj, fi): aa_eq(f_traj.xyz, f_fi.xyz) aa_eq(f_fi.mass, f_traj.mass) aa_eq(f_fi.mass, traj.top.mass)
def test_pickle_datasetlist(self): traj = pt.iterload(fn('Tc5b.x'), fn('Tc5b.top')) dslist = pt.multidihedral(traj) pt.to_pickle(dslist, 'ds.pk') dslist2 = pt.read_pickle('ds.pk') aa_eq(dslist.values, dslist2.values)
def test_frame_indices_for_function(self): traj = self.traj pdict = pt.__dict__ funclist = list( set(pdict[key] for key in dir(pt) if hasattr(pdict[key], '_issuper_dispatched'))) frame_indices = [0, 2] # remove 'calc_jcoupling' since does not have kfile on travis # remove energy_decomposition since does not have sander # remove center, why? # remove search_neighbors, why? (got messup with Frame memory owner) excluded_fn = [ jcoupling, volmap, center, search_neighbors, atomiccorr, autoimage, closest, volume, superpose, randomize_ions, check_structure, align_principal_axis, ] func_nu = [ calc_epsilon, calc_alpha, calc_zeta, calc_beta, calc_nu1, calc_nu2, calc_delta, calc_chin, calc_gamma, ] # default mask, default ref for func in funclist: if func not in excluded_fn: if func is pt.calc_multivector: data_0 = func( traj, resrange='1-6', names='C N', frame_indices=frame_indices) data_1 = func( traj[frame_indices], resrange='1-6', names='C N') elif func is pt.volmap: # use water data_0 = func( self.traj_ortho, mask=':WAT@O', grid_spacing=(0.2, 0.2, 0.2), centermask='!:1-13', frame_indices=frame_indices) data_1 = func( self.traj_ortho[frame_indices], mask=':WAT@O', centermask='!:1-13', grid_spacing=(0.2, 0.2, 0.2)) elif func in func_nu: data_0 = func(self.traj_nu, frame_indices=frame_indices) data_1 = func(self.traj_nu[frame_indices]) else: data_0 = func(traj, frame_indices=frame_indices) data_1 = func(traj[frame_indices]) if isinstance(data_0, np.ndarray): aa_eq(data_0, data_1) elif isinstance(data_0, pt.DatasetList): for arr0, arr1 in zip(data_0, data_1): # do each element in case we can not convert DatasetList to # ndarray if not isinstance(arr0[0], string_types): aa_eq(arr0.values, arr1.values) elif isinstance(data_0, DatasetHBond): aa_eq(data_0.data.values, data_1.data.values) elif isinstance(data_0, (list, tuple)): # dssp aa_eq(data_0[-1].values, data_1[-1].values) else: raise RuntimeError( 'must return ndarray or DatasetList or DatasetHBond') # test excluded fns aa_eq( pt.atomiccorr(traj[frame_indices], '@CA'), pt.atomiccorr(traj, '@CA', frame_indices=frame_indices)) # align_principal_axis indices = [0, 3, 7] t0 = self.traj[:] t1 = self.traj[indices] pt.align_principal_axis(t0, frame_indices=indices) pt.align_principal_axis(t1) aa_eq(t0[indices].xyz, t1.xyz) # make sure that other frames are not affected other_indices = list(set(range(10)) - set(indices)) aa_eq(self.traj[other_indices].xyz, t0[other_indices].xyz)
def test_load_comprehensive(): traj = traj_tz2_ortho trajin, tn = fn("tz2.ortho.nc"), fn("tz2.ortho.parm7") # load from filelist t0 = pt.load([trajin, trajin], tn) n_frames_half = int(t0.n_frames / 2) aa_eq(traj.xyz, t0[:n_frames_half].xyz) aa_eq(traj.xyz, t0[n_frames_half:].xyz) # frame_slice t0 = pt.io.load_traj(trajin, tn, frame_slice=(0, 3)) aa_eq(traj_tz2_ortho[:3].xyz, t0.xyz) # mask t1 = pt.load(trajin, tn, mask='@CA') aa_eq(t1.xyz, traj['@CA'].xyz) # frame_indices, list t1 = pt.load(trajin, tn, frame_indices=[0, 3]) aa_eq(t1.xyz, traj[[0, 3]].xyz) # frame_indices, tuple t1 = pt.load(trajin, tn, frame_indices=(0, 3)) aa_eq(t1.xyz, traj[[0, 3]].xyz) # frame_indices with negative index t12 = pt.load(trajin, tn, frame_indices=(-2, -1)) aa_eq(t12.xyz, traj[[traj.n_frames - 2, traj.n_frames - 1]].xyz) # mask and frame_indices t2 = pt.load(trajin, tn, mask='@CA', frame_indices=[3, 8]) aa_eq(t2.xyz, traj[[3, 8], '@CA'].xyz) # stride t2 = pt.load(trajin, tn, stride=2) aa_eq(t2.xyz, traj[::2].xyz) # stride with mask t2 = pt.load(trajin, tn, stride=2, mask='@CA') aa_eq(t2.xyz, traj[::2, '@CA'].xyz) # stride, ignore frame_indices if stride is given t2 = pt.load(trajin, tn, stride=2, frame_indices=[2, 5, 8]) aa_eq(t2.xyz, traj[::2].xyz)
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 test_iterload_comprehensive(): trajin, tn = fn("tz2.ortho.nc"), fn("tz2.ortho.parm7") # frame_slice t0 = pt.iterload(trajin, tn, frame_slice=(0, -1, 0)) aa_eq(traj_tz2_ortho.xyz, t0.xyz) t0 = pt.iterload(trajin, tn, frame_slice=(0, -1, 2)) aa_eq(traj_tz2_ortho.xyz[::2], t0.xyz) # stride t0 = pt.iterload(trajin, tn, stride=2) aa_eq(traj_tz2_ortho.xyz[::2], t0.xyz) # stride, ignore frame_slice t0 = pt.iterload(trajin, tn, stride=2, frame_slice=(0, -1, 3)) aa_eq(traj_tz2_ortho.xyz[::2], t0.xyz) # stride, load two files t0 = pt.iterload([trajin, trajin], tn, stride=2) xyz_2 = np.vstack((traj_tz2_ortho.xyz[::2], traj_tz2_ortho.xyz[::2])) aa_eq(xyz_2, t0.xyz) # stride, load two files, ignore frame_slice t0 = pt.iterload([trajin, trajin], tn, stride=2, frame_slice=[(0, -1, 5), (0, -1, 2)]) xyz_2 = np.vstack((traj_tz2_ortho.xyz[::2], traj_tz2_ortho.xyz[::2])) aa_eq(xyz_2, t0.xyz) # stride, 4 trajs filenames, tn = get_remd_fn('remd_ala2') t0 = pt.iterload(filenames, tn, stride=3) # add frame_slice t1 = pt.iterload(filenames, tn, frame_slice=[ (0, -1, 3), ] * 4) xyz_expected = np.vstack( [pt.iterload(fname, tn)[::3].xyz for fname in filenames]) aa_eq(xyz_expected, t0.xyz) aa_eq(xyz_expected, t1.xyz) # stride, 4 trajs, ignore frame_slice filenames, tn = get_remd_fn('remd_ala2') t0 = pt.iterload(filenames, tn, stride=3, frame_slice=(0 - 1, 4)) xyz_expected = np.vstack( [pt.iterload(fname, tn)[::3].xyz for fname in filenames]) aa_eq(xyz_expected, t0.xyz)
def test_get_coordinates_trajecotoryiterator(): '''immutable pytraj.TrajectoryIterator ''' traj = traj_tz2_ortho.copy() # all coordinates xyz = pt.get_coordinates(traj) aa_eq(traj.xyz, xyz) # given frames xyz = pt.get_coordinates(traj, frame_indices=[0, 5]) aa_eq(traj[[0, 5]].xyz, xyz) # given frames, autoimage=True xyz = pt.get_coordinates(traj, frame_indices=[0, 5], autoimage=True) aa_eq(traj[[0, 5]].autoimage().xyz, xyz) # given frames, autoimage=True, rmsfit=ref ref = traj[-3] pt.autoimage(ref, top=traj.top) xyz = pt.get_coordinates(traj, frame_indices=[0, 5], autoimage=True, rmsfit=ref) aa_eq(traj[[0, 5]].autoimage().superpose(ref=ref).xyz, xyz) xyz = pt.get_coordinates(traj, frame_indices=range(3), autoimage=True, rmsfit=ref) # with mask xyz = pt.get_coordinates(traj, mask='@CA') aa_eq(xyz, traj['@CA'].xyz) # slow fi = pt.pipe(traj, ['autoimage']) aa_eq(pt.get_coordinates(fi), traj[:].autoimage().xyz) # raise with pytest.raises(ValueError): pt.get_coordinates(traj(), frame_indices=[0, 2])
def test_nupars_vs_x3dna(self): traj = pt.iterload(fn('Test_NAstruct/x3dna/rna.pdb')) ref = pt.iterload(fn('Test_NAstruct/x3dna/rna_nab.pdb')) nu = pt.nastruct(traj, ref=ref, groove_3dna=True) root = fn('Test_NAstruct/x3dna/') # helical pars saved_helical_pars = np.loadtxt(root + 'bp_helical.par', skiprows=3, usecols=range(1, 13)).T aa_eq(nu.shear[1][0], saved_helical_pars[0], decimal=3) aa_eq(nu.stretch[1][0], saved_helical_pars[1], decimal=3) aa_eq(nu.stagger[1][0], saved_helical_pars[2], decimal=3) aa_eq(nu.buckle[1][0], saved_helical_pars[3], decimal=3) aa_eq(nu.prop[1][0], saved_helical_pars[4], decimal=3) aa_eq(nu.open[1][0], saved_helical_pars[5], decimal=3) aa_eq(nu.xdisp[1][0], saved_helical_pars[6][1:], decimal=3) aa_eq(nu.ydisp[1][0], saved_helical_pars[7][1:], decimal=3) aa_eq(nu.hrise[1][0], saved_helical_pars[8][1:], decimal=3) aa_eq(nu.incl[1][0], saved_helical_pars[9][1:], decimal=3) aa_eq(nu.tip[1][0], saved_helical_pars[10][1:], decimal=3) aa_eq(nu.htwist[1][0], saved_helical_pars[11][1:], decimal=3) # bp_step saved_helical_pars = np.loadtxt(root + 'bp_step.par', skiprows=3, usecols=range(1, 13)).T aa_eq(nu.shift[1][0], saved_helical_pars[6][1:], decimal=3) aa_eq(nu.slide[1][0], saved_helical_pars[7][1:], decimal=3) aa_eq(nu.tilt[1][0], saved_helical_pars[9][1:], decimal=3) aa_eq(nu.roll[1][0], saved_helical_pars[10][1:], decimal=3) aa_eq(nu.twist[1][0], saved_helical_pars[11][1:], decimal=3) # grove aa_eq(nu.minor[1][0], [15.8, 15.8, 15.5], decimal=1) aa_eq(nu.major[1][0], [19.9, 20.8, 20.0], decimal=1)