Ejemplo n.º 1
0
def mdaalignto(universe, reference, selection='all'):
    """
    Align universe to reference.

    Uses `MDAnalysis.analysis.align.alignto <https://www.mdanalysis.org/docs/documentation_pages/analysis/align.html?highlight=alignto#MDAnalysis.analysis.align.alignto>`_.

    Parameters
    ----------
    universe, reference, selection
        Same as in ``MDAnalysis.analysis.align.alignto`` function.

    Raises
    ------
    ZeroDivisionError
        If selection gives empty selection.
    """  # noqa: E501
    try:
        mdaalign.alignto(universe, reference, select=selection)
    except (ValueError, ZeroDivisionError) as err:
        log.debug(err, exc_info=True)
        errmsg = (
            f'Could not perform alignment due to {err}, '
            'most likely the alignment selection does not match '
            'any possible selection in the system. You selection : '
            f'\'{selection}\'.'
            )
        log.info(errmsg)
        raise err
Ejemplo n.º 2
0
def sort_numbered_input(*inputs):
    """
    Sort input paths to tail number.

    If possible, sort criteria is provided by :py:func:`get_number`.
    If paths do not have a numbered tag, sort paths alphabetically.

    Parameters
    ----------
    *inputs : str of Paths
        Paths to files.

    Returns
    -------
    list
        The sorted pathlist.
    """
    try:
        return sorted(inputs, key=get_number)
    except TypeError as err:
        log.exception(err)
        emsg = "Mind the packing *argument, input should be strings or Paths"
        raise TypeError(emsg)
    except IndexError as err:
        log.exception(err)
        log.info(S('sorting done by string type'))
        return sorted(inputs)
Ejemplo n.º 3
0
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
Ejemplo n.º 4
0
def report_input(topology, trajectories):
    """Report on topology and trajectory file paths used as input."""
    pp = PrettyPrinter()
    trajs = pp.pformat(trajectories)
    log.info(S('loading trajectory(ies): {}', trajs))
    log.info(S('with topology: {}', topology))
    return
Ejemplo n.º 5
0
def frame_slice(start=None, stop=None, step=None,):
    """
    Create a slice object from parameters.

    Logs the created slice object.

    Returns
    -------
    Slice Object
        The slice object created from slice(start, stop, step)
    """
    log.info(S('slicing: {}:{}:{}', start, stop, step))
    return slice(start, stop, step)
Ejemplo n.º 6
0
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
Ejemplo n.º 7
0
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
Ejemplo n.º 8
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
Ejemplo n.º 9
0
def imagemol_protocol2(traj):
    """Attempt to image molecules frame by frame."""
    reimaged = []
    for frame in range(len(traj)):
        log.info(S('reimaging frame: {}', frame))

        mols = traj[frame].top.find_molecules()

        reimaged.append(traj[frame].image_molecules(
            inplace=False,
            anchor_molecules=mols[:1],
            other_molecules=mols[1:],
        ))

    log.info(S('concatenating traj frames'))
    # http://mdtraj.org/1.9.3/api/generated/mdtraj.join.html#mdtraj.join
    reimaged_traj = reimaged[0].join(reimaged[1:])

    return reimaged_traj
Ejemplo n.º 10
0
def main(
        topology,
        trajectories,
        insort=False,
        start=None,
        stop=None,
        step=None,
        flist=None,
        prefix='frame_',
        ext='pdb',
        selection='all',
        **kwargs):
    """Execute main client logic."""
    log.info('Starting...')

    u = libmda.load_universe(topology, *trajectories, insort=insort)

    frames_to_extract = libio.frame_list(
        len(u.trajectory),
        start=start,
        stop=stop,
        step=step,
        flist=flist,
        )

    log.info(S('extracting {} frames', len(frames_to_extract)))

    zeros = len(str(len(u.trajectory)))
    ext = ext.lstrip('.').strip()

    atom_group = u.select_atoms(selection)

    with libcli.ProgressBar(len(frames_to_extract), suffix='frames') as pb:
        for frame in frames_to_extract:
            file_name = '{}{}.{}'.format(
                prefix,
                str(frame).zfill(zeros),
                ext,
                )

            atom_group.write(
                filename=Path(file_name),
                frames=[frame],
                )

        log.info(S('writen frame {}, to {}', frame, file_name))
        pb.increment()

    return
Ejemplo n.º 11
0
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)))
Ejemplo n.º 12
0
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
Ejemplo n.º 13
0
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]
Ejemplo n.º 14
0
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
Ejemplo n.º 15
0
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
Ejemplo n.º 16
0
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'))
Ejemplo n.º 17
0
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
Ejemplo n.º 18
0
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
Ejemplo n.º 19
0
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
Ejemplo n.º 20
0
def report_input(topology, trajectory):
    """Report on topology and trajectory file paths used as input."""
    log.info(S('loading trajectory: {}', trajectory))
    log.info(S('with topology: {}', topology))
    return
Ejemplo n.º 21
0
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