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 vector(traj=None, command="", frame_indices=None, dtype='ndarray', top=None): """perform vector calculation. See example below. Same as 'vector' command in cpptraj. Parameters ---------- traj : Trajectory-like or iterable that produces :class:`pytraj.Frame` command : str or a list of strings, cpptraj command frame_indices : array-like, optional, default None only perform calculation for given frame indices dtype : output's dtype, default 'ndarray' top : Topology, optional, default None Returns ------- out : numpy ndarray, shape (n_frames, 3) if command is a string numpy ndarray, shape (n_vectors, n_frames, 3) if command is a list of strings Examples -------- >>> import pytraj as pt >>> traj = pt.datafiles.load_tz2_ortho() >>> data = pt.vector.vector(traj, "@CA @CB") >>> data = pt.vector.vector(traj, [("@CA @CB"),]) >>> data = pt.vector.vector(traj, "principal z") >>> data = pt.vector.vector(traj, "principal x") >>> data = pt.vector.vector(traj, "ucellx") >>> data = pt.vector.vector(traj, "boxcenter") >>> data = pt.vector.vector(traj, "box") Notes ----- It's faster to calculate with a list of commands. For example, if you need to perform 3 calculations for 'ucellx', 'boxcenter', 'box' like below: >>> data = pt.vector.vector(traj, "ucellx") >>> data = pt.vector.vector(traj, "boxcenter") >>> data = pt.vector.vector(traj, "box") You should use a list of commands for faster calculation. >>> comlist = ['ucellx', 'boxcenter', 'box'] >>> data = pt.vector.vector(traj, comlist) """ c_dslist = CpptrajDatasetList() top_ = get_topology(traj, top) list_of_commands = get_list_of_commands(command) fi = get_fiterator(traj, frame_indices) actlist = ActionList() for command in list_of_commands: act = c_action.Action_Vector() actlist.add(act, command, top_, dslist=c_dslist) actlist.compute(fi) return get_data_from_dtype(c_dslist, dtype=dtype)
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 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 _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 multivector(traj, resrange, names, top=None, dtype='dataset', frame_indices=None): ''' Parameters ---------- traj : Trajectory-like resrange : str, residue range names : {str, tuple of str} top : Topology, optional dtype : str, default 'dataset' frame_indices : {None, 1D array-like}, optional, default None Examples -------- >>> import pytraj as pt >>> traj = pt.datafiles.load_tz2_ortho() >>> vecs = pt.multivector(traj, resrange='1-5', names=('C', 'N')) >>> vecs = pt.multivector(traj, resrange='1-5', names='C N') ''' _resrange = 'resrange ' + resrange if 'name1' in names or 'name2' in names: # cpptraj style _names = names else: if isinstance(names, str): name1, name2 = names.split() else: # try to unpack name1, name2 = names _names = ' '.join(('name1', name1, 'name2', name2)) command = ' '.join((_resrange, _names)) c_dslist, _ = do_action(traj, command, c_action.Action_MultiVector) return get_data_from_dtype(c_dslist, dtype)
def vector_mask(traj=None, mask="", frame_indices=None, dtype='ndarray', top=None): """compute vector between two maskes Parameters ---------- traj : Trajectory-like or iterable that produces Frame mask: str or array of string or array of intergers, shape (n_vectors, 2) vector maskes frame_indices : array-like or iterable that produces integer number frame indices dtype : str, default 'ndarray' output dtype top : Topology, optional, default None Returns ------- if mask is a string, return 2D ndarray, shape (n_frames, 3) if mask is a list of strings or a 2D ndarray, return 3D ndarray, shape (n_vectors, n_frames, 3) Examples -------- >>> # calcualte N-H vector >>> import pytraj as pt >>> import numpy as np >>> traj = pt.load_sample_data('tz2') >>> from pytraj import vector as va >>> n_indices = pt.select_atoms('@N', traj.top) >>> h_indices = n_indices + 1 >>> # create n-h pair for vector calculation >>> n_h_pairs = np.array(list(zip(n_indices, h_indices))) >>> data_vec = va.vector_mask(traj, n_h_pairs, dtype='ndarray') >>> # compute vectors for specific frame indices (0, 4) >>> data_vec = va.vector_mask(traj, n_h_pairs, frame_indices=[0, 4], dtype='ndarray') """ from pytraj.utils.get_common_objects import get_topology, get_data_from_dtype, get_fiterator from pytraj.utils.get_common_objects import get_list_of_commands from pytraj.datasets.c_datasetlist import DatasetList as CpptrajDatasetList from pytraj.analysis.c_action.c_action import Action_Vector from pytraj.analysis.c_action.actionlist import ActionList fi = get_fiterator(traj, frame_indices) _top = get_topology(fi, top) dslist = CpptrajDatasetList() template_command = ' mask ' cm_arr = np.asarray(mask) if cm_arr.dtype.kind != 'i': list_of_commands = get_list_of_commands(mask) else: if cm_arr.ndim != 2: raise ValueError( 'if mask is a numpy.ndarray, it must have ndim = 2') list_of_commands = _2darray_to_atommask_groups(cm_arr) actlist = ActionList() for command in list_of_commands: act = Action_Vector() _command = command + template_command actlist.add(act, _command, _top, dslist=dslist) actlist.compute(fi) return get_data_from_dtype(dslist, dtype=dtype)
def _cluster(traj, algorithm, mask="", frame_indices=None, dtype='dataset', top=None, options=''): """clustering. Limited support. Parameters ---------- traj : Trajectory-like or any iterable that produces Frame mask : str atom mask dtype : str return data type top : Topology, optional options: str more cpptraj option Notes ----- Call `pytraj._verbose()` to see more output. Turn it off by `pytraj._verbose(False)` cpptraj manual:: Algorithms: [hieragglo [epsilon <e>] [clusters <n>] [linkage|averagelinkage|complete] [epsilonplot <file>]] [dbscan minpoints <n> epsilon <e> [sievetoframe] [kdist <k> [kfile <prefix>]]] [dpeaks epsilon <e> [noise] [dvdfile <density_vs_dist_file>] [choosepoints {manual | auto}] [distancecut <distcut>] [densitycut <densitycut>] [runavg <runavg_file>] [deltafile <file>] [gauss]] [kmeans clusters <n> [randompoint [kseed <seed>]] [maxit <iterations>] [{readtxt|readinfo} infofile <file>] Distance metric options: {rms | srmsd | dme | data} { [[rms | srmsd] [<mask>] [mass] [nofit]] | [dme [<mask>]] | [data <dset0>[,<dset1>,...]] } [sieve <#> [random [sieveseed <#>]]] [loadpairdist] [savepairdist] [pairdist <name>] [pairwisecache {mem | none}] Output options: [out <cnumvtime>] [gracecolor] [summary <summaryfile>] [info <infofile>] [summarysplit <splitfile>] [splitframe <comma-separated frame list>] [clustersvtime <filename> cvtwindow <window size>] [cpopvtime <file> [normpop | normframe]] [lifetime] [sil <silhouette file prefix>] Coordinate output options: [ clusterout <trajfileprefix> [clusterfmt <trajformat>] ] [ singlerepout <trajfilename> [singlerepfmt <trajformat>] ] [ repout <repprefix> [repfmt <repfmt>] [repframe] ] [ avgout <avgprefix> [avgfmt <avgfmt>] ] Experimental options: [[drawgraph | drawgraph3d] [draw_tol <tolerance>] [draw_maxit <iterations]] Cluster structures based on coordinates (RMSD/DME) or given data set(s). <crd set> can be created with the 'createcrd' command. """ # Note: do not use super_dispatch here. We use get_iterator_from_dslist ana = c_analysis.Analysis_Clustering() # need to creat `dslist` here so that every time `do_clustering` is called, # we will get a fresh one (or will get segfault) crdname = 'DEFAULT_NAME' dslist, _top, mask2 = get_iterator_from_dslist(traj, mask, frame_indices, top, crdname=crdname) if 'summary' not in options.split(): options += ' summary' # do not output cluster info to STDOUT command = ' '.join( (algorithm, mask2, "crdset {0}".format(crdname), options)) with capture_stdout() as (out, _): ana(command, dslist) # remove frames in dslist to save memory dslist.remove_set(dslist[crdname]) return ClusteringDataset( (get_data_from_dtype(dslist[:1], dtype='ndarray'), out.read()))