예제 #1
0
    def run(self, start=None, stop=None, step=None):
        """Runs _single_universe on each system and _single_frame
        on each frame in the system.

        First iterates through keys of ensemble, then runs _setup_system
        which defines the system and trajectory. Then iterates over
        trajectory frames.
        """
        logger.info("Setting up systems")
        self._prepare_ensemble()
        for self._key in ProgressBar(self._ensemble.keys(), verbose=True):
            self._setup_system(self._key, start=start, stop=stop, step=step)
            self._prepare_universe()
            self._single_universe()
            for i, ts in enumerate(
                    ProgressBar(
                        self._trajectory[self.start:self.stop:self.step],
                        verbose=True,
                        postfix=f'running system {self._key}')):
                self._frame_index = i
                self._ts = ts
                self.frames[i] = ts.frame
                self.times[i] = ts.time
                self._single_frame()
            self._conclude_universe()
            logger.info("Moving to next universe")
        logger.info("Finishing up")
        self._conclude_ensemble()
        return self
예제 #2
0
 def test_verbose_disable(self, capsys):
     for i in ProgressBar(list(range(10)), verbose=False):
         pass
     out, err = capsys.readouterr()
     expected = ''
     actual = err.strip().split('\r')[-1]
     assert actual == expected
예제 #3
0
 def test_output(self, capsys):
     for i in ProgressBar(list(range(10))):
         pass
     out, err = capsys.readouterr()
     expected = u'100%|██████████| 10/10 [00:00<00:00, 583.67it/s]'
     actual = err.strip().split('\r')[-1]
     assert actual[:24] == expected[:24]
예제 #4
0
    def run(self, start=None, stop=None, step=None, verbose=None):
        """Perform the calculation

        Parameters
        ----------
        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
        """
        logger.info("Choosing frames to analyze")
        # if verbose unchanged, use class default
        verbose = getattr(self, '_verbose',
                          False) if verbose is None else verbose

        self._setup_frames(self._trajectory, start, stop, step)
        logger.info("Starting preparation")
        self._prepare()
        for i, ts in enumerate(ProgressBar(
                self._trajectory[self.start:self.stop:self.step],
                verbose=verbose)):
            self._frame_index = i
            self._ts = ts
            self.frames[i] = ts.frame
            self.times[i] = ts.time
            # logger.info("--> Doing frame {} of {}".format(i+1, self.n_frames))
            self._single_frame()
        logger.info("Finishing up")
        self._conclude()
        return self
예제 #5
0
 def _selection_serial(self, universe, selection_str):
     selection = []
     for ts in ProgressBar(universe.trajectory,
                           verbose=True,
                           total=universe.trajectory.n_frames):
         selection.append(universe.select_atoms(selection_str))
     return selection
예제 #6
0
    def run(self, force=False):
        """Run all the required passes

        Parameters
        ----------
        force : bool, optional
            Will overwrite previous results if they exist
        """
        # if results exist, don't waste any time
        if self.solution['results'] is not None and not force:
            return

        master_results = np.zeros_like(np.arange(self._starts[0],
                                                 self._stops[0], self._skip),
                                       dtype=np.float32)
        # for normalising later
        counter = np.zeros_like(master_results, dtype=np.float32)

        for i, (start,
                stop) in ProgressBar(enumerate(zip(self._starts, self._stops)),
                                     total=self.nruns,
                                     desc="Performing run"):

            # needed else trj seek thinks a np.int64 isn't an int?
            results = self._single_run(int(start), int(stop))

            nresults = len(results)
            if nresults == len(master_results):
                master_results += results
                counter += 1.0
            else:
                master_results[:nresults] += results
                counter[:nresults] += 1.0

        master_results /= counter

        self.solution['time'] = np.arange(
            len(master_results),
            dtype=np.float32) * self.u.trajectory.dt * self._skip
        self.solution['results'] = master_results
