Esempio n. 1
0
 def _HBA(self,
          ts,
          conn,
          universe,
          selAtom1,
          selAtom2,
          verbose=None,
          quiet=None):
     """
     Main function for calculate C_i and C_c in parallel.
     """
     verbose = _set_verbose(verbose, quiet, default=False)
     finalGetResidue1 = selAtom1
     finalGetResidue2 = selAtom2
     frame = ts.frame
     h = MDAnalysis.analysis.hbonds.HydrogenBondAnalysis(universe,
                                                         finalGetResidue1,
                                                         finalGetResidue2,
                                                         distance=3.5,
                                                         angle=120.0,
                                                         start=frame - 1,
                                                         stop=frame)
     while True:
         try:
             h.run(verbose=verbose)
             break
         except:
             print("error")
             print("trying again")
             sys.stdout.flush()
     sys.stdout.flush()
     conn.send(h.timeseries[0])
     conn.close()
Esempio n. 2
0
def test__set_verbose():
    # Everything agrees verbose should be True
    assert_equal(_set_verbose(verbose=True, quiet=False, default=True), True)
    # Everything agrees verbose should be False
    assert_equal(_set_verbose(verbose=False, quiet=True, default=False), False)
    # Make sure the default does not overwrite the user choice
    assert_equal(_set_verbose(verbose=True, quiet=False, default=False), True)
    assert_equal(_set_verbose(verbose=False, quiet=True, default=True), False)
    # Quiet is not provided
    assert_equal(_set_verbose(verbose=True, quiet=None, default=False), True)
    assert_equal(_set_verbose(verbose=False, quiet=None, default=False), False)
    # Verbose is not provided
    assert_equal(_set_verbose(verbose=None, quiet=True, default=False), False)
    assert_equal(_set_verbose(verbose=None, quiet=False, default=False), True)
    # Nothing is provided
    assert_equal(_set_verbose(verbose=None, quiet=None, default=True), True)
    assert_equal(_set_verbose(verbose=None, quiet=None, default=False), False)
    # quiet and verbose contradict each other
    assert_raises(ValueError, _set_verbose, verbose=True, quiet=True)
    assert_raises(ValueError, _set_verbose, verbose=False, quiet=False)
Esempio n. 3
0
 def run(self, start=None, stop=None, step=None, progout=None,
         verbose=None, quiet=None):
     if any([el is not None for el in (start, stop, step, progout, quiet)]):
         warnings.warn("run arguments are deprecated. Please pass them at "
                       "class construction. These options will be removed in 0.17.0",
                       category=DeprecationWarning)
         verbose = _set_verbose(verbose, quiet, default=False)
         # regenerate class with correct args
         super(RMSF, self).__init__(self.atomgroup.universe.trajectory,
                                    start=start, stop=stop, step=step,
                                    verbose=verbose)
     super(RMSF, self).run()
Esempio n. 4
0
    def run(self, start=None, stop=None, step=None, progout=None,
            verbose=None, quiet=None):
        """Perform the analysis."""

        if any([el is not None for el in (start, stop, step, progout, quiet)]):
            warnings.warn("run arguments are deprecated. Please pass them at "
                          "class construction. These options will be removed in 0.17.0",
                          category=DeprecationWarning)
            verbose = _set_verbose(verbose, quiet, default=False)
            # regenerate class with correct args
            super(RMSF, self).__init__(self.atomgroup.universe.trajectory,
                                       start=start, stop=stop, step=step,
                                       verbose=verbose)
        return super(RMSF, self).run()
Esempio n. 5
0
def test__set_verbose():
    # Everything agrees verbose should be True
    assert_equal(_set_verbose(verbose=True, quiet=False, default=True), True)
    # Everything agrees verbose should be False
    assert_equal(_set_verbose(verbose=False, quiet=True, default=False), False)
    # Make sure the default does not overwrite the user choice
    assert_equal(_set_verbose(verbose=True, quiet=False, default=False), True)
    assert_equal(_set_verbose(verbose=False, quiet=True, default=True), False)
    # Quiet is not provided
    assert_equal(_set_verbose(verbose=True, quiet=None, default=False), True)
    assert_equal(_set_verbose(verbose=False, quiet=None, default=False), False)
    # Verbose is not provided
    assert_equal(_set_verbose(verbose=None, quiet=True, default=False), False)
    assert_equal(_set_verbose(verbose=None, quiet=False, default=False), True)
    # Nothing is provided
    assert_equal(_set_verbose(verbose=None, quiet=None, default=True), True)
    assert_equal(_set_verbose(verbose=None, quiet=None, default=False), False)
    # quiet and verbose contradict each other
    assert_raises(ValueError, _set_verbose, verbose=True, quiet=True)
    assert_raises(ValueError, _set_verbose, verbose=False, quiet=False)
    # A deprecation warning is issued when quiet is set
    assert_warns(DeprecationWarning, _set_verbose, verbose=None, quiet=True)
    assert_warns(DeprecationWarning, _set_verbose, verbose=False, quiet=True)
