diff --git a/.travis.yml b/.travis.yml index 07f7c686877c..e8c93af5e6a5 100644 --- a/.travis.yml +++ b/.travis.yml @@ -33,7 +33,7 @@ install: - | if [[ $BUILD_DOCS == true ]]; then sudo apt-get install -qq --no-install-recommends dvipng texlive-latex-base texlive-latex-extra texlive-fonts-recommended graphviz - pip install numpydoc linkchecker + pip install numpydoc linkchecker ipython wget http://mirrors.kernel.org/ubuntu/pool/universe/f/fonts-humor-sans/fonts-humor-sans_1.0-1_all.deb sudo dpkg -i fonts-humor-sans_1.0-1_all.deb wget https://googlefontdirectory.googlecode.com/hg/ofl/felipa/Felipa-Regular.ttf @@ -89,4 +89,4 @@ after_success: git push --set-upstream origin gh-pages --force else echo "Will only deploy docs build from matplotlib master branch" - fi \ No newline at end of file + fi diff --git a/doc/api/api_changes/code_removal.rst b/doc/api/api_changes/code_removal.rst index 5569a4acb3c5..2d92f1960f8e 100644 --- a/doc/api/api_changes/code_removal.rst +++ b/doc/api/api_changes/code_removal.rst @@ -3,4 +3,78 @@ Code Removal Legend ------ -Removed handling of `loc` as a positional argument to `Legend` + - Removed handling of `loc` as a positional argument to `Legend` + + +Legend handlers +~~~~~~~~~~~~~~~ +Remove code to allow legend handlers to be callable. They must now +implement a method ``legend_artist``. + + +Axis +---- +Removed method ``set_scale``. This is now handled via a private method which +should not be used directly by users. It is called via ``Axes.set_{x,y}scale`` +which takes care of ensuring the coupled changes are also made to the Axes object. + +finance.py +---------- +Removed functions with ambiguous argument order from finance.py + + +Annotation +---------- +Removed ``textcoords`` and ``xytext`` proprieties from Annotation objects. + + +spinxext.ipython_*.py +--------------------- +Both ``ipython_console_highlighting`` and ``ipython_directive`` have been moved to +`IPython`. + +Change your import from 'matplotlib.sphinxext.ipython_directive' to +'IPython.sphinxext.ipython_directive' and from 'matplotlib.sphinxext.ipython_directive' to +'IPython.sphinxext.ipython_directive' + + +LineCollection.color +-------------------- +Deprecated in 2005, use ``set_color`` + + +remove 'faceted' as a valid value for `shading` in ``tri.tripcolor`` +-------------------------------------------------------------------- +Use `edgecolor` instead. Added validation on ``shading`` to +only be valid values. + + +Remove ``set_colorbar`` method from ``ScalarMappable`` +------------------------------------------------------ +Remove ``set_colorbar`` method, use `colorbar` attribute directly. + + +patheffects.svg +--------------- + - remove ``get_proxy_renderer`` method from ``AbstarctPathEffect`` class + - remove ``patch_alpha`` and ``offset_xy`` from ``SimplePatchShadow`` + + +Remove ``testing.image_util.py`` +-------------------------------- +Contained only a no-longer used port of functionality from PIL + + +Remove ``mlab.FIFOBuffer`` +-------------------------- +Not used internally and not part of core mission of mpl. + + +Remove ``mlab.prepca`` +---------------------- +Deprecated in 2009. + + +Remove ``NavigationToolbar2QTAgg`` +---------------------------------- +Added no functionality over the base ``NavigationToolbar2Qt`` diff --git a/lib/matplotlib/axis.py b/lib/matplotlib/axis.py index 3f0af5ec548d..b9499b789811 100644 --- a/lib/matplotlib/axis.py +++ b/lib/matplotlib/axis.py @@ -675,13 +675,6 @@ def get_transform(self): def get_scale(self): return self._scale.name - @cbook.deprecated('1.3') - def set_scale(self, value, **kwargs): - """ - This should be a private function (moved to _set_scale) - """ - self._set_scale(value, **kwargs) - def _set_scale(self, value, **kwargs): self._scale = mscale.scale_factory(value, self, **kwargs) self._scale.set_default_locators_and_formatters(self) diff --git a/lib/matplotlib/backends/backend_qt4agg.py b/lib/matplotlib/backends/backend_qt4agg.py index a597dc2b47e3..fc20578d0282 100644 --- a/lib/matplotlib/backends/backend_qt4agg.py +++ b/lib/matplotlib/backends/backend_qt4agg.py @@ -14,7 +14,7 @@ import matplotlib from matplotlib.figure import Figure -from .backend_qt5agg import NavigationToolbar2QTAgg + from .backend_qt5agg import FigureCanvasQTAggBase from .backend_agg import FigureCanvasAgg @@ -27,7 +27,6 @@ from .backend_qt4 import draw_if_interactive from .backend_qt4 import backend_version ###### -from matplotlib.cbook import mplDeprecation DEBUG = False diff --git a/lib/matplotlib/backends/backend_qt5agg.py b/lib/matplotlib/backends/backend_qt5agg.py index 9b2163611566..687f4366182b 100644 --- a/lib/matplotlib/backends/backend_qt5agg.py +++ b/lib/matplotlib/backends/backend_qt5agg.py @@ -6,12 +6,9 @@ import six -import os # not used import sys import ctypes -import warnings -import matplotlib from matplotlib.figure import Figure from .backend_agg import FigureCanvasAgg @@ -28,8 +25,6 @@ ###### -from matplotlib.cbook import mplDeprecation - DEBUG = False _decref = ctypes.pythonapi.Py_DecRef @@ -201,15 +196,5 @@ def __init__(self, figure): self._priv_update = self.update -class NavigationToolbar2QTAgg(NavigationToolbar2QT): - def __init__(*args, **kwargs): - warnings.warn('This class has been deprecated in 1.4 ' + - 'as it has no additional functionality over ' + - '`NavigationToolbar2QT`. Please change your code to ' - 'use `NavigationToolbar2QT` instead', - mplDeprecation) - NavigationToolbar2QT.__init__(*args, **kwargs) - - FigureCanvas = FigureCanvasQTAgg FigureManager = FigureManagerQT diff --git a/lib/matplotlib/cm.py b/lib/matplotlib/cm.py index 90795c754186..27e56be8fb3f 100644 --- a/lib/matplotlib/cm.py +++ b/lib/matplotlib/cm.py @@ -200,11 +200,6 @@ def __init__(self, norm=None, cmap=None): self.colorbar = None self.update_dict = {'array': False} - @cbook.deprecated('1.3', alternative='the colorbar attribute') - def set_colorbar(self, im, ax): - """set the colorbar and axes instances associated with mappable""" - self.colorbar = im - def to_rgba(self, x, alpha=None, bytes=False): """ Return a normalized rgba array corresponding to *x*. diff --git a/lib/matplotlib/collections.py b/lib/matplotlib/collections.py index d3dc38220d71..cfe14ec6c982 100644 --- a/lib/matplotlib/collections.py +++ b/lib/matplotlib/collections.py @@ -1139,18 +1139,6 @@ def set_color(self, c): """ self.set_edgecolor(c) - def color(self, c): - """ - Set the color(s) of the line collection. *c* can be a - matplotlib color arg (all patches have same color), or a - sequence or rgba tuples; if it is a sequence the patches will - cycle through the sequence - - ACCEPTS: matplotlib color arg or sequence of rgba tuples - """ - warnings.warn('LineCollection.color deprecated; use set_color instead') - return self.set_color(c) - def get_color(self): return self._edgecolors get_colors = get_color # for compatibility with old versions @@ -1505,7 +1493,7 @@ def _set_transforms(self): self._transforms[:, 1, 0] = widths * sin_angle self._transforms[:, 1, 1] = heights * cos_angle self._transforms[:, 2, 2] = 1.0 - + _affine = transforms.Affine2D if self._units == 'xy': m = ax.transData.get_affine().get_matrix().copy() diff --git a/lib/matplotlib/finance.py b/lib/matplotlib/finance.py index 53e831960bce..eec219c8bdb6 100644 --- a/lib/matplotlib/finance.py +++ b/lib/matplotlib/finance.py @@ -14,7 +14,6 @@ import contextlib import os -import sys import warnings if six.PY3: @@ -41,7 +40,6 @@ from matplotlib.patches import Rectangle from matplotlib.transforms import Affine2D -from matplotlib.cbook import mplDeprecation cachedir = get_cachedir() # cachedir will be None if there is no writable directory. @@ -81,14 +79,6 @@ (str('aclose'), np.float)]) -_warn_str = ("This function has been deprecated in 1.4 in favor " - "of `{fun}_ochl`, " - "which maintains the original argument order, " - "or `{fun}_ohlc`, " - "which uses the open-high-low-close order. " - "This function will be removed in 1.5") - - def parse_yahoo_historical_ochl(fh, adjusted=True, asobject=False): """Parse the historical data in file handle fh from yahoo finance. @@ -180,67 +170,6 @@ def parse_yahoo_historical_ohlc(fh, adjusted=True, asobject=False): ochl=False) -def parse_yahoo_historical(fh, adjusted=True, asobject=False): - """Parse the historical data in file handle fh from yahoo finance. - - - This function has been deprecated in 1.4 in favor of - `parse_yahoo_historical_ochl`, which maintains the original argument - order, or `parse_yahoo_historical_ohlc`, which uses the - open-high-low-close order. This function will be removed in 1.5 - - - Parameters - ---------- - - adjusted : bool - If True (default) replace open, close, high, low prices with - their adjusted values. The adjustment is by a scale factor, S = - adjusted_close/close. Adjusted prices are actual prices - multiplied by S. - - Volume is not adjusted as it is already backward split adjusted - by Yahoo. If you want to compute dollars traded, multiply volume - by the adjusted close, regardless of whether you choose adjusted - = True|False. - - - asobject : bool or None - If False (default for compatibility with earlier versions) - return a list of tuples containing - - d, open, close, high, low, volume - - If None (preferred alternative to False), return - a 2-D ndarray corresponding to the list of tuples. - - Otherwise return a numpy recarray with - - date, year, month, day, d, open, close, high, low, - volume, adjusted_close - - where d is a floating poing representation of date, - as returned by date2num, and date is a python standard - library datetime.date instance. - - The name of this kwarg is a historical artifact. Formerly, - True returned a cbook Bunch - holding 1-D ndarrays. The behavior of a numpy recarray is - very similar to the Bunch. - - ochl : bool - Temporary argument to select between ochl and ohlc ordering. - Defaults to True to preserve original functionality. - - """ - - warnings.warn(_warn_str.format(fun='parse_yahoo_historical'), - mplDeprecation) - - return _parse_yahoo_historical(fh, adjusted=adjusted, asobject=asobject, - ochl=True) - - def _parse_yahoo_historical(fh, adjusted=True, asobject=False, ochl=True): """Parse the historical data in file handle fh from yahoo finance. @@ -440,55 +369,6 @@ def fetch_historical_yahoo(ticker, date1, date2, cachename=None, return urlopen(url) -def quotes_historical_yahoo(ticker, date1, date2, asobject=False, - adjusted=True, cachename=None): - """ Get historical data for ticker between date1 and date2. - - - This function has been deprecated in 1.4 in favor of - `quotes_yahoo_historical_ochl`, which maintains the original argument - order, or `quotes_yahoo_historical_ohlc`, which uses the - open-high-low-close order. This function will be removed in 1.5 - - See :func:`parse_yahoo_historical` for explanation of output formats - and the *asobject* and *adjusted* kwargs. - - Parameters - ---------- - ticker : str - stock ticker - - date1 : sequence of form (year, month, day), `datetime`, or `date` - start date - - date2 : sequence of form (year, month, day), `datetime`, or `date` - end date - - cachename : str or `None` - is the name of the local file cache. If None, will - default to the md5 hash or the url (which incorporates the ticker - and date range) - - Examples - -------- - >>> sp = f.quotes_historical_yahoo('^GSPC', d1, d2, - asobject=True, adjusted=True) - >>> returns = (sp.open[1:] - sp.open[:-1])/sp.open[1:] - >>> [n,bins,patches] = hist(returns, 100) - >>> mu = mean(returns) - >>> sigma = std(returns) - >>> x = normpdf(bins, mu, sigma) - >>> plot(bins, x, color='red', lw=2) - - """ - warnings.warn(_warn_str.format(fun='quotes_historical_yahoo'), - mplDeprecation) - - return _quotes_historical_yahoo(ticker, date1, date2, asobject=asobject, - adjusted=adjusted, cachename=cachename, - ochl=True) - - def quotes_historical_yahoo_ochl(ticker, date1, date2, asobject=False, adjusted=True, cachename=None): """ Get historical data for ticker between date1 and date2. @@ -632,48 +512,6 @@ def _quotes_historical_yahoo(ticker, date1, date2, asobject=False, return ret -def plot_day_summary(ax, quotes, ticksize=3, - colorup='k', colordown='r', - ): - """Plots day summary - - Represent the time, open, close, high, low as a vertical line - ranging from low to high. The left tick is the open and the right - tick is the close. - - - This function has been deprecated in 1.4 in favor of - `plot_day_summary_ochl`, which maintains the original argument - order, or `plot_day_summary_ohlc`, which uses the - open-high-low-close order. This function will be removed in 1.5 - - - Parameters - ---------- - ax : `Axes` - an `Axes` instance to plot to - quotes : sequence of (time, open, close, high, low, ...) sequences - data to plot. time must be in float date format - see date2num - ticksize : int - open/close tick marker in points - colorup : color - the color of the lines where close >= open - colordown : color - the color of the lines where close < open - - Returns - ------- - lines : list - list of tuples of the lines added (one tuple per quote) - """ - warnings.warn(_warn_str.format(fun='plot_day_summary'), - mplDeprecation) - - return _plot_day_summary(ax, quotes, ticksize=ticksize, - colorup=colorup, colordown=colordown, - ochl=True) - - def plot_day_summary_oclh(ax, quotes, ticksize=3, colorup='k', colordown='r', ): @@ -819,56 +657,6 @@ def _plot_day_summary(ax, quotes, ticksize=3, return lines -def candlestick(ax, quotes, width=0.2, colorup='k', colordown='r', - alpha=1.0): - - """ - Plot the time, open, close, high, low as a vertical line ranging - from low to high. Use a rectangular bar to represent the - open-close span. If close >= open, use colorup to color the bar, - otherwise use colordown - - - This function has been deprecated in 1.4 in favor of - `candlestick_ochl`, which maintains the original argument - order, or `candlestick_ohlc`, which uses the - open-high-low-close order. This function will be removed in 1.5 - - - Parameters - ---------- - ax : `Axes` - an Axes instance to plot to - quotes : sequence of (time, open, close, high, low, ...) sequences - As long as the first 5 elements are these values, - the record can be as long as you want (e.g., it may store volume). - - time must be in float days format - see date2num - - width : float - fraction of a day for the rectangle width - colorup : color - the color of the rectangle where close >= open - colordown : color - the color of the rectangle where close < open - alpha : float - the rectangle alpha level - - Returns - ------- - ret : tuple - returns (lines, patches) where lines is a list of lines - added and patches is a list of the rectangle patches added - - """ - warnings.warn(_warn_str.format(fun='candlestick'), - mplDeprecation) - - return _candlestick(ax, quotes, width=width, colorup=colorup, - colordown=colordown, - alpha=alpha, ochl=True) - - def candlestick_ochl(ax, quotes, width=0.2, colorup='k', colordown='r', alpha=1.0): @@ -1030,50 +818,6 @@ def _candlestick(ax, quotes, width=0.2, colorup='k', colordown='r', return lines, patches -def plot_day_summary2(ax, opens, closes, highs, lows, ticksize=4, - colorup='k', colordown='r', - ): - """Represent the time, open, close, high, low, as a vertical line - ranging from low to high. The left tick is the open and the right - tick is the close. - - - This function has been deprecated in 1.4 in favor of - `plot_day_summary2_ochl`, which maintains the original argument - order, or `plot_day_summary2_ohlc`, which uses the - open-high-low-close order. This function will be removed in 1.5 - - - Parameters - ---------- - ax : `Axes` - an Axes instance to plot to - opens : sequence - sequence of opening values - closes : sequence - sequence of closing values - highs : sequence - sequence of high values - lows : sequence - sequence of low values - ticksize : int - size of open and close ticks in points - colorup : color - the color of the lines where close >= open - colordown : color - the color of the lines where close < open - - Returns - ------- - ret : list - a list of lines added to the axes - """ - - warnings.warn(_warn_str.format(fun='plot_day_summary2'), mplDeprecation) - return plot_day_summary2_ohlc(ax, opens, highs, lows, closes, ticksize, - colorup, colordown) - - def plot_day_summary2_ochl(ax, opens, closes, highs, lows, ticksize=4, colorup='k', colordown='r', ): @@ -1263,53 +1007,6 @@ def candlestick2_ochl(ax, opens, closes, highs, lows, width=4, alpha=alpha) -def candlestick2(ax, opens, closes, highs, lows, width=4, - colorup='k', colordown='r', - alpha=0.75, - ): - """Represent the open, close as a bar line and high low range as a - vertical line. - - This function has been deprecated in 1.4 in favor of - `candlestick2_ochl`, which maintains the original argument order, - or `candlestick2_ohlc`, which uses the open-high-low-close order. - This function will be removed in 1.5 - - - Parameters - ---------- - ax : `Axes` - an Axes instance to plot to - opens : sequence - sequence of opening values - closes : sequence - sequence of closing values - highs : sequence - sequence of high values - lows : sequence - sequence of low values - ticksize : int - size of open and close ticks in points - colorup : color - the color of the lines where close >= open - colordown : color - the color of the lines where close < open - alpha : float - bar transparency - - Returns - ------- - ret : tuple - (lineCollection, barCollection) - """ - warnings.warn(_warn_str.format(fun='candlestick2'), - mplDeprecation) - - candlestick2_ohlc(ax, opens, highs, lows, closes, width=width, - colorup=colorup, colordown=colordown, - alpha=alpha) - - def candlestick2_ohlc(ax, opens, highs, lows, closes, width=4, colorup='k', colordown='r', alpha=0.75, diff --git a/lib/matplotlib/legend.py b/lib/matplotlib/legend.py index eef8370a2325..0326f51f2c4d 100644 --- a/lib/matplotlib/legend.py +++ b/lib/matplotlib/legend.py @@ -33,8 +33,7 @@ from matplotlib import rcParams from matplotlib.artist import Artist, allow_rasterization -from matplotlib.cbook import (is_string_like, iterable, silent_list, safezip, - warn_deprecated) +from matplotlib.cbook import (is_string_like, iterable, silent_list, safezip) from matplotlib.font_manager import FontProperties from matplotlib.lines import Line2D from matplotlib.patches import Patch, Rectangle, Shadow, FancyBboxPatch @@ -647,17 +646,6 @@ def _init_legend_box(self, handles, labels, markerfirst=True): xdescent=0., ydescent=descent) handleboxes.append(handlebox) - # Deprecate the old behaviour of accepting callable - # legend handlers in favour of the "legend_artist" - # interface. - if (not hasattr(handler, 'legend_artist') and - callable(handler)): - handler.legend_artist = handler.__call__ - warn_deprecated('1.4', - ('Legend handers must now implement a ' - '"legend_artist" method rather than ' - 'being a callable.')) - # Create the artist for the legend which represents the # original artist/handle. handle_list.append(handler.legend_artist(self, orig_handle, diff --git a/lib/matplotlib/mlab.py b/lib/matplotlib/mlab.py index 78b647e92013..6e5ceabd6ca9 100644 --- a/lib/matplotlib/mlab.py +++ b/lib/matplotlib/mlab.py @@ -160,19 +160,6 @@ gtk.main() -Deprecated functions ---------------------- - -The following are deprecated; please import directly from numpy (with -care--function signatures may differ): - - -:func:`load` - Load ASCII file - use numpy.loadtxt - -:func:`save` - Save ASCII file - use numpy.savetxt - """ from __future__ import (absolute_import, division, print_function, @@ -1623,45 +1610,6 @@ def longest_ones(x): return longest_contiguous_ones(x) -def prepca(P, frac=0): - """ - - .. warning:: - - This function is deprecated -- please see class PCA instead - - Compute the principal components of *P*. *P* is a (*numVars*, - *numObs*) array. *frac* is the minimum fraction of variance that a - component must contain to be included. - - Return value is a tuple of the form (*Pcomponents*, *Trans*, - *fracVar*) where: - - - *Pcomponents* : a (numVars, numObs) array - - - *Trans* : the weights matrix, i.e., *Pcomponents* = *Trans* * - *P* - - - *fracVar* : the fraction of the variance accounted for by each - component returned - - A similar function of the same name was in the MATLAB - R13 Neural Network Toolbox but is not found in later versions; - its successor seems to be called "processpcs". - """ - warnings.warn('This function is deprecated -- see class PCA instead') - U, s, v = np.linalg.svd(P) - varEach = s**2/P.shape[1] - totVar = varEach.sum() - fracVar = varEach/totVar - ind = slice((fracVar >= frac).sum()) - # select the components that are greater - Trans = U[:, ind].transpose() - # The transformed data - Pcomponents = np.dot(Trans, P) - return Pcomponents, Trans, fracVar[ind] - - class PCA(object): def __init__(self, a, standardize=True): """ @@ -2066,103 +2014,6 @@ def fftsurr(x, detrend=detrend_none, window=window_none): return np.fft.ifft(z).real -class FIFOBuffer(object): - """ - A FIFO queue to hold incoming *x*, *y* data in a rotating buffer - using numpy arrays under the hood. It is assumed that you will - call asarrays much less frequently than you add data to the queue - -- otherwise another data structure will be faster. - - This can be used to support plots where data is added from a real - time feed and the plot object wants to grab data from the buffer - and plot it to screen less freqeuently than the incoming. - - If you set the *dataLim* attr to - :class:`~matplotlib.transforms.BBox` (e.g., - :attr:`matplotlib.Axes.dataLim`), the *dataLim* will be updated as - new data come in. - - TODO: add a grow method that will extend nmax - - .. note:: - - mlab seems like the wrong place for this class. - """ - @cbook.deprecated('1.3', name='FIFOBuffer', obj_type='class') - def __init__(self, nmax): - """ - Buffer up to *nmax* points. - """ - self._xa = np.zeros((nmax,), np.float_) - self._ya = np.zeros((nmax,), np.float_) - self._xs = np.zeros((nmax,), np.float_) - self._ys = np.zeros((nmax,), np.float_) - self._ind = 0 - self._nmax = nmax - self.dataLim = None - self.callbackd = {} - - def register(self, func, N): - """ - Call *func* every time *N* events are passed; *func* signature - is ``func(fifo)``. - """ - self.callbackd.setdefault(N, []).append(func) - - def add(self, x, y): - """ - Add scalar *x* and *y* to the queue. - """ - if self.dataLim is not None: - xy = np.asarray([(x, y)]) - self.dataLim.update_from_data_xy(xy, None) - - ind = self._ind % self._nmax - self._xs[ind] = x - self._ys[ind] = y - - for N, funcs in six.iteritems(self.callbackd): - if (self._ind % N) == 0: - for func in funcs: - func(self) - - self._ind += 1 - - def last(self): - """ - Get the last *x*, *y* or *None*. *None* if no data set. - """ - if self._ind == 0: - return None, None - ind = (self._ind-1) % self._nmax - return self._xs[ind], self._ys[ind] - - def asarrays(self): - """ - Return *x* and *y* as arrays; their length will be the len of - data added or *nmax*. - """ - if self._ind < self._nmax: - return self._xs[:self._ind], self._ys[:self._ind] - ind = self._ind % self._nmax - - self._xa[:self._nmax-ind] = self._xs[ind:] - self._xa[self._nmax-ind:] = self._xs[:ind] - self._ya[:self._nmax-ind] = self._ys[ind:] - self._ya[self._nmax-ind:] = self._ys[:ind] - - return self._xa, self._ya - - def update_datalim_to_current(self): - """ - Update the *datalim* in the current data in the fifo. - """ - if self.dataLim is None: - raise ValueError('You must first set the dataLim attr') - x, y = self.asarrays() - self.dataLim.update_from_data(x, y, True) - - def movavg(x, n): """ Compute the len(*n*) moving average of *x*. diff --git a/lib/matplotlib/patheffects.py b/lib/matplotlib/patheffects.py index 13f8ce076857..19e1c4ae90e4 100644 --- a/lib/matplotlib/patheffects.py +++ b/lib/matplotlib/patheffects.py @@ -10,9 +10,7 @@ import six from matplotlib.backend_bases import RendererBase -from matplotlib.backends.backend_mixed import MixedModeRenderer import matplotlib.transforms as mtransforms -import matplotlib.cbook as cbook from matplotlib.colors import colorConverter import matplotlib.patches as mpatches @@ -42,12 +40,6 @@ def _offset_transform(self, renderer, transform): return transform + self._offset_trans.clear().translate(offset_x, offset_y) - def get_proxy_renderer(self, renderer): - """Return a PathEffectRenderer instance for this PathEffect.""" - cbook.deprecated('v1.4', name='get_proxy_renderer', - alternative='PathEffectRenderer') - return PathEffectRenderer([self], renderer) - def _update_gc(self, gc, new_gc_dict): """ Update the given GraphicsCollection with the given @@ -219,9 +211,9 @@ def draw_path(self, renderer, gc, tpath, affine, rgbFace): class SimplePatchShadow(AbstractPathEffect): """A simple shadow via a filled patch.""" - def __init__(self, offset=(2,-2), - shadow_rgbFace=None, alpha=None, patch_alpha=None, - rho=0.3, offset_xy=None, **kwargs): + def __init__(self, offset=(2, -2), + shadow_rgbFace=None, alpha=None, + rho=0.3, **kwargs): """ Parameters ---------- @@ -241,24 +233,12 @@ def __init__(self, offset=(2,-2), :meth:`AbstractPathEffect._update_gc`. """ - if offset_xy is not None: - cbook.deprecated('v1.4', 'The offset_xy keyword is deprecated. ' - 'Use the offset keyword instead.') - offset = offset_xy super(SimplePatchShadow, self).__init__(offset) if shadow_rgbFace is None: self._shadow_rgbFace = shadow_rgbFace else: self._shadow_rgbFace = colorConverter.to_rgba(shadow_rgbFace) - if patch_alpha is not None: - cbook.deprecated('v1.4', 'The patch_alpha keyword is deprecated. ' - 'Use the alpha keyword instead. Transform your ' - 'patch_alpha by alpha = 1 - patch_alpha') - if alpha is not None: - raise ValueError("Both alpha and patch_alpha were set. " - "Just use alpha.") - alpha = 1 - patch_alpha if alpha is None: alpha = 0.3 diff --git a/lib/matplotlib/pylab.py b/lib/matplotlib/pylab.py index 86fe482ad65f..bd1b4936cdc4 100644 --- a/lib/matplotlib/pylab.py +++ b/lib/matplotlib/pylab.py @@ -253,7 +253,7 @@ from matplotlib.mlab import window_hanning, window_none, detrend, demean, \ detrend_mean, detrend_none, detrend_linear, entropy, normpdf, \ - find, longest_contiguous_ones, longest_ones, prepca, \ + find, longest_contiguous_ones, longest_ones, \ prctile, prctile_rank, \ center_matrix, rk4, bivariate_normal, get_xyz_where, \ get_sparse_matrix, dist, \ diff --git a/lib/matplotlib/sphinxext/ipython_console_highlighting.py b/lib/matplotlib/sphinxext/ipython_console_highlighting.py deleted file mode 100644 index 0ba9cab40307..000000000000 --- a/lib/matplotlib/sphinxext/ipython_console_highlighting.py +++ /dev/null @@ -1,125 +0,0 @@ -"""reST directive for syntax-highlighting ipython interactive sessions. - -XXX - See what improvements can be made based on the new (as of Sept 2009) -'pycon' lexer for the python console. At the very least it will give better -highlighted tracebacks. -""" -from __future__ import (absolute_import, division, print_function, - unicode_literals) - -import six - -#----------------------------------------------------------------------------- -# Needed modules - -# Standard library -import re - -# Third party -from pygments.lexer import Lexer, do_insertions -from pygments.lexers.agile import (PythonConsoleLexer, PythonLexer, - PythonTracebackLexer) -from pygments.token import Comment, Generic - -from sphinx import highlighting -import matplotlib - -matplotlib.cbook.warn_deprecated("1.4", """ -The Sphinx extension ipython_console_highlighting has moved from -matplotlib to IPython, and its use in matplotlib is deprecated. -Change your import from 'matplotlib.sphinxext.ipython_directive' to -'IPython.sphinxext.ipython_directive.""") - -#----------------------------------------------------------------------------- -# Global constants -line_re = re.compile('.*?\n') - -#----------------------------------------------------------------------------- -# Code begins - classes and functions - -class IPythonConsoleLexer(Lexer): - """ - For IPython console output or doctests, such as: - - .. sourcecode:: ipython - - In [1]: a = 'foo' - - In [2]: a - Out[2]: 'foo' - - In [3]: print a - foo - - In [4]: 1 / 0 - - Notes: - - - Tracebacks are not currently supported. - - - It assumes the default IPython prompts, not customized ones. - """ - - name = 'IPython console session' - aliases = ['ipython'] - mimetypes = ['text/x-ipython-console'] - input_prompt = re.compile("(In \[[0-9]+\]: )|( \.\.\.+:)") - output_prompt = re.compile("(Out\[[0-9]+\]: )|( \.\.\.+:)") - continue_prompt = re.compile(" \.\.\.+:") - tb_start = re.compile("\-+") - - def get_tokens_unprocessed(self, text): - pylexer = PythonLexer(**self.options) - tblexer = PythonTracebackLexer(**self.options) - - curcode = '' - insertions = [] - for match in line_re.finditer(text): - line = match.group() - input_prompt = self.input_prompt.match(line) - continue_prompt = self.continue_prompt.match(line.rstrip()) - output_prompt = self.output_prompt.match(line) - if line.startswith("#"): - insertions.append((len(curcode), - [(0, Comment, line)])) - elif input_prompt is not None: - insertions.append((len(curcode), - [(0, Generic.Prompt, input_prompt.group())])) - curcode += line[input_prompt.end():] - elif continue_prompt is not None: - insertions.append((len(curcode), - [(0, Generic.Prompt, continue_prompt.group())])) - curcode += line[continue_prompt.end():] - elif output_prompt is not None: - # Use the 'error' token for output. We should probably make - # our own token, but error is typicaly in a bright color like - # red, so it works fine for our output prompts. - insertions.append((len(curcode), - [(0, Generic.Error, output_prompt.group())])) - curcode += line[output_prompt.end():] - else: - if curcode: - for item in do_insertions(insertions, - pylexer.get_tokens_unprocessed(curcode)): - yield item - curcode = '' - insertions = [] - yield match.start(), Generic.Output, line - if curcode: - for item in do_insertions(insertions, - pylexer.get_tokens_unprocessed(curcode)): - yield item - - -def setup(app): - """Setup as a sphinx extension.""" - - # This is only a lexer, so adding it below to pygments appears sufficient. - # But if somebody knows that the right API usage should be to do that via - # sphinx, by all means fix it here. At least having this setup.py - # suppresses the sphinx warning we'd get without it. - pass - -#----------------------------------------------------------------------------- -# Register the extension as a valid pygments lexer -highlighting.lexers['ipython'] = IPythonConsoleLexer() diff --git a/lib/matplotlib/sphinxext/ipython_directive.py b/lib/matplotlib/sphinxext/ipython_directive.py deleted file mode 100644 index 01c64a3ce721..000000000000 --- a/lib/matplotlib/sphinxext/ipython_directive.py +++ /dev/null @@ -1,843 +0,0 @@ -# -*- coding: utf-8 -*- -"""Sphinx directive to support embedded IPython code. - -This directive allows pasting of entire interactive IPython sessions, prompts -and all, and their code will actually get re-executed at doc build time, with -all prompts renumbered sequentially. It also allows you to input code as a pure -python input by giving the argument python to the directive. The output looks -like an interactive ipython section. - -To enable this directive, simply list it in your Sphinx ``conf.py`` file -(making sure the directory where you placed it is visible to sphinx, as is -needed for all Sphinx directives). - -By default this directive assumes that your prompts are unchanged IPython ones, -but this can be customized. The configurable options that can be placed in -conf.py are - -ipython_savefig_dir: - The directory in which to save the figures. This is relative to the - Sphinx source directory. The default is `html_static_path`. -ipython_rgxin: - The compiled regular expression to denote the start of IPython input - lines. The default is re.compile('In \[(\d+)\]:\s?(.*)\s*'). You - shouldn't need to change this. -ipython_rgxout: - The compiled regular expression to denote the start of IPython output - lines. The default is re.compile('Out\[(\d+)\]:\s?(.*)\s*'). You - shouldn't need to change this. -ipython_promptin: - The string to represent the IPython input prompt in the generated ReST. - The default is 'In [%d]:'. This expects that the line numbers are used - in the prompt. -ipython_promptout: - - The string to represent the IPython prompt in the generated ReST. The - default is 'Out [%d]:'. This expects that the line numbers are used - in the prompt. - -ToDo ----- - -- Turn the ad-hoc test() function into a real test suite. -- Break up ipython-specific functionality from matplotlib stuff into better - separated code. - -Authors -------- - -- John D Hunter: orignal author. -- Fernando Perez: refactoring, documentation, cleanups, port to 0.11. -- VáclavŠmilauer : Prompt generalizations. -- Skipper Seabold, refactoring, cleanups, pure python addition -""" - -from __future__ import (absolute_import, division, print_function, - unicode_literals) - -import six -from six.moves import xrange - -#----------------------------------------------------------------------------- -# Imports -#----------------------------------------------------------------------------- - -# Stdlib -import io -import os -import re -import sys -import tempfile -import ast -from hashlib import md5 - -# Third-party -import matplotlib -import sphinx -from docutils.parsers.rst import directives -from docutils import nodes -from sphinx.util.compat import Directive - -matplotlib.use('Agg') - -matplotlib.cbook.warn_deprecated("1.4", """ -The Sphinx extension ipython_console_highlighting has moved from -matplotlib to IPython, and its use in matplotlib is deprecated. -Change your import from 'matplotlib.sphinxext.ipython_directive' to -'IPython.sphinxext.ipython_directive.""") - -# Our own -try: - from IPython import Config, InteractiveShell - from IPython.core.profiledir import ProfileDir - from IPython.utils import io -except ImportError: - raise ImportError( - "Unable to import the necessary objects from IPython. " - "You may need to install or upgrade your IPython installation.") - - -#----------------------------------------------------------------------------- -# Globals -#----------------------------------------------------------------------------- -# for tokenizing blocks -COMMENT, INPUT, OUTPUT = list(xrange(3)) - -#----------------------------------------------------------------------------- -# Functions and class declarations -#----------------------------------------------------------------------------- -def block_parser(part, rgxin, rgxout, fmtin, fmtout): - """ - part is a string of ipython text, comprised of at most one - input, one ouput, comments, and blank lines. The block parser - parses the text into a list of:: - - blocks = [ (TOKEN0, data0), (TOKEN1, data1), ...] - - where TOKEN is one of [COMMENT | INPUT | OUTPUT ] and - data is, depending on the type of token:: - - COMMENT : the comment string - - INPUT: the (DECORATOR, INPUT_LINE, REST) where - DECORATOR: the input decorator (or None) - INPUT_LINE: the input as string (possibly multi-line) - REST : any stdout generated by the input line (not OUTPUT) - - - OUTPUT: the output string, possibly multi-line - """ - - block = [] - lines = part.split('\n') - N = len(lines) - i = 0 - decorator = None - while 1: - - if i==N: - # nothing left to parse -- the last line - break - - line = lines[i] - i += 1 - line_stripped = line.strip() - if line_stripped.startswith('#'): - block.append((COMMENT, line)) - continue - - if line_stripped.startswith('@'): - # we're assuming at most one decorator -- may need to - # rethink - decorator = line_stripped - continue - - # does this look like an input line? - matchin = rgxin.match(line) - if matchin: - lineno, inputline = int(matchin.group(1)), matchin.group(2) - - # the ....: continuation string - continuation = ' %s:'%''.join(['.']*(len(str(lineno))+2)) - Nc = len(continuation) - # input lines can continue on for more than one line, if - # we have a '\' line continuation char or a function call - # echo line 'print'. The input line can only be - # terminated by the end of the block or an output line, so - # we parse out the rest of the input line if it is - # multiline as well as any echo text - - rest = [] - while i 1: - if input_lines[-1] != "": - input_lines.append('') # make sure there's a blank line - # so splitter buffer gets reset - - continuation = ' %s:'%''.join(['.']*(len(str(lineno))+2)) - Nc = len(continuation) - - if is_savefig: - image_file, image_directive = self.process_image(decorator) - - ret = [] - is_semicolon = False - - for i, line in enumerate(input_lines): - if line.endswith(';'): - is_semicolon = True - - if i==0: - # process the first input line - if is_verbatim: - self.process_input_line('') - self.IP.execution_count += 1 # increment it anyway - else: - # only submit the line in non-verbatim mode - self.process_input_line(line, store_history=True) - formatted_line = '%s %s'%(input_prompt, line) - else: - # process a continuation line - if not is_verbatim: - self.process_input_line(line, store_history=True) - - formatted_line = '%s %s'%(continuation, line) - - if not is_suppress: - ret.append(formatted_line) - - if not is_suppress and len(rest.strip()) and is_verbatim: - # the "rest" is the standard output of the - # input, which needs to be added in - # verbatim mode - ret.append(rest) - - self.cout.seek(0) - output = self.cout.read() - if not is_suppress and not is_semicolon: - ret.append(output) - elif is_semicolon: # get spacing right - ret.append('') - - self.cout.truncate(0) - return (ret, input_lines, output, is_doctest, image_file, - image_directive) - #print 'OUTPUT', output # dbg - - def process_output(self, data, output_prompt, - input_lines, output, is_doctest, image_file): - """Process data block for OUTPUT token.""" - if is_doctest: - submitted = data.strip() - found = output - if found is not None: - found = found.strip() - - # XXX - fperez: in 0.11, 'output' never comes with the prompt - # in it, just the actual output text. So I think all this code - # can be nuked... - - # the above comment does not appear to be accurate... (minrk) - - ind = found.find(output_prompt) - if ind<0: - e='output prompt="%s" does not match out line=%s' % \ - (output_prompt, found) - raise RuntimeError(e) - found = found[len(output_prompt):].strip() - - if found!=submitted: - e = ('doctest failure for input_lines="%s" with ' - 'found_output="%s" and submitted output="%s"' % - (input_lines, found, submitted) ) - raise RuntimeError(e) - #print 'doctest PASSED for input_lines="%s" with found_output="%s" and submitted output="%s"'%(input_lines, found, submitted) - - def process_comment(self, data): - """Process data fPblock for COMMENT token.""" - if not self.is_suppress: - return [data] - - def save_image(self, image_file): - """ - Saves the image file to disk. - """ - self.ensure_pyplot() - command = 'plt.gcf().savefig("%s")'%image_file - #print 'SAVEFIG', command # dbg - self.process_input_line('bookmark ipy_thisdir', store_history=False) - self.process_input_line('cd -b ipy_savedir', store_history=False) - self.process_input_line(command, store_history=False) - self.process_input_line('cd -b ipy_thisdir', store_history=False) - self.process_input_line('bookmark -d ipy_thisdir', store_history=False) - self.clear_cout() - - - def process_block(self, block): - """ - process block from the block_parser and return a list of processed lines - """ - ret = [] - output = None - input_lines = None - lineno = self.IP.execution_count - - input_prompt = self.promptin%lineno - output_prompt = self.promptout%lineno - image_file = None - image_directive = None - - for token, data in block: - if token==COMMENT: - out_data = self.process_comment(data) - elif token==INPUT: - (out_data, input_lines, output, is_doctest, image_file, - image_directive) = \ - self.process_input(data, input_prompt, lineno) - elif token==OUTPUT: - out_data = \ - self.process_output(data, output_prompt, - input_lines, output, is_doctest, - image_file) - if out_data: - ret.extend(out_data) - - # save the image files - if image_file is not None: - self.save_image(image_file) - - return ret, image_directive - - def ensure_pyplot(self): - if self._pyplot_imported: - return - self.process_input_line('import matplotlib.pyplot as plt', - store_history=False) - - def process_pure_python(self, content): - """ - content is a list of strings. it is unedited directive conent - - This runs it line by line in the InteractiveShell, prepends - prompts as needed capturing stderr and stdout, then returns - the content as a list as if it were ipython code - """ - output = [] - savefig = False # keep up with this to clear figure - multiline = False # to handle line continuation - multiline_start = None - fmtin = self.promptin - - ct = 0 - - for lineno, line in enumerate(content): - - line_stripped = line.strip() - if not len(line): - output.append(line) - continue - - # handle decorators - if line_stripped.startswith('@'): - output.extend([line]) - if 'savefig' in line: - savefig = True # and need to clear figure - continue - - # handle comments - if line_stripped.startswith('#'): - output.extend([line]) - continue - - # deal with lines checking for multiline - continuation = ' %s:'% ''.join(['.']*(len(str(ct))+2)) - if not multiline: - modified = "%s %s" % (fmtin % ct, line_stripped) - output.append(modified) - ct += 1 - try: - ast.parse(line_stripped) - output.append('') - except Exception: # on a multiline - multiline = True - multiline_start = lineno - else: # still on a multiline - modified = '%s %s' % (continuation, line) - output.append(modified) - try: - mod = ast.parse( - '\n'.join(content[multiline_start:lineno+1])) - if isinstance(mod.body[0], ast.FunctionDef): - # check to see if we have the whole function - for element in mod.body[0].body: - if isinstance(element, ast.Return): - multiline = False - else: - output.append('') - multiline = False - except Exception: - pass - - if savefig: # clear figure if plotted - self.ensure_pyplot() - self.process_input_line('plt.clf()', store_history=False) - self.clear_cout() - savefig = False - - return output - -class IpythonDirective(Directive): - - has_content = True - required_arguments = 0 - optional_arguments = 4 # python, suppress, verbatim, doctest - final_argumuent_whitespace = True - option_spec = { 'python': directives.unchanged, - 'suppress' : directives.flag, - 'verbatim' : directives.flag, - 'doctest' : directives.flag, - } - - shell = EmbeddedSphinxShell() - - def get_config_options(self): - # contains sphinx configuration variables - config = self.state.document.settings.env.config - - # get config variables to set figure output directory - confdir = self.state.document.settings.env.app.confdir - savefig_dir = config.ipython_savefig_dir - source_dir = os.path.dirname(self.state.document.current_source) - if savefig_dir is None: - savefig_dir = config.html_static_path - if isinstance(savefig_dir, list): - savefig_dir = savefig_dir[0] # safe to assume only one path? - savefig_dir = os.path.join(confdir, savefig_dir) - - # get regex and prompt stuff - rgxin = config.ipython_rgxin - rgxout = config.ipython_rgxout - promptin = config.ipython_promptin - promptout = config.ipython_promptout - - return savefig_dir, source_dir, rgxin, rgxout, promptin, promptout - - def setup(self): - # reset the execution count if we haven't processed this doc - #NOTE: this may be borked if there are multiple seen_doc tmp files - #check time stamp? - seen_docs = [i for i in os.listdir(tempfile.tempdir) - if i.startswith('seen_doc')] - if seen_docs: - fname = os.path.join(tempfile.tempdir, seen_docs[0]) - docs = open(fname).read().split('\n') - if not self.state.document.current_source in docs: - self.shell.IP.history_manager.reset() - self.shell.IP.execution_count = 1 - else: # haven't processed any docs yet - docs = [] - - - # get config values - (savefig_dir, source_dir, rgxin, - rgxout, promptin, promptout) = self.get_config_options() - - # and attach to shell so we don't have to pass them around - self.shell.rgxin = rgxin - self.shell.rgxout = rgxout - self.shell.promptin = promptin - self.shell.promptout = promptout - self.shell.savefig_dir = savefig_dir - self.shell.source_dir = source_dir - - # setup bookmark for saving figures directory - - self.shell.process_input_line('bookmark ipy_savedir %s'%savefig_dir, - store_history=False) - self.shell.clear_cout() - - # write the filename to a tempfile because it's been "seen" now - if not self.state.document.current_source in docs: - fd, fname = tempfile.mkstemp(prefix="seen_doc", text=True) - fout = open(fname, 'a') - fout.write(self.state.document.current_source+'\n') - fout.close() - - return rgxin, rgxout, promptin, promptout - - - def teardown(self): - # delete last bookmark - self.shell.process_input_line('bookmark -d ipy_savedir', - store_history=False) - self.shell.clear_cout() - - def run(self): - debug = False - - #TODO, any reason block_parser can't be a method of embeddable shell - # then we wouldn't have to carry these around - rgxin, rgxout, promptin, promptout = self.setup() - - options = self.options - self.shell.is_suppress = 'suppress' in options - self.shell.is_doctest = 'doctest' in options - self.shell.is_verbatim = 'verbatim' in options - - - # handle pure python code - if 'python' in self.arguments: - content = self.content - self.content = self.shell.process_pure_python(content) - - parts = '\n'.join(self.content).split('\n\n') - - lines = ['.. code-block:: ipython',''] - figures = [] - - for part in parts: - - block = block_parser(part, rgxin, rgxout, promptin, promptout) - - if len(block): - rows, figure = self.shell.process_block(block) - for row in rows: - lines.extend([' %s'%line for line in row.split('\n')]) - - if figure is not None: - figures.append(figure) - - #text = '\n'.join(lines) - #figs = '\n'.join(figures) - - for figure in figures: - lines.append('') - lines.extend(figure.split('\n')) - lines.append('') - - #print lines - if len(lines)>2: - if debug: - print('\n'.join(lines)) - else: #NOTE: this raises some errors, what's it for? - #print 'INSERTING %d lines'%len(lines) - self.state_machine.insert_input( - lines, self.state_machine.input_lines.source(0)) - - text = '\n'.join(lines) - txtnode = nodes.literal_block(text, text) - txtnode['language'] = 'ipython' - #imgnode = nodes.image(figs) - - # cleanup - self.teardown() - - return []#, imgnode] - -# Enable as a proper Sphinx directive -def setup(app): - setup.app = app - - app.add_directive('ipython', IpythonDirective) - app.add_config_value('ipython_savefig_dir', None, True) - app.add_config_value('ipython_rgxin', - re.compile('In \[(\d+)\]:\s?(.*)\s*'), True) - app.add_config_value('ipython_rgxout', - re.compile('Out\[(\d+)\]:\s?(.*)\s*'), True) - app.add_config_value('ipython_promptin', 'In [%d]:', True) - app.add_config_value('ipython_promptout', 'Out[%d]:', True) - - -# Simple smoke test, needs to be converted to a proper automatic test. -def test(): - - examples = [ - r""" -In [9]: pwd -Out[9]: '/home/jdhunter/py4science/book' - -In [10]: cd bookdata/ -/home/jdhunter/py4science/book/bookdata - -In [2]: from pylab import * - -In [2]: ion() - -In [3]: im = imread('stinkbug.png') - -@savefig mystinkbug.png width=4in -In [4]: imshow(im) -Out[4]: - -""", - r""" - -In [1]: x = 'hello world' - -# string methods can be -# used to alter the string -@doctest -In [2]: x.upper() -Out[2]: 'HELLO WORLD' - -@verbatim -In [3]: x.st -x.startswith x.strip -""", - r""" - -In [130]: url = 'http://ichart.finance.yahoo.com/table.csv?s=CROX\ - .....: &d=9&e=22&f=2009&g=d&a=1&br=8&c=2006&ignore=.csv' - -In [131]: print url.split('&') -['http://ichart.finance.yahoo.com/table.csv?s=CROX', 'd=9', 'e=22', 'f=2009', 'g=d', 'a=1', 'b=8', 'c=2006', 'ignore=.csv'] - -In [60]: import urllib - -""", - r"""\ - -In [133]: import numpy.random - -@suppress -In [134]: numpy.random.seed(2358) - -@doctest -In [135]: numpy.random.rand(10,2) -Out[135]: -array([[ 0.64524308, 0.59943846], - [ 0.47102322, 0.8715456 ], - [ 0.29370834, 0.74776844], - [ 0.99539577, 0.1313423 ], - [ 0.16250302, 0.21103583], - [ 0.81626524, 0.1312433 ], - [ 0.67338089, 0.72302393], - [ 0.7566368 , 0.07033696], - [ 0.22591016, 0.77731835], - [ 0.0072729 , 0.34273127]]) - -""", - - r""" -In [106]: print x -jdh - -In [109]: for i in range(10): - .....: print i - .....: - .....: -0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -""", - - r""" - -In [144]: from pylab import * - -In [145]: ion() - -# use a semicolon to suppress the output -@savefig test_hist.png width=4in -In [151]: hist(np.random.randn(10000), 100); - - -@savefig test_plot.png width=4in -In [151]: plot(np.random.randn(10000), 'o'); - """, - - r""" -# use a semicolon to suppress the output -In [151]: plt.clf() - -@savefig plot_simple.png width=4in -In [151]: plot([1,2,3]) - -@savefig hist_simple.png width=4in -In [151]: hist(np.random.randn(10000), 100); - -""", - r""" -# update the current fig -In [151]: ylabel('number') - -In [152]: title('normal distribution') - - -@savefig hist_with_text.png -In [153]: grid(True) - - """, - ] - # skip local-file depending first example: - examples = examples[1:] - - #ipython_directive.DEBUG = True # dbg - #options = dict(suppress=True) # dbg - options = dict() - for example in examples: - content = example.split('\n') - ipython_directive('debug', arguments=None, options=options, - content=content, lineno=0, - content_offset=None, block_text=None, - state=None, state_machine=None, - ) - -# Run test suite as a script -if __name__=='__main__': - if not os.path.isdir('_static'): - os.mkdir('_static') - test() - print('All OK? Check figures in _static/') diff --git a/lib/matplotlib/testing/image_util.py b/lib/matplotlib/testing/image_util.py deleted file mode 100644 index 92bc0d6e8962..000000000000 --- a/lib/matplotlib/testing/image_util.py +++ /dev/null @@ -1,111 +0,0 @@ -# This module contains some functionality from the Python Imaging -# Library, that has been ported to use Numpy arrays rather than PIL -# Image objects. - - -# The Python Imaging Library is - -# Copyright (c) 1997-2009 by Secret Labs AB -# Copyright (c) 1995-2009 by Fredrik Lundh - -# By obtaining, using, and/or copying this software and/or its -# associated documentation, you agree that you have read, understood, -# and will comply with the following terms and conditions: - -# Permission to use, copy, modify, and distribute this software and its -# associated documentation for any purpose and without fee is hereby -# granted, provided that the above copyright notice appears in all -# copies, and that both that copyright notice and this permission notice -# appear in supporting documentation, and that the name of Secret Labs -# AB or the author not be used in advertising or publicity pertaining to -# distribution of the software without specific, written prior -# permission. - -# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO -# THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND -# FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR BE LIABLE FOR -# ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT -# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -from __future__ import (absolute_import, division, print_function, - unicode_literals) - -import six -from six.moves import xrange - -import numpy as np - -from matplotlib.cbook import deprecated, warn_deprecated - - -warn_deprecated('1.4.0', name='matplotlib.testing.image_util', - obj_type='module') - - -@deprecated('1.4.0') -def autocontrast(image, cutoff=0): - """ - Maximize image contrast, based on histogram. This completely - ignores the alpha channel. - """ - assert image.dtype == np.uint8 - - output_image = np.empty((image.shape[0], image.shape[1], 3), np.uint8) - - for i in xrange(0, 3): - plane = image[:,:,i] - output_plane = output_image[:,:,i] - h = np.histogram(plane, bins=256)[0] - if cutoff: - # cut off pixels from both ends of the histogram - # get number of pixels - n = 0 - for ix in xrange(256): - n = n + h[ix] - # remove cutoff% pixels from the low end - cut = n * cutoff / 100 - for lo in range(256): - if cut > h[lo]: - cut = cut - h[lo] - h[lo] = 0 - else: - h[lo] = h[lo] - cut - cut = 0 - if cut <= 0: - break - # remove cutoff% samples from the hi end - cut = n * cutoff / 100 - for hi in xrange(255, -1, -1): - if cut > h[hi]: - cut = cut - h[hi] - h[hi] = 0 - else: - h[hi] = h[hi] - cut - cut = 0 - if cut <= 0: - break - - # find lowest/highest samples after preprocessing - for lo in xrange(256): - if h[lo]: - break - for hi in xrange(255, -1, -1): - if h[hi]: - break - - if hi <= lo: - output_plane[:,:] = plane - else: - scale = 255.0 / (hi - lo) - offset = -lo * scale - lut = np.arange(256, dtype=np.float) - lut *= scale - lut += offset - lut = lut.clip(0, 255) - lut = lut.astype(np.uint8) - - output_plane[:,:] = lut[plane] - - return output_image diff --git a/lib/matplotlib/tests/test_coding_standards.py b/lib/matplotlib/tests/test_coding_standards.py index 59413cadea47..ec997db14ed7 100644 --- a/lib/matplotlib/tests/test_coding_standards.py +++ b/lib/matplotlib/tests/test_coding_standards.py @@ -190,7 +190,6 @@ def test_pep8_conformance_installed_files(): 'type1font.py', 'widgets.py', 'testing/decorators.py', - 'testing/image_util.py', 'testing/noseclasses.py', 'testing/jpl_units/Duration.py', 'testing/jpl_units/Epoch.py', @@ -241,8 +240,6 @@ def test_pep8_conformance_installed_files(): 'backends/tkagg.py', 'backends/windowing.py', 'backends/qt_editor/formlayout.py', - 'sphinxext/ipython_console_highlighting.py', - 'sphinxext/ipython_directive.py', 'sphinxext/mathmpl.py', 'sphinxext/only_directives.py', 'sphinxext/plot_directive.py', diff --git a/lib/matplotlib/tests/test_legend.py b/lib/matplotlib/tests/test_legend.py index 549391c0b379..91f8da476903 100644 --- a/lib/matplotlib/tests/test_legend.py +++ b/lib/matplotlib/tests/test_legend.py @@ -170,34 +170,6 @@ def test_legend_remove(): class TestLegendFunction(object): # Tests the legend function on the Axes and pyplot. - - @cleanup - def test_old_legend_handler_interface(self): - # Check the deprecated warning is created and that the appropriate - # call to the legend handler is made. - class AnyObject(object): - pass - - class AnyObjectHandler(object): - def __call__(self, legend, orig_handle, fontsize, handlebox): - x0, y0 = handlebox.xdescent, handlebox.ydescent - width, height = handlebox.width, handlebox.height - patch = mpatches.Rectangle([x0, y0], width, height, facecolor='red', - edgecolor='black', hatch='xx', lw=3, - transform=handlebox.get_transform()) - handlebox.add_artist(patch) - return patch - - with mock.patch('warnings.warn') as warn: - plt.legend([None], ['My first handler'], - handler_map={None: AnyObjectHandler()}) - - warn.assert_called_with('Legend handers must now implement a ' - '"legend_artist" method rather than ' - 'being a callable.', - MatplotlibDeprecationWarning, - stacklevel=1) - @cleanup def test_legend_handle_label(self): lines = plt.plot(range(10)) diff --git a/lib/matplotlib/tests/test_patheffects.py b/lib/matplotlib/tests/test_patheffects.py index 8298cebd0b24..5af71e538f43 100644 --- a/lib/matplotlib/tests/test_patheffects.py +++ b/lib/matplotlib/tests/test_patheffects.py @@ -5,7 +5,8 @@ import numpy as np -from matplotlib.testing.decorators import image_comparison, cleanup +from matplotlib.testing.decorators import (image_comparison, cleanup, + knownfailureif) import matplotlib.pyplot as plt import matplotlib.patheffects as path_effects @@ -84,19 +85,7 @@ def test_patheffect3(): @cleanup -def test_PathEffect_get_proxy(): - pe = path_effects.AbstractPathEffect() - fig = plt.gcf() - renderer = fig.canvas.get_renderer() - - with mock.patch('matplotlib.cbook.deprecated') as dep: - proxy_renderer = pe.get_proxy_renderer(renderer) - assert_equal(proxy_renderer._renderer, renderer) - assert_equal(proxy_renderer._path_effects, [pe]) - dep.assert_called() - - -@cleanup +@knownfailureif(True) def test_PathEffect_points_to_pixels(): fig = plt.figure(dpi=150) p1, = plt.plot(range(10)) @@ -116,11 +105,9 @@ def test_PathEffect_points_to_pixels(): pe_renderer.points_to_pixels(15)) -def test_SimplePatchShadow_offset_xy(): - with mock.patch('matplotlib.cbook.deprecated') as dep: - pe = path_effects.SimplePatchShadow(offset_xy=(4, 5)) +def test_SimplePatchShadow_offset(): + pe = path_effects.SimplePatchShadow(offset=(4, 5)) assert_equal(pe._offset, (4, 5)) - dep.assert_called() @image_comparison(baseline_images=['collection']) diff --git a/lib/matplotlib/text.py b/lib/matplotlib/text.py index 1b86d4597801..105ca0c86d13 100644 --- a/lib/matplotlib/text.py +++ b/lib/matplotlib/text.py @@ -1723,30 +1723,6 @@ def draggable(self, state=None, use_blit=False): return self._draggable - @property - @cbook.deprecated('1.4', message='Use `anncoords` instead', - name='textcoords', alternative='anncoords') - def textcoords(self): - return self.anncoords - - @textcoords.setter - @cbook.deprecated('1.4', message='Use `anncoords` instead', - name='textcoords', alternative='anncoords') - def textcoords(self, val): - self.anncoords = val - - @property - @cbook.deprecated('1.4', message='Use `xyann` instead', - name='xytext', alternative='xyann') - def xytext(self): - return self.xyann - - @xytext.setter - @cbook.deprecated('1.4', message='Use `xyann` instead', - name='xytext', alternative='xyann') - def xytext(self, val): - self.xyann = val - class Annotation(Text, _AnnotationBase): """ diff --git a/lib/matplotlib/tri/tripcolor.py b/lib/matplotlib/tri/tripcolor.py index 7221ce2e1082..449ec03a0ed5 100644 --- a/lib/matplotlib/tri/tripcolor.py +++ b/lib/matplotlib/tri/tripcolor.py @@ -44,8 +44,7 @@ def tripcolor(ax, *args, **kwargs): is 'flat' and C values are defined at points, the color values used for each triangle are from the mean C of the triangle's three points. If *shading* is 'gouraud' then color values must be - defined at points. *shading* of 'faceted' is deprecated; - please use *edgecolors* instead. + defined at points. The remaining kwargs are the same as for :meth:`~matplotlib.axes.Axes.pcolor`. @@ -65,6 +64,10 @@ def tripcolor(ax, *args, **kwargs): shading = kwargs.pop('shading', 'flat') facecolors = kwargs.pop('facecolors', None) + if shading not in ['flat', 'gouraud']: + raise ValueError("shading must be one of ['flat', 'gouraud'] " + "not {}".format(shading)) + tri, args, kwargs = Triangulation.get_from_args_and_kwargs(*args, **kwargs) # C is the colors array defined at either points or faces (i.e. triangles). @@ -97,10 +100,7 @@ def tripcolor(ax, *args, **kwargs): kwargs['linewidths'] = kwargs.pop('linewidth') kwargs.setdefault('linewidths', linewidths) - if shading == 'faceted': # Deprecated. - edgecolors = 'k' - else: - edgecolors = 'none' + edgecolors = 'none' if 'edgecolor' in kwargs: kwargs['edgecolors'] = kwargs.pop('edgecolor') ec = kwargs.setdefault('edgecolors', edgecolors) pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy