def main(topology, trajectories, insort=False, selection=None, maintain=None, top_output='_frame0.pdb', traj_output='nosol.dcd', **kwargs): """Execute main client logic.""" log.info(T('Removing solvent')) trj = libmdt.load_traj(topology, trajectories, insort=insort) if selection: log.info(S('selecting {}', selection)) atom_sel = trj.top.select(selection) trj.atom_slice(atom_sel, inplace=True) trj.remove_solvent(inplace=True, exclude=maintain) if top_output: fout = libio.parse_top_output(top_output, traj_output) trj[0].save(fout.str()) log.info(S('first frame topology saved: {}', fout)) log.info(T('saving trajectory')) log.info(S('destination: {}', traj_output)) trj.save(traj_output) log.info(S('saved'))
def main( topology, trajectories, insort=False, traj_output='imaged.dcd', top_output=False, protocol=1, **kwargs ): """Execute main client logic.""" log.info(T('Attempting image molecules')) log.info(T('loading input')) traj = libmdt.load_traj(topology, trajectories, insort=insort) protocols = { 1: libmdt.imagemol_protocol1, 2: libmdt.imagemol_protocol2, } reimaged = protocols[protocol](traj) log.info(T('saving the output')) reimaged.save(traj_output) log.info(S('saved trajectory: {}', traj_output)) if top_output: fout = libio.parse_top_output(top_output, traj_output) reimaged[0].save(fout.str()) log.info(S('saved frame 0 to: {}', fout.resolve())) return
def imagemol_protocol1(traj): """Attempt to image molecules acting on the whole traj.""" log.info(T('running reimage protocol #1')) log.info(S('finding molecules')) mols = traj.top.find_molecules() log.info(S('done')) log.info(T('reimaging')) reimaged = traj.image_molecules( inplace=False, anchor_molecules=mols[:1], other_molecules=mols[1:], ) log.info(S('done')) return reimaged
def _log_simtkimport_error(): msg = ("To use .cif files as Topologies taurenmd requires OpenMM, " "which is currently not installed. " "Please visit our Installation instruction at " "https://taurenmd.readthedocs.io/") log.error(T('Dependency Error')) log.error(S(msg)) sys.exit(0)
def main( topology, trajectory, # trajectories, # additional args... # ... **kwargs): """Execute main client logic.""" log.info(T('starting')) # write your logic here. # use the log.info and log.debug registries to log and output # information to the user. # you can always refer to other clients for examples. log.info(S('done')) return
def mda_rmsf( atom_group, frame_slice=None, ): """ Calculate RMSFs. Uses `MDAnalysis RMSF <https://www.mdanalysis.org/docs/documentation_pages/analysis/rms.html?highlight=rmsd#MDAnalysis.analysis.rms.RMSF>`_. Parameters ---------- atom_group : MDAnalysis Atom Group. `MDAnalysis Atom group <https://www.mdanalysis.org/docs/documentation_pages/core/groups.html?highlight=atom%20group#MDAnalysis.core.groups.AtomGroup>`_. frame_slice : any, optional Any argument that :py:func:`taurenmd.libs.libio.evaluate_to_slice` can receive. Defaults to ``None``, considers all frames. Returns ------- Numpy Array With the calculated RMSFs values, of shape (N,) where N are the frames sliced from ``frame_slice``. Raises ------ MDAnalysis Exceptions Any exceptions that could come from MDAnalysis RMSF computation. """ # noqa: E501 log.info(T('Calculating RMSFs')) frame_slice = libio.evaluate_to_slice(value=frame_slice) log.info(S('for trajectory slice: {}', frame_slice)) R = mdaRMSF( atom_group, start=frame_slice.start, stop=frame_slice.stop, step=frame_slice.step, verbose=False, ) R.run() return R.rmsf
def report(universe): """ Report information about the Universe. Example ------- >>> u = libmda.load_universe('topology.pdb', 'trajectory.xtc') >>> libmda.report(u) Parameters ---------- universe : MDAnalysis Universe `MDAnalysis universe <https://www.mdanalysis.org/docs/documentation_pages/core/universe.html?highlight=universe#core-object-universe-mdanalysis-core-universe>`_. Returns ------- None """ # noqa: E501 log.info(T('Reporting')) log.info(S('number of frames: {}', len(universe.trajectory))) log.info(S('number of atoms: {}', len(universe.atoms)))
def main(topology, trajectories, plane_selection, aunit='degrees', ref_frame=0, start=None, stop=None, step=None, export=False, plot=False, plotvars=None, **kwargs): """Execute main client logic.""" log.info(T('calculating angles')) topology = Path(topology) trajectories = [Path(t) for t in trajectories] u = libmda.load_universe(topology, *trajectories) frame_slice = libio.frame_slice( start=start, stop=stop, step=step, ) log.info(S('for slice {}', frame_slice)) log.info(T('calculating plane eq. for reference frame')) log.info(S('using frame: {}', ref_frame)) u.trajectory[ref_frame] reference_point_1 = u.select_atoms(plane_selection[0]).center_of_geometry() reference_point_2 = u.select_atoms(plane_selection[1]).center_of_geometry() reference_point_3 = u.select_atoms(plane_selection[2]).center_of_geometry() ra, rb, rc, rd = libcalc.calc_plane_eq( reference_point_1, reference_point_2, reference_point_3, ) log.info(S('the equation is {}x + {}y + {}z = {}', ra, rb, rc, rd)) log.info(T('Calculating angles')) angles = [] for _ts in u.trajectory[frame_slice]: point1 = u.select_atoms(plane_selection[0]).center_of_geometry() point2 = u.select_atoms(plane_selection[1]).center_of_geometry() point3 = u.select_atoms(plane_selection[2]).center_of_geometry() a, b, c, d = libcalc.calc_plane_eq(point1, point2, point3) angles.append( libcalc.calc_planes_angle( ra, rb, rc, a, b, c, aunit=aunit, )) log.info(S('calculated a total of {} angles.', len(angles))) if export: libio.export_data_to_file( list(range(len(u.trajectory))[frame_slice]), angles, fname=export, header=('# Angular oscillation between a plane representatives\n' '# topology: {}\n' '# trajectories: {}\n' '# selections: {}\n' '# frame,angle({})\n').format( topology, ', '.join(t.resolve().str() for t in trajectories), plane_selection, aunit, ), ) if plot: plotvars = plotvars or dict() plotvars.setdefault( 'labels', 'plane: {}'.format(' and '.join(plane_selection)), ) log.info(T('plot params:')) for k, v in plotvars.items(): log.info(S('{} = {!r}', k, v)) libplot.param( list(range(len(u.trajectory))[frame_slice]), angles, **plotvars, ) log.info(S('done')) return
def main(topology, trajectories, insort=False, **kwargs): """Execute main client logic.""" log.info(T('reporting')) libmda.load_universe(topology, *trajectories, insort=insort) log.info(S('done')) return
def main(topology, trajectories, start=None, stop=None, step=None, selections=None, export=False, plot=False, plotvars=None, **kwargs): """Execute client main logic.""" log.info(T('starting RMSFs calculation')) topology = Path(topology) trajectories = [Path(t) for t in trajectories] u = libmda.load_universe(topology, *trajectories) frame_slice = libio.frame_slice( start=start, stop=stop, step=step, ) if selections is None: selections = ['all'] if not isinstance(selections, list) or len(selections) == 0: raise TypeError('selections must be LIST with at least one element') log.info(T('calculating')) for sel in selections: labels = [] rmsfs = [] log.info(S('for selection: {}', sel)) atom_group = u.select_atoms(sel) labels = libmda.draw_atom_label_from_atom_group(atom_group) rmsfs = libcalc.mda_rmsf( atom_group, frame_slice=frame_slice, ) if export: libio.export_data_to_file( labels, rmsfs, fname=export, header=("# Date: {}\n" "# Topology: {}\n" "# Trajectories {}\n" "# Atom,RMSF\n").format( datetime.now().strftime("%d/%m/%Y, %H:%M:%S"), Path(topology).resolve(), ', '.join(f.resolve().str() for f in trajectories), ), ) if plot: plotvars = plotvars or dict() plotvars.setdefault('series_labels', selections) log.info(T('plot params:')) for k, v in plotvars.items(): log.info(S('{} = {!r}', k, v)) libplot.label_dots( labels, rmsfs, **plotvars, ) return
def main( topology, trajectories, insort=False, start=None, stop=None, step=None, ref_frame=0, selections=None, export=False, plot=False, plotvars=None, **kwargs ): """Execute main client logic.""" log.info(T('starting')) u = libmda.load_universe(topology, *trajectories, insort=insort) frame_slice = libio.frame_slice( start=start, stop=stop, step=step, ) if selections is None: selections = ['all'] rmsds = [] for selection in selections: rmsds.append( libcalc.mda_rmsd( u, frame_slice=frame_slice, selection=selection, ref_frame=ref_frame, ) ) if export: libio.export_data_to_file( list(range(len(u.trajectory))[frame_slice]), *rmsds, fname=export, delimiter=',', header=( "# Date: {}\n'" "# Topology: {}\n" "# Trajectories : {}\n" "# ref frame: {}\n" "# frame number,{}\n" ).format( datetime.now(), Path(topology).resolve(), ', '.join(f.resolve().str() for f in trajectories), ref_frame, ','.join(selections), ), ) if plot: plotvars = plotvars or dict() plotvars.setdefault('labels', selections) log.info(T('plot params:')) for k, v in plotvars.items(): log.info(S('{} = {!r}', k, v)) libplot.param( list(range(len(u.trajectory))[frame_slice]), rmsds, **plotvars, ) return
def main( topology, trajectories, insort=None, start=None, stop=None, step=None, selection='all', traj_output='traj_out.dcd', top_output=None, unwrap=False, unwrap_reference=None, unwrap_compound='fragments', align=False, **kwargs, ): """Execute main client logic.""" log.info(T('editing trajectory')) topology = Path(topology) trajectories = [Path(t) for t in trajectories] if insort: trajectories = libio.sort_numbered_input(*trajectories) u = libmda.load_universe(topology, *trajectories) if unwrap: log.info(T('unwrapping')) log.info(S('set to: {}', unwrap)) log.info(S('reference: {}', unwrap_reference)) log.info(S('compound: {}', unwrap_compound)) if align: log.info(T('Alignment')) log.info(S('trajectory selection will be aligned to subselection:')) log.info(S('- {}', align, indent=2)) align_reference = mda.Universe(Path(topology).str()) log.info(T('transformation')) sliceObj = libio.frame_slice(start, stop, step) log.info(S('selecting: {}', selection)) atom_selection = u.select_atoms(selection) log.info(S('with {} atoms', atom_selection.n_atoms, indent=2)) log.info(T('saving trajectory')) traj_output = Path(traj_output) log.info(S('destination: {}', traj_output.resolve().str())) with mda.Writer(traj_output.str(), atom_selection.n_atoms) as W: for i, _ts in zip( range(len(u.trajectory))[sliceObj], u.trajectory[sliceObj], ): log.info(S('working on frame: {}', i)) if unwrap: log.debug(S('unwrapping', indent=2)) atom_selection.unwrap( reference=unwrap_reference, compound=unwrap_compound, ) if align: try: libmda.mdaalignto(u, align_reference, selection=align) except ZeroDivisionError: _controlled_exit() W.write(atom_selection) log.info(S('trajectory saved')) if top_output: log.info(T('saving topology')) fout = libio.parse_top_output(top_output, traj_output) log.info(S('saving frame 0 to: {}', fout.resolve())) with mda.Writer(fout.str(), atom_selection.n_atoms) as W: for _ts in u.trajectory[sliceObj][0:1]: if unwrap: log.debug(S('unwrapping for topology', indent=2)) atom_selection.unwrap( reference=unwrap_reference, compound=unwrap_compound, ) W.write(atom_selection) log.info(S('Done')) return
def main(topology, trajectories, insort=False, sel1='all', sel2='all', start=None, stop=None, step=None, export=False, plot=False, plotvars=None, **kwargs): """Execute main client logic.""" log.info(T('measuring distances')) topology = Path(topology) trajectories = [Path(t) for t in trajectories] u = libmda.load_universe(topology, *trajectories, insort=insort) frame_slice = libio.frame_slice( start=start, stop=stop, step=step, ) log.info(T('defining atom seletions')) log.info(S('atom selection #1: {}', sel1)) log.info(S('atom selection #2: {}', sel2)) atom_sel1 = u.select_atoms(sel1) atom_sel2 = u.select_atoms(sel2) distances = np.ones(len(u.trajectory[frame_slice]), dtype=np.float32) log.info(T('Calculating distances')) # https://www.mdanalysis.org/MDAnalysisTutorial/atomgroups.html # https://www.mdanalysis.org/docs/documentation_pages/core/groups.html#MDAnalysis.core.groups.AtomGroup.center_of_geometry with libcli.ProgressBar(distances.size, suffix='frames') as pb: for i, _ts in enumerate(u.trajectory[frame_slice]): distances[i] = np.linalg.norm( np.subtract( atom_sel1.center_of_geometry(), atom_sel2.center_of_geometry(), )) pb.increment() log.info(S('calculated a total of {} distances.', len(distances))) if export: libio.export_data_to_file( list(range(len(u.trajectory))[frame_slice]), distances, fname=export, header=('# Distances between two selections centers of geomemtry\n' '# topology: {}\n' '# trajectories: {}\n' '# selection #1: {}\n' '# selection #2: {}\n' '# frame,distance\n').format( topology, ', '.join(t.resolve().str() for t in trajectories), sel1, sel2, ), ) if plot: plotvars = plotvars or dict() plotvars.setdefault('labels', '{} dist {}'.format(sel1, sel2)) log.info(T('plot params:')) for k, v in plotvars.items(): log.info(S('{} = {!r}', k, v)) libplot.param( list(range(len(u.trajectory))[frame_slice]), distances, **plotvars, ) log.info(S('done')) return
def mda_rmsd( universe, frame_slice=None, selection='all', ref_frame=0, ): """ Calculate RMSDs observed for a selection. Uses `MDAnalysis RMSD <https://www.mdanalysis.org/docs/documentation_pages/analysis/rms.html?highlight=rmsd#MDAnalysis.analysis.rms.RMSD>`_. Example ------- * Calculate RMSDs observed for the whole system along the whole trajectory. >>> mda_rmsd(universe) * Calculate the RMSDs observed for selection `segid A` for every 10 frames. >>> mda_rmsd(universe, slice(0, None, 10), selection='segid A') Parameters ---------- MDAnalysis Universe The MDAnalysis `universe <https://www.mdanalysis.org/docs/documentation_pages/core/universe.html?highlight=universe#core-object-universe-mdanalysis-core-universe>`_. frame_slice : any, optional The frames in the trajectory to consider. If ``None`` considers all frames. Accepts any argument that :py:func:`taurenmd.libs.libio.evaluate_to_slice` can receive. Defaults to ``None``. selection : str, optional The selection upon which calculate the RMSDs. Defaults to ``'all'``. ref_frames : int, optional The reference frame against which calculate the RMSDs. Defaults to ``0``. Returns ------- Numpy Array The array containing the calculated RMSDs of shape (N,), where N is the number of frames. Raises ------ ValueError If ``frame_slice`` is not ``None`` or ``slice`` object. MDAnalysis Exceptions Any exceptions that could come from MDAnalysis RMSF computation. """ # noqa: E501 log.info(T('Calculating RMSDs')) frame_slice = libio.evaluate_to_slice(value=frame_slice) log.info(S('for selection: {}', selection)) log.info(S('for trajectory slice: {}', frame_slice)) R = mdaRMSD( universe, universe, select=selection, groupselection=None, ref_frame=ref_frame, verbose=False, ) R.run(verbose=False) # rmsds[:, ii] = R.rmsd[:, 2][self._fslicer] return R.rmsd[frame_slice, 2]
def main( topology, trajectories, plane_selection, aunit='degrees', start=None, stop=None, step=None, export=False, **kwargs, ): """Execute main client logic.""" log.info(T('starting')) topology = Path(topology) trajectories = [Path(t) for t in trajectories] u = libmda.load_universe(topology, *trajectories) log.info(T('transformation')) fSlice = libio.frame_slice(start=start, stop=stop, step=step) origin_selection = ' or '.join(plane_selection) pABC_atomG = u.select_atoms(origin_selection) ABC_selections = plane_selection # p stands for point pA_atomG = u.select_atoms(ABC_selections[0]) pB_atomG = u.select_atoms(ABC_selections[1]) pC_atomG = u.select_atoms(ABC_selections[2]) u.trajectory[0] # defining the center of reference pABC_cog = pABC_atomG.center_of_geometry() log.info(T('Original Center of Geometry')) log.info(S('for frame: 0')) log.info(S('for selection: {}', origin_selection)) log.info(S('pABC_cog: {}', pABC_cog)) log.info(T('Transfering')) log.info(S('all coordinates of reference frame to the origin 0, 0, 0')) pABC_atomG.positions = pABC_atomG.positions - pABC_cog log.info(S('COG in origin: {}', pABC_atomG.center_of_geometry())) log.info(T('defining the reference axes')) pA_cog = pA_atomG.center_of_geometry() pB_cog = pB_atomG.center_of_geometry() pC_cog = pC_atomG.center_of_geometry() log.info(S('plane points definition:')) log.info(S('pA: {}', pA_cog)) log.info(S('pB: {}', pB_cog)) log.info(S('pC: {}', pC_cog)) log.info(T('defining the normal vector to reference plane')) ref_plane_normal = libcalc.calc_plane_normal(pA_cog, pB_cog, pC_cog) log.info(S('plane normal: {}', ref_plane_normal)) log.info(S('done')) log.info(T('defining the cross product vector')) ref_plane_cross = np.cross(pA_cog, ref_plane_normal) log.info(S('np cross: {}', ref_plane_cross)) roll_angles = [] pitch_angles = [] yaw_angles = [] for i, _ts in enumerate(u.trajectory[fSlice]): print(f'.. working for frame :{i}') pABC_cog_ts = pABC_atomG.center_of_geometry() pABC_atomG.positions = pABC_atomG.positions - pABC_cog_ts pA_cog_ts = pA_atomG.center_of_geometry() pB_cog_ts = pB_atomG.center_of_geometry() pC_cog_ts = pC_atomG.center_of_geometry() ts_plane_normal = libcalc.calc_plane_normal( pA_cog_ts, pB_cog_ts, pC_cog_ts, ) ts_plane_cross = np.cross(pA_cog_ts, ts_plane_normal) # Calculating Quaternion Rotations roll_Qs_tuples = libcalc.generate_quaternion_rotations( ref_plane_normal, pA_cog_ts, ) pitch_Qs_tuples = libcalc.generate_quaternion_rotations( ref_plane_cross, ts_plane_normal, ) yaw_Qs_tuples = libcalc.generate_quaternion_rotations( pA_cog, ts_plane_cross, ) roll_minimum = libcalc.sort_by_minimum_Qdistances( roll_Qs_tuples, pA_cog, )[0][0] pitch_minimum = libcalc.sort_by_minimum_Qdistances( pitch_Qs_tuples, ref_plane_normal, )[0][0] yaw_minimum = libcalc.sort_by_minimum_Qdistances( yaw_Qs_tuples, ref_plane_cross, )[0][0] if aunit == 'degrees': roll_angles.append(round(roll_minimum.degrees, 3)) pitch_angles.append(round(pitch_minimum.degrees, 3)) yaw_angles.append(round(yaw_minimum.degrees, 3)) else: roll_angles.append(round(roll_minimum.radians, 3)) pitch_angles.append(round(pitch_minimum.radians, 3)) yaw_angles.append(round(yaw_minimum.radians, 3)) if export: file_names = [] for _fname in ['roll', 'pitch', 'yaw']: file_names.append( libio.add_prefix_to_path( export, f"{_fname}_angles_", ) ) log.info(T('Saving data to files')) for data, fname in zip( [roll_angles, pitch_angles, yaw_angles], file_names, ): log.info(S('saving {}', fname)) libio.export_data_to_file( list(range(len(u.trajectory))[fSlice]), data, fname=fname, header=( '# Topology: {}\n' '# Trajectories: {}\n' '# Plane Selection: {}\n' '# frame,ange{}\n' ).format( topology, ', '.join(t.resolve().str() for t in trajectories), origin_selection, aunit, ), ) log.info(S('done')) return