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 assert_equal_topology(top, new_top, traj): import pytraj as pt assert new_top.n_atoms == top.n_atoms, 'same n_atoms' assert new_top.n_residues == top.n_residues, 'same n_residues' assert new_top.n_mols == top.n_mols, 'same n_mols' # there are inverted bond indices [5292 5291] vs [5291 5292] # so use distance to assert aa_eq( pt.distance(traj, new_top.bond_indices), pt.distance(traj, top.bond_indices)) # same for dihedral_indices aa_eq( pt.dihedral(traj, new_top.dihedral_indices), pt.dihedral(traj, top.dihedral_indices)) aa_eq(new_top.dihedral_indices, top.dihedral_indices) aa_eq(new_top.mass, top.mass) aa_eq(new_top.charge, top.charge) aa_eq(new_top.box.values, top.box.values) assert [res.name for res in top.residues ] == [res.name for res in new_top.residues], 'equal resnames' assert [atom.name for atom in top.atoms ] == [atom.name for atom in new_top.atoms], 'equal resnames' for res, res_new in zip(top.residues, new_top.residues): assert res.first_atom_index == res_new.first_atom_index, 'first atom' assert res.last_atom_index == res_new.last_atom_index, 'last atom'
def assert_equal_topology(top, new_top, traj): import pytraj as pt assert new_top.n_atoms == top.n_atoms, 'same n_atoms' assert new_top.n_residues == top.n_residues, 'same n_residues' assert new_top.n_mols == top.n_mols, 'same n_mols' # there are inverted bond indices [5292 5291] vs [5291 5292] # so use distance to assert aa_eq(pt.distance(traj, new_top.bond_indices), pt.distance(traj, top.bond_indices)) # same for dihedral_indices aa_eq(pt.dihedral(traj, new_top.dihedral_indices), pt.dihedral(traj, top.dihedral_indices)) aa_eq(new_top.dihedral_indices, top.dihedral_indices) aa_eq(new_top.mass, top.mass) aa_eq(new_top.charge, top.charge) aa_eq(new_top.box.values, top.box.values) assert [res.name for res in top.residues ] == [res.name for res in new_top.residues], 'equal resnames' assert [atom.name for atom in top.atoms ] == [atom.name for atom in new_top.atoms], 'equal resnames' for res, res_new in zip(top.residues, new_top.residues): assert res.first_atom_index == res_new.first_atom_index, 'first atom' assert res.last_atom_index == res_new.last_atom_index, 'last atom'
def test_general(self): traj = pt.iterload("./data/Tc5b.x", "./data/Tc5b.top") fa = traj[:] mask = ':1@CA :14@CB' d0 = pt.calc_distance(traj, mask) d1 = pt.distance(traj, mask) d2 = pt.calc_distance(fa, mask) aa_eq(d0, d1) aa_eq(d0, d2) Nsize = 12 arr = np.random.randint(0, 300, size=Nsize * 2).reshape(Nsize, 2) d3 = pt.calc_distance(fa, arr) d4 = pt.distance(traj, arr) d5 = pt.calc_distance(traj, arr) d6 = pt.calc_distance(fa, arr) d7 = pt.calc_distance([fa, traj], arr, n_frames=2 * fa.n_frames) d8 = pt.calc_distance([fa, traj], arr, n_frames=2 * fa.n_frames, dtype='dataset') aa_eq(d3, d4) aa_eq(d3, d5) aa_eq(d3, d6) aa_eq(d3.T, d7.T[:fa.n_frames]) aa_eq(d3.T, d7.T[fa.n_frames:]) aa_eq(d7, d8.values) # raise self.assertRaises(ValueError, lambda: pt.dihedrals(traj, [[0, 3, 2]]))
def test_constructor_from_command_list_Trajectory(self): '''mutable Trajectory''' # use `load` method rather `iterload` traj = pt.load(fn("tz2.ortho.nc"), fn("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_mpi_cpptraj_style(): comm = MPI.COMM_WORLD # end. you are free to update anything below here # split remd.x.000 to N cores and do calc_surf in parallel root_dir = "data/" traj_name = root_dir + "tz2.ortho.nc" parm_name = root_dir + "tz2.ortho.parm7" # load to TrajectoryIterator traj = pt.iterload(traj_name, parm_name) # save `total_arr` to rank=0 # others: total_arr = None total_arr = pt.pmap_mpi( ['autoimage', 'center :2', 'distance :3 :7', 'angle :3 :7 :8'], traj) if comm.rank != 0: assert total_arr is None if comm.rank == 0: # assert to serial from pytraj.utils.tools import dict_to_ndarray arr = dict_to_ndarray(total_arr) t0 = pt.center(traj[:].autoimage(), ':2') aa_eq(pt.distance(t0, ':3 :7'), arr[0]) aa_eq(pt.angle(t0, ':3 :7 :8'), arr[1])
def test_multiple_cores(self): from multiprocessing import Pool traj = pt.iterload('data/tz2.nc', 'data/tz2.parm7') for _ in range(10): traj._load(traj.filelist) saved_angle = pt.angle(traj, ':3 :10 :11') saved_dist = pt.distance(traj, ':3 :10') for n_cores in [2, 3]: lines = ['angle :3 :10 :11', 'distance :3 :10'] pfuncs = partial(worker_state, n_cores=n_cores, traj=traj, dtype='dict', lines=lines) p = Pool(n_cores) data_list = p.map(pfuncs, [rank for rank in range(n_cores)]) p.close() p.join() data_list_sorted_rank = (data[1] for data in sorted(data_list, key=lambda x: x[0])) final_data = concat_dict(data_list_sorted_rank) aa_eq(final_data['Ang_00002'], saved_angle) aa_eq(final_data['Dis_00003'], saved_dist)
def calc_autocorr(self): '''Autocorrelation between the center of mass of the two halves of the protein.''' half = int(self.atoms / 2) R = pd.Series(pt.distance(self.traj, ':1-{} :{}-{}'.format(half, half, self.atoms))) # [R.autocorr(lag=i) for i in range(self.frames-5)] self.autocorr = pt.acorr(R)
def calc_cov(self): '''Calculates covariance and correlation from fluctuations, and distance matrix.''' # Compute covariance coefficient matrix # diagonal for i in range(self.atoms): for frm in self.fluct: self.cov[i][i] += np.sum([frm[i][q] * frm[i][q] for q in range(3)]) self.cov[i][i] /= self.frames # outside diagonal, taking advantage of symmetry for i in range(self.atoms): for j in range(i+1, self.atoms): for frm in self.fluct: self.cov[i][j] += np.sum([frm[i][q] * frm[j][q] for q in range(3)]) self.cov[i][j] /= self.frames self.cov[j][i] = self.cov[i][j] # correlation and distance self.corr[i][j] = self.cov[i][j] / np.sqrt(self.cov[i][i] * self.cov[j][j]) self.corr[j][i] = self.corr[i][j] self.dist[i][j] = pt.distance( self.traj, ':{} :{}'.format(i+1, j+1), frame_indices=[0])[0] self.dist[j][i] = self.dist[i][j] print(u'\u2713 calculated covariance and correlation')
def calc_avg_dist(self): avg_d = [] for i in range(self.atoms - 2): mask = ":{} :{}".format(i+1, i+2) dd = np.mean(pt.distance(self.traj, mask)) avg_d.append(dd) self.avg_dist = np.mean(avg_d)
def test_iterload_and_load_remd(): # iterload_remd traj = pt.iterload_remd(fn("Test_RemdTraj/rem.nc.000"), fn("Test_RemdTraj/ala2.99sb.mbondi2.parm7"), T=300.0) for frame in traj: assert frame.temperature == 300.0, 'frame temperature must be 300.0 K' dist = pt.distance(traj, '@10 @20') trajin_text = ''' parm {} trajin {} remdtraj remdtrajtemp 300. distance @10 @20 '''.format(fn('Test_RemdTraj/ala2.99sb.mbondi2.parm7'), fn('Test_RemdTraj/rem.nc.000 ')) state = pt.load_cpptraj_state(trajin_text) state.run() aa_eq(dist, state.data[-1].values) # load_remd traj2 = pt.load_remd(fn("Test_RemdTraj/rem.nc.000"), fn("Test_RemdTraj/ala2.99sb.mbondi2.parm7"), T=300.0) aa_eq(traj.xyz, traj2.xyz) # with Topology traj2 = pt.iterload_remd(fn("Test_RemdTraj/rem.nc.000"), top=traj.top, T=300.0) aa_eq(traj.xyz, traj2.xyz)
def test_different_cores(self): # use different frame_slice with different n_cores to test REF_0 = pt.iterload(fn('tz2.nc'), fn('tz2.parm7'))[0] for frame_slice in [ (0, 100), (10, 100, 3), (50, 80, 2), (51, 80, 3), ]: traj = pt.iterload( fn('tz2.nc'), fn('tz2.parm7'), frame_slice=frame_slice) saved_angle = pt.angle(traj, ':3 :7 :9') saved_dist = pt.distance(traj, ':2 :10') saved_rmsd = pt.rmsd(traj, ref=REF_0, mask='@CA') lines = ['angle :3 :7 :9', 'distance :2 :10'] for n_cores in [1, 2]: data_list = [ worker_by_state(rank, n_cores, traj, lines) for rank in range(n_cores) ] final_data = concat_dict([x[1] for x in data_list]) aa_eq(final_data['Ang_00002'], saved_angle) aa_eq(final_data['Dis_00003'], saved_dist)
def getDistances(top, traj, list1, list2): #the two lists contain tuples (residue number, atom type) #read trajectory traj = pt.load(traj, top) #read distances dist = dict() first_in_seq = list(traj.top.residues)[0].index for (r1, a1), (r2, a2) in zip(list1, list2): dist[str(r1)+a1+':'+str(r2)+a2] = \ pt.distance(traj, \ ':'+str(r1-first_in_seq)+searchAT[a1]+' :'+str(r2-first_in_seq)+searchAT[a2]) dump(dist, open(get_today() + '-rij.pkl', 'wb')) #make statistics on distances reff = dict() for k in sorted(list(dist.keys())): temp = np.array(dist[k])**(-6) reff[k] = np.mean(temp)**(-1. / 6) dump(reff, open(get_today() + '-reff.pkl', 'wb')) #make plots with PdfPages(get_today() + '-rij.pdf') as pdf: for k in sorted(list(dist.keys())): plt.figure() plt.hist(dist[k]) plt.axvline(x=reff[k]) plt.title(k) pdf.savefig() plt.close() return [dist, reff]
def main(): args = get_argument() #check_input_data(args) print(f'Current working directory: {os.getcwd()}') #if not check_config_file(args.config, args.verbose): # sys.exit(1) #configfile = configparser.ConfigParser() #configfile.read(f'{args.config}') #hdlr = logging.FileHandler( # f'framework_{strftime("%Y-%m-%d__%H-%M-%S", localtime())}.log') #logging.root.addHandler(hdlr) #logging.root.setLevel(logging.INFO) #logging.root.setLevel(logging.DEBUG) #logging.info(f'***Output from framework*** {strftime("%Y-%m-%d__%H-%M-%S", localtime())} \n') #logging.info(f'#Protein : {args.protein} -> protein.pdb \n') #logging.info(f'#Ligand : {args.ligand} {configfile["LIGAND"]["name"]} \n') #logging.info(f'#Tunnel: {args.tunnel} \n') pdb = pt.load("protein_with_tunnel.pdb") pdb_topology = pt.load_topology('protein_with_tunnel.pdb') restraint_residue = [] for i in range(1, pdb_topology.n_residues): #print(f'\':{i} FIL T\'') string_index = f':{i} :FIL T' if pt.distance(pdb, string_index) < 12.0: # simp_top = pdb_topology.simplify() #name = simp_top.residue() restraint_residue.append(f'{pdb_topology.residue(i).index},') #string_residues.join(f':{pdb_topology.residue(i).index}') #restraint_residue.append(name) string_residues = ' '.join([str(elem) for elem in restraint_residue]) print(string_residues)
def test_hbonds_from_pdb(self): traj = pt.load(fn('1L2Y.pdb')) hb = pt.search_hbonds(traj) state = pt.load_cpptraj_state(''' parm {pdb} trajin {pdb} hbond series '''.format(pdb=fn('1L2Y.pdb'))) state.run() for data_p, data_cpp in zip(hb.data, state.data[1:]): assert len( data_p) == traj.n_frames == 38, 'size of dataset must be 38' aa_eq(data_p, data_cpp.values) # make sure distances are smaller than cutoff distance_cutoff = 2.5 angle_cutoff = 135. hb = pt.search_hbonds(traj) distances = pt.distance(traj, hb.get_amber_mask()[0]) angles = pt.angles(traj, hb.get_amber_mask()[1]) dist_indices = np.where(distances > distance_cutoff) angle_indices = np.where(angles < angle_cutoff) saved_donor_acceptors = [ 'ASP9_OD2-ARG16_NH1-HH12', 'ASP9_OD2-ARG16_NH2-HH22', 'ASP9_OD2-ARG16_NE-HE', 'ASP9_OD2-ARG16_NH2-HH21', 'ASP9_OD2-ARG16_NH1-HH11' ] donor_acceptors = pt.search_hbonds(traj, ':9,16').donor_acceptor assert saved_donor_acceptors == donor_acceptors, 'saved_donor_acceptors' aa_eq(hb.total_solute_hbonds(), hb.data['total_solute_hbonds'])
def getDistances(self): #read distances self.dist = dict() first_in_seq = list(self.traj.top.residues)[0].index for (r1, a1), (r2, a2) in zip(self.list1, self.list2): self.dist[str(r1)+a1+':'+str(r2)+a2] = \ pt.distance(self.traj, \ ':'+str(r1-first_in_seq)+searchAT[a1]+' :'+str(r2-first_in_seq)+searchAT[a2]) #print(str(r1)+a1+':'+str(r2)+a2, self.dist[str(r1)+a1+':'+str(r2)+a2]) dump(self.dist, open(get_today() + '-rij.pkl', 'wb')) #make statistics on distances self.reff = dict() for k in sorted(list(self.dist.keys())): temp = np.array(self.dist[k])**(-6) self.reff[k] = np.mean(temp)**(-1. / 6) dump(self.reff, open(get_today() + '-reff.pkl', 'wb')) #make plots with PdfPages(get_today() + '-rij.pdf') as pdf: for k in sorted(list(self.dist.keys())): plt.figure() plt.hist(self.dist[k]) plt.axvline(x=self.reff[k]) plt.title(k) pdf.savefig() plt.close()
def test_distance_with_dry_traj_and_PBC_topology(self): '''Issue: trajectory has no box but its topology does has box. ''' traj = pt.iterload( fn('dry_traj_with_PBC_top/strip.nc'), fn('dry_traj_with_PBC_top/strip.prmtop')) assert traj.top.has_box(), 'Topology must have box for testing' correct_distance_with_image_True = pt.distance( traj, ':8@OP2 :5@N1', image=True) # image=True will be ignored with message correct_distance_with_image_False = pt.distance( traj, ':8@OP2 :5@N1', image=False) expected_distance = [3.08030475, 2.68452183] aa_eq(correct_distance_with_image_True, expected_distance) aa_eq(correct_distance_with_image_False, expected_distance)
def calc_autocorr(self): '''Autocorrelation.''' half = int(self.atoms / 2) R = pd.Series(pt.distance( self.traj, ':1-{} :{}-{}'.format(half, half, self.atoms))) # [R.autocorr(lag=i) for i in range(self.frames-5)] self.autocorr = pt.acorr(R)
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_atom_distance(self): traj = pt.iterload("./data/tz2.nc", "./data/tz2.parm7") top = traj.top ref = traj[0] # test for 1st frame top.set_distance_mask_reference(ref) ref.top = top # all atoms within 5 Angtrom from :3@CA indices = top.select(":3@CA <@5.0") saved_indices = np.loadtxt("./data/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_distance_mask_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 calc_TA_MSD(self): '''Time averaged mean squared deviation.''' half = int(self.atoms / 2) dist = pt.distance(self.traj, ':1-{} :{}-{}'.format(half, half, self.atoms)) aux = [] for lag in range(len(dist) - 5): dif = np.mean([(dist[i + lag] - dist[i]) ** 2 for i in range(len(dist)-lag)]) aux.append(dif) self.TA_MSD = aux
def test_constructor_from_command_list_TrajectoryIterator_no_DatasetList( self): traj = pt.iterload(tc5b_trajin, tc5b_top) commands = [ 'rmsd @CA', 'distance :3 :7', 'distance :3 :7', 'vector :2 :3' ] actlist = ActionList(commands, top=traj.top) for frame in traj: actlist.compute(frame) aa_eq(pt.rmsd(traj, mask='@CA'), actlist.data[0]) aa_eq(pt.distance(traj, ':3 :7'), actlist.data[1]) aa_eq(pt.distance(traj, ':3 :7'), actlist.data[2]) aa_eq(pt.vector.vector_mask(traj(rmsfit=(0, '@CA')), ':2 :3'), actlist.data[3].values)
def calc_corr(self): '''Calculates correlation and distance matrices.''' # Compute correlation coefficient matrix # Calculate mutual distances between residues for i in range(self.atoms): for j in range(self.atoms): self.corr[i][j] = self.cov[i][j] / np.sqrt(self.cov[i][i] * self.cov[j][j]) self.dist[i][j] = pt.distance( self.traj, ':{} :{}'.format(i+1, j+1), frame_indices=[0])[0] print(u'\u2713 calculated correlations')
def test_distance_with_dry_traj_and_PBC_topology(self): '''Situation: there is dry traj (no box) but Topology has box info ''' traj = pt.iterload( fn('dry_traj_with_PBC_top/strip.nc'), fn('dry_traj_with_PBC_top/strip.prmtop')) assert traj.top.has_box(), 'Topology must have box for testing' correct_distance_with_image_True = pt.distance( traj, ':8@OP2 :5@N1', image=True) correct_distance_with_image_False = pt.distance( traj, ':8@OP2 :5@N1', image=False) state = pt.load_batch(traj, ''' distance :8@OP2 :5@N1 ''') state.run() expected_distance = [3.08030475, 2.68452183] aa_eq(correct_distance_with_image_False, expected_distance) aa_eq(correct_distance_with_image_True, [0., 0.])
def test_constructor_from_command_list_TrajectoryIterator_no_DatasetList( self): traj = pt.iterload("./data/Tc5b.x", "./data/Tc5b.top") commands = ['rmsd @CA', 'distance :3 :7', 'distance :3 :7', 'vector :2 :3'] actlist = ActionList(commands, top=traj.top) for frame in traj: actlist.compute(frame) aa_eq(pt.rmsd(traj, mask='@CA'), actlist.data[0]) aa_eq(pt.distance(traj, ':3 :7'), actlist.data[1]) aa_eq(pt.distance(traj, ':3 :7'), actlist.data[2]) aa_eq( pt.vector.vector_mask( traj(rmsfit=(0, '@CA')), ':2 :3'), actlist.data[3].values)
def test_constructor_from_command_list_TrajectoryIterator(self): traj = pt.iterload("./data/Tc5b.x", "./data/Tc5b.top") commands = [ 'rmsd @CA', 'distance :3 :7', 'distance :3 :7', 'vector :2 :3' ] dslist = CpptrajDatasetList() actlist = ActionList(commands, traj.top, dslist=dslist) d0 = dslist.add('ref_frame', 'my_ref') d0.add_frame(traj[3]) 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]) aa_eq(pt.vector.vector_mask(traj(rmsfit=(0, '@CA')), ':2 :3'), dslist[3].values)
def candidatevalues(thread): # Returns a space-separated string containing all the candidate OP values requested by the user in the form of the # candidateops list object. output = '' traj = pytraj.iterload(thread.start_name, thread.prmtop) for index in range(0, len(candidateops[0])): value = pytraj.distance(traj, mask=candidateops[0][index] + ' ' + candidateops[1][index]) output += str(value) + ' ' return output
def test_residue_distance(self): traj = pt.iterload(tz2_trajin, tz2_top) top = traj.top ref = traj[0] top.set_reference(ref) ref.top = top indices_smaler = pt.select_atoms(':3@CA <:5.0', top) ca_indices = pt.select_atoms(':3@CA', traj.top) all_pairs_smaller = list(product(ca_indices, indices_smaler)) pt.tools.flatten(pt.distance(ref, all_pairs_smaller))
def test_residue_distance(self): traj = pt.iterload("./data/tz2.nc", "./data/tz2.parm7") top = traj.top ref = traj[0] top.set_distance_mask_reference(ref) ref.top = top indices_smaler = pt.select_atoms(':3@CA <:5.0', top) ca_indices = pt.select_atoms(':3@CA', traj.top) all_pairs_smaller = list(product(ca_indices, indices_smaler)) distances = pt.tools.flatten(pt.distance(ref, all_pairs_smaller))
def test_constructor_from_command_list_TrajectoryIterator(self): traj = pt.iterload("./data/Tc5b.x", "./data/Tc5b.top") commands = ['rmsd @CA', 'distance :3 :7', 'distance :3 :7', 'vector :2 :3'] dslist = CpptrajDatasetList() actlist = ActionList(commands, traj.top, dslist=dslist) d0 = dslist.add('ref_frame', 'my_ref') d0.add_frame(traj[3]) 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]) aa_eq( pt.vector.vector_mask( traj(rmsfit=(0, '@CA')), ':2 :3'), dslist[3].values)
def test_pairwise(self): traj = pt.iterload('data/tz2.nc', 'data/tz2.parm7') distances = pt.pairwise_distance(traj, '@CA', '@CB')[0] ca_indices = pt.select_atoms('@CA', traj.top) cb_indices = pt.select_atoms('@CB', traj.top) known_shape = (traj.n_frames, len(ca_indices), len(cb_indices)) assert known_shape == distances.shape, 'distance array shape' slow_distances = [] for ca_i in ca_indices: for cb_i in cb_indices: slow_distances.append(pt.distance(traj, [ca_i, cb_i])) slow_distances = np.array(slow_distances).T aa_eq(slow_distances.flatten(), distances.flatten())
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_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_calculate_distance_without_specifying_n_frames(self): # TrajectoryIterator traj = pt.iterload(fn('Tc5b.x'), fn('Tc5b.top')) arr = pt.distance(traj(stop=4), [0, 5]) arr1 = pt.distance(traj(stop=4), [0, 5], n_frames=4) assert np.all(arr == arr1) arr2 = pt.distance(traj(stop=1000), [0, 5]) arr3 = pt.distance(traj(stop=traj.n_frames), [0, 5]) assert np.all(arr2 == arr3) # Trajectory traj = traj[:] arr = pt.distance(traj(stop=4), [0, 5]) arr1 = pt.distance(traj(stop=4), [0, 5], n_frames=4) assert np.all(arr == arr1) arr2 = pt.distance(traj(stop=1000), [0, 5]) arr3 = pt.distance(traj(stop=traj.n_frames), [0, 5]) assert np.all(arr2 == arr3)
def test_0(self): from itertools import product import numpy as np traj = pt.iterload(fn('Tc5b.x'), fn('Tc5b.top')) top = traj.top d0 = pt.mindist(traj, "@CA @CB") i0 = top("@CA").indices i1 = top("@CB").indices combinations = np.array(list(product(i0, i1))) d1 = pt.distance(traj, combinations).T min_list = [] for arr0 in d1: min_list.append(np.min(arr0)) aa_eq(d0, min_list) d0 = pt.mindist(traj, [[0, 1], [2, 3]]) d1 = pt.mindist(traj, '@1,2 @3,4') aa_eq(d0, d1)
def test_calculate_distance_without_specifying_n_frames(self): # TrajectoryIterator import numpy as np traj = pt.iterload("./data/Tc5b.x", "./data/Tc5b.top") arr = pt.distance(traj(stop=4), [0, 5]) arr1 = pt.distance(traj(stop=4), [0, 5], n_frames=4) assert np.all(arr == arr1) arr2 = pt.distance(traj(stop=1000), [0, 5]) arr3 = pt.distance(traj(stop=traj.n_frames), [0, 5]) assert np.all(arr2 == arr3) # Trajectory traj = traj[:] arr = pt.distance(traj(stop=4), [0, 5]) arr1 = pt.distance(traj(stop=4), [0, 5], n_frames=4) assert np.all(arr == arr1) arr2 = pt.distance(traj(stop=1000), [0, 5]) arr3 = pt.distance(traj(stop=traj.n_frames), [0, 5]) assert np.all(arr2 == arr3)
def test_c_command_style(self): traj = pt.iterload(fn('tz2.nc'), fn('tz2.parm7')) angle_ = pt.angle(traj, ':3 :4 :5') distance_ = pt.distance(traj, '@10 @20') data = pt.pmap(['angle :3 :4 :5', 'distance @10 @20'], traj, n_cores=2) assert isinstance(data, OrderedDict), 'must be OrderDict' arr = pt.tools.dict_to_ndarray(data) aa_eq(angle_, arr[0]) aa_eq(distance_, arr[1]) # as whole text, case 1 data = pt.pmap( '''angle :3 :4 :5 distance @10 @20''', traj, n_cores=2) assert isinstance(data, OrderedDict), 'must be OrderDict' arr = pt.tools.dict_to_ndarray(data) aa_eq(angle_, arr[0]) aa_eq(distance_, arr[1])
def test_c_command_style(self): traj = pt.iterload("data/tz2.nc", "data/tz2.parm7") angle_ = pt.angle(traj, ':3 :4 :5') distance_ = pt.distance(traj, '@10 @20') data = pt.pmap(['angle :3 :4 :5', 'distance @10 @20'], traj, n_cores=2) assert isinstance(data, OrderedDict), 'must be OrderDict' arr = pt.tools.dict_to_ndarray(data) aa_eq(angle_, arr[0]) aa_eq(distance_, arr[1]) # as whole text, case 1 data = pt.pmap('''angle :3 :4 :5 distance @10 @20''', traj, n_cores=2) assert isinstance(data, OrderedDict), 'must be OrderDict' arr = pt.tools.dict_to_ndarray(data) aa_eq(angle_, arr[0]) aa_eq(distance_, arr[1])
def test_different_cores(self): # use different frame_slice with different n_cores to test REF_0 = pt.iterload("./data/tz2.nc", "./data/tz2.parm7")[0] for frame_slice in [(0, 100), (10, 100, 3), (50, 80, 2), (51, 80, 3), ]: traj = pt.iterload("./data/tz2.nc", "./data/tz2.parm7", frame_slice=frame_slice) saved_angle = pt.angle(traj, ':3 :7 :9') saved_dist = pt.distance(traj, ':2 :10') saved_rmsd = pt.rmsd(traj, ref=REF_0, mask='@CA') lines = ['angle :3 :7 :9', 'distance :2 :10'] for n_cores in [2, 3]: data_list = [worker_state(rank, n_cores, traj, lines) for rank in range(n_cores)] final_data = concat_dict([x[1] for x in data_list]) aa_eq(final_data['Ang_00002'], saved_angle) aa_eq(final_data['Dis_00003'], saved_dist)
def test_hbonds_from_pdb(self): traj = pt.load('data/1L2Y.pdb') hb = pt.search_hbonds(traj) state = pt.load_cpptraj_state(''' parm data/1L2Y.pdb trajin data/1L2Y.pdb hbond series ''') state.run() for data_p, data_cpp in zip(hb.data, state.data[1:]): assert len( data_p) == traj.n_frames == 38, 'size of dataset must be 38' aa_eq(data_p, data_cpp) # make sure distances are smaller than cutoff distance_cutoff = 2.5 angle_cutoff = 135. hb = pt.search_hbonds(traj) distances = pt.distance(traj, hb.get_amber_mask()[0]) angles = pt.angles(traj, hb.get_amber_mask()[1]) dist_indices = np.where(distances > distance_cutoff) angle_indices = np.where(angles < angle_cutoff) print('FILL ME', dist_indices, angle_indices) saved_donor_acceptors = ['ASP9_OD2-ARG16_NH1-HH12', 'ASP9_OD2-ARG16_NH2-HH22', 'ASP9_OD2-ARG16_NE-HE', 'ASP9_OD2-ARG16_NH2-HH21', 'ASP9_OD2-ARG16_NH1-HH11'] donor_acceptors = pt.search_hbonds(traj, ':9,16').donor_acceptor assert saved_donor_acceptors == donor_acceptors, 'saved_donor_acceptors' aa_eq(hb.total_solute_hbonds(), hb.data['total_solute_hbonds'])
def test_iterload_and_load_remd(self): # iterload_remd traj = pt.iterload_remd("data/Test_RemdTraj/rem.nc.000", "data/Test_RemdTraj/ala2.99sb.mbondi2.parm7", T=300.0) for frame in traj: assert frame.temperature == 300.0, 'frame temperature must be 300.0 K' dist = pt.distance(traj, '@10 @20') state = pt.load_cpptraj_state(self.trajin_text) state.run() aa_eq(dist, state.data[-1]) # load_remd traj2 = pt.load_remd("data/Test_RemdTraj/rem.nc.000", "data/Test_RemdTraj/ala2.99sb.mbondi2.parm7", T=300.0) aa_eq(traj.xyz, traj2.xyz) # with Topology traj2 = pt.iterload_remd("data/Test_RemdTraj/rem.nc.000", top=traj.top, T=300.0) aa_eq(traj.xyz, traj2.xyz)
import pytraj as pt # use `iterload` to save memory traj = pt.iterload("../tests/data/tz2.ortho.nc", "../tests/data/tz2.ortho.parm7") print(traj) # perform distance calculation with cpptraj mask pt.distance(traj, ':2 :3') # index starts from 1 pt.distance(traj, [':2 :3', '@CA @CB']) # perform distance calculation with atom_indices array pt.distance(traj, [[2, 5], [7, 9], [10, 13]]) # index starts from 0
import pytraj as pt from pytraj.testing import aa_eq comm = MPI.COMM_WORLD # end. you are free to update anything below here # split remd.x.000 to N cores and do calc_surf in parallel root_dir = "data/" traj_name = root_dir + "tz2.ortho.nc" parm_name = root_dir + "tz2.ortho.parm7" # load to TrajectoryIterator traj = pt.iterload(traj_name, parm_name) # save `total_arr` to rank=0 # others: total_arr = None total_arr = pt.pmap_mpi( ['autoimage', 'center :2', 'distance :3 :7', 'angle :3 :7 :8'], traj) if comm.rank != 0: assert total_arr is None if comm.rank == 0: # assert to serial from pytraj.tools import dict_to_ndarray arr = dict_to_ndarray(total_arr) t0 = pt.center(traj[:].autoimage(), ':2') aa_eq(pt.distance(t0, ':3 :7'), arr[0]) aa_eq(pt.angle(t0, ':3 :7 :8'), arr[1])
def test_pytraj(): print('pytraj') traj = pt.iterload('GAAC3.1000frames.nc', 'GAAC.parm7', frame_slice=(0, 1000)) data = pt.distance(traj, masklist)
usage = '''python ./plot_bond_distance.py input.parm7 input.rst7 ''' import sys import pytraj as pt top, crd = sys.argv[1:] traj = pt.iterload(crd, top) indices = traj.top.bond_indices distances = pt.distance(traj, indices) from matplotlib import pyplot as plt try: import seaborn as snb snb.set() except ImportError: pass plt.plot(distances, 'bo') pt.show()