Esempio n. 6
0
 def __init__(self, trajectory, start=None,
              stop=None, step=None, verbose=None, quiet=None):
     """
     Parameters
     ----------
     trajectory : mda.Reader
         A trajectory Reader
     start : int, optional
         start frame of analysis
     stop : int, optional
         stop frame of analysis
     step : int, optional
         number of frames to skip between each analysed frame
     verbose : bool, optional
         Turn on verbosity
     """
     self._verbose = _set_verbose(verbose, quiet, default=False)
     self._quiet = not self._verbose
     self._setup_frames(trajectory, start, stop, step)
Esempio n. 7
0
 def _HBA(self, ts, conn, universe, selAtom1, selAtom2,
          verbose=None, quiet=None):
     """
     Main function for calculate C_i and C_c in parallel.
     """
     verbose = _set_verbose(verbose, quiet, default=False)
     finalGetResidue1 = selAtom1
     finalGetResidue2 = selAtom2
     frame = ts.frame
     h = MDAnalysis.analysis.hbonds.HydrogenBondAnalysis(universe, finalGetResidue1,
                                                         finalGetResidue2, distance=3.5, angle=120.0,
                                                         start=frame-1, stop=frame)
     while True:
         try:
             h.run(verbose=verbose)
             break
         except:
             print("error")
             print("trying again")
             sys.stdout.flush()
     sys.stdout.flush()
     conn.send(h.timeseries[0])
     conn.close()
Esempio n. 8
0
 def __init__(self,
              trajectory,
              start=None,
              stop=None,
              step=None,
              verbose=None,
              quiet=None):
     """
     Parameters
     ----------
     trajectory : mda.Reader
         A trajectory Reader
     start : int, optional
         start frame of analysis
     stop : int, optional
         stop frame of analysis
     step : int, optional
         number of frames to skip between each analysed frame
     verbose : bool, optional
         Turn on verbosity
     """
     self._verbose = _set_verbose(verbose, quiet, default=False)
     self._quiet = not self._verbose
     self._setup_frames(trajectory, start, stop, step)
Esempio n. 9
0
 def test__set_verbose_invalid_args(self, verbose):
     # can't combine the two context managers
     with pytest.deprecated_call():
         with pytest.raises(ValueError):
             # setting quiet==verbose is a contradiction
             _set_verbose(verbose=verbose, quiet=verbose, default=None)
Esempio n. 10
0
 def test__set_verbose(self, verbose, quiet, default, result):
     assert _set_verbose(verbose=verbose, quiet=quiet,
                         default=default) == result
Esempio n. 11
0
 def test__set_verbose_deprecated(self, verbose, quiet, default, result):
     with pytest.deprecated_call():
         assert _set_verbose(verbose=verbose, quiet=quiet,
                             default=default) == result