예제 #7
0
    def _prepare(self):
        # access start index
        self._u.trajectory[self.start]
        # reference will be start index
        self._reference = self._u.select_atoms(self._select)
        self._atoms = self._u.select_atoms(self._select)
        self._n_atoms = self._atoms.n_atoms

        if self._mean is None:
            self.mean = np.zeros(self._n_atoms*3)
            self._calc_mean = True
        else:
            self.mean = self._mean.positions
            self._calc_mean = False

        if self.n_frames == 1:
            raise ValueError('No covariance information can be gathered from a'
                             'single trajectory frame.\n')
        n_dim = self._n_atoms * 3
        self.cov = np.zeros((n_dim, n_dim))
        self._ref_atom_positions = self._reference.positions
        self._ref_cog = self._reference.center_of_geometry()
        self._ref_atom_positions -= self._ref_cog

        if self._calc_mean:
            for ts in ProgressBar(self._u.trajectory[self.start:self.stop:self.step],
                                  verbose=self._verbose, desc="Mean Calculation"):
                if self.align:
                    mobile_cog = self._atoms.center_of_geometry()
                    mobile_atoms, old_rmsd = _fit_to(self._atoms.positions - mobile_cog,
                                                     self._ref_atom_positions,
                                                     self._atoms,
                                                     mobile_com=mobile_cog,
                                                     ref_com=self._ref_cog)

                self.mean += self._atoms.positions.ravel()
            self.mean /= self.n_frames

        self.mean_atoms = self._atoms
        self.mean_atoms.positions = self._atoms.positions
예제 #8
0
def helanal_trajectory(universe,
                       select="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=False):
    """Perform HELANAL helix analysis on all frames in `universe`.

    Parameters
    ----------
    universe : Universe
    select : 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
    ------
    ValueError
          If the specified start (begin) time occurs after the end of the
          trajectory object.
          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 `select`. 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.

    .. versionchanged:: 0.20.0
       ProgressMeter now iterates over the number of frames analysed.

    .. versionchanged:: 1.0.0
       Changed `selection` keyword to `select`
    """
    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(select)
    start, end = ca.resids[[0, -1]]
    trajectory = universe.trajectory

    # Validate user supplied begin / end times
    traj_end_time = trajectory.ts.time + trajectory.totaltime

    if begin is not None:
        if traj_end_time < begin:
            # Begin occurs after the end of the trajectory, throw error
            msg = ("The input begin time ({0} ps) occurs after the end "
                   "of the trajectory ({1} ps)".format(begin, traj_end_time))
            raise ValueError(msg)
        elif trajectory.ts.time > begin:
            # Begin occurs before trajectory start, warn and reset
            msg = ("The input begin time ({0} ps) precedes the starting "
                   "trajectory time --- Setting starting frame to 0".format(
                       begin))
            warnings.warn(msg)
            logger.warning(msg)
            start_frame = None
        else:
            start_frame = int(
                np.ceil((begin - trajectory.ts.time) / trajectory.ts.dt))
    else:
        start_frame = None

    if finish is not None:
        if (begin is not None) and (begin > finish):
            # finish occurs before begin time
            msg = ("The input finish time ({0} ps) precedes the input begin "
                   "time ({1} ps)".format(finish, begin))
            raise ValueError(msg)
        elif trajectory.ts.time > finish:
            # you'd be starting with a finish time(in ps) that has already
            # passed or is not available
            msg = ("The input finish time ({0} ps) precedes the current "
                   "trajectory time ({1} ps)".format(finish, trajectory.time))
            raise ValueError(msg)
        elif traj_end_time < finish:
            # finish time occurs after the end of trajectory, warn
            msg = ("The input finish time ({0} ps) occurs after the end of "
                   "the trajectory ({1} ps). Finish time will be set to the "
                   "end of the trajectory".format(finish, traj_end_time))
            warnings.warn(msg)
            logger.warning(msg)
            end_frame = None
        else:
            # To replicate the original behaviour of break when
            # trajectory.time > finish, we add 1 here.
            end_frame = int(
                np.floor((finish - trajectory.ts.time) // trajectory.ts.dt) +
                1)
    else:
        end_frame = None

    start_frame, end_frame, frame_step = trajectory.check_slice_indices(
        start_frame, end_frame, 1)
    n_frames = len(range(start_frame, end_frame, frame_step))

    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 = []

    for ts in ProgressBar(trajectory[start_frame:end_frame:frame_step],
                          verbose=verbose,
                          desc="Helix analysis"):

        frame = ts.frame
        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)