diff --git a/package/CHANGELOG b/package/CHANGELOG index 4d32658309c..2f51f4c37e6 100644 --- a/package/CHANGELOG +++ b/package/CHANGELOG @@ -93,6 +93,8 @@ Changes * removes deprecated `as_Universe` function from MDAnalysis.core.universe, as a result :class:`MDAnalysis.analysis.leaflet.LeafletFinder` now only accepts Universes for its `universe` argument (Issue #2920) + * deprecated Python escape sequence usage has been fixed in our test suite, + and the test suite will now raise an error for this usage of `\` (PR #2885) * deprecated NumPy type aliases have been replaced with their actual types (see upstream NumPy PR 14882), and our pytest configuration will raise an error for any violation when testing with development NumPy builds diff --git a/package/MDAnalysis/analysis/data/filenames.py b/package/MDAnalysis/analysis/data/filenames.py index ffbee5a1a0b..8cde8217ee3 100644 --- a/package/MDAnalysis/analysis/data/filenames.py +++ b/package/MDAnalysis/analysis/data/filenames.py @@ -20,24 +20,26 @@ # MDAnalysis: A Toolkit for the Analysis of Molecular Dynamics Simulations. # J. Comput. Chem. 32 (2011), 2319--2327, doi:10.1002/jcc.21787 # -"""Analysis data files +r"""Analysis data files =================== :mod:`MDAnalysis.analysis.data` contains data files that are used as part of analysis. These can be experimental or theoretical data. Files are stored inside the package and made accessible via variables in :mod:`MDAnalysis.analysis.data.filenames`. These variables are documented -below, including references to the literature and where they are used -inside :mod:`MDAnalysis.analysis`. +below, including references to the literature and where they are used inside +:mod:`MDAnalysis.analysis`. Data files ---------- .. data:: Rama_ref - Reference Ramachandran histogram for :class:`MDAnalysis.analysis.dihedrals.Ramachandran`. - The data were calculated on a data set of 500 PDB structures taken from [Lovell2003]_. - This is a numpy array in the :math:`\phi` and :math:`psi` backbone dihedral angles. + Reference Ramachandran histogram for + :class:`MDAnalysis.analysis.dihedrals.Ramachandran`. The data were + calculated on a data set of 500 PDB structures taken from [Lovell2003]_. + This is a numpy array in the :math:`\phi` and :math:`\psi` backbone dihedral + angles. Load and plot it with :: @@ -55,8 +57,9 @@ .. data:: Janin_ref Reference Janin histogram for :class:`MDAnalysis.analysis.dihedrals.Janin`. - The data were calculated on a data set of 500 PDB structures taken from [Lovell2003]_. - This is a numpy array in the :math:`\chi_1` and :math:`chi_2` sidechain dihedral angles. + The data were calculated on a data set of 500 PDB structures taken from + [Lovell2003]_. This is a numpy array in the :math:`\chi_1` and + :math:`\chi_2` sidechain dihedral angles. Load and plot it with :: @@ -73,7 +76,7 @@ """ __all__ = [ - "Rama_ref", "Janin_ref" # reference plots for Ramachandran and Janin classes + "Rama_ref", "Janin_ref", # reference plots for Ramachandran and Janin classes ] from pkg_resources import resource_filename diff --git a/package/MDAnalysis/analysis/dihedrals.py b/package/MDAnalysis/analysis/dihedrals.py index cbbf0c19bfa..8243e8c1a9b 100644 --- a/package/MDAnalysis/analysis/dihedrals.py +++ b/package/MDAnalysis/analysis/dihedrals.py @@ -349,6 +349,7 @@ class Ramachandran(AnalysisBase): .. versionchanged:: 1.0.0 added c_name, n_name, ca_name, and check_protein keyword arguments + """ def __init__(self, atomgroup, c_name='C', n_name='N', ca_name='CA', @@ -422,8 +423,8 @@ def _conclude(self): def plot(self, ax=None, ref=False, **kwargs): """Plots data into standard Ramachandran plot. - Each time step in :attr:`Ramachandran.angles` is plotted onto - the same graph. + Each time step in :attr:`Ramachandran.angles` is plotted onto the same + graph. Parameters ---------- @@ -468,8 +469,8 @@ def plot(self, ax=None, ref=False, **kwargs): class Janin(Ramachandran): - r"""Calculate :math:`\chi_1` and :math:`\chi_2` dihedral angles of - selected residues. + r"""Calculate :math:`\chi_1` and :math:`\chi_2` dihedral angles of selected + residues. :math:`\chi_1` and :math:`\chi_2` angles will be calculated for each residue corresponding to `atomgroup` for each time step in the trajectory. A diff --git a/package/MDAnalysis/analysis/encore/clustering/ClusterCollection.py b/package/MDAnalysis/analysis/encore/clustering/ClusterCollection.py index 2a9b28daf51..df8be6817f4 100644 --- a/package/MDAnalysis/analysis/encore/clustering/ClusterCollection.py +++ b/package/MDAnalysis/analysis/encore/clustering/ClusterCollection.py @@ -101,8 +101,9 @@ def __init__(self, elem_list=None, centroid=None, idn=None, metadata=None): if metadata: for name, data in metadata.items(): if len(data) != self.size: - raise TypeError("Size of metadata having label \"{0}\"\ -is not equal to the number of cluster elmements".format(name)) + raise TypeError('Size of metadata having label "{0}"' + 'is not equal to the number of cluster ' + 'elements'.format(name)) self.add_metadata(name, data) def __iter__(self): @@ -119,8 +120,8 @@ def __len__(self): def add_metadata(self, name, data): if len(data) != self.size: - raise TypeError("Size of metadata is not equal to the number of\ - cluster elmements") + raise TypeError("Size of metadata is not equal to the number of" + "cluster elmements") self.metadata[name] = np.array(data) def __repr__(self): @@ -192,8 +193,9 @@ def __init__(self, elements=None, metadata=None): centroids = np.unique(elements_array) for i in centroids: if elements[i] != i: - raise ValueError("element {0}, which is a centroid, doesn't \ -belong to its own cluster".format(elements[i])) + raise ValueError("element {0}, which is a centroid, doesn't " + "belong to its own cluster".format( + elements[i])) for c in centroids: this_metadata = {} this_array = np.where(elements_array == c) diff --git a/package/MDAnalysis/analysis/encore/confdistmatrix.py b/package/MDAnalysis/analysis/encore/confdistmatrix.py index e5389c67ebf..483964d5594 100644 --- a/package/MDAnalysis/analysis/encore/confdistmatrix.py +++ b/package/MDAnalysis/analysis/encore/confdistmatrix.py @@ -171,7 +171,7 @@ def conformational_distance_matrix(ensemble, # Initialize workers. Simple worker doesn't perform fitting, # fitter worker does. indices = trm_indices((0, 0), (framesn - 1, framesn - 1)) - Parallel(n_jobs=n_jobs, verbose=verbose, require='sharedmem', + Parallel(n_jobs=n_jobs, verbose=verbose, require='sharedmem', max_nbytes=max_nbytes)(delayed(conf_dist_function)( np.int64(element), rmsd_coordinates, @@ -247,8 +247,8 @@ def set_rmsd_matrix_elements(tasks, coords, rmsdmat, weights, fit_coords=None, rotated_i.astype(np.float64), translated_j.astype(np.float64), coords[j].shape[0], weights, sumweights) else: - raise TypeError("Both fit_coords and fit_weights must be specified \ - if one of them is given") + raise TypeError("Both fit_coords and fit_weights must be specified " + "if one of them is given") def get_distance_matrix(ensemble, diff --git a/package/MDAnalysis/analysis/encore/covariance.py b/package/MDAnalysis/analysis/encore/covariance.py index 07e65c292bd..352d934f9d5 100644 --- a/package/MDAnalysis/analysis/encore/covariance.py +++ b/package/MDAnalysis/analysis/encore/covariance.py @@ -119,7 +119,7 @@ def shrinkage_covariance_estimator( coordinates, xmkt = np.average(x, axis=1) # Call maximum likelihood estimator (note the additional column) - sample = ml_covariance_estimator(np.hstack([x, xmkt[:, np.newaxis]]), 0) \ + sample = ml_covariance_estimator(np.hstack([x, xmkt[:, np.newaxis]]), 0)\ * (t-1)/float(t) # Split covariance matrix into components diff --git a/package/MDAnalysis/analysis/encore/similarity.py b/package/MDAnalysis/analysis/encore/similarity.py index 6f8bb4bdd3e..c338ba28ee3 100644 --- a/package/MDAnalysis/analysis/encore/similarity.py +++ b/package/MDAnalysis/analysis/encore/similarity.py @@ -469,30 +469,33 @@ def gen_kde_pdfs(embedded_space, ensemble_assignment, nensembles, def dimred_ensemble_similarity(kde1, resamples1, kde2, resamples2, ln_P1_exp_P1=None, ln_P2_exp_P2=None, ln_P1P2_exp_P1=None, ln_P1P2_exp_P2=None): - """ - Calculate the Jensen-Shannon divergence according the the - Dimensionality reduction method. In this case, we have continuous - probability densities, this we need to integrate over the measurable - space. The aim is to first calculate the Kullback-Liebler divergence, which - is defined as: + r"""Calculate the Jensen-Shannon divergence according the Dimensionality + reduction method. + + In this case, we have continuous probability densities, this we need to + integrate over the measurable space. The aim is to first calculate the + Kullback-Liebler divergence, which is defined as: .. math:: - D_{KL}(P(x) || Q(x)) = \\int_{-\\infty}^{\\infty}P(x_i) ln(P(x_i)/Q(x_i)) = \\langle{}ln(P(x))\\rangle{}_P - \\langle{}ln(Q(x))\\rangle{}_P - where the :math:`\\langle{}.\\rangle{}_P` denotes an expectation calculated + D_{KL}(P(x) || Q(x)) = + \int_{-\infty}^{\infty}P(x_i) ln(P(x_i)/Q(x_i)) = + \langle{}ln(P(x))\rangle{}_P - \langle{}ln(Q(x))\rangle{}_P + + where the :math:`\langle{}.\rangle{}_P` denotes an expectation calculated under the distribution P. We can, thus, just estimate the expectation - values of the components to get an estimate of dKL. - Since the Jensen-Shannon distance is actually more complex, we need to - estimate four expectation values: + values of the components to get an estimate of dKL. Since the + Jensen-Shannon distance is actually more complex, we need to estimate four + expectation values: .. math:: - \\langle{}log(P(x))\\rangle{}_P + \langle{}log(P(x))\rangle{}_P - \\langle{}log(Q(x))\\rangle{}_Q + \langle{}log(Q(x))\rangle{}_Q - \\langle{}log(0.5*(P(x)+Q(x)))\\rangle{}_P + \langle{}log(0.5*(P(x)+Q(x)))\rangle{}_P - \\langle{}log(0.5*(P(x)+Q(x)))\\rangle{}_Q + \langle{}log(0.5*(P(x)+Q(x)))\rangle{}_Q Parameters ---------- @@ -512,22 +515,22 @@ def dimred_ensemble_similarity(kde1, resamples1, kde2, resamples2, calculate the expected values according to 'Q' as detailed before. ln_P1_exp_P1 : float or None - Use this value for :math:`\\langle{}log(P(x))\\rangle{}_P`; if None, + Use this value for :math:`\langle{}log(P(x))\rangle{}_P`; if ``None``, calculate it instead ln_P2_exp_P2 : float or None - Use this value for :math:`\\langle{}log(Q(x))\\rangle{}_Q`; if - None, calculate it instead + Use this value for :math:`\langle{}log(Q(x))\rangle{}_Q`; if + ``None``, calculate it instead ln_P1P2_exp_P1 : float or None Use this value for - :math:`\\langle{}log(0.5*(P(x)+Q(x)))\\rangle{}_P`; - if None, calculate it instead + :math:`\langle{}log(0.5*(P(x)+Q(x)))\rangle{}_P`; + if ``None``, calculate it instead ln_P1P2_exp_P2 : float or None Use this value for - :math:`\\langle{}log(0.5*(P(x)+Q(x)))\\rangle{}_Q`; - if None, calculate it instead + :math:`\langle{}log(0.5*(P(x)+Q(x)))\rangle{}_Q`; + if ``None``, calculate it instead Returns ------- @@ -720,11 +723,10 @@ def hes(ensembles, estimate_error=False, bootstrapping_samples=100, calc_diagonal=False): - """ + r"""Calculates the Harmonic Ensemble Similarity (HES) between ensembles. - Calculates the Harmonic Ensemble Similarity (HES) between ensembles using - the symmetrized version of Kullback-Leibler divergence as described - in [Tiberti2015]_. + The HES is calculated with the symmetrized version of Kullback-Leibler + divergence as described in [Tiberti2015]_. Parameters ---------- @@ -766,13 +768,13 @@ def hes(ensembles, symmetrized version of Kullback-Leibler divergence defined as: .. math:: - D_{KL}(P(x) || Q(x)) = \\int_{-\\infty}^{\\infty}P(x_i) - ln(P(x_i)/Q(x_i)) = \\langle{}ln(P(x))\\rangle{}_P - - \\langle{}ln(Q(x))\\rangle{}_P + D_{KL}(P(x) || Q(x)) = + \int_{-\infty}^{\infty}P(x_i) ln(P(x_i)/Q(x_i)) = + \langle{}ln(P(x))\rangle{}_P - \langle{}ln(Q(x))\rangle{}_P - where the :math:`\\langle{}.\\rangle{}_P` denotes an expectation - calculated under the distribution P. + where the :math:`\langle{}.\rangle{}_P` denotes an expectation + calculated under the distribution :math:`P`. For each ensemble, the mean conformation is estimated as the average over the ensemble, and the covariance matrix is calculated by default using a @@ -802,16 +804,17 @@ def hes(ensembles, [ 38279683.95892926 0. ]] - You can use the align=True option to align the ensembles first. This will + You can use the ``align=True`` option to align the ensembles first. This will align everything to the current timestep in the first ensemble. Note that - this changes the ens1 and ens2 objects: + this changes the ``ens1`` and ``ens2`` objects: >>> print(encore.hes([ens1, ens2], align=True)[0]) [[ 0. 6880.34140106] [ 6880.34140106 0. ]] Alternatively, for greater flexibility in how the alignment should be done - you can call use an AlignTraj object manually: + you can call use an :class:`~MDAnalysis.analysis.align.AlignTraj` object + manually: >>> from MDAnalysis.analysis import align >>> align.AlignTraj(ens1, ens1, select="name CA", in_memory=True).run() @@ -820,9 +823,10 @@ def hes(ensembles, [[ 0. 7032.19607004] [ 7032.19607004 0. ]] + .. versionchanged:: 1.0.0 - hes doesn't accept the *details* argument anymore, it always returns the - details of the calculation instead, in the form of a dictionary + ``hes`` doesn't accept the `details` argument anymore, it always returns + the details of the calculation instead, in the form of a dictionary """ diff --git a/package/MDAnalysis/analysis/encore/utils.py b/package/MDAnalysis/analysis/encore/utils.py index a41ebe30174..399eedd320c 100644 --- a/package/MDAnalysis/analysis/encore/utils.py +++ b/package/MDAnalysis/analysis/encore/utils.py @@ -190,7 +190,7 @@ def __str__(self): class ParallelCalculation(object): - """ + r""" Generic parallel calculation class. Can use arbitrary functions, arguments to functions and kwargs to functions. @@ -279,7 +279,7 @@ def worker(self, q, results): results.put((i, self.functions[i](*self.args[i], **self.kwargs[i]))) def run(self): - """ + r""" Run parallel calculation. Returns diff --git a/package/MDAnalysis/analysis/gnm.py b/package/MDAnalysis/analysis/gnm.py index aae83c9c0f2..65c5356f73c 100644 --- a/package/MDAnalysis/analysis/gnm.py +++ b/package/MDAnalysis/analysis/gnm.py @@ -352,7 +352,7 @@ def run(self, start=None, stop=None, step=None): class closeContactGNMAnalysis(GNMAnalysis): - """GNMAnalysis only using close contacts. + r"""GNMAnalysis only using close contacts. This is a version of the GNM where the Kirchoff matrix is constructed from the close contacts between individual atoms diff --git a/package/MDAnalysis/analysis/hole2/hole.py b/package/MDAnalysis/analysis/hole2/hole.py index b8532ebdd41..d3f0faf9edc 100644 --- a/package/MDAnalysis/analysis/hole2/hole.py +++ b/package/MDAnalysis/analysis/hole2/hole.py @@ -195,12 +195,12 @@ def hole(pdbfile, dcd_iniskip=0, dcd_step=1, keep_files=True): - """Run :program:`hole` on a single frame or a DCD trajectory. + r"""Run :program:`hole` on a single frame or a DCD trajectory. :program:`hole` is part of the HOLE_ suite of programs. It is used to analyze channels and cavities in proteins, especially ion channels. - Only a subset of all `HOLE control parameters `_ + Only a subset of all `HOLE control parameters `_ is supported and can be set with keyword arguments. Parameters @@ -238,7 +238,7 @@ def hole(pdbfile, path to the file specifying van der Waals radii for each atom. If set to ``None``, then a set of default radii, :data:`SIMPLE2_RAD`, is used (an extension of ``simple.rad`` from - the HOLE distribution). + the HOLE distribution). executable: str, optional Path to the :program:`hole` executable. (e.g. ``~/hole2/exe/hole``). If @@ -291,13 +291,13 @@ def hole(pdbfile, (1,0,0), Y axis (0,1,0) or Z axis (0,0,1). If the structure is not aligned on one of these axis the results will clearly be approximate. If a guess is used then results should be carefully - checked. + checked. random_seed : int, optional integer number to start the random number generator. By default, :program:`hole` will use the time of the day. For reproducible runs (e.g., for testing) set ``random_seed`` - to an integer. + to an integer. ignore_residues : array_like, optional sequence of three-letter residues that are not taken into account during the calculation; wildcards are *not* @@ -326,7 +326,7 @@ def hole(pdbfile, initially. dcd_step : int, optional step size for going through the trajectory (skips ``dcd_step-1`` - frames). + frames). keep_files : bool, optional Whether to keep the HOLE output files and possible temporary symlinks after running the function. Default: ``True`` @@ -407,14 +407,13 @@ def hole(pdbfile, class HoleAnalysis(AnalysisBase): - - """ + r""" Run :program:`hole` on a trajectory. :program:`hole` is part of the HOLE_ suite of programs. It is used to analyze channels and cavities in proteins, especially ion channels. - Only a subset of all `HOLE control parameters `_ + Only a subset of all `HOLE control parameters `_ is supported and can be set with keyword arguments. This class creates temporary PDB files for each frame and runs HOLE on @@ -477,7 +476,7 @@ class HoleAnalysis(AnalysisBase): (1,0,0), Y axis (0,1,0) or Z axis (0,0,1). If the structure is not aligned on one of these axis the results will clearly be approximate. If a guess is used then results should be carefully - checked. + checked. sample : float, optional distance of sample points in Å. Specifies the distance between the planes used in the HOLE @@ -485,13 +484,13 @@ class HoleAnalysis(AnalysisBase): purposes. However, if you wish to visualize a very tight constriction then specify a smaller value. This value determines how many points in the pore profile are - calculated. + calculated. end_radius : float, optional Radius in Å, which is considered to be the end of the pore. This keyword can be used to specify the radius above which the program regards a result as indicating that the end of the pore has been reached. This may need to be increased for large channels, - or reduced for small channels. + or reduced for small channels. output_level : int, optional Determines the output of output in the ``outfile``. For automated processing, this must be < 3. @@ -508,10 +507,10 @@ class HoleAnalysis(AnalysisBase): supported. Note that all residues must have 3 letters. Pad with space on the right-hand side if necessary. prefix: str, optional - Prefix for HOLE output files. + Prefix for HOLE output files. write_input_files: bool, optional Whether to write out the input HOLE text as files. - Files are called `hole.inp`. + Files are called `hole.inp`. Returns @@ -783,7 +782,7 @@ def create_vmd_surface(self, filename='hole.vmd', dot_density=15, source hole.vmd The level of detail is determined by ``dot_density``. - The surface will be colored by ``no_water_color``, ``one_water_color``, and + The surface will be colored by ``no_water_color``, ``one_water_color``, and ``double_water_color``. You can change these in the Tk Console:: @@ -805,14 +804,14 @@ def create_vmd_surface(self, filename='hole.vmd', dot_density=15, (few dots per sphere) and 35 (many dots per sphere). no_water_color: str, optional - Color of the surface where the pore radius is too tight for a + Color of the surface where the pore radius is too tight for a water molecule. one_water_color: str, optional Color of the surface where the pore can fit one water molecule. double_water_color: str, optional - Color of the surface where the radius is at least double the + Color of the surface where the radius is at least double the minimum radius for one water molecule. @@ -859,7 +858,7 @@ def create_vmd_surface(self, filename='hole.vmd', dot_density=15, frames.append('set triangles({i}) '.format(i=i) + tri) trinorms = '\n'.join(frames) - vmd_1 = vmd_script_array.format(no_water_color=no_water_color, + vmd_1 = vmd_script_array.format(no_water_color=no_water_color, one_water_color=one_water_color, double_water_color=double_water_color) vmd_text = vmd_1 + trinorms + vmd_script_function @@ -868,7 +867,7 @@ def create_vmd_surface(self, filename='hole.vmd', dot_density=15, f.write(vmd_text) return filename - + def min_radius(self): """Return the minimum radius over all profiles as a function of q""" if not self.profiles: @@ -948,7 +947,7 @@ def plot(self, frames=None, linestyle='-', y_shift=0.0, label=True, ax=None, legend_loc='best', **kwargs): - """Plot HOLE profiles :math:`R(\zeta)` in a 1D graph. + r"""Plot HOLE profiles :math:`R(\zeta)` in a 1D graph. Lines are colored according to the specified ``color`` or drawn from the color map ``cmap``. One line is @@ -1016,7 +1015,7 @@ def plot3D(self, frames=None, color=None, cmap='viridis', linestyle='-', ax=None, r_max=None, ylabel='Frames', **kwargs): - """Stacked 3D graph of profiles :math:`R(\zeta)`. + r"""Stacked 3D graph of profiles :math:`R(\zeta)`. Lines are colored according to the specified ``color`` or drawn from the color map ``cmap``. One line is @@ -1122,7 +1121,7 @@ def over_order_parameters(self, order_parameters, frames=None): 'or a filename with array data ' 'that can be read by np.loadtxt') raise ValueError(msg.format(order_parameters)) - + order_parameters = np.asarray(order_parameters) @@ -1298,13 +1297,13 @@ def bin_radii(self, frames=None, bins=100, range=None): def histogram_radii(self, aggregator=np.mean, frames=None, bins=100, range=None): """Histograms the pore radii into bins by reaction coordinate, - aggregate the radii with an `aggregator` function, and returns the + aggregate the radii with an `aggregator` function, and returns the aggregated radii and bin edges. Parameters ---------- aggregator: callable, optional - this function must take an iterable of floats and return a + this function must take an iterable of floats and return a single value. Default: np.mean frames: int or iterable of ints, optional @@ -1418,7 +1417,7 @@ def plot3D_order_parameters(self, order_parameters, r_max=None, ylabel=r'Order parameter', **kwargs): - """Plot HOLE radii over order parameters as a 3D graph. + r"""Plot HOLE radii over order parameters as a 3D graph. Lines are colored according to the specified ``color`` or drawn from the color map ``cmap``. One line is diff --git a/package/MDAnalysis/analysis/hole2/templates.py b/package/MDAnalysis/analysis/hole2/templates.py index 855104aaddb..cc4182f7b11 100644 --- a/package/MDAnalysis/analysis/hole2/templates.py +++ b/package/MDAnalysis/analysis/hole2/templates.py @@ -45,7 +45,7 @@ #: *Simple* - Only use one value for each element C O H etc. #: Added radii for K+, NA+, CL- (Pauling hydration radius from Hille 2002). #: The data file can be written with the convenience function :func:`write_simplerad2`. -SIMPLE2_RAD = """ +SIMPLE2_RAD = r""" remark: Time-stamp: <2005-11-21 13:57:55 oliver> [OB] remark: van der Waals radii: AMBER united atom remark: from Weiner et al. (1984), JACS, vol 106 pp765-768 @@ -111,7 +111,7 @@ array set triangles {{}} """ -vmd_script_function = """ +vmd_script_function = r""" global vmd_frame; trace add variable vmd_frame([molinfo top]) write drawFrame @@ -134,6 +134,6 @@ } } -drawFrame 0 0 0 +drawFrame 0 0 0 """ diff --git a/package/MDAnalysis/analysis/hole2/utils.py b/package/MDAnalysis/analysis/hole2/utils.py index 317060ce6d2..a13aeab42c9 100644 --- a/package/MDAnalysis/analysis/hole2/utils.py +++ b/package/MDAnalysis/analysis/hole2/utils.py @@ -22,8 +22,9 @@ # -"""HOLE Analysis --- :mod:`MDAnalysis.analysis.hole2.helper` -===================================================================================== +""" +HOLE Analysis --- :mod:`MDAnalysis.analysis.hole2.helper` +========================================================= :Author: Lily Wang :Year: 2020 @@ -130,10 +131,10 @@ def check_and_fix_long_filename(filename, tmpdir=os.path.curdir, fd, newname = tempfile.mkstemp(suffix=ext, dir=dirname) os.close(fd) os.unlink(newname) - + if len(newname) > max_length: newname = os.path.relpath(newname) - + if len(newname) <= max_length: os.symlink(filename, newname) msg = 'Using symlink: {} -> {}' @@ -173,13 +174,13 @@ def set_up_hole_input(pdbfile, are read. infile_text: str, optional - HOLE input text or template. If set to ``None``, the function will + HOLE input text or template. If set to ``None``, the function will create the input text from the other parameters. Default: ``None`` infile: str, optional - File to write the HOLE input text for later inspection. If set to - ``None``, the input text is not written out. + File to write the HOLE input text for later inspection. If set to + ``None``, the input text is not written out. Default: ``None`` sphpdb_file : str, optional @@ -194,7 +195,7 @@ def set_up_hole_input(pdbfile, distance of particular atoms from the sphere-centre line. .sph files can be used to produce molecular graphical output from a hole run, by using the - :program:`sph_process` program to read the .sph file. + :program:`sph_process` program to read the .sph file. Default: 'hole.sph' vdwradii_file: str, optional @@ -204,7 +205,7 @@ def set_up_hole_input(pdbfile, the HOLE distribution). Default: ``None`` tmpdir: str, optional - The temporary directory that files can be symlinked to, to shorten + The temporary directory that files can be symlinked to, to shorten the path name. HOLE can only read filenames up to a certain length. Default: current working directory @@ -215,13 +216,13 @@ def set_up_hole_input(pdbfile, purposes. However, if you wish to visualize a very tight constriction then specify a smaller value. This value determines how many points in the pore profile are - calculated. Default: 0.2 + calculated. Default: 0.2 end_radius : float, optional Radius in Å, which is considered to be the end of the pore. This keyword can be used to specify the radius above which the program regards a result as indicating that the end of the pore - has been reached. This may need to be increased for large channels, + has been reached. This may need to be increased for large channels, or reduced for small channels. Default: 22.0 cpoint : array_like, 'center_of_geometry' or None, optional @@ -249,7 +250,7 @@ def set_up_hole_input(pdbfile, cvect : array_like, optional Search direction, should be parallel to the pore axis, - e.g. ``[0,0,1]`` for the z-axis. + e.g. ``[0,0,1]`` for the z-axis. If this keyword is ``None`` (the default), then HOLE attempts to guess where the channel will be. The procedure assumes that the channel is reasonably symmetric. The guess will be either along the X axis @@ -261,15 +262,15 @@ def set_up_hole_input(pdbfile, random_seed : int, optional integer number to start the random number generator. By default, - :program:`hole` will use the time of the day. - For reproducible runs (e.g., for testing) set ``random_seed`` + :program:`hole` will use the time of the day. + For reproducible runs (e.g., for testing) set ``random_seed`` to an integer. Default: ``None`` ignore_residues : array_like, optional sequence of three-letter residues that are not taken into account during the calculation; wildcards are *not* - supported. Note that all residues must have 3 letters. Pad - with space on the right-hand side if necessary. + supported. Note that all residues must have 3 letters. Pad + with space on the right-hand side if necessary. Default: {}. output_level : int, optional @@ -281,7 +282,7 @@ def set_up_hole_input(pdbfile, 2: Ditto plus no graph type output - only leaving minimum radius and conductance calculations. 3: All text output other than input card mirroring and error messages - turned off. + turned off. Default: 0 dcd : str, optional @@ -380,7 +381,7 @@ def run_hole(outfile, infile_text, executable): outfile: str Output file name infile_text: str - HOLE input text + HOLE input text (typically generated by :func:`set_up_hole_input`) executable: str HOLE executable @@ -487,19 +488,19 @@ def create_vmd_surface(sphpdb='hole.sph', sphpdb: str, optional sphpdb file to read. Default: 'hole.sph' filename: str, optional - output VMD surface file. If ``None``, a temporary file + output VMD surface file. If ``None``, a temporary file is generated. Default: ``None`` sph_process: str, optional Executable for ``sph_process`` program. Default: 'sph_process' sos_triangle: str, optional - Executable for ``sos_triangle`` program. Default: 'sos_triangle' + Executable for ``sos_triangle`` program. Default: 'sos_triangle' dot_density: int, optional density of facets for generating a 3D pore representation. The number controls the density of dots that will be used. - A sphere of dots is placed on each centre determined in the - Monte Carlo procedure. The actual number of dots written is - controlled by ``dot_density`` and the ``sample`` level of the - original analysis. ``dot_density`` should be set between 5 + A sphere of dots is placed on each centre determined in the + Monte Carlo procedure. The actual number of dots written is + controlled by ``dot_density`` and the ``sample`` level of the + original analysis. ``dot_density`` should be set between 5 (few dots per sphere) and 35 (many dots per sphere). Default: 15 diff --git a/package/MDAnalysis/coordinates/H5MD.py b/package/MDAnalysis/coordinates/H5MD.py index a49594282d5..d77a06c1a38 100644 --- a/package/MDAnalysis/coordinates/H5MD.py +++ b/package/MDAnalysis/coordinates/H5MD.py @@ -236,7 +236,7 @@ def dimensions(self, box): class H5MDReader(base.ReaderBase): - """Reader for the H5MD format. + r"""Reader for the H5MD format. See `h5md documentation `_ for a detailed overview of the H5MD file format. diff --git a/package/MDAnalysis/core/groups.py b/package/MDAnalysis/core/groups.py index 5359f11bf71..0264617c469 100644 --- a/package/MDAnalysis/core/groups.py +++ b/package/MDAnalysis/core/groups.py @@ -121,7 +121,7 @@ def _unpickle_uag(basepickle, selections, selstrs): def make_classes(): - """Make a fresh copy of all classes + r"""Make a fresh copy of all classes Returns ------- @@ -129,7 +129,6 @@ def make_classes(): to serve as bases for :class:`~MDAnalysis.core.universe.Universe`\ -specific MDA container classes. Another with the final merged versions of those classes. The classes themselves are used as hashing keys. - """ bases = {} classes = {} @@ -356,7 +355,7 @@ def __getattr__(self, attr): raise NoDataError(err.format(selfcls=selfcls, attrname=attrname, topattr=topattr)) - + else: clean = attr.lower().replace('_', '') err = '{selfcls} has no attribute {attr}. '.format(selfcls=selfcls, @@ -410,7 +409,7 @@ def wrapped(self, other): class GroupBase(_MutableBase): - """Base class from which a :class:`<~MDAnalysis.core.universe.Universe`\ 's + r"""Base class from which a :class:`<~MDAnalysis.core.universe.Universe`\ 's Group class is built. Instances of :class:`GroupBase` provide the following operations that @@ -525,7 +524,7 @@ def __getitem__(self, item): # subclasses, such as UpdatingAtomGroup, to control the class # resulting from slicing. return self._derived_class(self.ix[item], self.universe) - + def __getattr__(self, attr): selfcls = type(self).__name__ if attr in _TOPOLOGY_ATTRS: @@ -921,7 +920,7 @@ def center_of_geometry(self, pbc=False, compound='group', unwrap=False): @warn_if_not_unique def accumulate(self, attribute, function=np.sum, compound='group'): - """Accumulates the attribute associated with (compounds of) the group. + r"""Accumulates the attribute associated with (compounds of) the group. Accumulates the attribute of :class:`Atoms` in the group. The accumulation per :class:`Residue`, :class:`Segment`, molecule, @@ -1347,7 +1346,7 @@ def pack_into_box(self, box=None, inplace=True): return self.wrap(box=box, inplace=inplace) def wrap(self, compound="atoms", center="com", box=None, inplace=True): - """Shift the contents of this group back into the primary unit cell + r"""Shift the contents of this group back into the primary unit cell according to periodic boundary conditions. Specifying a `compound` will keep the :class:`Atoms` in each @@ -1368,8 +1367,8 @@ def wrap(self, compound="atoms", center="com", box=None, inplace=True): box : array_like, optional The unitcell dimensions of the system, which can be orthogonal or triclinic and must be provided in the same format as returned by - :attr:`MDAnalysis.coordinates.base.Timestep.dimensions`:\n - ``[lx, ly, lz, alpha, beta, gamma]``.\n + :attr:`MDAnalysis.coordinates.base.Timestep.dimensions`: + ``[lx, ly, lz, alpha, beta, gamma]``. If ``None``, uses the dimensions of the current time step. inplace: bool, optional @@ -1406,14 +1405,14 @@ def wrap(self, compound="atoms", center="com", box=None, inplace=True): .. math:: - x_i' = x_i - \left\lfloor\\frac{x_i}{L_i}\\right\\rfloor\,. + x_i' = x_i - \left\lfloor\frac{x_i}{L_i}\right\rfloor\,. When specifying a `compound`, the translation is calculated based on each compound. The same translation is applied to all atoms within this compound, meaning it will not be broken by the shift. This might however mean that not all atoms of a compound will be inside the unit cell after wrapping, but rather will be the center of - the compound.\n + the compound. Be aware of the fact that only atoms *belonging to the group* will be taken into account! @@ -1548,7 +1547,7 @@ def wrap(self, compound="atoms", center="com", box=None, inplace=True): return positions def unwrap(self, compound='fragments', reference='com', inplace=True): - """Move atoms of this group so that bonds within the + r"""Move atoms of this group so that bonds within the group's compounds aren't split across periodic boundaries. This function is most useful when atoms have been packed into the @@ -1601,7 +1600,7 @@ def unwrap(self, compound='fragments', reference='com', inplace=True): ---- Be aware of the fact that only atoms *belonging to the group* will be unwrapped! If you want entire molecules to be unwrapped, make sure - that all atoms of these molecules are part of the group.\n + that all atoms of these molecules are part of the group. An AtomGroup containing all atoms of all fragments in the group ``ag`` can be created with:: @@ -2486,7 +2485,7 @@ def unique(self): @property def positions(self): - """Coordinates of the :class:`Atoms` in the :class:`AtomGroup`. + r"""Coordinates of the :class:`Atoms` in the :class:`AtomGroup`. A :class:`numpy.ndarray` with :attr:`~numpy.ndarray.shape`\ ``=(``\ :attr:`~AtomGroup.n_atoms`\ ``, 3)`` @@ -2524,7 +2523,7 @@ def positions(self, values): @property def velocities(self): - """Velocities of the :class:`Atoms` in the :class:`AtomGroup`. + r"""Velocities of the :class:`Atoms` in the :class:`AtomGroup`. A :class:`numpy.ndarray` with :attr:`~numpy.ndarray.shape`\ ``=(``\ :attr:`~AtomGroup.n_atoms`\ ``, 3)`` @@ -2553,7 +2552,7 @@ def velocities(self, values): @property def forces(self): - """Forces on each :class:`Atom` in the :class:`AtomGroup`. + r"""Forces on each :class:`Atom` in the :class:`AtomGroup`. A :class:`numpy.ndarray` with :attr:`~numpy.ndarray.shape`\ ``=(``\ :attr:`~AtomGroup.n_atoms`\ ``, 3)`` @@ -3591,7 +3590,7 @@ def unique(self): @functools.total_ordering class ComponentBase(_MutableBase): - """Base class from which a :class:`~MDAnalysis.core.universe.Universe`\ 's + r"""Base class from which a :class:`~MDAnalysis.core.universe.Universe`\ 's Component class is built. Components are the individual objects that are found in Groups. diff --git a/package/MDAnalysis/core/selection.py b/package/MDAnalysis/core/selection.py index dfb25e1c44a..d3589caf6d4 100644 --- a/package/MDAnalysis/core/selection.py +++ b/package/MDAnalysis/core/selection.py @@ -297,7 +297,7 @@ def __init__(self, parser, tokens): self.inRadius = float(tokens.popleft()) self.exRadius = float(tokens.popleft()) self.sel = parser.parse_expression(self.precedence) - + @return_empty_on_apply def apply(self, group): indices = [] @@ -604,8 +604,8 @@ class AltlocSelection(StringSelection): class AromaticSelection(Selection): """Select aromatic atoms. - - Aromaticity is available in the `aromaticities` attribute and is made + + Aromaticity is available in the `aromaticities` attribute and is made available through RDKit""" token = 'aromatic' field = 'aromaticities' @@ -691,7 +691,7 @@ def __init__(self, parser, tokens): lowers = [] for val in values: - m1 = re.match("(\d+)(\w?)$", val) + m1 = re.match(r"(\d+)(\w?)$", val) if not m1 is None: res = m1.groups() lower = int(res[0]), res[1] @@ -699,7 +699,7 @@ def __init__(self, parser, tokens): else: # check if in appropriate format 'lower:upper' or 'lower-upper' # each val is one or more digits, maybe a letter - selrange = re.match("(\d+)(\w?)[:-](\d+)(\w?)", val) + selrange = re.match(r"(\d+)(\w?)[:-](\d+)(\w?)", val) if selrange is None: # re.match returns None on failure raise ValueError("Failed to parse value: {0}".format(val)) res = selrange.groups() @@ -811,7 +811,7 @@ def __init__(self, parser, tokens): upper = None except ValueError: # check if in appropriate format 'lower:upper' or 'lower-upper' - selrange = re.match("(\d+)[:-](\d+)", val) + selrange = re.match(r"(\d+)[:-](\d+)", val) if not selrange: errmsg = f"Failed to parse number: {val}" raise ValueError(errmsg) from None @@ -1207,7 +1207,7 @@ class SameSelection(Selection): Selects all atoms that have the same subkeyword value as any atom in selection .. versionchanged:: 1.0.0 - Map :code:`"residue"` to :code:`"resindices"` and :code:`"segment"` to + Map :code:`"residue"` to :code:`"resindices"` and :code:`"segment"` to :code:`"segindices"` (see #2669 and #2672) """ diff --git a/package/MDAnalysis/core/topologyattrs.py b/package/MDAnalysis/core/topologyattrs.py index a591f09cb3a..8fee00e53a8 100644 --- a/package/MDAnalysis/core/topologyattrs.py +++ b/package/MDAnalysis/core/topologyattrs.py @@ -21,7 +21,7 @@ # J. Comput. Chem. 32 (2011), 2319--2327, doi:10.1002/jcc.21787 # -"""\ +r""" Topology attribute objects --- :mod:`MDAnalysis.core.topologyattrs` =================================================================== @@ -31,6 +31,7 @@ TopologyAttrs are used to contain attributes such as atom names or resids. These are usually read by the TopologyParser. """ + import Bio.Seq import Bio.SeqRecord from collections import defaultdict @@ -476,7 +477,7 @@ def _gen_initial_values(na, nr, ns): class _AtomStringAttr(AtomAttr): def __init__(self, vals, guessed=False): self._guessed = guessed - + self.namedict = dict() # maps str to nmidx name_lookup = [] # maps idx to str # eg namedict['O'] = 5 & name_lookup[5] = 'O' @@ -589,7 +590,7 @@ def phi_selection(residue, c_name='C', n_name='N', ca_name='CA'): transplants[Residue].append(('phi_selection', phi_selection)) def phi_selections(residues, c_name='C', n_name='N', ca_name='CA'): - """Select list of AtomGroups corresponding to the phi protein + """Select list of AtomGroups corresponding to the phi protein backbone dihedral C'-N-CA-C. Parameters @@ -708,13 +709,13 @@ def psi_selection(residue, c_name='C', n_name='N', ca_name='CA'): transplants[Residue].append(('psi_selection', psi_selection)) def _get_next_residues_by_resid(residues): - """Select list of Residues corresponding to the next resid for each + """Select list of Residues corresponding to the next resid for each residue in `residues`. Returns ------- List of Residues - List of the next residues in the Universe, by resid and segid. + List of the next residues in the Universe, by resid and segid. If not found, the corresponding item in the list is ``None``. .. versionadded:: 1.0.0 @@ -748,13 +749,13 @@ def _get_next_residues_by_resid(residues): _get_next_residues_by_resid)) def _get_prev_residues_by_resid(residues): - """Select list of Residues corresponding to the previous resid for each + """Select list of Residues corresponding to the previous resid for each residue in `residues`. Returns ------- List of Residues - List of the previous residues in the Universe, by resid and segid. + List of the previous residues in the Universe, by resid and segid. If not found, the corresponding item in the list is ``None``. .. versionadded:: 1.0.0 @@ -780,7 +781,7 @@ def _get_prev_residues_by_resid(residues): _get_prev_residues_by_resid)) def psi_selections(residues, c_name='C', n_name='N', ca_name='CA'): - """Select list of AtomGroups corresponding to the psi protein + """Select list of AtomGroups corresponding to the psi protein backbone dihedral N-CA-C-N'. Parameters @@ -796,7 +797,7 @@ def psi_selections(residues, c_name='C', n_name='N', ca_name='CA'): ------- List of AtomGroups 4-atom selections in the correct order. If no N' found in the - following residue (by resid) then the corresponding item in the + following residue (by resid) then the corresponding item in the list is ``None``. .. versionadded:: 1.0.0 @@ -884,7 +885,7 @@ def omega_selection(residue, c_name='C', n_name='N', ca_name='CA'): transplants[Residue].append(('omega_selection', omega_selection)) def omega_selections(residues, c_name='C', n_name='N', ca_name='CA'): - """Select list of AtomGroups corresponding to the omega protein + """Select list of AtomGroups corresponding to the omega protein backbone dihedral CA-C-N'-CA'. omega describes the -C-N- peptide bond. Typically, it is trans (180 @@ -904,7 +905,7 @@ def omega_selections(residues, c_name='C', n_name='N', ca_name='CA'): ------- List of AtomGroups 4-atom selections in the correct order. If no C' found in the - previous residue (by resid) then the corresponding item in the + previous residue (by resid) then the corresponding item in the list is ``None``. .. versionadded:: 1.0.0 @@ -973,7 +974,7 @@ def chi1_selection(residue, n_name='N', ca_name='CA', cb_name='CB', def chi1_selections(residues, n_name='N', ca_name='CA', cb_name='CB', cg_name='CG'): - """Select list of AtomGroups corresponding to the chi1 sidechain dihedral + """Select list of AtomGroups corresponding to the chi1 sidechain dihedral N-CA-CB-CG. Parameters @@ -1139,7 +1140,7 @@ def get_segments(self, sg): @warn_if_not_unique @check_pbc_and_unwrap def center_of_mass(group, pbc=False, compound='group', unwrap=False): - """Center of mass of (compounds of) the group. + r"""Center of mass of (compounds of) the group. Computes the center of mass of :class:`Atoms` in the group. Centers of mass per :class:`Residue`, :class:`Segment`, molecule, or @@ -1200,7 +1201,7 @@ def center_of_mass(group, pbc=False, compound='group', unwrap=False): @warn_if_not_unique def total_mass(group, compound='group'): - """Total mass of (compounds of) the group. + r"""Total mass of (compounds of) the group. Computes the total mass of :class:`Atoms` in the group. Total masses per :class:`Residue`, :class:`Segment`, molecule, or @@ -1467,7 +1468,7 @@ def principal_axes(group, pbc=False): .. versionchanged:: 0.8 Added *pbc* keyword - .. versionchanged:: 1.0.0 + .. versionchanged:: 1.0.0 Always return principal axes in right-hand convention. """ @@ -1558,7 +1559,7 @@ def get_segments(self, sg): @warn_if_not_unique def total_charge(group, compound='group'): - """Total charge of (compounds of) the group. + r"""Total charge of (compounds of) the group. Computes the total charge of :class:`Atoms` in the group. Total charges per :class:`Residue`, :class:`Segment`, molecule, or @@ -1775,7 +1776,7 @@ def _gen_initial_values(na, nr, ns): class _ResidueStringAttr(ResidueAttr): def __init__(self, vals, guessed=False): self._guessed = guessed - + self.namedict = dict() # maps str to nmidx name_lookup = [] # maps idx to str # eg namedict['O'] = 5 & name_lookup[5] = 'O' @@ -1794,7 +1795,7 @@ def __init__(self, vals, guessed=False): self.nmidx[i] = nextidx self.name_lookup = np.array(name_lookup, dtype=object) - self.values = self.name_lookup[self.nmidx] + self.values = self.name_lookup[self.nmidx] @staticmethod def _gen_initial_values(na, nr, ns): @@ -1826,7 +1827,7 @@ def set_residues(self, rg, values): self.nmidx[rg.ix] = newidx # newidx either single value or same size array if newnames: self.name_lookup = np.concatenate([self.name_lookup, newnames]) - self.values = self.name_lookup[self.nmidx] + self.values = self.name_lookup[self.nmidx] # TODO: update docs to property doc @@ -2011,7 +2012,7 @@ def set_segments(self, sg, values): class _SegmentStringAttr(SegmentAttr): def __init__(self, vals, guessed=False): self._guessed = guessed - + self.namedict = dict() # maps str to nmidx name_lookup = [] # maps idx to str # eg namedict['O'] = 5 & name_lookup[5] = 'O' @@ -2030,7 +2031,7 @@ def __init__(self, vals, guessed=False): self.nmidx[i] = nextidx self.name_lookup = np.array(name_lookup, dtype=object) - self.values = self.name_lookup[self.nmidx] + self.values = self.name_lookup[self.nmidx] @staticmethod def _gen_initial_values(na, nr, ns): @@ -2062,9 +2063,9 @@ def set_segments(self, sg, values): self.nmidx[sg.ix] = newidx # newidx either single value or same size array if newnames: self.name_lookup = np.concatenate([self.name_lookup, newnames]) - self.values = self.name_lookup[self.nmidx] + self.values = self.name_lookup[self.nmidx] + - # TODO: update docs to property doc class Segids(_SegmentStringAttr): attrname = 'segids' @@ -2268,7 +2269,7 @@ def fragindex(self): return self.universe._fragdict[self.ix].ix def fragindices(self): - """The + r"""The :class:`fragment indices` of all :class:`Atoms` in this :class:`~MDAnalysis.core.groups.AtomGroup`. diff --git a/package/MDAnalysis/lib/distances.py b/package/MDAnalysis/lib/distances.py index e1755511b5c..74782a67797 100644 --- a/package/MDAnalysis/lib/distances.py +++ b/package/MDAnalysis/lib/distances.py @@ -195,7 +195,7 @@ def distance_array(reference, configuration, box=None, result=None, box : array_like, optional The unitcell dimensions of the system, which can be orthogonal or triclinic and must be provided in the same format as returned by - :attr:`MDAnalysis.coordinates.base.Timestep.dimensions`:\n + :attr:`MDAnalysis.coordinates.base.Timestep.dimensions`: ``[lx, ly, lz, alpha, beta, gamma]``. result : numpy.ndarray, optional Preallocated result array which must have the shape ``(n, m)`` and dtype @@ -263,7 +263,7 @@ def self_distance_array(reference, box=None, result=None, backend="serial"): box : array_like, optional The unitcell dimensions of the system, which can be orthogonal or triclinic and must be provided in the same format as returned by - :attr:`MDAnalysis.coordinates.base.Timestep.dimensions`:\n + :attr:`MDAnalysis.coordinates.base.Timestep.dimensions`: ``[lx, ly, lz, alpha, beta, gamma]``. result : numpy.ndarray, optional Preallocated result array which must have the shape ``(n*(n-1)/2,)`` and @@ -346,7 +346,7 @@ def capped_distance(reference, configuration, max_cutoff, min_cutoff=None, box : array_like, optional The unitcell dimensions of the system, which can be orthogonal or triclinic and must be provided in the same format as returned by - :attr:`MDAnalysis.coordinates.base.Timestep.dimensions`:\n + :attr:`MDAnalysis.coordinates.base.Timestep.dimensions`: ``[lx, ly, lz, alpha, beta, gamma]``. method : {'bruteforce', 'nsgrid', 'pkdtree'}, optional Keyword to override the automatic guessing of the employed search @@ -422,7 +422,7 @@ def _determine_method(reference, configuration, max_cutoff, min_cutoff=None, box : numpy.ndarray The unitcell dimensions of the system, which can be orthogonal or triclinic and must be provided in the same format as returned by - :attr:`MDAnalysis.coordinates.base.Timestep.dimensions`:\n + :attr:`MDAnalysis.coordinates.base.Timestep.dimensions`: ``[lx, ly, lz, alpha, beta, gamma]``. method : {'bruteforce', 'nsgrid', 'pkdtree'}, optional Keyword to override the automatic guessing of the employed search @@ -498,7 +498,7 @@ def _bruteforce_capped(reference, configuration, max_cutoff, min_cutoff=None, box : numpy.ndarray, optional The unitcell dimensions of the system, which can be orthogonal or triclinic and must be provided in the same format as returned by - :attr:`MDAnalysis.coordinates.base.Timestep.dimensions`:\n + :attr:`MDAnalysis.coordinates.base.Timestep.dimensions`: ``[lx, ly, lz, alpha, beta, gamma]``. return_distances : bool, optional If set to ``True``, distances will also be returned. @@ -575,7 +575,7 @@ def _pkdtree_capped(reference, configuration, max_cutoff, min_cutoff=None, box : numpy.ndarray, optional The unitcell dimensions of the system, which can be orthogonal or triclinic and must be provided in the same format as returned by - :attr:`MDAnalysis.coordinates.base.Timestep.dimensions`:\n + :attr:`MDAnalysis.coordinates.base.Timestep.dimensions`: ``[lx, ly, lz, alpha, beta, gamma]``. return_distances : bool, optional If set to ``True``, distances will also be returned. @@ -657,7 +657,7 @@ def _nsgrid_capped(reference, configuration, max_cutoff, min_cutoff=None, box : numpy.ndarray (``dtype=numpy.float64``, ``shape=(n_pairs,)``), optional The unitcell dimensions of the system, which can be orthogonal or triclinic and must be provided in the same format as returned by - :attr:`MDAnalysis.coordinates.base.Timestep.dimensions`:\n + :attr:`MDAnalysis.coordinates.base.Timestep.dimensions`: ``[lx, ly, lz, alpha, beta, gamma]``. return_distances : bool, optional If set to ``True``, distances will also be returned. @@ -749,7 +749,7 @@ def self_capped_distance(reference, max_cutoff, min_cutoff=None, box=None, box : array_like, optional The unitcell dimensions of the system, which can be orthogonal or triclinic and must be provided in the same format as returned by - :attr:`MDAnalysis.coordinates.base.Timestep.dimensions`:\n + :attr:`MDAnalysis.coordinates.base.Timestep.dimensions`: ``[lx, ly, lz, alpha, beta, gamma]``. method : {'bruteforce', 'nsgrid', 'pkdtree'}, optional Keyword to override the automatic guessing of the employed search @@ -825,7 +825,7 @@ def _determine_method_self(reference, max_cutoff, min_cutoff=None, box=None, box : numpy.ndarray The unitcell dimensions of the system, which can be orthogonal or triclinic and must be provided in the same format as returned by - :attr:`MDAnalysis.coordinates.base.Timestep.dimensions`:\n + :attr:`MDAnalysis.coordinates.base.Timestep.dimensions`: ``[lx, ly, lz, alpha, beta, gamma]``. method : {'bruteforce', 'nsgrid', 'pkdtree'}, optional Keyword to override the automatic guessing of the employed search @@ -889,7 +889,7 @@ def _bruteforce_capped_self(reference, max_cutoff, min_cutoff=None, box=None, box : numpy.ndarray, optional The unitcell dimensions of the system, which can be orthogonal or triclinic and must be provided in the same format as returned by - :attr:`MDAnalysis.coordinates.base.Timestep.dimensions`:\n + :attr:`MDAnalysis.coordinates.base.Timestep.dimensions`: ``[lx, ly, lz, alpha, beta, gamma]``. return_distances : bool, optional If set to ``True``, distances will also be returned. @@ -964,7 +964,7 @@ def _pkdtree_capped_self(reference, max_cutoff, min_cutoff=None, box=None, box : numpy.ndarray, optional The unitcell dimensions of the system, which can be orthogonal or triclinic and must be provided in the same format as returned by - :attr:`MDAnalysis.coordinates.base.Timestep.dimensions`:\n + :attr:`MDAnalysis.coordinates.base.Timestep.dimensions`: ``[lx, ly, lz, alpha, beta, gamma]``. return_distances : bool, optional If set to ``True``, distances will also be returned. @@ -1040,7 +1040,7 @@ def _nsgrid_capped_self(reference, max_cutoff, min_cutoff=None, box=None, box : numpy.ndarray, optional The unitcell dimensions of the system, which can be orthogonal or triclinic and must be provided in the same format as returned by - :attr:`MDAnalysis.coordinates.base.Timestep.dimensions`:\n + :attr:`MDAnalysis.coordinates.base.Timestep.dimensions`: ``[lx, ly, lz, alpha, beta, gamma]``. Returns @@ -1125,7 +1125,7 @@ def transform_RtoS(coords, box, backend="serial"): box : numpy.ndarray The unitcell dimensions of the system, which can be orthogonal or triclinic and must be provided in the same format as returned by - :attr:`MDAnalysis.coordinates.base.Timestep.dimensions`:\n + :attr:`MDAnalysis.coordinates.base.Timestep.dimensions`: ``[lx, ly, lz, alpha, beta, gamma]``. backend : {'serial', 'OpenMP'}, optional Keyword selecting the type of acceleration. @@ -1174,7 +1174,7 @@ def transform_StoR(coords, box, backend="serial"): box : numpy.ndarray The unitcell dimensions of the system, which can be orthogonal or triclinic and must be provided in the same format as returned by - :attr:`MDAnalysis.coordinates.base.Timestep.dimensions`:\n + :attr:`MDAnalysis.coordinates.base.Timestep.dimensions`: ``[lx, ly, lz, alpha, beta, gamma]``. backend : {'serial', 'OpenMP'}, optional Keyword selecting the type of acceleration. @@ -1238,7 +1238,7 @@ def calc_bonds(coords1, coords2, box=None, result=None, backend="serial"): box : numpy.ndarray, optional The unitcell dimensions of the system, which can be orthogonal or triclinic and must be provided in the same format as returned by - :attr:`MDAnalysis.coordinates.base.Timestep.dimensions`:\n + :attr:`MDAnalysis.coordinates.base.Timestep.dimensions`: ``[lx, ly, lz, alpha, beta, gamma]``. result : numpy.ndarray, optional Preallocated result array of dtype ``numpy.float64`` and shape ``(n,)`` @@ -1327,7 +1327,7 @@ def calc_angles(coords1, coords2, coords3, box=None, result=None, box : numpy.ndarray, optional The unitcell dimensions of the system, which can be orthogonal or triclinic and must be provided in the same format as returned by - :attr:`MDAnalysis.coordinates.base.Timestep.dimensions`:\n + :attr:`MDAnalysis.coordinates.base.Timestep.dimensions`: ``[lx, ly, lz, alpha, beta, gamma]``. result : numpy.ndarray, optional Preallocated result array of dtype ``numpy.float64`` and shape ``(n,)`` @@ -1379,7 +1379,7 @@ def calc_angles(coords1, coords2, coords3, box=None, result=None, @check_coords('coords1', 'coords2', 'coords3', 'coords4') def calc_dihedrals(coords1, coords2, coords3, coords4, box=None, result=None, backend="serial"): - """Calculates the dihedral angles formed between quadruplets of positions + r"""Calculates the dihedral angles formed between quadruplets of positions from the four coordinate arrays `coords1`, `coords2`, `coords3`, and `coords4`, which must contain the same number of coordinates. @@ -1429,7 +1429,7 @@ def calc_dihedrals(coords1, coords2, coords3, coords4, box=None, result=None, box : numpy.ndarray, optional The unitcell dimensions of the system, which can be orthogonal or triclinic and must be provided in the same format as returned by - :attr:`MDAnalysis.coordinates.base.Timestep.dimensions`:\n + :attr:`MDAnalysis.coordinates.base.Timestep.dimensions`: ``[lx, ly, lz, alpha, beta, gamma]``. result : numpy.ndarray, optional Preallocated result array of dtype ``numpy.float64`` and shape ``(n,)`` @@ -1493,7 +1493,7 @@ def apply_PBC(coords, box, backend="serial"): box : numpy.ndarray The unitcell dimensions of the system, which can be orthogonal or triclinic and must be provided in the same format as returned by - :attr:`MDAnalysis.coordinates.base.Timestep.dimensions`:\n + :attr:`MDAnalysis.coordinates.base.Timestep.dimensions`: ``[lx, ly, lz, alpha, beta, gamma]``. backend : {'serial', 'OpenMP'}, optional Keyword selecting the type of acceleration. diff --git a/package/MDAnalysis/lib/transformations.py b/package/MDAnalysis/lib/transformations.py index 2723c53dec6..c1079d49784 100644 --- a/package/MDAnalysis/lib/transformations.py +++ b/package/MDAnalysis/lib/transformations.py @@ -65,14 +65,14 @@ Documentation in HTML format can be generated with epydoc. -Matrices (M) can be inverted using numpy.linalg.inv(M), concatenated using -numpy.dot(M0, M1), or used to transform homogeneous coordinates (v) using -numpy.dot(M, v) for shape (4, \*) "point of arrays", respectively -numpy.dot(v, M.T) for shape (\*, 4) "array of points". +Matrices (M) can be inverted using ``numpy.linalg.inv(M)``, concatenated using +``numpy.dot(M0, M1)``, or used to transform homogeneous coordinates (v) using +``numpy.dot(M, v)`` for shape ``(4, *)`` "point of arrays", respectively +``numpy.dot(v, M.T)`` for shape ``(*, 4)`` "array of points". -Use the transpose of transformation matrices for OpenGL glMultMatrixd(). +Use the transpose of transformation matrices for OpenGL ``glMultMatrixd()``. -Calculations are carried out with numpy.float64 precision. +Calculations are carried out with ``numpy.float64`` precision. Vector, point, quaternion, and matrix function arguments are expected to be "array like", i.e. tuple, list, or numpy arrays. @@ -81,23 +81,23 @@ Angles are in radians unless specified otherwise. -Quaternions w+ix+jy+kz are represented as [w, x, y, z]. +Quaternions w+ix+jy+kz are represented as ``[w, x, y, z]``. A triple of Euler angles can be applied/interpreted in 24 ways, which can be specified using a 4 character string or encoded 4-tuple: - *Axes 4-string*: e.g. 'sxyz' or 'ryxy' + - *Axes 4-string*: e.g. 'sxyz' or 'ryxy' - - first character : rotations are applied to 's'tatic or 'r'otating frame - - remaining characters : successive rotation axis 'x', 'y', or 'z' + - first character : rotations are applied to 's'tatic or 'r'otating frame + - remaining characters : successive rotation axis 'x', 'y', or 'z' - *Axes 4-tuple*: e.g. (0, 0, 0, 0) or (1, 1, 1, 1) + - *Axes 4-tuple*: e.g. (0, 0, 0, 0) or (1, 1, 1, 1) - - inner axis: code of axis ('x':0, 'y':1, 'z':2) of rightmost matrix. - - parity : even (0) if inner axis 'x' is followed by 'y', 'y' is followed - by 'z', or 'z' is followed by 'x'. Otherwise odd (1). - - repetition : first and last axis are same (1) or different (0). - - frame : rotations are applied to static (0) or rotating (1) frame. + - inner axis: code of axis ('x':0, 'y':1, 'z':2) of rightmost matrix. + - parity : even (0) if inner axis 'x' is followed by 'y', 'y' is followed + by 'z', or 'z' is followed by 'x'. Otherwise odd (1). + - repetition : first and last axis are same (1) or different (0). + - frame : rotations are applied to static (0) or rotating (1) frame. References ---------- @@ -896,9 +896,9 @@ def orthogonalization_matrix(lengths, angles): def superimposition_matrix(v0, v1, scaling=False, usesvd=True): """Return matrix to transform given vector set into second vector set. - v0 and v1 are shape (3, \*) or (4, \*) arrays of at least 3 vectors. + `v0` and `v1` are shape `(3, *)` or `(4, *)` arrays of at least 3 vectors. - If usesvd is True, the weighted sum of squared deviations (RMSD) is + If `usesvd` is ``True``, the weighted sum of squared deviations (RMSD) is minimized according to the algorithm by W. Kabsch [8]. Otherwise the quaternion based algorithm by B. Horn [9] is used (slower when using this Python implementation). @@ -1377,7 +1377,7 @@ def quaternion_imag(quaternion): def quaternion_slerp(quat0, quat1, fraction, spin=0, shortestpath=True): - """Return spherical linear interpolation between two quaternions. + r"""Return spherical linear interpolation between two quaternions. >>> q0 = random_quaternion() >>> q1 = random_quaternion() diff --git a/package/MDAnalysis/lib/util.py b/package/MDAnalysis/lib/util.py index 1e2a893556f..9916c45bd8d 100644 --- a/package/MDAnalysis/lib/util.py +++ b/package/MDAnalysis/lib/util.py @@ -20,7 +20,7 @@ # MDAnalysis: A Toolkit for the Analysis of Molecular Dynamics Simulations. # J. Comput. Chem. 32 (2011), 2319--2327, doi:10.1002/jcc.21787 # -""" +r""" Helper functions --- :mod:`MDAnalysis.lib.util` ==================================================== @@ -1057,7 +1057,8 @@ def asiterable(obj): #: ``(?P\d?)(?P[IFELAX])(?P(?P\d+)(\.(?P\d+))?)?`` #: #: .. _FORTRAN edit descriptor: http://www.cs.mtu.edu/~shene/COURSES/cs201/NOTES/chap05/format.html -FORTRAN_format_regex = "(?P\d+?)(?P[IFEAX])(?P(?P\d+)(\.(?P\d+))?)?" +FORTRAN_format_regex = (r"(?P\d+?)(?P[IFEAX])" + r"(?P(?P\d+)(\.(?P\d+))?)?") _FORTRAN_format_pattern = re.compile(FORTRAN_format_regex) @@ -1424,7 +1425,7 @@ def convert_aa_code(x): #: Regular expression to match and parse a residue-atom selection; will match #: "LYS300:HZ1" or "K300:HZ1" or "K300" or "4GB300:H6O" or "4GB300" or "YaA300". -RESIDUE = re.compile(""" +RESIDUE = re.compile(r""" (?P([ACDEFGHIKLMNPQRSTVWY]) # 1-letter amino acid | # or ([0-9A-Z][a-zA-Z][A-Z][A-Z]?) # 3-letter or 4-letter residue name @@ -2176,7 +2177,7 @@ def newfunc(*args, **kwds): def deprecate(*args, **kwargs): - """Issues a DeprecationWarning, adds warning to `old_name`'s + r"""Issues a DeprecationWarning, adds warning to `old_name`'s docstring, rebinds ``old_name.__name__`` and returns the new function object. @@ -2310,7 +2311,7 @@ def check_box(box): box : array_like The unitcell dimensions of the system, which can be orthogonal or triclinic and must be provided in the same format as returned by - :attr:`MDAnalysis.coordinates.base.Timestep.dimensions`:\n + :attr:`MDAnalysis.coordinates.base.Timestep.dimensions`: ``[lx, ly, lz, alpha, beta, gamma]``. Returns diff --git a/testsuite/MDAnalysisTests/analysis/test_density.py b/testsuite/MDAnalysisTests/analysis/test_density.py index 600de2590f7..8db8b2df1a3 100644 --- a/testsuite/MDAnalysisTests/analysis/test_density.py +++ b/testsuite/MDAnalysisTests/analysis/test_density.py @@ -213,8 +213,8 @@ def test_userdefn_boxshape(self, universe): assert D.density.grid.shape == (8, 12, 17) def test_warn_userdefn_padding(self, universe): - regex = ("Box padding \(currently set at 1\.0\) is not used " - "in user defined grids\.") + regex = (r"Box padding \(currently set at 1\.0\) is not used " + r"in user defined grids\.") with pytest.warns(UserWarning, match=regex): D = density.DensityAnalysis( universe.select_atoms(self.selections['static']), diff --git a/testsuite/MDAnalysisTests/analysis/test_hydrogenbonds_analysis.py b/testsuite/MDAnalysisTests/analysis/test_hydrogenbonds_analysis.py index b12b8087867..d90a2ce0488 100644 --- a/testsuite/MDAnalysisTests/analysis/test_hydrogenbonds_analysis.py +++ b/testsuite/MDAnalysisTests/analysis/test_hydrogenbonds_analysis.py @@ -474,7 +474,7 @@ def test_guess_hydrogens_empty_selection(self, h): def test_guess_hydrogens_min_max_mass(self, h): - errmsg = "min_mass is higher than \(or equal to\) max_mass" + errmsg = r"min_mass is higher than \(or equal to\) max_mass" with pytest.raises(ValueError, match=errmsg): diff --git a/testsuite/MDAnalysisTests/core/test_fragments.py b/testsuite/MDAnalysisTests/core/test_fragments.py index 55c4d22d271..f71c48866e5 100644 --- a/testsuite/MDAnalysisTests/core/test_fragments.py +++ b/testsuite/MDAnalysisTests/core/test_fragments.py @@ -78,7 +78,7 @@ def case2(): class TestFragments(object): - """Use 125 atom test Universe + r"""Use 125 atom test Universe 5 segments of 5 residues of 5 atoms diff --git a/testsuite/MDAnalysisTests/util.py b/testsuite/MDAnalysisTests/util.py index 91a58508808..45b7121346c 100644 --- a/testsuite/MDAnalysisTests/util.py +++ b/testsuite/MDAnalysisTests/util.py @@ -153,7 +153,7 @@ def in_dir(dirname): def assert_nowarns(warning_class, *args, **kwargs): - """Fail if the given callable throws the specified warning. + r"""Fail if the given callable throws the specified warning. A warning of class warning_class should NOT be thrown by the callable when invoked with arguments args and keyword arguments kwargs. diff --git a/testsuite/MDAnalysisTests/utils/test_meta.py b/testsuite/MDAnalysisTests/utils/test_meta.py index 3de7b828de9..15a30961c44 100644 --- a/testsuite/MDAnalysisTests/utils/test_meta.py +++ b/testsuite/MDAnalysisTests/utils/test_meta.py @@ -44,7 +44,7 @@ def test_version_format(version=None): import MDAnalysis.version version = MDAnalysis.version.__version__ # see https://github.com/MDAnalysis/mdanalysis/wiki/SemanticVersioning for format definition - m = re.match('(?P\d+)\.(?P\d+)\.(?P\d+)(-(?P\w+))?$', + m = re.match(r'(?P\d+)\.(?P\d+)\.(?P\d+)(-(?P\w+))?$', version) assert m, "version {0} does not match the MAJOR.MINOR.PATCH(-suffix) format".format(version) diff --git a/testsuite/setup.cfg b/testsuite/setup.cfg index 0473b68e784..0c926b54caf 100644 --- a/testsuite/setup.cfg +++ b/testsuite/setup.cfg @@ -10,6 +10,7 @@ filterwarnings= # don't enforce for third party packages though: ignore:`np.*` is a deprecated alias for the builtin:DeprecationWarning:networkx.*: error:Creating an ndarray from ragged nested sequences + error:invalid escape sequence \\:DeprecationWarning # Settings to test for warnings we throw # [tool:pytest]