Esempio n. 12
0
    def run(self, **kwargs):
        """Analyze trajectory and produce timeseries.

        Stores the water bridge data per frame as
        :attr:`WaterBridgeAnalysis.timeseries` (see there for output
        format).

        Parameters
        ----------
        verbose : bool (optional)
             toggle progress meter output
             :class:`~MDAnalysis.lib.log.ProgressMeter` [``True``]
        debug : bool (optional)
             enable detailed logging of debugging information; this can create
             *very big* log files so it is disabled (``False``) by default;
             setting `debug` toggles the debug status for
             :class:`WaterBridgeAnalysis`, namely the value of
             :attr:`WaterBridgeAnalysis.debug`.

        See Also
        --------
        :meth:`WaterBridgeAnalysis.generate_table` :
               processing the data into a different format.
        """
        logger.info("WBridge analysis: starting")
        logger.debug("WBridge analysis: donors    %r", self.donors)
        logger.debug("WBridge analysis: acceptors %r", self.acceptors)
        logger.debug("WBridge analysis: water bridge %r", self.water_selection)

        debug = kwargs.pop('debug', None)
        if debug is not None and debug != self.debug:
            self.debug = debug
            logger.debug("Toggling debug to %r", self.debug)
        if not self.debug:
            logger.debug(
                "WBridge analysis: For full step-by-step debugging output use debug=True"
            )

        self._timeseries = []
        self.timesteps = []
        self._water_network = []

        logger.info("checking trajectory...")  # n_frames can take a while!
        try:
            frames = np.arange(self.u.trajectory.n_frames)[self.traj_slice]
        except:
            logger.error(
                "Problem reading trajectory or trajectory slice incompatible.")
            logger.exception()
            raise
        verbose = _set_verbose(verbose=kwargs.get('verbose', None),
                               quiet=kwargs.get('quiet', None),
                               default=True)
        pm = ProgressMeter(
            len(frames),
            format=
            "WBridge frame {current_step:5d}: {step:5d}/{numsteps} [{percentage:5.1f}%]\r",
            verbose=verbose)

        logger.info(
            "Starting analysis (frame index start=%d stop=%d, step=%d)",
            (self.traj_slice.start or 0),
            (self.traj_slice.stop or self.u.trajectory.n_frames),
            self.traj_slice.step or 1)

        for progress, ts in enumerate(self.u.trajectory[self.traj_slice]):
            # all bonds for this timestep

            # dict of tuples (atom.index, atom.index) for quick check if
            # we already have the bond (to avoid duplicates)

            frame = ts.frame
            timestep = ts.time
            self.timesteps.append(timestep)
            pm.echo(progress, current_step=frame)
            self.logger_debug(
                "Analyzing frame %(frame)d, timestep %(timestep)f ps", vars())
            if self.update_selection1:
                self._update_selection_1()
            if self.update_selection2:
                self._update_selection_2()
            if self.update_water_selection:
                self._update_water_selection()

            s1_frame_results_dict = defaultdict(list)
            if (self.selection1_type in ('donor', 'both')
                    and self._water_acceptors):

                self.logger_debug("Selection 1 Donors <-> Water Acceptors")
                ns_acceptors = AtomNeighborSearch(self._water_acceptors)
                for i, donor_h_set in self._s1_donors_h.items():
                    d = self._s1_donors[i]
                    for h in donor_h_set:
                        res = ns_acceptors.search(h, self.distance)
                        for a in res:
                            donor_atom = h if self.distance_type != 'heavy' else d
                            dist = self.calc_eucl_distance(donor_atom, a)
                            if dist <= self.distance:
                                angle = self.calc_angle(d, h, a)
                                if angle >= self.angle:
                                    self.logger_debug(
                                        "S1-D: {0!s} <-> W-A: {1!s} {2:f} A, {3:f} DEG"\
                                        .format(h.index, a.index, dist, angle))
                                    s1_frame_results_dict[(a.resname,
                                                           a.resid)].append(
                                                               (h.index,
                                                                a.index,
                                                                (h.resname,
                                                                 h.resid,
                                                                 h.name),
                                                                (a.resname,
                                                                 a.resid,
                                                                 a.name), dist,
                                                                angle))

            if (self.selection1_type in ('acceptor', 'both')
                    and self._s1_acceptors):

                self.logger_debug("Selection 1 Acceptors <-> Water Donors")
                ns_acceptors = AtomNeighborSearch(self._s1_acceptors)
                for i, donor_h_set in self._water_donors_h.items():
                    d = self._water_donors[i]
                    for h in donor_h_set:
                        res = ns_acceptors.search(h, self.distance)
                        for a in res:
                            donor_atom = h if self.distance_type != 'heavy' else d
                            dist = self.calc_eucl_distance(donor_atom, a)
                            if dist <= self.distance:
                                angle = self.calc_angle(d, h, a)
                                if angle >= self.angle:
                                    self.logger_debug(
                                        "S1-A: {0!s} <-> W-D: {1!s} {2:f} A, {3:f} DEG"\
                                        .format(a.index, h.index, dist, angle))
                                    s1_frame_results_dict[(h.resname,
                                                           h.resid)].append(
                                                               (h.index,
                                                                a.index,
                                                                (h.resname,
                                                                 h.resid,
                                                                 h.name),
                                                                (a.resname,
                                                                 a.resid,
                                                                 a.name), dist,
                                                                angle))

            # Narrow down the water selection
            selection_resn_id = list(s1_frame_results_dict.keys())
            if not selection_resn_id:
                self._timeseries.append([])
                continue
            selection_resn_id = [
                '(resname {} and resid {})'.format(resname, resid)
                for resname, resid in selection_resn_id
            ]
            water_bridges = self._water.select_atoms(
                ' or '.join(selection_resn_id))
            self.logger_debug(
                "Size of water bridge selection: {0} atoms".format(
                    len(water_bridges)))
            if not water_bridges:
                logger.warning(
                    "No water forming hydrogen bonding with selection 1.")
            water_bridges_donors = water_bridges.select_atoms(
                'name {0}'.format(' '.join(self.donors)))
            water_bridges_donors_h = {}
            for i, d in enumerate(water_bridges_donors):
                tmp = self._get_bonded_hydrogens(d)
                if tmp:
                    water_bridges_donors_h[i] = tmp
            self.logger_debug("water bridge donors: {0}".format(
                len(water_bridges_donors)))
            self.logger_debug("water bridge donor hydrogens: {0}".format(
                len(water_bridges_donors_h)))
            water_bridges_acceptors = water_bridges.select_atoms(
                'name {0}'.format(' '.join(self.acceptors)))
            self.logger_debug("water bridge: {0}".format(
                len(water_bridges_acceptors)))

            # Finding the hydrogen bonds between water bridge and selection 2
            s2_frame_results_dict = defaultdict(list)
            if self._s2_acceptors:
                self.logger_debug(
                    "Water bridge Donors <-> Selection 2 Acceptors")
                ns_acceptors = AtomNeighborSearch(self._s2_acceptors)
                for i, donor_h_set in water_bridges_donors_h.items():
                    d = water_bridges_donors[i]
                    for h in donor_h_set:
                        res = ns_acceptors.search(h, self.distance)
                        for a in res:
                            donor_atom = h if self.distance_type != 'heavy' else d
                            dist = self.calc_eucl_distance(donor_atom, a)
                            if dist <= self.distance:
                                angle = self.calc_angle(d, h, a)
                                if angle >= self.angle:
                                    self.logger_debug(
                                        "WB-D: {0!s} <-> S2-A: {1!s} {2:f} A, {3:f} DEG"\
                                        .format(h.index, a.index, dist, angle))
                                    s2_frame_results_dict[(h.resname,
                                                           h.resid)].append(
                                                               (h.index,
                                                                a.index,
                                                                (h.resname,
                                                                 h.resid,
                                                                 h.name),
                                                                (a.resname,
                                                                 a.resid,
                                                                 a.name), dist,
                                                                angle))

            if water_bridges_acceptors:
                self.logger_debug(
                    "Selection 2 Donors <-> Selection 2 Acceptors")
                ns_acceptors = AtomNeighborSearch(water_bridges_acceptors)
                for i, donor_h_set in self._s2_donors_h.items():
                    d = self._s2_donors[i]
                    for h in donor_h_set:
                        res = ns_acceptors.search(h, self.distance)
                        for a in res:
                            donor_atom = h if self.distance_type != 'heavy' else d
                            dist = self.calc_eucl_distance(donor_atom, a)
                            if dist <= self.distance:
                                angle = self.calc_angle(d, h, a)
                                if angle >= self.angle:
                                    self.logger_debug(
                                        "WB-A: {0!s} <-> S2-D: {1!s} {2:f} A, {3:f} DEG"\
                                        .format(a.index, h.index, dist, angle))
                                    s2_frame_results_dict[(a.resname,
                                                           a.resid)].append(
                                                               (h.index,
                                                                a.index,
                                                                (h.resname,
                                                                 h.resid,
                                                                 h.name),
                                                                (a.resname,
                                                                 a.resid,
                                                                 a.name), dist,
                                                                angle))

            # Generate the water network
            water_network = {}
            for key in s2_frame_results_dict:
                s1_frame_results = set(s1_frame_results_dict[key])
                s2_frame_results = set(s2_frame_results_dict[key])
                if len(s1_frame_results.union(s2_frame_results)) > 1:
                    # Thus if selection 1 and selection 2 are the same and both
                    # only form a single hydrogen bond with a water, this entry
                    # won't be included.
                    water_network[key] = [
                        s1_frame_results,
                        s2_frame_results.difference(s1_frame_results)
                    ]
            # Generate frame_results
            frame_results = []
            for s1_frame_results, s2_frame_results in water_network.values():
                frame_results.extend(list(s1_frame_results))
                frame_results.extend(list(s2_frame_results))

            self._timeseries.append(frame_results)
            self._water_network.append(water_network)

        logger.info("WBridge analysis: complete; timeseries  %s.timeseries",
                    self.__class__.__name__)
