Use a stacklevel of 2 by default for all warnings

This commit is contained in:
Steven Silvester
2016-01-30 08:57:46 -06:00
parent 114f7f8ae0
commit b710bd21d2
25 changed files with 122 additions and 121 deletions
+1 -1
View File
@@ -158,7 +158,7 @@ else:
if sys.version.startswith('2.6'):
warnings.warn("Python 2.6 is deprecated and will not be supported in scikit-image 0.13+")
warnings.warn("Python 2.6 is deprecated and will not be supported in scikit-image 0.13+", stacklevel=2)
del warnings, functools, osp, imp, sys
+11 -4
View File
@@ -7,6 +7,13 @@ import inspect
import re
def warn(*args, **kwargs):
"""A version of `warnings.warn` with a default stacklevel of 2
"""
kwargs.setdefault('stacklevel', 2)
warnings.warn(*args, **kwargs)
@contextmanager
def all_warnings():
"""
@@ -67,7 +74,7 @@ def all_warnings():
@contextmanager
def expected_warnings(matching):
"""Context for use in testing to catch known warnings matching regexes
Parameters
----------
matching : list of strings or compiled regexes
@@ -84,10 +91,10 @@ def expected_warnings(matching):
-----
Uses `all_warnings` to ensure all warnings are raised.
Upon exiting, it checks the recorded warnings for the desired matching
pattern(s).
pattern(s).
Raises a ValueError if any match was not found or an unexpected
warning was raised.
Allows for three types of behaviors: "and", "or", and "optional" matches.
warning was raised.
Allows for three types of behaviors: "and", "or", and "optional" matches.
This is done to accomodate different build enviroments or loop conditions
that may produce different warnings. The behaviors can be combined.
If you pass multiple patterns, you get an orderless "and", where all of the
+3 -3
View File
@@ -6,10 +6,10 @@ import types
import six
from ._warnings import all_warnings
from ._warnings import all_warnings, warn
__all__ = ['deprecated', 'get_bound_method_class', 'all_warnings',
'safe_as_int', 'assert_nD']
'safe_as_int', 'assert_nD', 'warn']
class skimage_deprecation(Warning):
@@ -170,7 +170,7 @@ def _mode_deprecations(mode):
"""Used to update deprecated mode names in
`skimage._shared.interpolation.pyx`."""
if mode.lower() == 'nearest':
warnings.warn(skimage_deprecation(
warn(skimage_deprecation(
"Mode 'nearest' has been renamed to 'edge'. Mode 'nearest' will be "
"removed in a future release."))
mode = 'edge'
+2 -2
View File
@@ -1,8 +1,8 @@
import warnings
import itertools
import numpy as np
from .._shared.utils import warn
from .. import img_as_float
from . import rgb_colors
from .colorconv import rgb2gray, gray2rgb
@@ -148,7 +148,7 @@ def _label2rgb_overlay(label, image=None, colors=None, alpha=0.3,
raise ValueError("`image` and `label` must be the same shape")
if image.min() < 0:
warnings.warn("Negative intensities in `image` are not supported")
warn("Negative intensities in `image` are not supported")
image = img_as_float(rgb2gray(image))
image = gray2rgb(image) * image_alpha + (1 - image_alpha)
+4 -4
View File
@@ -19,7 +19,7 @@ import numpy as np
from .. import img_as_float, img_as_uint
from ..color.adapt_rgb import adapt_rgb, hsv_value
from ..exposure import rescale_intensity
from .._shared.utils import skimage_deprecation, warnings
from .._shared.utils import skimage_deprecation, warn
NR_OF_GREY = 2 ** 14 # number of grayscale levels to use in CLAHE algorithm
@@ -77,9 +77,9 @@ def equalize_adapthist(image, ntiles_x=8, ntiles_y=8, clip_limit=0.01,
image = rescale_intensity(image, out_range=(0, NR_OF_GREY - 1))
if kernel_size is None:
warnings.warn('`ntiles_*` have been deprecated in favor of '
'`kernel_size`. The `ntiles_*` keyword arguments '
'will be removed in v0.14', skimage_deprecation)
warn('`ntiles_*` have been deprecated in favor of '
'`kernel_size`. The `ntiles_*` keyword arguments '
'will be removed in v0.14', skimage_deprecation)
ntiles_x = ntiles_x or 8
ntiles_y = ntiles_y or 8
kernel_size = (np.round(image.shape[0] / ntiles_y),
+6 -6
View File
@@ -1,9 +1,9 @@
from __future__ import division
import warnings
import numpy as np
from ..color import rgb2gray
from ..util.dtype import dtype_range, dtype_limits
from .._shared.utils import warn
__all__ = ['histogram', 'cumulative_distribution', 'equalize_hist',
@@ -60,9 +60,9 @@ def histogram(image, nbins=256):
"""
sh = image.shape
if len(sh) == 3 and sh[-1] < 4:
warnings.warn("This might be a color image. The histogram will be "
"computed on the flattened image. You can instead "
"apply this function to each color channel.")
warn("This might be a color image. The histogram will be "
"computed on the flattened image. You can instead "
"apply this function to each color channel.")
# For integer types, histogramming with bincount is more efficient.
if np.issubdtype(image.dtype, np.integer):
@@ -292,12 +292,12 @@ def rescale_intensity(image, in_range='image', out_range='dtype'):
if in_range is None:
in_range = 'image'
msg = "`in_range` should not be set to None. Use {!r} instead."
warnings.warn(msg.format(in_range))
warn(msg.format(in_range))
if out_range is None:
out_range = 'dtype'
msg = "`out_range` should not be set to None. Use {!r} instead."
warnings.warn(msg.format(out_range))
warn(msg.format(out_range))
imin, imax = intensity_range(image, in_range)
omin, omax = intensity_range(image, out_range, clip_negative=(imin >= 0))
+2 -2
View File
@@ -1,10 +1,10 @@
import collections as coll
import numpy as np
from scipy import ndimage as ndi
import warnings
from ..util import img_as_float
from ..color import guess_spatial_dimensions
from .._shared.utils import warn
__all__ = ['gaussian']
@@ -91,7 +91,7 @@ def gaussian(image, sigma, output=None, mode='nearest', cval=0,
msg = ("Images with dimensions (M, N, 3) are interpreted as 2D+RGB "
"by default. Use `multichannel=False` to interpret as "
"3D image with last dimension of length 3.")
warnings.warn(RuntimeWarning(msg))
warn(RuntimeWarning(msg))
multichannel = True
if np.any(np.asarray(sigma) < 0.0):
raise ValueError("Sigma values less than zero are not valid")
+6 -7
View File
@@ -16,17 +16,16 @@ References
"""
import warnings
import numpy as np
from ... import img_as_ubyte
from ..._shared.utils import assert_nD
from ..._shared.utils import assert_nD, warn
from . import generic_cy
__all__ = ['autolevel', 'bottomhat', 'equalize', 'gradient', 'maximum', 'mean',
'geometric_mean', 'subtract_mean', 'median', 'minimum', 'modal',
'enhance_contrast', 'pop', 'threshold', 'tophat', 'noise_filter',
'geometric_mean', 'subtract_mean', 'median', 'minimum', 'modal',
'enhance_contrast', 'pop', 'threshold', 'tophat', 'noise_filter',
'entropy', 'otsu']
@@ -65,8 +64,8 @@ def _handle_input(image, selem, out, mask, out_dtype=None, pixel_size=1):
bitdepth = int(np.log2(max_bin))
if bitdepth > 10:
warnings.warn("Bitdepth of %d may result in bad rank filter "
"performance due to large number of bins." % bitdepth)
warn("Bitdepth of %d may result in bad rank filter "
"performance due to large number of bins." % bitdepth)
return image, selem, out, mask, max_bin
@@ -377,7 +376,7 @@ def geometric_mean(image, selem, out=None, mask=None, shift_x=False, shift_y=Fal
References
----------
.. [1] Gonzalez, R. C. and Wood, R. E. "Digital Image Processing (3rd Edition)."
.. [1] Gonzalez, R. C. and Wood, R. E. "Digital Image Processing (3rd Edition)."
Prentice-Hall Inc, 2006.
"""
+2 -3
View File
@@ -7,8 +7,7 @@ __all__ = ['threshold_adaptive',
import numpy as np
from scipy import ndimage as ndi
from ..exposure import histogram
from .._shared.utils import assert_nD
import warnings
from .._shared.utils import assert_nD, warn
def threshold_adaptive(image, block_size, method='gaussian', offset=0,
@@ -130,7 +129,7 @@ def threshold_otsu(image, nbins=256):
if image.shape[-1] in (3, 4):
msg = "threshold_otsu is expected to work correctly only for " \
"grayscale images; image shape {0} looks like an RGB image"
warnings.warn(msg.format(image.shape))
warn(msg.format(image.shape))
# Check if the image is multi-colored or not
if image.min() == image.max():
+2 -2
View File
@@ -1,8 +1,8 @@
try:
import networkx as nx
except ImportError:
import warnings
warnings.warn('RAGs require networkx')
from ..._shared.utils import warn
warn('RAGs require networkx')
import numpy as np
from scipy import sparse
from . import _ncut_cy
+3 -2
View File
@@ -1,8 +1,9 @@
try:
import networkx as nx
except ImportError:
import warnings
warnings.warn('RAGs require networkx')
from ..._shared.utils import warn
warn('RAGs require networkx')
import numpy as np
from . import _ncut
from . import _ncut_cy
+2 -3
View File
@@ -1,5 +1,4 @@
from io import BytesIO
import warnings
import numpy as np
import six
@@ -8,7 +7,7 @@ from ..io.manage_plugins import call_plugin
from ..color import rgb2grey
from .util import file_or_url_context
from ..exposure import is_low_contrast
from .._shared._warnings import all_warnings
from .._shared.utils import all_warnings, warn
__all__ = ['imread', 'imread_collection', 'imsave', 'imshow', 'show']
@@ -129,7 +128,7 @@ def imsave(fname, arr, plugin=None, **plugin_args):
if fname.lower().endswith(('.tiff', '.tif')):
plugin = 'tifffile'
if is_low_contrast(arr):
warnings.warn('%s is a low contrast image' % fname)
warn('%s is a low contrast image' % fname)
return call_plugin('imsave', fname, arr, plugin=plugin, **plugin_args)
+7 -7
View File
@@ -1,10 +1,10 @@
from collections import namedtuple
import numpy as np
import warnings
import matplotlib.pyplot as plt
from ...util import dtype as dtypes
from ...exposure import is_low_contrast
from ...util.colormap import viridis
from ..._shared.utils import warn
_default_colormap = 'gray'
_nonstandard_colormap = viridis
@@ -67,14 +67,14 @@ def _raise_warnings(image_properties):
"""
ip = image_properties
if ip.unsupported_dtype:
warnings.warn("Non-standard image type; displaying image with "
"stretched contrast.")
warn("Non-standard image type; displaying image with "
"stretched contrast.")
if ip.low_dynamic_range:
warnings.warn("Low image dynamic range; displaying image with "
"stretched contrast.")
warn("Low image dynamic range; displaying image with "
"stretched contrast.")
if ip.out_of_range_float:
warnings.warn("Float image out of standard range; displaying "
"image with stretched contrast.")
warn("Float image out of standard range; displaying "
"image with stretched contrast.")
def _get_display_range(image):
+2 -3
View File
@@ -1,3 +1,4 @@
from ..._shared import warn
from .util import prepare_for_display, window_manager
import numpy as np
@@ -10,7 +11,6 @@ try:
QLabel, QMainWindow, QPixmap, QWidget)
from PyQt4 import QtCore, QtGui
import sip
import warnings
except ImportError:
window_manager._release('qt')
@@ -119,8 +119,7 @@ if sip.SIP_VERSION >= 0x040c00:
# doesn't work with earlier versions
imread = imread_qt
else:
warnings.warn(RuntimeWarning(
"sip version too old. QT imread disabled"))
warn(RuntimeWarning("sip version too old. QT imread disabled"))
def imshow(arr, fancy=False):
+4 -5
View File
@@ -1,5 +1,6 @@
import numpy as np
import scipy.ndimage as ndi
from .._shared.utils import warn
from . import _marching_cubes_cy
@@ -239,11 +240,9 @@ def correct_mesh_orientation(volume, verts, faces, spacing=(1., 1., 1.),
skimage.measure.mesh_surface_area
"""
import warnings
warnings.warn(
DeprecationWarning("`correct_mesh_orientation` is deprecated for "
"removal as `marching_cubes` now guarantess "
"correct mesh orientation."))
warn(DeprecationWarning("`correct_mesh_orientation` is deprecated for "
"removal as `marching_cubes` now guarantess "
"correct mesh orientation."))
verts = verts.copy()
verts[:, 0] /= spacing[0]
+4 -6
View File
@@ -1,8 +1,7 @@
import math
import warnings
import numpy as np
from scipy import optimize
from .._shared.utils import skimage_deprecation
from .._shared.utils import skimage_deprecation, warn
def _check_data_dim(data, dim):
@@ -27,8 +26,7 @@ class BaseModel(object):
@property
def _params(self):
warnings.warn('`_params` attribute is deprecated, '
'use `params` instead.')
warn('`_params` attribute is deprecated, use `params` instead.')
return self.params
@@ -61,8 +59,8 @@ class LineModel(BaseModel):
def __init__(self):
self.params = None
warnings.warn(skimage_deprecation('`LineModel` is deprecated, '
'use `LineModelND` instead.'))
warn(skimage_deprecation('`LineModel` is deprecated, '
'use `LineModelND` instead.'))
def estimate(self, data):
"""Estimate line model from data using total least squares.
+16 -16
View File
@@ -1,7 +1,7 @@
import numpy as np
import functools
import warnings
from scipy import ndimage as ndi
from .._shared.utils import warn
from .selem import _default_selem
# Our function names don't exactly correspond to ndimages.
@@ -37,8 +37,8 @@ def default_selem(func):
return func(image, selem=selem, *args, **kwargs)
return func_out
def _check_dtype_supported(ar):
def _check_dtype_supported(ar):
# Should use `issubdtype` for bool below, but there's a bug in numpy 1.7
if not (ar.dtype == bool or np.issubdtype(ar.dtype, np.integer)):
raise TypeError("Only bool or integer image types are supported. "
@@ -119,8 +119,8 @@ def remove_small_objects(ar, min_size=64, connectivity=1, in_place=False):
"`skimage.morphology.label`.")
if len(component_sizes) == 2:
warnings.warn("Only one label was provided to `remove_small_objects`. "
"Did you mean to use a boolean array?")
warn("Only one label was provided to `remove_small_objects`. "
"Did you mean to use a boolean array?")
too_small = component_sizes < min_size
too_small_mask = too_small[ccs]
@@ -181,35 +181,35 @@ def remove_small_holes(ar, min_size=64, connectivity=1, in_place=False):
Notes
-----
If the array type is int, it is assumed that it contains already-labeled
objects. The labels are not kept in the output image (this function always
outputs a bool image). It is suggested that labeling is completed after
If the array type is int, it is assumed that it contains already-labeled
objects. The labels are not kept in the output image (this function always
outputs a bool image). It is suggested that labeling is completed after
using this function.
"""
_check_dtype_supported(ar)
#Creates warning if image is an integer image
if ar.dtype != bool:
warnings.warn("Any labeled images will be returned as a boolean array. "
"Did you mean to use a boolean array?", UserWarning)
warn("Any labeled images will be returned as a boolean array. "
"Did you mean to use a boolean array?", UserWarning)
if in_place:
out = ar
else:
out = ar.copy()
#Creating the inverse of ar
if in_place:
out = np.logical_not(out,out)
else:
out = np.logical_not(out)
#removing small objects from the inverse of ar
out = remove_small_objects(out, min_size, connectivity, in_place)
if in_place:
out = np.logical_not(out,out)
else:
out = np.logical_not(out)
return out
+5 -4
View File
@@ -1,7 +1,8 @@
import numpy as np
import warnings
from six import string_types
from .._shared.utils import warn
from ._unwrap_1d import unwrap_1d
from ._unwrap_2d import unwrap_2d
from ._unwrap_3d import unwrap_3d
@@ -83,9 +84,9 @@ def unwrap_phase(image, wrap_around=False, seed=None):
if wrap_around[0]:
raise ValueError('`wrap_around` is not supported for 1D images')
if image.ndim in (2, 3) and 1 in image.shape:
warnings.warn('Image has a length 1 dimension. Consider using an '
'array of lower dimensionality to use a more efficient '
'algorithm')
warn('Image has a length 1 dimension. Consider using an '
'array of lower dimensionality to use a more efficient '
'algorithm')
if np.ma.isMaskedArray(image):
mask = np.require(np.ma.getmaskarray(image), np.uint8, ['C'])
+3 -3
View File
@@ -1,6 +1,6 @@
import warnings
import numpy as np
from .._shared.utils import warn
from ._felzenszwalb_cy import _felzenszwalb_grey
@@ -56,8 +56,8 @@ def felzenszwalb(image, scale=1, sigma=0.8, min_size=20):
# assume we got 2d image with multiple channels
n_channels = image.shape[2]
if n_channels != 3:
warnings.warn("Got image with %d channels. Is that really what you"
" wanted?" % image.shape[2])
warn("Got image with %d channels. Is that really what you"
" wanted?" % image.shape[2])
segmentations = []
# compute quickshift for each channel
for c in range(n_channels):
@@ -8,10 +8,12 @@ Installing pyamg and using the 'cg_mg' mode of random_walker improves
significantly the performance.
"""
import warnings
import numpy as np
from scipy import sparse, ndimage as ndi
from .._shared.utils import warn
# executive summary for next code block: try to import umfpack from
# scipy, but make sure not to raise a fuss if it fails since it's only
# needed to speed up a few cases.
@@ -345,17 +347,17 @@ def random_walker(data, labels, beta=130, mode='bf', tol=1.e-3, copy=True,
mode = 'bf'
if UmfpackContext is None and mode == 'cg':
warnings.warn('"cg" mode will be used, but it may be slower than '
'"bf" because SciPy was built without UMFPACK. Consider'
' rebuilding SciPy with UMFPACK; this will greatly '
'accelerate the conjugate gradient ("cg") solver. '
'You may also install pyamg and run the random_walker '
'function in "cg_mg" mode (see docstring).')
warn('"cg" mode will be used, but it may be slower than '
'"bf" because SciPy was built without UMFPACK. Consider'
' rebuilding SciPy with UMFPACK; this will greatly '
'accelerate the conjugate gradient ("cg") solver. '
'You may also install pyamg and run the random_walker '
'function in "cg_mg" mode (see docstring).')
if (labels != 0).all():
warnings.warn('Random walker only segments unlabeled areas, where '
'labels == 0. No zero valued areas in labels were '
'found. Returning provided labels.')
warn('Random walker only segments unlabeled areas, where '
'labels == 0. No zero valued areas in labels were '
'found. Returning provided labels.')
if return_full_prob:
# Find and iterate over valid labels
@@ -438,8 +440,7 @@ def random_walker(data, labels, beta=130, mode='bf', tol=1.e-3, copy=True,
return_full_prob=return_full_prob)
if mode == 'cg_mg':
if not amg_loaded:
warnings.warn(
"""pyamg (http://pyamg.org/)) is needed to use
warn("""pyamg (http://pyamg.org/)) is needed to use
this mode, but is not installed. The 'cg' mode will be used
instead.""")
X = _solve_cg(lap_sparse, B, tol=tol,
+3 -3
View File
@@ -3,8 +3,8 @@
import collections as coll
import numpy as np
from scipy import ndimage as ndi
import warnings
from .._shared.utils import warn
from ..util import img_as_float, regular_grid
from ..segmentation._slic import (_slic_cython,
_enforce_label_connectivity_cython)
@@ -111,8 +111,8 @@ def slic(image, n_segments=100, compactness=10., max_iter=10, sigma=0,
"""
if enforce_connectivity is None:
warnings.warn('Deprecation: enforce_connectivity will default to'
' True in future versions.')
warn('Deprecation: enforce_connectivity will default to'
' True in future versions.')
enforce_connectivity = False
image = img_as_float(image)
+10 -13
View File
@@ -1,12 +1,11 @@
import six
import math
import warnings
import numpy as np
from scipy import spatial
from scipy import ndimage as ndi
from .._shared.utils import (get_bound_method_class, safe_as_int,
_mode_deprecations)
_mode_deprecations, warn)
from ..util import img_as_float
from ._warps_cy import _warp_fast
@@ -184,8 +183,7 @@ class ProjectiveTransform(GeometricTransform):
@property
def _matrix(self):
warnings.warn('`_matrix` attribute is deprecated, '
'use `params` instead.')
warn('`_matrix` attribute is deprecated, use `params` instead.')
return self.params
@property
@@ -782,8 +780,7 @@ class PolynomialTransform(GeometricTransform):
@property
def _params(self):
warnings.warn('`_params` attribute is deprecated, '
'use `params` instead.')
warn('`_params` attribute is deprecated, use `params` instead.')
return self.params
def estimate(self, src, dst, order=2):
@@ -1320,13 +1317,13 @@ def warp(image, inverse_map=None, map_args={}, output_shape=None, order=1,
if order == 2:
# When fixing this issue, make sure to fix the branches further
# below in this function
warnings.warn("Bi-quadratic interpolation behavior has changed due "
"to a bug in the implementation of scikit-image. "
"The new version now serves as a wrapper "
"around SciPy's interpolation functions, which itself "
"is not verified to be a correct implementation. Until "
"skimage's implementation is fixed, we recommend "
"to use bi-linear or bi-cubic interpolation instead.")
warn("Bi-quadratic interpolation behavior has changed due "
"to a bug in the implementation of scikit-image. "
"The new version now serves as a wrapper "
"around SciPy's interpolation functions, which itself "
"is not verified to be a correct implementation. Until "
"skimage's implementation is fixed, we recommend "
"to use bi-linear or bi-cubic interpolation instead.")
if order in (0, 1, 3) and not map_args:
# use fast Cython version for specific interpolation orders and input
+7 -5
View File
@@ -1,6 +1,8 @@
import numpy as np
import collections
import warnings
from .._shared.utils import warn
def integral_image(img):
"""Integral image / summed area table.
@@ -81,10 +83,10 @@ def integrate(ii, start, end, *args):
rows = start.shape[0]
# handle deprecated input format
else:
warnings.warn("The syntax 'integrate(ii, r0, c0, r1, c1)' is "
"deprecated, and will be phased out in release 0.14. "
"The new syntax is "
"'integrate(ii, (r0, c0), (r1, c1))'.")
warn("The syntax 'integrate(ii, r0, c0, r1, c1)' is "
"deprecated, and will be phased out in release 0.14. "
"The new syntax is "
"'integrate(ii, (r0, c0), (r1, c1))'.")
if isinstance(start, collections.Iterable):
rows = len(start)
args = (start, end) + args
+2 -2
View File
@@ -1,6 +1,6 @@
import warnings
from .._shared.utils import warn
from .viewers import ImageViewer, CollectionViewer
from .qt import has_qt
if not has_qt:
warnings.warn('Viewer requires Qt')
warn('Viewer requires Qt')
+2 -3
View File
@@ -1,14 +1,13 @@
import warnings
import numpy as np
from ..qt import QtWidgets, has_qt, FigureManagerQT, FigureCanvasQTAgg
from ..._shared.utils import warn
import matplotlib as mpl
from matplotlib.figure import Figure
from matplotlib import _pylab_helpers
from matplotlib.colors import LinearSegmentedColormap
if has_qt and 'agg' not in mpl.get_backend().lower():
warnings.warn("Recommended matplotlib backend is `Agg` for full "
warn("Recommended matplotlib backend is `Agg` for full "
"skimage.viewer functionality.")