From 00cf3b783c779bf9320bdaab1f3436ec0734d7b2 Mon Sep 17 00:00:00 2001 From: richardjgowers Date: Wed, 22 Aug 2018 13:50:16 -0500 Subject: [PATCH] removed quiet in favour of verbose updated usage of Analysis API, start/stop/step now deprecated in __init__ and should be given in run method made PCA setup respect start frame more, if start is given then initial weights are from that frame not frame 0 --- benchmarks/benchmarks/analysis/rms.py | 5 +- package/CHANGELOG | 11 ++- package/MDAnalysis/analysis/base.py | 88 ++++++++++++------- package/MDAnalysis/analysis/contacts.py | 8 -- package/MDAnalysis/analysis/density.py | 4 +- package/MDAnalysis/analysis/diffusionmap.py | 44 +++++----- .../analysis/hbonds/hbond_analysis.py | 68 ++++++-------- .../analysis/hbonds/wbridge_analysis.py | 52 +++++------ package/MDAnalysis/analysis/helanal.py | 5 +- package/MDAnalysis/analysis/pca.py | 51 +++++------ package/MDAnalysis/analysis/rms.py | 25 +----- package/MDAnalysis/analysis/waterdynamics.py | 7 +- package/MDAnalysis/core/universe.py | 6 +- package/MDAnalysis/lib/log.py | 61 +------------ .../MDAnalysisTests/analysis/test_align.py | 2 +- .../MDAnalysisTests/analysis/test_base.py | 57 ++++++------ .../MDAnalysisTests/analysis/test_contacts.py | 4 +- .../analysis/test_diffusionmap.py | 8 +- .../analysis/test_dihedrals.py | 8 +- .../MDAnalysisTests/analysis/test_pca.py | 12 ++- .../MDAnalysisTests/analysis/test_rms.py | 45 +++------- testsuite/MDAnalysisTests/utils/test_log.py | 41 --------- 22 files changed, 239 insertions(+), 373 deletions(-) diff --git a/benchmarks/benchmarks/analysis/rms.py b/benchmarks/benchmarks/analysis/rms.py index 882eaafcef8..c9811a5984d 100644 --- a/benchmarks/benchmarks/analysis/rms.py +++ b/benchmarks/benchmarks/analysis/rms.py @@ -96,13 +96,10 @@ def setup(self, n_atoms, step, weights): self.u = MDAnalysis.Universe(PSF, DCD) self.ag = self.u.atoms[:n_atoms] self.RMSF_inst = rms.RMSF(atomgroup=self.ag, - start=None, - stop=None, - step=step, weights=weights) def time_RMSF(self, n_atoms, step, weights): """Benchmark RMSF.run() method, which parses over the entire trajectory. """ - self.RMSF_inst.run() + self.RMSF_inst.run(step=step) diff --git a/package/CHANGELOG b/package/CHANGELOG index 078aea20630..acb0c32cbb5 100644 --- a/package/CHANGELOG +++ b/package/CHANGELOG @@ -78,7 +78,7 @@ Enhancements analysis module (PR #1997, PR #2033) * Added the analysis.data module for reference data used in analysis (PR #2033) * Added analysis.dihedrals with Ramachandran class to analysis module (PR #1997) - * Added augment functionality to create relevant images of particles + * Added augment functionality to create relevant images of particles * Most functions in `MDanalysis.lib.distances` previously only accepting arrays of coordinates now also accept single coordinates as input (PR #2048, Issues #1262 #1938) @@ -109,6 +109,8 @@ Fixes * Fixed SphericalLayer and SphericalZone selections with pbc=True. Previously these shifted all atoms to inside the primary unit cell when calculating the center of the reference group (Issue #1795) + * PCA analysis now uses start frame as reference frame rather than 0th frame + (PR #2055) Changes * TopologyAttrs are now statically typed (Issue #1876) @@ -130,8 +132,15 @@ Changes enforced to be of the form ``[lx, ly, lz, alpha, beta, gamma]`` as required by the docs (Issue #2046, PR #2048) * Added periodic keyword to select_atoms (#759) + * PCA.transform now requires that PCA.run() has already been called + otherwise a ValueError is raised (PR #2055) + * The quiet keyword has been removed and replaced with verbose (Issue #1975 + PR #2055) Deprecations + * start/stop/step are deprecated in the initialization of Analysis classes. + These parameters should instead be given to the run() method of the class. + (Issue #1463 #1979 PR #2055) * Almost all "save()", "save_results()", "save_table()" methods in analysis classes were deprecated and will be removed in 1.0 (Issue #1972 and #1745) diff --git a/package/MDAnalysis/analysis/base.py b/package/MDAnalysis/analysis/base.py index ddf45904029..0d41b1dc2c9 100644 --- a/package/MDAnalysis/analysis/base.py +++ b/package/MDAnalysis/analysis/base.py @@ -32,11 +32,12 @@ from six.moves import range, zip import inspect import logging +import warnings import numpy as np from MDAnalysis import coordinates from MDAnalysis.core.groups import AtomGroup -from MDAnalysis.lib.log import ProgressMeter, _set_verbose +from MDAnalysis.lib.log import ProgressMeter logger = logging.getLogger(__name__) @@ -84,30 +85,34 @@ def _conclude(self): .. code-block:: python - na = NewAnalysis(u.select_atoms('name CA'), 35).run() + na = NewAnalysis(u.select_atoms('name CA'), 35).run(start=10, stop=20) print(na.result) """ - def __init__(self, trajectory, start=None, - stop=None, step=None, verbose=None, quiet=None): + def __init__(self, trajectory, verbose=False, **kwargs): """ 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 + Turn on more logging and debugging, default ``False`` """ - self._verbose = _set_verbose(verbose, quiet, default=False) - self._quiet = not self._verbose - self._setup_frames(trajectory, start, stop, step) + self._trajectory = trajectory + self._verbose = verbose + # do deprecated kwargs + # remove in 1.0 + deps = [] + for arg in ['start', 'stop', 'step']: + if arg in kwargs and not kwargs[arg] is None: + deps.append(arg) + setattr(self, arg, kwargs[arg]) + if deps: + warnings.warn('Setting the following kwargs should be ' + 'done in the run() method: {}'.format( + ', '.join(deps)), + DeprecationWarning) def _setup_frames(self, trajectory, start=None, stop=None, step=None): """ @@ -126,6 +131,11 @@ def _setup_frames(self, trajectory, start=None, stop=None, step=None): number of frames to skip between each analysed frame """ self._trajectory = trajectory + # TODO: Remove once start/stop/step are deprecated from init + # See if these have been set as class attributes, and use that + start = getattr(self, 'start', start) + stop = getattr(self, 'stop', stop) + step = getattr(self, 'step', step) start, stop, step = trajectory.check_slice_indices(start, stop, step) self.start = start self.stop = stop @@ -135,21 +145,9 @@ def _setup_frames(self, trajectory, start=None, stop=None, step=None): if interval == 0: interval = 1 - # ensure _verbose is set when __init__ wasn't called, this is to not - # break pre 0.16.0 API usage of AnalysisBase - if not hasattr(self, '_verbose'): - if hasattr(self, '_quiet'): - # Here, we are in the odd case where a children class defined - # self._quiet without going through AnalysisBase.__init__. - warnings.warn("The *_quiet* attribute of analyses is " - "deprecated (from 0.16)use *_verbose* instead.", - DeprecationWarning) - self._verbose = not self._quiet - else: - self._verbose = True - self._quiet = not self._verbose + verbose = getattr(self, '_verbose', False) self._pm = ProgressMeter(self.n_frames if self.n_frames else 1, - interval=interval, verbose=self._verbose) + interval=interval, verbose=verbose) def _single_frame(self): """Calculate data from a single frame of trajectory @@ -169,8 +167,25 @@ def _conclude(self): """ pass - def run(self): - """Perform the calculation""" + 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( @@ -241,10 +256,15 @@ def __init__(self, function, trajectory=None, *args, **kwargs): self.function = function self.args = args - base_kwargs, self.kwargs = _filter_baseanalysis_kwargs(self.function, - kwargs) - super(AnalysisFromFunction, self).__init__(trajectory, **base_kwargs) + # TODO: Remove in 1.0 + my_kwargs = {} + for depped_arg in ['start', 'stop', 'step']: + if depped_arg in kwargs: + my_kwargs[depped_arg] = kwargs.pop(depped_arg) + self.kwargs = kwargs + + super(AnalysisFromFunction, self).__init__(trajectory, **my_kwargs) def _prepare(self): self.results = [] @@ -272,7 +292,7 @@ def analysis_class(function): >>> def RotationMatrix(mobile, ref): >>> return mda.analysis.align.rotation_matrix(mobile, ref)[0] - >>> rot = RotationMatrix(u.trajectory, mobile, ref, step=2).run() + >>> rot = RotationMatrix(u.trajectory, mobile, ref).run(step=2) >>> print(rot.results) """ diff --git a/package/MDAnalysis/analysis/contacts.py b/package/MDAnalysis/analysis/contacts.py index a982160145c..66f8d0470ff 100644 --- a/package/MDAnalysis/analysis/contacts.py +++ b/package/MDAnalysis/analysis/contacts.py @@ -388,14 +388,6 @@ def __init__(self, u, selection, refgroup, method="hard_cut", radius=4.5, kwargs : dict, optional dictionary of additional kwargs passed to `method`. Check respective functions for reasonable values. - start : int, optional - First frame of trajectory to analyse, Default: None becomes 0. - stop : int, optional - Frame index to stop analysis. Default: None becomes - n_frames. Iteration stops *before* this frame number, - which means that the trajectory would be read until the end. - step : int, optional - Step between frames to analyse, Default: None becomes 1. verbose : bool (optional) Show detailed progress of the calculation if set to ``True``; the default is ``False``. diff --git a/package/MDAnalysis/analysis/density.py b/package/MDAnalysis/analysis/density.py index 33588b1c1dd..b9a71deb340 100644 --- a/package/MDAnalysis/analysis/density.py +++ b/package/MDAnalysis/analysis/density.py @@ -552,7 +552,7 @@ def density_from_Universe(universe, delta=1.0, atomselection='name OH2', start=None, stop=None, step=None, metadata=None, padding=2.0, cutoff=0, soluteselection=None, use_kdtree=True, update_selection=False, - verbose=None, interval=1, quiet=None, + verbose=False, interval=1, quiet=None, parameters=None, gridcenter=None, xdim=None, ydim=None, zdim=None): """Create a density grid from a :class:`MDAnalysis.Universe` object. @@ -751,7 +751,7 @@ def current_coordinates(): h = grid.copy() pm = ProgressMeter(u.trajectory.n_frames, interval=interval, - verbose=verbose, quiet=quiet, + verbose=verbose, format="Histogramming %(n_atoms)6d atoms in frame " "%(step)5d/%(numsteps)d [%(percentage)5.1f%%]\r") start, stop, step = u.trajectory.check_slice_indices(start, stop, step) diff --git a/package/MDAnalysis/analysis/diffusionmap.py b/package/MDAnalysis/analysis/diffusionmap.py index aac0cc94576..0de2c618b9c 100644 --- a/package/MDAnalysis/analysis/diffusionmap.py +++ b/package/MDAnalysis/analysis/diffusionmap.py @@ -198,8 +198,7 @@ class DistanceMatrix(AnalysisBase): """ def __init__(self, u, select='all', metric=rmsd, cutoff=1E0-5, - weights=None, start=None, stop=None, step=None, - **kwargs): + weights=None, **kwargs): """ Parameters ---------- @@ -226,14 +225,6 @@ def __init__(self, u, select='all', metric=rmsd, cutoff=1E0-5, Default: 1EO-5 weights : array, optional Weights to be given to coordinates for metric calculation - start : int, optional - First frame of trajectory to analyse, Default: None becomes 0. - stop : int, optional - Frame index to stop analysis. Default: None becomes - n_frames. Iteration stops *before* this frame number, - which means that the trajectory would be read until the end. - step : int, optional - Step between frames to analyse, Default: None becomes 1. verbose : bool (optional) Show detailed progress of the calculation if set to ``True``; the default is ``False``. @@ -242,8 +233,7 @@ def __init__(self, u, select='all', metric=rmsd, cutoff=1E0-5, traj = self._u.trajectory # remember that this must be called before referencing self.n_frames - super(DistanceMatrix, self).__init__(self._u.trajectory, - start=start, stop=stop, step=step, **kwargs) + super(DistanceMatrix, self).__init__(self._u.trajectory, **kwargs) self.atoms = self._u.select_atoms(select) self._metric = metric @@ -325,7 +315,7 @@ def __init__(self, u, epsilon=1, **kwargs): **kwargs Parameters to be passed for the initialization of a :class:`DistanceMatrix`. - """ + """ if isinstance(u, Universe): self._dist_matrix = DistanceMatrix(u, **kwargs) elif isinstance(u, DistanceMatrix): @@ -334,20 +324,32 @@ def __init__(self, u, epsilon=1, **kwargs): raise ValueError("U is not a Universe or DistanceMatrix and" " so the DiffusionMap has no data to work with.") self._epsilon = epsilon + + def run(self, start=None, stop=None, step=None): + """ Create and decompose the diffusion matrix in preparation + for a diffusion map. + + 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 + + .. versionchanged:: 0.19.0 + Added start/stop/step kwargs + """ + # run only if distance matrix not already calculated + if not self._dist_matrix._calculated: + self._dist_matrix.run(start=start, stop=stop, step=step) # important for transform function and length of .run() method self._n_frames = self._dist_matrix.n_frames if self._n_frames > 5000: warnings.warn("The distance matrix is very large, and can " "be very slow to compute. Consider picking a larger " "step size in distance matrix initialization.") - - - def run(self): - """ Create and decompose the diffusion matrix in preparation - for a diffusion map.""" - # run only if distance matrix not already calculated - if not self._dist_matrix._calculated: - self._dist_matrix.run() self._scaled_matrix = (self._dist_matrix.dist_matrix ** 2 / self._epsilon) # take negative exponent of scaled matrix to create Isotropic kernel diff --git a/package/MDAnalysis/analysis/hbonds/hbond_analysis.py b/package/MDAnalysis/analysis/hbonds/hbond_analysis.py index 2a57b6c0559..29d58e78574 100644 --- a/package/MDAnalysis/analysis/hbonds/hbond_analysis.py +++ b/package/MDAnalysis/analysis/hbonds/hbond_analysis.py @@ -326,7 +326,8 @@ class HydrogenBondAnalysis_OtherFF(HydrogenBondAnalysis): import numpy as np from MDAnalysis import MissingDataWarning, NoDataError, SelectionError, SelectionWarning -from MDAnalysis.lib.log import ProgressMeter, _set_verbose +from .. import base +from MDAnalysis.lib.log import ProgressMeter from MDAnalysis.lib.NeighborSearch import AtomNeighborSearch from MDAnalysis.lib import distances from MDAnalysis.lib.util import deprecate @@ -335,7 +336,7 @@ class HydrogenBondAnalysis_OtherFF(HydrogenBondAnalysis): logger = logging.getLogger('MDAnalysis.analysis.hbonds') -class HydrogenBondAnalysis(object): +class HydrogenBondAnalysis(base.AnalysisBase): """Perform a hydrogen bond analysis The analysis of the trajectory is performed with the @@ -406,8 +407,7 @@ def __init__(self, universe, selection1='protein', selection2='all', selection1_ update_selection1=True, update_selection2=True, filter_first=True, distance_type='hydrogen', distance=3.0, angle=120.0, forcefield='CHARMM27', donors=None, acceptors=None, - start=None, stop=None, step=None, - debug=None, detect_hydrogens='distance', verbose=None, pbc=False): + debug=False, detect_hydrogens='distance', verbose=False, pbc=False, **kwargs): """Set up calculation of hydrogen bonds between two selections in a universe. The timeseries is accessible as the attribute :attr:`HydrogenBondAnalysis.timeseries`. @@ -470,15 +470,6 @@ def __init__(self, universe, selection1='protein', selection2='all', selection1_ acceptors : sequence (optional) Extra H acceptor atom types (in addition to those in :attr:`~HydrogenBondAnalysis.DEFAULT_ACCEPTORS`), must be a sequence. - start : int (optional) - starting frame-index for analysis, ``None`` is the first one, 0. - `start` and `stop` are 0-based frame indices and are used to slice - the trajectory (if supported) [``None``] - stop : int (optional) - last trajectory frame for analysis, ``None`` is the last one [``None``] - step : int (optional) - read every `step` between `start` (included) and `stop` (excluded), - ``None`` selects 1. [``None``] detect_hydrogens : {"distance", "heuristic"} (optional) Determine the algorithm to find hydrogens connected to donor atoms. Can be "distance" (default; finds all hydrogens in the @@ -496,7 +487,7 @@ def __init__(self, universe, selection1='protein', selection2='all', selection1_ If set to ``True`` enables per-frame debug logging. This is disabled by default because it generates a very large amount of output in the log file. (Note that a logger must have been started to see - the output, e.g. using :func:`MDAnalysis.start_logging`.) + the output, e.g. using :func:`MDAnalysis.start_logging`.) [``False``] verbose : bool (optional) Toggle progress output. (Can also be given as keyword argument to :meth:`run`.) @@ -564,6 +555,9 @@ def __init__(self, universe, selection1='protein', selection2='all', selection1_ .. _`Issue 138`: https://github.com/MDAnalysis/mdanalysis/issues/138 """ + super(HydrogenBondAnalysis, self).__init__(universe.trajectory, **kwargs) + # per-frame debugging output? + self.debug = debug self._get_bonded_hydrogens_algorithms = { "distance": self._get_bonded_hydrogens_dist, # 0.7.6 default @@ -584,7 +578,6 @@ def __init__(self, universe, selection1='protein', selection2='all', selection1_ self.distance = distance self.distance_type = distance_type # note: everything except 'heavy' will give the default behavior self.angle = angle - self.traj_slice = slice(start, stop, step) self.pbc = pbc and all(self.u.dimensions[:3]) # set up the donors/acceptors lists @@ -606,19 +599,8 @@ def __init__(self, universe, selection1='protein', selection2='all', selection1_ self.table = None # placeholder for output table - self.debug = True # always enable debug output for initial selection update self._update_selection_1() self._update_selection_2() - # per-frame debugging output? - # This line must be changed at the end of the deprecation period for - # the *quiet* keyword argument. Then it must become: - # self.debug = debug - # In the signature, *verbose* must be removed and the default value - # for *debug* must be set to False. - # See the docstring for lib.log._set_verbose, the pull request #1150, - # and the issue #903. - self.debug = _set_verbose(debug, verbose, default=False, - was='verbose', now='debug') self._log_parameters() @@ -635,7 +617,6 @@ def __init__(self, universe, selection1='protein', selection2='all', selection1_ self._sanity_check(2, 'donors') logger.info("HBond analysis: initial checks passed.") - def _sanity_check(self, selection, htype): """sanity check the selections 1 and 2 @@ -873,7 +854,7 @@ def logger_debug(self, *args): if self.debug: logger.debug(*args) - def run(self, **kwargs): + def run(self, start=None, stop=None, step=None, verbose=None, **kwargs): """Analyze trajectory and produce timeseries. Stores the hydrogen bond data per frame as @@ -882,6 +863,15 @@ def run(self, **kwargs): Parameters ---------- + start : int (optional) + starting frame-index for analysis, ``None`` is the first one, 0. + `start` and `stop` are 0-based frame indices and are used to slice + the trajectory (if supported) [``None``] + stop : int (optional) + last trajectory frame for analysis, ``None`` is the last one [``None``] + step : int (optional) + read every `step` between `start` (included) and `stop` (excluded), + ``None`` selects 1. [``None``] verbose : bool (optional) toggle progress meter output :class:`~MDAnalysis.lib.log.ProgressMeter` [``True``] @@ -919,6 +909,9 @@ def run(self, **kwargs): argument `debug`. """ + # sets self.start/stop/step and _pm + self._setup_frames(self._trajectory, start, stop, step) + logger.info("HBond analysis: starting") logger.debug("HBond analysis: donors %r", self.donors) logger.debug("HBond analysis: acceptors %r", self.acceptors) @@ -937,19 +930,9 @@ def run(self, **kwargs): self._timeseries = [] self.timesteps = [] - 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), + pm = ProgressMeter(self.n_frames, format="HBonds frame {current_step:5d}: {step:5d}/{numsteps} [{percentage:5.1f}%]\r", - verbose=verbose) + verbose=kwargs.get('verbose', False)) try: self.u.trajectory.time @@ -963,10 +946,9 @@ def _get_timestep(): logger.warning("HBond analysis is recording frame number instead of time step") 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) + self.start, self.stop, self.step) - for progress, ts in enumerate(self.u.trajectory[self.traj_slice]): + for progress, ts in enumerate(self.u.trajectory[self.start:self.stop:self.step]): # all bonds for this timestep frame_results = [] # dict of tuples (atom.index, atom.index) for quick check if diff --git a/package/MDAnalysis/analysis/hbonds/wbridge_analysis.py b/package/MDAnalysis/analysis/hbonds/wbridge_analysis.py index 419355e33c6..6f81b22c029 100644 --- a/package/MDAnalysis/analysis/hbonds/wbridge_analysis.py +++ b/package/MDAnalysis/analysis/hbonds/wbridge_analysis.py @@ -292,7 +292,7 @@ class WaterBridgeAnalysis_OtherFF(WaterBridgeAnalysis): from .hbond_analysis import HydrogenBondAnalysis from MDAnalysis.lib.NeighborSearch import AtomNeighborSearch -from MDAnalysis.lib.log import ProgressMeter, _set_verbose +from MDAnalysis.lib.log import ProgressMeter from MDAnalysis.lib import distances from MDAnalysis import SelectionWarning @@ -319,8 +319,7 @@ def __init__(self, universe, selection1='protein', update_selection2=False, update_water_selection=True, filter_first=True, distance_type='hydrogen', distance=3.0, angle=120.0, forcefield='CHARMM27', donors=None, - acceptors=None, start=None, stop=None, step=None, debug=None, - verbose=None): + acceptors=None, debug=None, verbose=False, **kwargs): """Set up the calculation of water bridges between two selections in a universe. @@ -406,16 +405,6 @@ def __init__(self, universe, selection1='protein', Extra H acceptor atom types (in addition to those in :attr:`~HydrogenBondAnalysis.DEFAULT_ACCEPTORS`), must be a sequence. - start : int (optional) - starting frame-index for analysis, ``None`` is the first one, 0. - `start` and `stop` are 0-based frame indices and are used to slice - the trajectory (if supported) [``None``] - stop : int (optional) - last trajectory frame for analysis, ``None`` is the last one - [``None``] - step : int (optional) - read every `step` between `start` (included) and `stop` (excluded), - ``None`` selects 1. [``None``] distance_type : {"hydrogen", "heavy"} (optional) Measure hydrogen bond lengths between donor and acceptor heavy attoms ("heavy") or between donor hydrogen and acceptor heavy @@ -451,7 +440,7 @@ def __init__(self, universe, selection1='protein', update_selection2=update_selection2, filter_first=filter_first, distance_type=distance_type, distance=distance, angle=angle, forcefield=forcefield, donors=donors, acceptors=acceptors, - start=start, stop=stop, step=step, debug=debug, verbose=verbose) + debug=debug, verbose=verbose, **kwargs) self._update_water_selection() def _log_parameters(self): @@ -547,7 +536,7 @@ def _update_water_selection(self): 'name {0}'.format(' '.join(self.acceptors))) self.logger_debug("Water acceptors: {0}".format(len(self._water_acceptors))) - def run(self, **kwargs): + def run(self, start=None, stop=None, step=None, verbose=None, debug=None): """Analyze trajectory and produce timeseries. Stores the water bridge data per frame as @@ -556,6 +545,16 @@ def run(self, **kwargs): Parameters ---------- + start : int (optional) + starting frame-index for analysis, ``None`` is the first one, 0. + `start` and `stop` are 0-based frame indices and are used to slice + the trajectory (if supported) [``None``] + stop : int (optional) + last trajectory frame for analysis, ``None`` is the last one + [``None``] + step : int (optional) + read every `step` between `start` (included) and `stop` (excluded), + ``None`` selects 1. [``None``] verbose : bool (optional) toggle progress meter output :class:`~MDAnalysis.lib.log.ProgressMeter` [``True``] @@ -571,12 +570,13 @@ def run(self, **kwargs): :meth:`WaterBridgeAnalysis.generate_table` : processing the data into a different format. """ + self._setup_frames(self.u.trajectory, start, stop, step) + 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) @@ -587,26 +587,16 @@ def run(self, **kwargs): 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), + if verbose is None: + verbose = self._verbose + pm = ProgressMeter(self.n_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) + self.start, self.stop, self.step) - for progress, ts in enumerate(self.u.trajectory[self.traj_slice]): + for progress, ts in enumerate(self.u.trajectory[self.start:self.stop:self.step]): # all bonds for this timestep # dict of tuples (atom.index, atom.index) for quick check if diff --git a/package/MDAnalysis/analysis/helanal.py b/package/MDAnalysis/analysis/helanal.py index d1b88f89a10..963c628a9b6 100644 --- a/package/MDAnalysis/analysis/helanal.py +++ b/package/MDAnalysis/analysis/helanal.py @@ -124,7 +124,7 @@ import MDAnalysis from MDAnalysis import FinishTimeException -from MDAnalysis.lib.log import ProgressMeter, _set_verbose +from MDAnalysis.lib.log import ProgressMeter from MDAnalysis.lib import mdamath import logging @@ -168,7 +168,7 @@ def helanal_trajectory(universe, selection="name CA", bend_filename="local_bend.xvg", twist_filename="unit_twist.xvg", prefix="helanal_", ref_axis=None, - verbose=None, quiet=None): + verbose=False): """Perform HELANAL helix analysis on all frames in `universe`. Parameters @@ -236,7 +236,6 @@ def helanal_trajectory(universe, selection="name CA", `verbose` one. """ - verbose = _set_verbose(verbose, quiet, default=True) if ref_axis is None: ref_axis = np.array([0., 0., 1.]) else: diff --git a/package/MDAnalysis/analysis/pca.py b/package/MDAnalysis/analysis/pca.py index 7d7c82a88e1..370c11dcb9b 100644 --- a/package/MDAnalysis/analysis/pca.py +++ b/package/MDAnalysis/analysis/pca.py @@ -160,6 +160,10 @@ class PCA(AnalysisBase): Notes ----- Computation can be speed up by supplying a precalculated mean structure + + .. versionchanged:: 0.19.0 + The start frame is used when performing selections and calculating + mean positions. Previously the 0th frame was always used. """ def __init__(self, universe, select='all', align=False, mean=None, @@ -181,46 +185,39 @@ def __init__(self, universe, select='all', align=False, mean=None, n_components : int, optional The number of principal components to be saved, default saves all principal components, Default: None - start : int, optional - First frame of trajectory to use for generation - of covariance matrix, Default: None - stop : int, optional - Last frame of trajectory to use for generation - of covariance matrix, Default: None - step : int, optional - Step between frames of trajectory to use for generation - of covariance matrix, Default: None verbose : bool (optional) Show detailed progress of the calculation if set to ``True``; the default is ``False``. """ - super(PCA, self).__init__(universe.trajectory, - **kwargs) - if self.n_frames == 1: - raise ValueError('No covariance information can be gathered from a' - 'single trajectory frame.\n') - + super(PCA, self).__init__(universe.trajectory, **kwargs) self._u = universe # for transform function self.align = align - # access 0th index - self._u.trajectory[0] - # reference will be 0th index - self._reference = self._u.select_atoms(select) - self._atoms = self._u.select_atoms(select) + + self._calculated = False self.n_components = n_components + self._select = select + self._mean = mean + + 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 - self._calculated = False - if mean is None: + if self._mean is None: self.mean = np.zeros(self._n_atoms*3) self._calc_mean = True else: - self.mean = mean.positions + self.mean = self._mean.positions self._calc_mean = False - def _prepare(self): + 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 @@ -303,9 +300,13 @@ def transform(self, atomgroup, n_components=None, start=None, stop=None, Returns ------- pca_space : array, shape (number of frames, number of components) + + .. versionchanged:: 0.19.0 + Transform now requires that :meth:`run` has been called before, + otherwise a :exc:`ValueError` is raised. """ if not self._calculated: - self.run() + raise ValueError('Call run() on the PCA before using transform') if isinstance(atomgroup, Universe): atomgroup = atomgroup.atoms diff --git a/package/MDAnalysis/analysis/rms.py b/package/MDAnalysis/analysis/rms.py index 21fd9efcf3f..1e3fefd29d1 100644 --- a/package/MDAnalysis/analysis/rms.py +++ b/package/MDAnalysis/analysis/rms.py @@ -145,7 +145,7 @@ import MDAnalysis.lib.qcprot as qcp from MDAnalysis.analysis.base import AnalysisBase from MDAnalysis.exceptions import SelectionError, NoDataError -from MDAnalysis.lib.log import ProgressMeter, _set_verbose +from MDAnalysis.lib.log import ProgressMeter from MDAnalysis.lib.util import asiterable, iterable, get_weights, deprecate @@ -370,15 +370,6 @@ def __init__(self, atomgroup, reference=None, select='all', .. Note:: Experimental feature. Only limited error checking implemented. - - start : int (optional) - starting frame, default None becomes 0. - stop : int (optional) - Frame index to stop analysis. Default: None becomes - n_frames. Iteration stops *before* this frame number, - which means that the trajectory would be read until the end. - step : int (optional) - step between frames, default ``None`` becomes 1. filename : str (optional) write RMSD into file with :meth:`RMSD.save` @@ -810,20 +801,6 @@ def __init__(self, atomgroup, **kwargs): super(RMSF, self).__init__(atomgroup.universe.trajectory, **kwargs) self.atomgroup = atomgroup - def run(self, start=None, stop=None, step=None, verbose=None, quiet=None): - """Perform the analysis.""" - - if any([el is not None for el in (start, stop, step, 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() - def _prepare(self): self.sumsquares = np.zeros((self.atomgroup.n_atoms, 3)) self.mean = self.sumsquares.copy() diff --git a/package/MDAnalysis/analysis/waterdynamics.py b/package/MDAnalysis/analysis/waterdynamics.py index 2428095e8c5..efc2b5949b2 100644 --- a/package/MDAnalysis/analysis/waterdynamics.py +++ b/package/MDAnalysis/analysis/waterdynamics.py @@ -419,7 +419,7 @@ import multiprocessing import MDAnalysis.analysis.hbonds -from MDAnalysis.lib.log import _set_verbose, ProgressMeter +from MDAnalysis.lib.log import ProgressMeter class HydrogenBondLifetimes(object): @@ -596,11 +596,10 @@ def _getGraphics(self, HBP, t0, tf, maxdt): return a def _HBA(self, ts, conn, universe, selAtom1, selAtom2, - verbose=None, quiet=None): + verbose=False): """ 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 @@ -1303,4 +1302,4 @@ def run(self, tau_max=20, start=0, stop=None, step=1, verbose=False): self.tau_timeseries = tau_timeseries self.sp_timeseries = [np.mean(sp) for sp in sp_timeseries_data] - return self \ No newline at end of file + return self diff --git a/package/MDAnalysis/core/universe.py b/package/MDAnalysis/core/universe.py index 8cd98b758c7..139b0a02fd0 100644 --- a/package/MDAnalysis/core/universe.py +++ b/package/MDAnalysis/core/universe.py @@ -115,7 +115,7 @@ from .. import _ANCHOR_UNIVERSES, _TOPOLOGY_ATTRS, _PARSERS from ..exceptions import NoDataError from ..lib import util -from ..lib.log import ProgressMeter, _set_verbose +from ..lib.log import ProgressMeter from ..lib.util import cached, NamedStream, isstream from ..lib.mdamath import find_fragments from . import groups @@ -602,7 +602,7 @@ def load_new(self, filename, format=None, in_memory=False, **kwargs): return self def transfer_to_memory(self, start=None, stop=None, step=None, - verbose=None, quiet=None): + verbose=False): """Transfer the trajectory to in memory representation. Replaces the current trajectory reader object with one of type @@ -626,8 +626,6 @@ def transfer_to_memory(self, start=None, stop=None, step=None, """ from ..coordinates.memory import MemoryReader - verbose = _set_verbose(verbose, quiet, default=False) - if not isinstance(self.trajectory, MemoryReader): # Try to extract coordinates using Timeseries object # This is significantly faster, but only implemented for certain diff --git a/package/MDAnalysis/lib/log.py b/package/MDAnalysis/lib/log.py index 71ac5be41e1..be4ae0f9fb4 100644 --- a/package/MDAnalysis/lib/log.py +++ b/package/MDAnalysis/lib/log.py @@ -221,59 +221,6 @@ def _guess_string_format(template): return _legacy_format -def _set_verbose(verbose, quiet, default=True, - was='quiet', now='verbose'): - """Return the expected value of verbosity - - This function aims at handling the deprecation of the *quiet* keyword in - versin 0.16. - - This function issues a deprecation warning if *quiet* was set (is not - None), and raises a ValueError if *verbose* and *quiet* are set to - contradicting values. - - If *verbose* is set, then the function returns the set value of *verbose*. - If it is not set, but *quiet* is set, then the function returns - `not quiet`. Finally, if none of *verbose* nor *quiet* is set, then - *default* is returned. - - During the deprecation phase of the *quiet* keyword, this function is - expected to be used as follow: - - .. code-block:: python - - def method(verbose=None, quiet=None): - # *verbose* and *quiet* are set to None to distinguish explicitly - # set values. - self.verbose = _set_verbose(verbose, quiet, default=True) - - At the end of the deprecation period, the code above should be replaced by: - - .. code-block:: python - - def method(verbose=True): - # The *quiet* keyword disapeard and the default value for *verbose* - # is set to the actual default value. - self.verbose = verbose - - In `MDAnalysis.analysis.hbonds.hbonds_analysis`, the deprecation scheme is - more complex: *quiet* becomes *verbose*, and *verbose* becomes *debug*. - Hence, this function allows to use diffrent argument names to display in - error messages and deprecation warnings. - """ - if quiet is not None: - warnings.warn("Keyword *{}* is deprecated (from version 0.16); " - "use *{}* instead.".format(was, now), DeprecationWarning) - if verbose is not None and verbose == quiet: - raise ValueError("Keywords *{}* and *{}* are contradicting each other." - .format(now, was)) - return not quiet - elif verbose is None: - return default - else: - return verbose - - class ProgressMeter(object): r"""Simple progress meter @@ -378,17 +325,15 @@ class ProgressMeter(object): """ def __init__(self, numsteps, format=None, interval=10, offset=1, - verbose=None, dynamic=True, - format_handling='auto', quiet=None): + verbose=True, dynamic=True, + format_handling='auto'): self.numsteps = numsteps self.interval = int(interval) self.offset = int(offset) + self.verbose = verbose self.dynamic = dynamic self.numouts = -1 - # The *quiet* keyword argument is deprecated. - self.verbose = _set_verbose(verbose, quiet, default=True) - if format is None: format = "Step {step:5d}/{numsteps} [{percentage:5.1f}%]" self.format_handler = _new_format diff --git a/testsuite/MDAnalysisTests/analysis/test_align.py b/testsuite/MDAnalysisTests/analysis/test_align.py index 8ef3eba270c..16390d7f039 100644 --- a/testsuite/MDAnalysisTests/analysis/test_align.py +++ b/testsuite/MDAnalysisTests/analysis/test_align.py @@ -209,7 +209,7 @@ def test_AlignTraj_step_works(self, universe, reference, tmpdir): reference.trajectory[-1] outfile = str(tmpdir.join('align_test.dcd')) # this shouldn't throw an exception - align.AlignTraj(universe, reference, filename=outfile, step=10).run() + align.AlignTraj(universe, reference, filename=outfile).run(step=10) def test_AlignTraj(self, universe, reference, tmpdir): reference.trajectory[-1] diff --git a/testsuite/MDAnalysisTests/analysis/test_base.py b/testsuite/MDAnalysisTests/analysis/test_base.py index 81c4089d291..fc4e522bf95 100644 --- a/testsuite/MDAnalysisTests/analysis/test_base.py +++ b/testsuite/MDAnalysisTests/analysis/test_base.py @@ -72,19 +72,19 @@ def test_default(u): def test_start(u): - an = FrameAnalysis(u.trajectory, start=20).run() + an = FrameAnalysis(u.trajectory).run(start=20) assert an.n_frames == len(u.trajectory) - 20 assert_equal(an.frames, list(range(20, len(u.trajectory)))) def test_stop(u): - an = FrameAnalysis(u.trajectory, stop=20).run() + an = FrameAnalysis(u.trajectory).run(stop=20) assert an.n_frames == 20 assert_equal(an.frames, list(range(20))) def test_step(u): - an = FrameAnalysis(u.trajectory, step=20).run() + an = FrameAnalysis(u.trajectory).run(step=20) assert an.n_frames == 5 assert_equal(an.frames, list(range(98))[::20]) @@ -92,7 +92,6 @@ def test_step(u): def test_verbose(u): a = FrameAnalysis(u.trajectory, verbose=True) assert a._verbose - assert not a._quiet def test_incomplete_defined_analysis(u): @@ -104,36 +103,29 @@ def test_old_api(u): OldAPIAnalysis(u.trajectory).run() -def test_start_stop_step_conversion(u): - an = FrameAnalysis(u.trajectory) - assert an.start == 0 - assert an.stop == u.trajectory.n_frames - assert an.step == 1 +def test_filter_baseanalysis_kwargs_VE(): + def bad_f(mobile, verbose=2): + pass + kwargs = {'step': 3, 'foo': None} -def test_filter_baseanalysis_kwargs(): - def bad_f(mobile, step=2): - pass + with pytest.raises(ValueError): + base._filter_baseanalysis_kwargs(bad_f, kwargs) + +def test_filter_baseanalysis_kwargs(): def good_f(mobile, ref): pass kwargs = {'step': 3, 'foo': None} - with pytest.raises(ValueError): - base._filter_baseanalysis_kwargs(bad_f, kwargs) - base_kwargs, kwargs = base._filter_baseanalysis_kwargs(good_f, kwargs) - assert 1 == len(kwargs) + assert 2 == len(kwargs) assert kwargs['foo'] == None - assert 5 == len(base_kwargs) - assert base_kwargs['start'] is None - assert base_kwargs['step'] == 3 - assert base_kwargs['stop'] is None - assert base_kwargs['quiet'] is None - assert base_kwargs['verbose'] is None + assert len(base_kwargs) == 1 + assert base_kwargs['verbose'] is False def simple_function(mobile): @@ -144,10 +136,10 @@ def test_AnalysisFromFunction(): u = mda.Universe(PSF, DCD) step = 2 ana1 = base.AnalysisFromFunction( - simple_function, mobile=u.atoms, step=step).run() - ana2 = base.AnalysisFromFunction(simple_function, u.atoms, step=step).run() + simple_function, mobile=u.atoms).run(step=step) + ana2 = base.AnalysisFromFunction(simple_function, u.atoms).run(step=step) ana3 = base.AnalysisFromFunction( - simple_function, u.trajectory, u.atoms, step=step).run() + simple_function, u.trajectory, u.atoms).run(step=step) results = [] for ts in u.trajectory[::step]: @@ -165,7 +157,7 @@ def test_analysis_class(): u = mda.Universe(PSF, DCD) step = 2 - ana = ana_class(u.atoms, step=step).run() + ana = ana_class(u.atoms).run(step=step) results = [] for ts in u.trajectory[::step]: @@ -190,3 +182,16 @@ def distance(a, b): with no_deprecated_call(): d = Distances(u.atoms[:10], u.atoms[10:20]).run() + +@pytest.mark.parametrize('param', ['start', 'stop', 'step']) +def test_runargs_deprecation(param): + u = mda.Universe(PSF, DCD) + + class NothingAnalysis(base.AnalysisBase): + def _single_frame(self): + self.results = [] + + with pytest.warns(DeprecationWarning): + ana = NothingAnalysis(u.trajectory, **{param: 10}) + + ana.run() diff --git a/testsuite/MDAnalysisTests/analysis/test_contacts.py b/testsuite/MDAnalysisTests/analysis/test_contacts.py index ee0b96ea819..ff21825385b 100644 --- a/testsuite/MDAnalysisTests/analysis/test_contacts.py +++ b/testsuite/MDAnalysisTests/analysis/test_contacts.py @@ -170,7 +170,7 @@ class TestContacts(object): def universe(): return mda.Universe(PSF, DCD) - def _run_Contacts(self, universe, **kwargs): + def _run_Contacts(self, universe, start=None, stop=None, step=None, **kwargs): acidic = universe.select_atoms(self.sel_acidic) basic = universe.select_atoms(self.sel_basic) return contacts.Contacts( @@ -178,7 +178,7 @@ def _run_Contacts(self, universe, **kwargs): selection=(self.sel_acidic, self.sel_basic), refgroup=(acidic, basic), radius=6.0, - **kwargs).run() + **kwargs).run(start=start, stop=stop, step=step) def test_startframe(self, universe): """test_startframe: TestContactAnalysis1: start frame set to 0 (resolution of diff --git a/testsuite/MDAnalysisTests/analysis/test_diffusionmap.py b/testsuite/MDAnalysisTests/analysis/test_diffusionmap.py index 842d3a4d778..accf1a3d3ba 100644 --- a/testsuite/MDAnalysisTests/analysis/test_diffusionmap.py +++ b/testsuite/MDAnalysisTests/analysis/test_diffusionmap.py @@ -56,8 +56,8 @@ def test_eg(dist, dmap): def test_dist_weights(u): backbone = u.select_atoms('backbone') weights_atoms = np.ones(len(backbone.atoms)) - dist = diffusionmap.DistanceMatrix(u, select='backbone', weights=weights_atoms, step=3) - dist.run() + dist = diffusionmap.DistanceMatrix(u, select='backbone', weights=weights_atoms) + dist.run(step=3) dmap = diffusionmap.DiffusionMap(dist) dmap.run() assert_array_almost_equal(dmap.eigenvalues, [1, 1, 1, 1], 4) @@ -69,8 +69,8 @@ def test_dist_weights(u): def test_different_steps(u): - dmap = diffusionmap.DiffusionMap(u, select='backbone', step=3) - dmap.run() + dmap = diffusionmap.DiffusionMap(u, select='backbone') + dmap.run(step=3) assert dmap._eigenvectors.shape == (4, 4) diff --git a/testsuite/MDAnalysisTests/analysis/test_dihedrals.py b/testsuite/MDAnalysisTests/analysis/test_dihedrals.py index 92b7ebb7864..c6e4eba69f1 100644 --- a/testsuite/MDAnalysisTests/analysis/test_dihedrals.py +++ b/testsuite/MDAnalysisTests/analysis/test_dihedrals.py @@ -51,7 +51,7 @@ def test_dihedral(self, atomgroup): "match test values") def test_dihedral_single_frame(self, atomgroup): - dihedral = Dihedral([atomgroup], start=5, stop=6).run() + dihedral = Dihedral([atomgroup]).run(start=5, stop=6) test_dihedral = [np.load(DihedralArray)[5]] assert_almost_equal(dihedral.angles, test_dihedral, 5, @@ -88,8 +88,8 @@ def test_ramachandran(self, universe, rama_ref_array): "match test values") def test_ramachandran_single_frame(self, universe, rama_ref_array): - rama = Ramachandran(universe.select_atoms("protein"), - start=5, stop=6).run() + rama = Ramachandran(universe.select_atoms("protein")).run( + start=5, stop=6) assert_almost_equal(rama.angles[0], rama_ref_array[5], 5, err_msg="error: dihedral angles should " @@ -140,7 +140,7 @@ def test_janin(self, universe, janin_ref_array): "match test values") def test_janin_single_frame(self, universe, janin_ref_array): - janin = Janin(universe.select_atoms("protein"), start=5, stop=6).run() + janin = Janin(universe.select_atoms("protein")).run(start=5, stop=6) assert_almost_equal(janin.angles[0], janin_ref_array[5], 3, err_msg="error: dihedral angles should " diff --git a/testsuite/MDAnalysisTests/analysis/test_pca.py b/testsuite/MDAnalysisTests/analysis/test_pca.py index 5609b653324..0716efc2bb3 100644 --- a/testsuite/MDAnalysisTests/analysis/test_pca.py +++ b/testsuite/MDAnalysisTests/analysis/test_pca.py @@ -81,16 +81,24 @@ def test_transform_different_atoms(pca, u): def test_transform_rerun(u): atoms = u.select_atoms('bynum 1-10') u.transfer_to_memory() - pca = PCA(u, select='bynum 1-10', stop=5) + pca = PCA(u, select='bynum 1-10').run(stop=5) dot = pca.transform(atoms) assert_equal(dot.shape, (98, atoms.n_atoms * 3)) +def test_pca_not_run(u): + atoms = u.select_atoms('bynum 1-10') + u.transfer_to_memory() + pca = PCA(u, select='bynum 1-10') + with pytest.raises(ValueError): + dot = pca.transform(atoms, stop=5) + + def test_no_frames(u): atoms = u.select_atoms(SELECTION) u.transfer_to_memory() with pytest.raises(ValueError): - PCA(u, select=SELECTION, stop=1).run() + PCA(u, select=SELECTION).run(stop=1) def test_transform(pca, u): diff --git a/testsuite/MDAnalysisTests/analysis/test_rms.py b/testsuite/MDAnalysisTests/analysis/test_rms.py index f92f1e38fd4..fa560cd8120 100644 --- a/testsuite/MDAnalysisTests/analysis/test_rms.py +++ b/testsuite/MDAnalysisTests/analysis/test_rms.py @@ -191,17 +191,15 @@ def test_progress_meter(self, capsys, universe): assert_equal(actual, expected) def test_rmsd(self, universe, correct_values): - RMSD = MDAnalysis.analysis.rms.RMSD(universe, select='name CA', - step=49) - RMSD.run() + RMSD = MDAnalysis.analysis.rms.RMSD(universe, select='name CA') + RMSD.run(step=49) assert_almost_equal(RMSD.rmsd, correct_values, 4, err_msg="error: rmsd profile should match" + "test values") def test_rmsd_unicode_selection(self, universe, correct_values): - RMSD = MDAnalysis.analysis.rms.RMSD(universe, select=u'name CA', - step=49) - RMSD.run() + RMSD = MDAnalysis.analysis.rms.RMSD(universe, select=u'name CA') + RMSD.run(step=49) assert_almost_equal(RMSD.rmsd, correct_values, 4, err_msg="error: rmsd profile should match" + "test values") @@ -216,7 +214,7 @@ def test_rmsd_atomgroup_selections(self, universe): def test_rmsd_single_frame(self, universe): RMSD = MDAnalysis.analysis.rms.RMSD(universe, select='name CA', - start=5, stop=6).run() + ).run(start=5, stop=6) single_frame = [[5, 6, 0.91544906]] assert_almost_equal(RMSD.rmsd, single_frame, 4, err_msg="error: rmsd profile should match" + @@ -226,7 +224,7 @@ def test_mass_weighted_and_save(self, universe, outfile, correct_values): # mass weighting the CA should give the same answer as weighing # equally because all CA have the same mass RMSD = MDAnalysis.analysis.rms.RMSD(universe, select='name CA', - step=49, weights='mass').run() + weights='mass').run(step=49) RMSD.save(outfile) assert_almost_equal(RMSD.rmsd, correct_values, 4, @@ -238,8 +236,7 @@ def test_mass_weighted_and_save(self, universe, outfile, correct_values): "saved test values") def test_custom_weighted(self, universe, correct_values_mass): - RMSD = MDAnalysis.analysis.rms.RMSD(universe, - step=49, weights="mass").run() + RMSD = MDAnalysis.analysis.rms.RMSD(universe, weights="mass").run(step=49) assert_almost_equal(RMSD.rmsd, correct_values_mass, 4, err_msg="error: rmsd profile should match" @@ -247,10 +244,9 @@ def test_custom_weighted(self, universe, correct_values_mass): def test_weights_mass_is_mass_weighted(self, universe): RMSD_mass = MDAnalysis.analysis.rms.RMSD(universe, - step=49, weights="mass").run() + weights="mass").run(step=49) RMSD_cust = MDAnalysis.analysis.rms.RMSD(universe, - step=49, - weights=universe.atoms.masses).run() + weights=universe.atoms.masses).run(step=49) assert_almost_equal(RMSD_mass.rmsd, RMSD_cust.rmsd, 4, err_msg="error: rmsd profiles should match for 'mass' " "and universe.atoms.masses") @@ -258,8 +254,7 @@ def test_weights_mass_is_mass_weighted(self, universe): def test_custom_weighted_list(self, universe, correct_values_mass): weights = universe.atoms.masses RMSD = MDAnalysis.analysis.rms.RMSD(universe, - step=49, - weights=list(weights)).run() + weights=list(weights)).run(step=49) assert_almost_equal(RMSD.rmsd, correct_values_mass, 4, err_msg="error: rmsd profile should match" + "test values") @@ -287,9 +282,8 @@ def test_rmsd_group_selections_wrong_weights(self, universe): def test_rmsd_group_selections(self, universe, correct_values_group): RMSD = MDAnalysis.analysis.rms.RMSD(universe, - groupselections= - ['backbone', 'name CA'], - step=49).run() + groupselections=['backbone', 'name CA'] + ).run(step=49) assert_almost_equal(RMSD.rmsd, correct_values_group, 4, err_msg="error: rmsd profile should match" "test values") @@ -301,13 +295,11 @@ def test_rmsd_backbone_and_group_selection(self, universe, reference=universe, select="backbone", groupselections=['backbone and resid 1:10', - 'backbone and resid 10:20'], - step=49).run() + 'backbone and resid 10:20']).run(step=49) assert_almost_equal( RMSD.rmsd, correct_values_backbone_group, 4, err_msg="error: rmsd profile should match test values") - def test_ref_length_unequal_len(self, universe): reference = MDAnalysis.Universe(PSF, DCD) reference.atoms = reference.atoms[:-1] @@ -352,16 +344,7 @@ def test_rmsf(self, universe): "values") def test_rmsf_single_frame(self, universe): - rmsfs = rms.RMSF(universe.select_atoms('name CA'), start=5, stop=6).run() - - assert_almost_equal(rmsfs.rmsf, 0, 5, - err_msg="error: rmsfs should all be zero") - - def test_rmsf_old_run(self, universe): - # start/stop arguments should be given at class initialization - with pytest.deprecated_call(): - rmsfs = rms.RMSF(universe.select_atoms('name CA')).run(start=5, - stop=6) + rmsfs = rms.RMSF(universe.select_atoms('name CA')).run(start=5, stop=6) assert_almost_equal(rmsfs.rmsf, 0, 5, err_msg="error: rmsfs should all be zero") diff --git a/testsuite/MDAnalysisTests/utils/test_log.py b/testsuite/MDAnalysisTests/utils/test_log.py index 3acc9bb9119..70f7200b3f0 100644 --- a/testsuite/MDAnalysisTests/utils/test_log.py +++ b/testsuite/MDAnalysisTests/utils/test_log.py @@ -29,7 +29,6 @@ import MDAnalysis import MDAnalysis.lib.log import pytest -from MDAnalysis.lib.log import _set_verbose def test_start_stop_logging(): @@ -143,43 +142,3 @@ def test_not_dynamic_ProgressMeter(buffer, step, percentage, n=51, interval=10): buffer.seek(0) output = "".join(buffer.readlines()) _assert_in(output, (template + '\n').format(**{'step': step, 'numsteps': n, 'percentage': percentage})) - - -class TestSetVerbose(object): - - @pytest.mark.parametrize('verbose, quiet, default, result', [ - (True, False, True, True), # Everything agrees verbose should be True - (False, True, False, False),# Everything agrees verbose should be False - (True, False, False, True), # Make sure the default does not overwrite the user choice - (False, True, True, False), # Make sure the default does not overwrite the user choice - (None, True, False, False), # Verbose is not provided - (None, False, False, True), # Verbose is not provided - ]) - def test__set_verbose_deprecated(self, verbose, quiet, default, result): - with pytest.deprecated_call(): - assert _set_verbose(verbose=verbose, quiet=quiet, default=default) == result - - @pytest.mark.parametrize('verbose, quiet, default, result', [ - (True, None, False, True), # Quiet is not provided - (False, None, False, False),# Quiet is not provided - (None, None, True, True), # Nothing is provided - (None, None, False, False), # Nothing is provided - ]) - def test__set_verbose(self, verbose, quiet, default, result): - assert _set_verbose(verbose=verbose, quiet=quiet, default=default) == result - - @pytest.mark.parametrize('verbose', (True, False)) - 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) - - - @pytest.mark.parametrize('verbose, quiet', [ - (None, True), - (False, True) - ]) - def test_warnings__set_verbose(self, verbose, quiet): - pytest.deprecated_call(_set_verbose, verbose=verbose, quiet=quiet)