Esempio n. 13
0
def helanal_trajectory(universe, selection="name CA",
                       begin=None, finish=None,
                       matrix_filename="bending_matrix.dat",
                       origin_pdbfile="origin.pdb",
                       summary_filename="summary.txt",
                       screw_filename="screw.xvg",
                       tilt_filename="local_tilt.xvg",
                       fitted_tilt_filename="fit_tilt.xvg",
                       bend_filename="local_bend.xvg",
                       twist_filename="unit_twist.xvg",
                       prefix="helanal_", ref_axis=None,
                       verbose=None, quiet=None):
    """Perform HELANAL helix analysis on all frames in `universe`.

    Parameters
    ----------
    universe : Universe
    selection : str (optional)
        selection string that selects Calpha atoms [``"name CA"``]
    begin : float (optional)
        start analysing for time (ps) >= *begin*; ``None`` starts from the
        beginning [``None``]
    finish : float (optional)
        stop analysis for time (ps) =< *finish*; ``None`` goes to the
        end of the trajectory [``None``]
    matrix_filename : str (optional)
        Output file- bending matrix [``"bending_matrix.dat"``]
    origin_pdbfile : str (optional)
        Output file- origin pdb file [``"origin.pdb"``]
    summary_filename : str (optional)
        Output file- all of the basic data [``"summary.txt"``]
    screw_filename : str (optional)
        Output file- local tilts of individual residues from 2 to n-1
        [``"screw.xvg"``]
    tilt_filename : str (optional)
        Output file- tilt of line of best fit applied to origin axes
        [``"local_tilt.xvg"``]
    bend_filename : str (optional)
        Output file- local bend angles between successive local helix axes
        [``"local_bend.xvg"``]
    twist_filename : str (optional)
        Output file- local unit twist between successive helix turns
        [``"unit_twist.xvg"``]
    prefix : str (optional)
        Prefix to add to all output file names; set to ``None`` to disable
        [``"helanal__"``]
    ref_axis : array_like (optional)
        Calculate tilt angle relative to the axis; if ``None`` then ``[0,0,1]``
        is chosen [``None``]
    verbose : bool (optional)
        Toggle diagnostic outputs. [``True``]

    Raises
    ------
    FinishTimeException
          If the specified finish time precedes the specified start time or
          current time stamp of trajectory object.

    Notes
    -----
    Only a single helix is analyzed. Use the selection to specify the helix,
    e.g. with "name CA and resid 1:20" or use start=1, stop=20.


    .. versionchanged:: 0.13.0
       New `quiet` keyword to silence frame progress output and most of the
       output that used to be printed to stdout is now logged to the logger
       *MDAnalysis.analysis.helanal* (at logelevel *INFO*).

    .. versionchanged:: 0.16.0
       Removed the `start` and `end` keywords for selecting residues because this can
       be accomplished more transparently with `selection`. The first and last resid
       are directly obtained from the selection.

    .. deprecated:: 0.16.0
       The `quiet` keyword argument is deprecated in favor of the new
       `verbose` one.

    """
    verbose = _set_verbose(verbose, quiet, default=True)
    if ref_axis is None:
        ref_axis = np.array([0., 0., 1.])
    else:
        # enable MDA API so that one can use a tuple of atoms or AtomGroup with
        # two atoms
        ref_axis = np.asarray(ref_axis)

    ca = universe.select_atoms(selection)
    start, end = ca.resids[[0, -1]]
    trajectory = universe.trajectory

    if finish is not None:
        if trajectory.ts.time > finish:
            # you'd be starting with a finish time (in ps) that has already passed or not
            # available
            raise FinishTimeException(
                'The input finish time ({finish} ps) precedes the current trajectory time of {traj_time} ps.'.format(
                    finish=finish, traj_time=trajectory.time))

    if start is not None and end is not None:
        logger.info("Analysing from residue %d to %d", start, end)
    elif start is not None and end is None:
        logger.info("Analysing from residue %d to the C termini", start)
    elif start is None and end is not None:
        logger.info("Analysing from the N termini to %d", end)
    logger.info("Analysing %d/%d residues", ca.n_atoms, universe.atoms.n_residues)

    if prefix is not None:
        prefix = str(prefix)
        matrix_filename = prefix + matrix_filename
        origin_pdbfile = prefix + origin_pdbfile
        summary_filename = prefix + summary_filename
        screw_filename = prefix + screw_filename
        tilt_filename = prefix + tilt_filename
        fitted_tilt_filename = prefix + fitted_tilt_filename
        bend_filename = prefix + bend_filename
        twist_filename = prefix + twist_filename
    backup_file(matrix_filename)
    backup_file(origin_pdbfile)
    backup_file(summary_filename)
    backup_file(screw_filename)
    backup_file(tilt_filename)
    backup_file(fitted_tilt_filename)
    backup_file(bend_filename)
    backup_file(twist_filename)

    global_height = []
    global_twist = []
    global_rnou = []
    global_bending = []
    global_bending_matrix = []
    global_tilt = []
    global_fitted_tilts = []
    global_screw = []

    pm = ProgressMeter(trajectory.n_frames, verbose=verbose,
                       format="Frame %(step)10d: %(time)20.1f ps\r")
    for ts in trajectory:
        pm.echo(ts.frame, time=ts.time)
        frame = ts.frame
        if begin is not None:
            if trajectory.time < begin:
                continue
        if finish is not None:
            if trajectory.time > finish:
                break

        ca_positions = ca.positions
        twist, bending_angles, height, rnou, origins, local_helix_axes, local_screw_angles = \
            main_loop(ca_positions, ref_axis=ref_axis)

        origin_pdb(origins, origin_pdbfile)

        #calculate local bending matrix( it is looking at all i, j combinations)
        if len(global_bending_matrix) == 0:
            global_bending_matrix = [[[] for item in local_helix_axes] for item in local_helix_axes]

        for i in range(len(local_helix_axes)):
            for j in range(i + 1, len(local_helix_axes)):
                angle = np.rad2deg(np.arccos(np.dot(local_helix_axes[i], local_helix_axes[j])))
                global_bending_matrix[i][j].append(angle)
                #global_bending_matrix[j][i].append(angle)
                #global_bending_matrix[i][i].append(0.)

        fit_vector, fit_tilt = vector_of_best_fit(origins)
        global_height += height
        global_twist += twist
        global_rnou += rnou
        #global_screw.append(local_screw_angles)
        global_fitted_tilts.append(np.rad2deg(fit_tilt))

        #print out rotations across the helix to a file
        with open(twist_filename, "a") as twist_output:
            print(frame, end='', file=twist_output)
            for loc_twist in twist:
                print(loc_twist, end='', file=twist_output)
            print("", file=twist_output)

        with open(bend_filename, "a") as bend_output:
            print(frame, end='', file=bend_output)
            for loc_bend in bending_angles:
                print(loc_bend, end='', file=bend_output)
            print("", file=bend_output)

        with open(screw_filename, "a") as rot_output:
            print(frame, end='', file=rot_output)
            for rotation in local_screw_angles:
                print(rotation, end='', file=rot_output)
            print("", file=rot_output)

        with open(tilt_filename, "a") as tilt_output:
            print(frame, end='', file=tilt_output)
            for tilt in local_helix_axes:
                print(np.rad2deg(mdamath.angle(tilt, ref_axis)),
                      end='', file=tilt_output)
            print("", file=tilt_output)

        with open(fitted_tilt_filename, "a") as tilt_output:
            print(frame, np.rad2deg(fit_tilt), file=tilt_output)

        if len(global_bending) == 0:
            global_bending = [[] for item in bending_angles]
            #global_tilt = [ [] for item in local_helix_axes ]
        for store, tmp in zip(global_bending, bending_angles):
            store.append(tmp)
        #for store,tmp in zip(global_tilt,local_helix_axes): store.append(mdamath.angle(tmp,ref_axis))


    twist_mean, twist_sd, twist_abdev = stats(global_twist)
    height_mean, height_sd, height_abdev = stats(global_height)
    rnou_mean, rnou_sd, rnou_abdev = stats(global_rnou)
    ftilt_mean, ftilt_sd, ftilt_abdev = stats(global_fitted_tilts)

    bending_statistics = [stats(item) for item in global_bending]
    #tilt_statistics =    [ stats(item) for item in global_tilt]

    bending_statistics_matrix = [[stats(col) for col in row] for row in global_bending_matrix]
    with open(matrix_filename, 'w') as mat_output:
        print("Mean", file=mat_output)
        for row in bending_statistics_matrix:
            for col in row:
                formatted_angle = "{0:6.1f}".format(col[0])
                print(formatted_angle, end='', file=mat_output)
            print('', file=mat_output)

        print('\nSD', file=mat_output)
        for row in bending_statistics_matrix:
            for col in row:
                formatted_angle = "{0:6.1f}".format(col[1])
                print(formatted_angle, end='', file=mat_output)
            print('', file=mat_output)

        print("\nABDEV", file=mat_output)
        for row in bending_statistics_matrix:
            for col in row:
                formatted_angle = "{0:6.1f}".format(col[2])
                print(formatted_angle, end='', file=mat_output)
            print('', file=mat_output)

    logger.info("Height: %g  SD: %g  ABDEV: %g  (Angstroem)", height_mean, height_sd, height_abdev)
    logger.info("Twist: %g  SD: %g  ABDEV: %g", twist_mean, twist_sd, twist_abdev)
    logger.info("Residues/turn: %g  SD: %g  ABDEV: %g", rnou_mean, rnou_sd, rnou_abdev)
    logger.info("Fitted tilt: %g  SD: %g  ABDEV: %g", ftilt_mean, ftilt_sd, ftilt_abdev)
    logger.info("Local bending angles:")
    residue_statistics = list(zip(*bending_statistics))
    measure_names = ["Mean ", "SD   ", "ABDEV"]
    if start is None:
        output = " ".join(["{0:8d}".format(item)
                           for item in range(4, len(residue_statistics[0]) + 4)])
    else:
        output = " ".join(["{0:8d}".format(item)
                           for item in range(start + 3, len(residue_statistics[0]) + start + 3)])
    logger.info("ResID %s", output)
    for measure, name in zip(residue_statistics, measure_names):
        output = str(name) + " "
        output += " ".join(["{0:8.1f}".format(residue) for residue in measure])
        logger.info(output)

    with open(summary_filename, 'w') as summary_output:
        print("Height:", height_mean, "SD", height_sd, "ABDEV", height_abdev, '(nm)', file=summary_output)
        print("Twist:", twist_mean, "SD", twist_sd, "ABDEV", twist_abdev,
              file=summary_output)
        print("Residues/turn:", rnou_mean, "SD", rnou_sd, "ABDEV", rnou_abdev,
              file=summary_output)
        print("Local bending angles:", file=summary_output)
        residue_statistics = list(zip(*bending_statistics))
        measure_names = ["Mean ", "SD   ", "ABDEV"]
        print("ResID", end='', file=summary_output)
        if start is None:
            for item in range(4, len(residue_statistics[0]) + 4):
                output = "{0:8d}".format(item)
                print(output, end='', file=summary_output)
        else:
            for item in range(start + 3, len(residue_statistics[0]) + start + 3):
                output = "{0:8d}".format(item)
                print(output, end='', file=summary_output)
        print('', file=summary_output)

        for measure, name in zip(residue_statistics, measure_names):
            print(name, end='', file=summary_output)
            for residue in measure:
                output = "{0:8.1f}".format(residue)
                print(output, end='', file=summary_output)
            print('', file=summary_output)
