def calc_density(traj=None, command="", top=None, dtype='ndarray', frame_indices=None): # NOTE: trick cpptraj to write to file first and the reload ''' Examples -------- >>> import pytraj as pt >>> traj = pt.datafiles.load_tz2_ortho() >>> pt.density(traj, 'charge') ''' with tempfolder(): def _calc_density(traj, command): # TODO: update this method if cpptraj save data to # CpptrajDatasetList dflist = DataFileList() tmp_filename = "tmp_pytraj_out.txt" command = "out " + tmp_filename + " " + command act = c_action.Action_Density() act(command, traj, top=top, dflist=dflist) act.post_process() dflist.write_all_datafiles() absolute_path_tmp = os.path.abspath(tmp_filename) return absolute_path_tmp dslist = CpptrajDatasetList() fname = _calc_density(traj, command) dslist.read_data(fname) return get_data_from_dtype(dslist, dtype)
def calc_density(traj=None, command="", top=None, dtype='ndarray', frame_indices=None): # NOTE: trick cpptraj to write to file first and the reload ''' Examples -------- >>> import pytraj as pt >>> traj = pt.datafiles.load_tz2_ortho() >>> pt.density(traj, 'charge') ''' with tempfolder(): def _calc_density(traj, command): # TODO: update this method if cpptraj save data to # CpptrajDatasetList dflist = DataFileList() tmp_filename = "tmp_pytraj_out.txt" command = "out " + tmp_filename + " " + command act = c_action.Action_Density() act(command, traj, top=top, dflist=dflist) act.post_process() dflist.write_all_datafiles() absolute_path_tmp = os.path.abspath(tmp_filename) return absolute_path_tmp dslist = CpptrajDatasetList() fname = _calc_density(traj, command) dslist.read_data(fname) return get_data_from_dtype(dslist, dtype)
def get_iterator_from_dslist(traj, mask, frame_indices, top, crdname='dataset_coords'): from pytraj import Trajectory, TrajectoryIterator from pytraj.datasets import CpptrajDatasetList dslist = CpptrajDatasetList() dslist.add("coords", crdname) # need to set "rmsout" to trick cpptraj not giving error # need " " (space) before crdset too if isinstance(traj, (Trajectory, TrajectoryIterator)): # we do atom stripping here before copying to DatasetCoordsCRD to save memory if # loading from TrajectoryIterator fi = traj.iterframe(mask=mask, frame_indices=frame_indices) command = '' # use Topology from fi (could be stripped to save memory) dslist[0].top = fi.top top_ = fi.top else: # ignore frame_indices fi = iterframe_master(traj) command = mask top_ = get_topology(traj, top) dslist[0].top = top_ for frame in fi: dslist[0].append(frame) return dslist, top_, command
def test_DatasetDouble(self): dslist = CpptrajDatasetList() d = dslist.add_new(dtype='double') a = range(8) # append for i in a: d.append(i) aa_eq(a, d) assert int(d[2]) == a[2] == 2, 'must be equal'
def test_DatasetDouble(self): dslist = CpptrajDatasetList() d = dslist.add_new(dtype='double') a = range(8) # append for i in a: d.append(i) aa_eq(a, d) assert int(d[2]) == a[2] == 2, 'must be equal'
def worker_by_actlist(rank, n_cores=2, traj=None, lines=None, dtype='dict', ref=None, kwd=None): '''worker for cpptraj commands (string) ''' # need to make a copy if lines since python's list is dangerous # it's easy to mess up with mutable list # do not use lines.copy() since this is not available in py2.7 # Note: dtype is a dummy argument, it is always 'dict' if lines is None: lines = [] frame_indices = kwd.pop('frame_indices', None) new_lines, need_ref = check_valid_command(lines) if frame_indices is None: my_iter = traj._split_iterators(n_cores, rank=rank) else: my_iter = traj.iterframe( frame_indices=np.array_split(frame_indices, n_cores)[rank]) if ref is not None: if isinstance(ref, Frame): reflist = [ ref, ] else: # list/tuplex reflist = ref else: reflist = [ traj[0], ] if need_ref else [] dslist = CpptrajDatasetList() if reflist: for ref_ in reflist: ref_dset = dslist.add('reference') ref_dset.top = traj.top ref_dset.add_frame(ref_) # create Frame generator fi = pipe(my_iter, commands=new_lines, dslist=dslist) # just iterate Frame to trigger calculation. for _ in fi: pass # remove ref return (rank, dslist[len(reflist):].to_dict())
def read_data(filename, options=''): """same as readdata in cpptraj Returns ------- out : CpptrajDatasetList """ from pytraj.datasets import CpptrajDatasetList cdslist = CpptrajDatasetList() cdslist.read_data(filename, options) return cdslist
def worker_by_actlist(rank, n_cores=2, traj=None, lines=None, dtype='dict', ref=None, kwd=None): '''worker for cpptraj commands (string) ''' # need to make a copy if lines since python's list is dangerous # it's easy to mess up with mutable list # do not use lines.copy() since this is not available in py2.7 # Note: dtype is a dummy argument, it is always 'dict' if lines is None: lines = [] frame_indices = kwd.pop('frame_indices', None) new_lines, need_ref = check_valid_command(lines) if frame_indices is None: my_iter = traj._split_iterators(n_cores, rank=rank) else: my_iter = traj.iterframe( frame_indices=np.array_split(frame_indices, n_cores)[rank]) if ref is not None: if isinstance(ref, Frame): reflist = [ref, ] else: # list/tuplex reflist = ref else: reflist = [traj[0],] if need_ref else [] dslist = CpptrajDatasetList() if reflist: for ref_ in reflist: ref_dset = dslist.add('reference') ref_dset.top = traj.top ref_dset.add_frame(ref_) # create Frame generator fi = pipe(my_iter, commands=new_lines, dslist=dslist) # just iterate Frame to trigger calculation. for _ in fi: pass # remove ref return (rank, dslist[len(reflist):].to_dict())
def _rotdif(arr, nvecs=1000, rvecin=None, rseed=80531, order=2, ncorr=-1, tol=1E-6, d0=0.03, nmesh=2, dt=0.002, ti=0.0, tf=-1, itmax=-1., dtype='ndarray'): ''' Parameters ---------- arr : array-like, shape (n_frames, 3, 3) or (n_frames, 9) ''' _nvecs = 'nvecs ' + str(nvecs) _rvecin = 'rvecin ' + rvecin if rvecin is not None else '' _rseed = 'rseed ' + str(rseed) _order = 'order ' + str(order) _ncorr = 'ncorr ' + str(ncorr) if ncorr > 0 else '' _tol = 'tol ' + str(tol) _d0 = 'd0 ' + str(d0) _nmesh = 'nmesh ' + str(nmesh) _dt = 'dt ' + str(dt) _ti = 'ti ' + str(ti) _tf = 'tf ' + str(tf) _itmax = 'itmax ' + str(itmax) _rmatrix = 'rmatrix mymat' act = CpptrajAnalyses.Analysis_Rotdif() dslist = CpptrajDatasetList() dslist.add_set('mat3x3', 'mymat') arr = np.asarray(arr, dtype='f8') msg = 'array must have shape=(n_frames, 9) or (n_frames, 3, 3)' shape = arr.shape if arr.ndim == 2: assert shape[1] == 9, msg elif arr.ndim == 3: assert shape[1:3] == (3, 3), msg # need to reshape to (n_frames, 9) arr = arr.reshape(shape[0], shape[1] * shape[2]) else: raise ValueError(msg)
def _rotdif(arr, nvecs=1000, rvecin=None, rseed=80531, order=2, ncorr=-1, tol=1E-6, d0=0.03, nmesh=2, dt=0.002, ti=0.0, tf=-1, itmax=-1., dtype='ndarray'): ''' Parameters ---------- arr : array-like, shape (n_frames, 3, 3) or (n_frames, 9) ''' _nvecs = 'nvecs ' + str(nvecs) _rvecin = 'rvecin ' + rvecin if rvecin is not None else '' _rseed = 'rseed ' + str(rseed) _order = 'order ' + str(order) _ncorr = 'ncorr ' + str(ncorr) if ncorr > 0 else '' _tol = 'tol ' + str(tol) _d0 = 'd0 ' + str(d0) _nmesh = 'nmesh ' + str(nmesh) _dt = 'dt ' + str(dt) _ti = 'ti ' + str(ti) _tf = 'tf ' + str(tf) _itmax = 'itmax ' + str(itmax) _rmatrix = 'rmatrix mymat' act = CpptrajAnalyses.Analysis_Rotdif() dslist = CpptrajDatasetList() dslist.add_set('mat3x3', 'mymat') arr = np.asarray(arr, dtype='f8') msg = 'array must have shape=(n_frames, 9) or (n_frames, 3, 3)' shape = arr.shape if arr.ndim == 2: assert shape[1] == 9, msg elif arr.ndim == 3: assert shape[1:3] == (3, 3), msg # need to reshape to (n_frames, 9) arr = arr.reshape(shape[0], shape[1] * shape[2]) else: raise ValueError(msg)
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_combine_with_frame_iterator(self): traj = pt.iterload(fn("tz2.ortho.nc"), fn("tz2.ortho.parm7")) dslist = CpptrajDatasetList() commands = [ 'autoimage', 'rms', ] actlist = ActionList(commands, top=traj.top, dslist=dslist) def get_frameiter(actlist, traj): for frame in traj: actlist.compute(frame) yield frame def do_extra(fi): a = [] for frame in fi: frame.xyz = frame.xyz + 2. a.append(frame.copy()) return a new_list = do_extra(get_frameiter(actlist, traj)) t0 = traj[:].autoimage().superpose() t0.xyz += 2. aa_eq(np.array([frame.xyz for frame in new_list]), t0.xyz)
def test_combine_cpptraj_iterating_with_pytraj(self): traj = pt.iterload(fn("tz2.ortho.nc"), fn("tz2.ortho.parm7")) commands = [ 'autoimage', 'rms', ] dslist = CpptrajDatasetList() actlist = ActionList(commands, top=traj.top, dslist=dslist) def get_fi(actlist, traj): '''create a frame iterator with pre-processed by cpptraj ''' for frame in traj: actlist.compute(frame) yield frame ref = traj[3] pt.autoimage(ref, top=traj.top) fi = get_fi(actlist, traj) rmsd_nofit_after_fitting = pt.rmsd_nofit(fi, ref=ref, top=traj.top) t0 = traj[:].autoimage().superpose() saved_rmsd_ = pt.rmsd_nofit(t0, ref=ref) aa_eq(rmsd_nofit_after_fitting, saved_rmsd_)
def test_reference_with_different_topology_basic(self): traj1 = pt.iterload(filename=tc5b_trajin, top=tc5b_top) traj2 = pt.iterload(fn('tz2.nc'), fn('tz2.parm7')) # re-establish ActionList dslist = CpptrajDatasetList() dslist.add('reference', name='myref') dslist[0].top = traj2.top dslist[0].add_frame(traj2[0]) actlist = pt.ActionList(['rmsd @1-11 @CB ref myref'], top=traj1.top, dslist=dslist) for frame in traj1: actlist.compute(frame) # raise if ref_mask is given but not mask self.assertRaises(ValueError, lambda: pt.rmsd(traj1, ref=3, ref_mask='@CB')) self.assertRaises( ValueError, lambda: pt.rmsd(traj1, ref=traj2[:1], ref_mask='@CB')) # assert to cpptraj tc5b_traj = traj1[:] tz2_traj = traj2[:1] cm = ''' parm {} [tc5b] trajin {} parm {} [tz2] reference {} parm [tz2] 1 [myref] rms myrmsd ref [myref] @1-10 @11-20 '''.format(tc5b_top, tc5b_trajin, tz2_top, tz2_trajin) print(cm) state = pt.load_cpptraj_state(cm) with tempfolder(): state.run() expected_rmsd = state.data[-1].values rmsd_data = pt.rmsd(tc5b_traj, mask='@1-10', ref=tz2_traj, ref_mask='@11-20') aa_eq(expected_rmsd, rmsd_data)
def test_run_0(self): # load traj farray = pt.load(filename="./data/tz2.truncoct.nc", top="./data/tz2.truncoct.parm7")[:2] fold = farray.copy() act = allactions.Action_Image() ptrajin = """ center :2-11 image center familiar com :6 """ # create 'strip' action stripact = allactions.Action_Strip() # creat datasetlist to hold distance data dsetlist = CpptrajDatasetList() dflist = DataFileList() # creat ActionList to hold actions alist = ActionList() top = farray.top # add two actions: Action_Strip and Action_Distance alist.add(allactions.Action_Center(), ArgList(":2-11"), top=top) alist.add(allactions.Action_Image(), ArgList("center familiar com :6"), top=top) # do checking alist.check_topology(top) farray2 = Trajectory() frame0 = Frame() # testing how fast to do the actions # loop all frames # use iterator to make faster loop # don't use "for i in range(farray.n_frames)" for frame in farray: # perform actions for each frame # we make a copy since we want to keep orginal Frame frame0 = frame.copy() alist.compute(frame0) # we need to keep the modified frame in farray2 farray2.append(frame0) # make sure that Action_Strip does its job in stripping assert farray2.n_frames == farray.n_frames fsaved = pt.iterload(cpptraj_test_dir + "/Test_Image/image4.crd.save", "data/tz2.truncoct.parm7") assert fsaved.n_frames == 2
def test_reference_with_different_topology_basic(self): traj1 = pt.iterload(filename="./data/Tc5b.x", top="./data/Tc5b.top") traj2 = pt.iterload('data/tz2.nc', 'data/tz2.parm7') # re-establish ActionList dslist = CpptrajDatasetList() dslist.add('reference', name='myref') dslist[0].top = traj2.top dslist[0].add_frame(traj2[0]) actlist = pt.ActionList(['rmsd @1-11 @CB ref myref'], top=traj1.top, dslist=dslist) for frame in traj1: actlist.compute(frame) # raise if ref_mask is given but not mask self.assertRaises(ValueError, lambda: pt.rmsd(traj1, ref=3, ref_mask='@CB')) self.assertRaises(ValueError, lambda: pt.rmsd(traj1, ref=traj2[:1], ref_mask='@CB')) # assert to cpptraj tc5b_traj = traj1[:] tz2_traj = traj2[:1] cm = ''' parm data/Tc5b.top [tc5b] trajin data/Tc5b.x [tc5b] parm data/tz2.parm7 [tz2] reference data/tz2.nc parm [tz2] 1 [myref] rms myrmsd ref [myref] @1-10 @11-20 ''' state = pt.load_cpptraj_state(cm) state.run() expected_rmsd = state.data[-1].values rmsd_data = pt.rmsd(tc5b_traj, mask='@1-10', ref=tz2_traj, ref_mask='@11-20') aa_eq(expected_rmsd, rmsd_data)
def test_run_5(self): traj = pt.iterload(tc5b_trajin, tc5b_top) mask_list = ('@CB @CA', '@CA @H') dslist = CpptrajDatasetList() actlist = ActionList() for mask in mask_list: actlist.add(CA.Action_Distance(), mask, traj.top, dslist=dslist) actlist.compute(traj) dslist2 = pt.calc_distance(traj, mask_list) aa_eq(dslist.values, dslist2)
def calc_linear_interaction_energy(traj=None, mask="", top=None, dtype='dataset', frame_indices=None, *args, **kwd): command = mask act = c_action.Action_LIE() dslist = CpptrajDatasetList() act(command, traj, top=top, dslist=dslist, *args, **kwd) return get_data_from_dtype(dslist, dtype)
def test_unstrip(self): from pytraj.datasets import CpptrajDatasetList traj = pt.iterload(fn('tz2.nc'), fn('tz2.parm7')) dslist = CpptrajDatasetList() actlist = pt.ActionList(['strip !@CA', 'unstrip', 'radgyr nomax'], top=traj.top, dslist=dslist) actlist.compute(traj) # make sure that after stripping and unstrip the Frame coords are restored aa_eq(pt.radgyr(traj), dslist.values) dslist2 = CpptrajDatasetList() actlist2 = pt.ActionList(['strip !@CA', 'radgyr nomax'], top=traj.top, dslist=dslist2) actlist2.compute(traj) # make sure get correct radgyr after stripping all but CA atoms aa_eq(dslist2.values, pt.radgyr(traj, '@CA'))
def test_run_2(self): # load traj traj = pt.iterload(tc5b_trajin, tc5b_top) dslist = CpptrajDatasetList() dflist = DataFileList() # creat ActionList to hold actions alist = ActionList() alist.add(adict['distance'], ":2@CA :10@CA out _dist.out", traj.top, dslist, dflist) with tempfolder(): alist.compute([traj.iterchunk()]) assert len(dslist) == 1 assert dslist[0].size == traj.n_frames
def test_run_2(self): # load traj traj = pt.iterload("./data/Tc5b.x", "./data/Tc5b.top") dslist = CpptrajDatasetList() dflist = DataFileList() # creat ActionList to hold actions alist = ActionList() alist.add(adict['distance'], ":2@CA :10@CA out ./output/_dist.out", traj.top, dslist, dflist) alist.compute([traj.iterchunk()]) print('dslist', dslist[0].size) assert len(dslist) == 1 assert dslist[0].size == traj.n_frames
def read_data(cls, filename, arg=""): ''' >>> from pytraj.datasetlist import DatasetList >>> DatasetList.read_data('data/tc5b.native_contacts.dat') <pytraj.DatasetList with 2 datasets> Contacts_00001[native] [ 7095. 5904. 5638. 5600. 5695. 5745. 5611. 5556. 5739. 5748.] <BLANKLINE> Contacts_00001[nonnative] [ 0. 2696. 3065. 3552. 3700. 2624. 4000. 3797. 3482. 4265.] ''' df = DataFile() dslist = CpptrajDatasetList() df.read_data(filename, ArgList(arg), dslist) return DatasetList(dslist)
def test_reference(self): traj = pt.iterload(fn("tz2.ortho.nc"), fn("tz2.ortho.parm7")) # store reference dslist = CpptrajDatasetList() ref = dslist.add('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')) aa_eq(xyz, t0.xyz) t1 = traj[:].autoimage() aa_eq(pt.rmsd(t1, ref=traj[3], mask='@CA'), dslist[-1].values)
def lifetime(data, cut=0.5, rawcurve=False, more_options='', dtype='ndarray'): """lifetime (adapted lightly from cpptraj doc) Parameters ---------- data : 1D-array or 2D array-like cut : cutoff to use when determining if data is 'present', default 0.5 more_options : str, more cpptraj's options. Check cpptraj's manual. """ data = np.asarray(data) if data.ndim == 1: data_ = [ data, ] else: data_ = data _outname = 'name lifetime_' _cut = 'cut ' + str(cut) _rawcurve = 'rawcurve' if rawcurve else '' # do not sorting dataset's names. We can accessing by indexing them. _nosort = 'nosort' namelist = [] cdslist = CpptrajDatasetList() for idx, arr in enumerate(data_): # create datasetname so we can reference them name = 'data_' + str(idx) if 'int' in arr.dtype.name: cdslist.add_set("integer", name) else: cdslist.add_set("double", name) cdslist[-1].data = np.asarray(arr) namelist.append(name) act = CpptrajAnalyses.Analysis_Lifetime() _cm = ' '.join(namelist) command = " ".join((_cm, _outname, _cut, _rawcurve, _nosort, more_options)) act(command, dslist=cdslist) for name in namelist: cdslist.remove_set(cdslist[name]) return get_data_from_dtype(cdslist, dtype=dtype)
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_run_4(self): dslist = CpptrajDatasetList() actlist = ActionList() traj = pt.iterload("./data/Tc5b.x", "./data/Tc5b.top") mask_list = ['@CB @CA @N @H', '@CA @H @N @H='] for mask in mask_list: actlist.add(CA.Action_Dihedral(), mask, traj.top, dslist=dslist) actlist.compute(traj) dslist2 = pt.calc_dihedral(traj, mask_list) dslist3_0 = pt.calc_dihedral(traj, mask_list[0]) dslist3_1 = pt.calc_dihedral(traj, mask_list[1]) aa_eq(dslist3_0, dslist2[0]) aa_eq(dslist3_1, dslist2[1]) aa_eq(dslist3_0, dslist[0].to_ndarray()) aa_eq(dslist3_1, dslist[1].to_ndarray())
def test_run_1(self): # load traj traj = pt.iterload(tc5b_trajin, tc5b_top) dslist = CpptrajDatasetList() dflist = DataFileList() # creat ActionList to hold actions alist = ActionList() # add two actions: Action_Dihedral and Action_Distance alist.add(adict['distance'], ":2@CA :10@CA out ./output/_dist.out", traj.top, dslist, dflist) alist.add(adict['dihedral'], ":2@CA :3@CA :4@CA :5@CA out ./output/_dih.out", traj.top, dslist, dflist) # using string for action 'dssp' alist.add('dssp', "out ./output/_dssp_alist.out", traj.top, dslist, dflist) alist.add('matrix', "out ./output/_mat_alist.out", traj.top, dslist, dflist)
def _toy_radgyr(traj, mask="", top=None, dtype='ndarray', nomax=True, frame_indices=None): ''' Examples -------- >>> import pytraj as pt >>> pt.mindist(traj, '@CA @H') ''' act = c_action.Action_Radgyr() dslist = CpptrajDatasetList() _nomax = 'nomax' if nomax else '' mask = ' '.join((mask, _nomax)) act(mask, traj, top=top, dslist=dslist) return get_data_from_dtype(dslist, dtype=dtype)
def test_modify_frame_use_Pipeline(self): traj = pt.iterload(fn("tz2.ortho.nc"), fn("tz2.ortho.parm7")) dslist = CpptrajDatasetList() dslist.add('topology', name='mytop') # add a new topology dslist[0].data = pt.strip(traj.top, ':WAT') commands = [ 'autoimage', 'strip :WAT', 'createcrd mycrd', ] actlist = Pipeline(commands, top=traj.top, dslist=dslist) for frame in traj: actlist.compute(frame) aa_eq(dslist['mycrd'].xyz, pt.get_coordinates(traj, mask='!:WAT', autoimage=True))
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 lifetime(data, cut=0.5, rawcurve=False, more_options='', dtype='ndarray'): """lifetime (adapted lightly from cpptraj doc) Parameters ---------- data : 1D-array or 2D array-like cut : cutoff to use when determining if data is 'present', default 0.5 more_options : str, more cpptraj's options. Check cpptraj's manual. """ data = np.asarray(data) if data.ndim == 1: data_ = [data, ] else: data_ = data _outname = 'name lifetime_' _cut = 'cut ' + str(cut) _rawcurve = 'rawcurve' if rawcurve else '' # do not sorting dataset's names. We can accessing by indexing them. _nosort = 'nosort' namelist = [] cdslist = CpptrajDatasetList() for idx, arr in enumerate(data_): # create datasetname so we can reference them name = 'data_' + str(idx) if 'int' in arr.dtype.name: cdslist.add_set("integer", name) else: cdslist.add_set("double", name) cdslist[-1].data = np.asarray(arr) namelist.append(name) act = CpptrajAnalyses.Analysis_Lifetime() _cm = ' '.join(namelist) command = " ".join((_cm, _outname, _cut, _rawcurve, _nosort, more_options)) act(command, dslist=cdslist) for name in namelist: cdslist.remove_set(cdslist[name]) return get_data_from_dtype(cdslist, dtype=dtype)
def test_add_new_for_CpptrajDatasetList(self): # TODO: dslist = CpptrajDatasetList() # integer dslist.add_new(dtype='integer', name='my_int') dslist[-1].data = [2, 3] aa_eq(dslist[-1].values, [2, 3]) # double dslist.add_new(dtype='double', name='my_double') dslist[-1].data = [2, 3] aa_eq(dslist[-1].values, [2, 3]) # float dslist.add_new(dtype='float', name='my_float') dslist[-1].data = [2, 3] aa_eq(dslist[-1].values, [2, 3]) # string dslist.add_new(dtype='string', name='my_string') dslist[-1].data = ['H', 'T'] assert dslist[-1].values.tolist() == ['H', 'T'], 'string must be equal' # reference dslist.add_new(dtype='reference', name='my_reference') dslist[-1].data = self.traj[-2] aa_eq(dslist[-1].xyz, self.traj[-2].xyz) # matrix3x3 dslist.add_new(dtype='matrix3x3', name='my_mat3x3') mat = pt.calc_rotation_matrix(self.traj, ref=0, mask='@CA') # there is no assignment. Need to update by another method dslist[-1]._append_from_array(mat) aa_eq(dslist[-1].values, mat) # TRAJ dslist.add_new(dtype='traj', name='my_traj') dslist[-1].top = self.traj.top dslist[-1]._load(self.traj.filename) traj_new = dslist[-1] # FIXME: segmentation fault # CRD dslist.add_new(dtype='coords', name='my_crd') dslist[-1].top = self.traj.top dslist[-1].load(self.traj.filename) traj_new = dslist[-1] aa_eq(traj_new.xyz, self.traj.xyz) aa_eq(pt.rmsd(traj_new), pt.rmsd(self.traj)) # vector dslist.add_new(dtype='vector', name='my_vec') vecs = pt.vector.vector_mask(self.traj, ':3 :2') dslist[-1].data = vecs aa_eq(dslist[-1].values, vecs) # grid dslist.add_new(dtype='grid', name='my_grid') arr = np.random.rand(8, 9, 3).astype('f4') dslist[-1].data = arr aa_eq(dslist[-1].values, arr) # mesh dslist.add_new(dtype='xymesh', name='my_mesh') arr = np.random.rand(8, 2).astype('f8') # there is not easy method to update, use _append_from_array dslist[-1]._append_from_array(arr) aa_eq(dslist[-1].values, arr) # modes mat = pt.matrix.covar(self.traj, '@CA') modes = pt.matrix.diagonalize(mat, n_vecs=mat.shape[0], dtype='dataset')[0] modes2 = modes.__class__() # dummy test to set name and scalar_type # (prepare for pca) modes2.name = 'test_mode' modes2.scalar_type = 'covar' modes2._set_modes(False, mat.shape[0], modes.eigenvectors.shape[0], modes.eigenvalues, modes.eigenvectors.flatten()) aa_eq(modes.eigenvalues, modes2.eigenvalues) aa_eq(modes.eigenvectors, modes2.eigenvectors)
def test_add_new_for_CpptrajDatasetList(self): # TODO: dslist = CpptrajDatasetList() # integer dslist.add_new(dtype='integer', name='my_int') dslist[-1].data = [2, 3] aa_eq(dslist[-1].values, [2, 3]) # double dslist.add_new(dtype='double', name='my_double') dslist[-1].data = [2, 3] aa_eq(dslist[-1].values, [2, 3]) # float dslist.add_new(dtype='float', name='my_float') dslist[-1].data = [2, 3] aa_eq(dslist[-1].values, [2, 3]) # string dslist.add_new(dtype='string', name='my_string') dslist[-1].data = ['H', 'T'] assert dslist[-1].values.tolist() == ['H', 'T'], 'string must be equal' # reference dslist.add_new(dtype='reference', name='my_reference') dslist[-1].data = self.traj[-2] aa_eq(dslist[-1].xyz, self.traj[-2].xyz) # matrix3x3 dslist.add_new(dtype='matrix3x3', name='my_mat3x3') mat = pt.calc_rotation_matrix(self.traj, ref=0, mask='@CA') # there is no assignment. Need to update by another method dslist[-1]._append_from_array(mat) aa_eq(dslist[-1].values, mat) # TRAJ dslist.add_new(dtype='traj', name='my_traj') dslist[-1].top = self.traj.top dslist[-1]._load(self.traj.filename) traj_new = dslist[-1] # FIXME: segmentation fault # CRD dslist.add_new(dtype='coords', name='my_crd') dslist[-1].top = self.traj.top dslist[-1].load(self.traj.filename) traj_new = dslist[-1] aa_eq(traj_new.xyz, self.traj.xyz) aa_eq(pt.rmsd(traj_new), pt.rmsd(self.traj)) # vector dslist.add_new(dtype='vector', name='my_vec') vecs = pt.vector.vector_mask(self.traj, ':3 :2') dslist[-1].data = vecs aa_eq(dslist[-1].values, vecs) # grid dslist.add_new(dtype='grid', name='my_grid') arr = np.random.rand(8, 9, 3).astype('f4') dslist[-1].data = arr aa_eq(dslist[-1].values, arr) # mesh dslist.add_new(dtype='xymesh', name='my_mesh') arr = np.random.rand(8, 2).astype('f8') # there is not easy method to update, use _append_from_array dslist[-1]._append_from_array(arr) aa_eq(dslist[-1].values, arr) # modes mat = pt.matrix.covar(self.traj, '@CA') modes = pt.matrix.diagonalize(mat, n_vecs=mat.shape[0], dtype='dataset')[0] modes2 = modes.__class__() # dummy test to set name and scalar_type # (prepare for pca) modes2.name = 'test_mode' modes2.scalar_type = 'covar' modes2._set_modes(False, mat.shape[0], modes.eigenvectors.shape[0], modes.eigenvalues, modes.eigenvectors.flatten()) aa_eq(modes.eigenvalues, modes2.eigenvalues) aa_eq(modes.eigenvectors, modes2.eigenvectors)