Esempio n. 14
0
def helanal_trajectory(universe, selection="name CA",
                       begin=None, finish=None,
                       matrix_filename="bending_matrix.dat",
                       origin_pdbfile="origin.pdb",
                       summary_filename="summary.txt",
                       screw_filename="screw.xvg",
                       tilt_filename="local_tilt.xvg",
                       fitted_tilt_filename="fit_tilt.xvg",
                       bend_filename="local_bend.xvg",
                       twist_filename="unit_twist.xvg",
                       prefix="helanal_", ref_axis=None,
                       verbose=None, quiet=None):
    """Perform HELANAL helix analysis on all frames in `universe`.

    Parameters
    ----------
    universe : Universe
    selection : str (optional)
        selection string that selects Calpha atoms [``"name CA"``]
    begin : float (optional)
        start analysing for time (ps) >= *begin*; ``None`` starts from the
        beginning [``None``]
    finish : float (optional)
        stop analysis for time (ps) =< *finish*; ``None`` goes to the
        end of the trajectory [``None``]
    matrix_filename : str (optional)
        Output file- bending matrix [``"bending_matrix.dat"``]
    origin_pdbfile : str (optional)
        Output file- origin pdb file [``"origin.pdb"``]
    summary_filename : str (optional)
        Output file- all of the basic data [``"summary.txt"``]
    screw_filename : str (optional)
        Output file- local tilts of individual residues from 2 to n-1
        [``"screw.xvg"``]
    tilt_filename : str (optional)
        Output file- tilt of line of best fit applied to origin axes
        [``"local_tilt.xvg"``]
    bend_filename : str (optional)
        Output file- local bend angles between successive local helix axes
        [``"local_bend.xvg"``]
    twist_filename : str (optional)
        Output file- local unit twist between successive helix turns
        [``"unit_twist.xvg"``]
    prefix : str (optional)
        Prefix to add to all output file names; set to ``None`` to disable
        [``"helanal__"``]
    ref_axis : array_like (optional)
        Calculate tilt angle relative to the axis; if ``None`` then ``[0,0,1]``
        is chosen [``None``]
    verbose : bool (optional)
        Toggle diagnostic outputs. [``True``]

    Raises
    ------
    FinishTimeException
          If the specified finish time precedes the specified start time or
          current time stamp of trajectory object.

    .. Note::

       Only a single helix is analyzed. Use the selection to specify the
       helix, e.g. with "name CA and resid 1:20" or use start=1, stop=20.


    .. versionchanged:: 0.13.0
       New `quiet` keyword to silence frame progress output and most of the
       output that used to be printed to stdout is now logged to the logger
       *MDAnalysis.analysis.helanal* (at logelevel *INFO*).

    .. versionchanged:: 0.16.0
       Removed the `start` and `end` keywords for selecting residues because this can
       be accomplished more transparently with `selection`. The first and last resid
       are directly obtained from the selection.

    .. deprecated:: 0.16.0
       The `quiet` keyword argument is deprecated in favor of the new
       `verbose` one.

    """
    verbose = _set_verbose(verbose, quiet, default=True)
    if ref_axis is None:
        ref_axis = np.array([0., 0., 1.])
    else:
        # enable MDA API so that one can use a tuple of atoms or AtomGroup with
        # two atoms
        ref_axis = np.asarray(ref_axis)

    ca = universe.select_atoms(selection)
    start, end = ca.resids[[0, -1]]
    trajectory = universe.trajectory

    if finish is not None:
        if trajectory.ts.time > finish:
            # you'd be starting with a finish time (in ps) that has already passed or not
            # available
            raise FinishTimeException(
                'The input finish time ({finish} ps) precedes the current trajectory time of {traj_time} ps.'.format(
                    finish=finish, traj_time=trajectory.time))

    if start is not None and end is not None:
        logger.info("Analysing from residue %d to %d", start, end)
    elif start is not None and end is None:
        logger.info("Analysing from residue %d to the C termini", start)
    elif start is None and end is not None:
        logger.info("Analysing from the N termini to %d", end)
    logger.info("Analysing %d/%d residues", ca.n_atoms, universe.atoms.n_residues)

    if prefix is not None:
        prefix = str(prefix)
        matrix_filename = prefix + matrix_filename
        origin_pdbfile = prefix + origin_pdbfile
        summary_filename = prefix + summary_filename
        screw_filename = prefix + screw_filename
        tilt_filename = prefix + tilt_filename
        fitted_tilt_filename = prefix + fitted_tilt_filename
        bend_filename = prefix + bend_filename
        twist_filename = prefix + twist_filename
    backup_file(matrix_filename)
    backup_file(origin_pdbfile)
    backup_file(summary_filename)
    backup_file(screw_filename)
    backup_file(tilt_filename)
    backup_file(fitted_tilt_filename)
    backup_file(bend_filename)
    backup_file(twist_filename)

    global_height = []
    global_twist = []
    global_rnou = []
    global_bending = []
    global_bending_matrix = []
    global_tilt = []
    global_fitted_tilts = []
    global_screw = []

    pm = ProgressMeter(trajectory.n_frames, verbose=verbose,
                       format="Frame %(step)10d: %(time)20.1f ps\r")
    for ts in trajectory:
        pm.echo(ts.frame, time=ts.time)
        frame = ts.frame
        if begin is not None:
            if trajectory.time < begin:
                continue
        if finish is not None:
            if trajectory.time > finish:
                break

        ca_positions = ca.positions
        twist, bending_angles, height, rnou, origins, local_helix_axes, local_screw_angles = \
            main_loop(ca_positions, ref_axis=ref_axis)

        origin_pdb(origins, origin_pdbfile)

        #calculate local bending matrix( it is looking at all i, j combinations)
        if len(global_bending_matrix) == 0:
            global_bending_matrix = [[[] for item in local_helix_axes] for item in local_helix_axes]

        for i in range(len(local_helix_axes)):
            for j in range(i + 1, len(local_helix_axes)):
                angle = np.rad2deg(np.arccos(np.dot(local_helix_axes[i], local_helix_axes[j])))
                global_bending_matrix[i][j].append(angle)
                #global_bending_matrix[j][i].append(angle)
                #global_bending_matrix[i][i].append(0.)

        fit_vector, fit_tilt = vector_of_best_fit(origins)
        global_height += height
        global_twist += twist
        global_rnou += rnou
        #global_screw.append(local_screw_angles)
        global_fitted_tilts.append(np.rad2deg(fit_tilt))

        #print out rotations across the helix to a file
        with open(twist_filename, "a") as twist_output:
            print(frame, end='', file=twist_output)
            for loc_twist in twist:
                print(loc_twist, end='', file=twist_output)
            print("", file=twist_output)

        with open(bend_filename, "a") as bend_output:
            print(frame, end='', file=bend_output)
            for loc_bend in bending_angles:
                print(loc_bend, end='', file=bend_output)
            print("", file=bend_output)

        with open(screw_filename, "a") as rot_output:
            print(frame, end='', file=rot_output)
            for rotation in local_screw_angles:
                print(rotation, end='', file=rot_output)
            print("", file=rot_output)

        with open(tilt_filename, "a") as tilt_output:
            print(frame, end='', file=tilt_output)
            for tilt in local_helix_axes:
                print(np.rad2deg(mdamath.angle(tilt, ref_axis)),
                      end='', file=tilt_output)
            print("", file=tilt_output)

        with open(fitted_tilt_filename, "a") as tilt_output:
            print(frame, np.rad2deg(fit_tilt), file=tilt_output)

        if len(global_bending) == 0:
            global_bending = [[] for item in bending_angles]
            #global_tilt = [ [] for item in local_helix_axes ]
        for store, tmp in zip(global_bending, bending_angles):
            store.append(tmp)
        #for store,tmp in zip(global_tilt,local_helix_axes): store.append(mdamath.angle(tmp,ref_axis))


    twist_mean, twist_sd, twist_abdev = stats(global_twist)
    height_mean, height_sd, height_abdev = stats(global_height)
    rnou_mean, rnou_sd, rnou_abdev = stats(global_rnou)
    ftilt_mean, ftilt_sd, ftilt_abdev = stats(global_fitted_tilts)

    bending_statistics = [stats(item) for item in global_bending]
    #tilt_statistics =    [ stats(item) for item in global_tilt]

    bending_statistics_matrix = [[stats(col) for col in row] for row in global_bending_matrix]
    with open(matrix_filename, 'w') as mat_output:
        print("Mean", file=mat_output)
        for row in bending_statistics_matrix:
            for col in row:
                formatted_angle = "{0:6.1f}".format(col[0])
                print(formatted_angle, end='', file=mat_output)
            print('', file=mat_output)

        print('\nSD', file=mat_output)
        for row in bending_statistics_matrix:
            for col in row:
                formatted_angle = "{0:6.1f}".format(col[1])
                print(formatted_angle, end='', file=mat_output)
            print('', file=mat_output)

        print("\nABDEV", file=mat_output)
        for row in bending_statistics_matrix:
            for col in row:
                formatted_angle = "{0:6.1f}".format(col[2])
                print(formatted_angle, end='', file=mat_output)
            print('', file=mat_output)

    logger.info("Height: %g  SD: %g  ABDEV: %g  (Angstroem)", height_mean, height_sd, height_abdev)
    logger.info("Twist: %g  SD: %g  ABDEV: %g", twist_mean, twist_sd, twist_abdev)
    logger.info("Residues/turn: %g  SD: %g  ABDEV: %g", rnou_mean, rnou_sd, rnou_abdev)
    logger.info("Fitted tilt: %g  SD: %g  ABDEV: %g", ftilt_mean, ftilt_sd, ftilt_abdev)
    logger.info("Local bending angles:")
    residue_statistics = zip(*bending_statistics)
    measure_names = ["Mean ", "SD   ", "ABDEV"]
    if start is None:
        output = " ".join(["{0:8d}".format(item)
                           for item in range(4, len(residue_statistics[0]) + 4)])
    else:
        output = " ".join(["{0:8d}".format(item)
                           for item in range(start + 3, len(residue_statistics[0]) + start + 3)])
    logger.info("ResID %s", output)
    for measure, name in zip(residue_statistics, measure_names):
        output = str(name) + " "
        output += " ".join(["{0:8.1f}".format(residue) for residue in measure])
        logger.info(output)

    with open(summary_filename, 'w') as summary_output:
        print("Height:", height_mean, "SD", height_sd, "ABDEV", height_abdev, '(nm)', file=summary_output)
        print("Twist:", twist_mean, "SD", twist_sd, "ABDEV", twist_abdev,
              file=summary_output)
        print("Residues/turn:", rnou_mean, "SD", rnou_sd, "ABDEV", rnou_abdev,
              file=summary_output)
        print("Local bending angles:", file=summary_output)
        residue_statistics = list(zip(*bending_statistics))
        measure_names = ["Mean ", "SD   ", "ABDEV"]
        print("ResID", end='', file=summary_output)
        if start is None:
            for item in range(4, len(residue_statistics[0]) + 4):
                output = "{0:8d}".format(item)
                print(output, end='', file=summary_output)
        else:
            for item in range(start + 3, len(residue_statistics[0]) + start + 3):
                output = "{0:8d}".format(item)
                print(output, end='', file=summary_output)
        print('', file=summary_output)

        for measure, name in zip(residue_statistics, measure_names):
            print(name, end='', file=summary_output)
            for residue in measure:
                output = "{0:8.1f}".format(residue)
                print(output, end='', file=summary_output)
            print('', file=summary_output)