Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit d7162a5

Browse files
committed
Remove workarounds for numpy<1.10.
Also py3fy category.py.
1 parent 74b6913 commit d7162a5

11 files changed

Lines changed: 39 additions & 170 deletions

File tree

examples/mplot3d/hist3d.py

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -20,18 +20,14 @@
2020
hist, xedges, yedges = np.histogram2d(x, y, bins=4, range=[[0, 4], [0, 4]])
2121

2222
# Construct arrays for the anchor positions of the 16 bars.
23-
# Note: np.meshgrid gives arrays in (ny, nx) so we use 'F' to flatten xpos,
24-
# ypos in column-major order. For numpy >= 1.7, we could instead call meshgrid
25-
# with indexing='ij'.
26-
xpos, ypos = np.meshgrid(xedges[:-1] + 0.25, yedges[:-1] + 0.25)
27-
xpos = xpos.flatten('F')
28-
ypos = ypos.flatten('F')
29-
zpos = np.zeros_like(xpos)
23+
xpos, ypos = np.meshgrid(xedges[:-1] + 0.25, yedges[:-1] + 0.25, indexing="ij")
24+
xpos = xpos.ravel()
25+
ypos = ypos.ravel()
26+
zpos = 0
3027

3128
# Construct arrays with the dimensions for the 16 bars.
32-
dx = 0.5 * np.ones_like(zpos)
33-
dy = dx.copy()
34-
dz = hist.flatten()
29+
dx = dy = 0.5 * np.ones_like(zpos)
30+
dz = hist.ravel()
3531

3632
ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color='b', zsort='average')
3733

lib/matplotlib/__init__.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,8 @@
141141
# definitions, so it is safe to import from it here.
142142
from . import cbook
143143
from matplotlib.cbook import (
144-
_backports, mplDeprecation, dedent, get_label, sanitize_sequence)
144+
mplDeprecation, dedent, get_label, sanitize_sequence)
145+
from matplotlib.compat import subprocess
145146
from matplotlib.rcsetup import defaultParams, validate_backend, cycler
146147

147148
import numpy
@@ -156,7 +157,7 @@
156157

157158
_log = logging.getLogger(__name__)
158159

159-
__version__numpy__ = str('1.10.0') # minimum required numpy version
160+
__version__numpy__ = '1.10.0' # minimum required numpy version
160161

161162
__bibtex__ = r"""@Article{Hunter:2007,
162163
Author = {Hunter, J. D.},

lib/matplotlib/axes/_axes.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,8 @@
4040
import matplotlib.transforms as mtransforms
4141
import matplotlib.tri as mtri
4242
from matplotlib.cbook import (
43-
_backports, mplDeprecation, warn_deprecated,
44-
STEP_LOOKUP_MAP, iterable, safe_first_element)
43+
mplDeprecation, warn_deprecated, STEP_LOOKUP_MAP, iterable,
44+
safe_first_element)
4545
from matplotlib.container import BarContainer, ErrorbarContainer, StemContainer
4646
from matplotlib.axes._base import _AxesBase, _process_plot_format
4747

@@ -2316,7 +2316,7 @@ def bar(self, *args, **kwargs):
23162316
self.add_container(bar_container)
23172317

23182318
if tick_labels is not None:
2319-
tick_labels = _backports.broadcast_to(tick_labels, len(patches))
2319+
tick_labels = np.broadcast_to(tick_labels, len(patches))
23202320
tick_label_axis.set_ticks(tick_label_position)
23212321
tick_label_axis.set_ticklabels(tick_labels)
23222322

lib/matplotlib/category.py

Lines changed: 11 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
# -*- coding: utf-8 -*-
21
"""
32
Module that allows plotting of string "category" data. i.e.
43
``plot(['d', 'f', 'a'],[1, 2, 3])`` will plot three points with x-axis
@@ -11,26 +10,15 @@
1110
strings to integers, provides a tick locator and formatter, and the
1211
class:`.UnitData` that creates and stores the string-to-integer mapping.
1312
"""
14-
from __future__ import (absolute_import, division, print_function,
15-
unicode_literals)
1613

1714
from collections import OrderedDict
1815
import itertools
1916

20-
import six
21-
22-
2317
import numpy as np
2418

2519
import matplotlib.units as units
2620
import matplotlib.ticker as ticker
2721

28-
# np 1.6/1.7 support
29-
from distutils.version import LooseVersion
30-
31-
VALID_TYPES = tuple(set(six.string_types +
32-
(bytes, six.text_type, np.str_, np.bytes_)))
33-
3422

3523
class StrCategoryConverter(units.ConversionInterface):
3624
@staticmethod
@@ -58,7 +46,7 @@ def convert(value, unit, axis):
5846

5947
# pass through sequence of non binary numbers
6048
if all((units.ConversionInterface.is_numlike(v) and
61-
not isinstance(v, VALID_TYPES)) for v in values):
49+
not isinstance(v, (str, bytes))) for v in values):
6250
return np.asarray(values, dtype=float)
6351

6452
# force an update so it also does type checking
@@ -96,7 +84,7 @@ def axisinfo(unit, axis):
9684

9785
@staticmethod
9886
def default_units(data, axis):
99-
""" Sets and updates the :class:`~matplotlib.Axis.axis~ units
87+
"""Sets and updates the :class:`~matplotlib.Axis.axis` units.
10088
10189
Parameters
10290
----------
@@ -156,28 +144,27 @@ def __call__(self, x, pos=None):
156144

157145
@staticmethod
158146
def _text(value):
159-
"""Converts text values into `utf-8` or `ascii` strings
147+
"""Converts text values into utf-8 or ascii strings.
160148
"""
161-
if LooseVersion(np.__version__) < LooseVersion('1.7.0'):
162-
if (isinstance(value, (six.text_type, np.unicode))):
163-
value = value.encode('utf-8', 'ignore').decode('utf-8')
164-
if isinstance(value, (np.bytes_, six.binary_type)):
149+
if isinstance(value, bytes):
165150
value = value.decode(encoding='utf-8')
166-
elif not isinstance(value, (np.str_, six.string_types)):
151+
elif not isinstance(value, str):
167152
value = str(value)
168153
return value
169154

170155

171156
class UnitData(object):
172157
def __init__(self, data=None):
173-
"""Create mapping between unique categorical values
174-
and integer identifiers
158+
"""
159+
Create mapping between unique categorical values and integer ids.
160+
161+
Parameters
175162
----------
176163
data: iterable
177164
sequence of string values
178165
"""
179166
self._mapping = OrderedDict()
180-
self._counter = itertools.count(start=0)
167+
self._counter = itertools.count()
181168
if data is not None:
182169
self.update(data)
183170

@@ -197,7 +184,7 @@ def update(self, data):
197184
data = np.atleast_1d(np.array(data, dtype=object))
198185

199186
for val in OrderedDict.fromkeys(data):
200-
if not isinstance(val, VALID_TYPES):
187+
if not isinstance(val, (str, bytes)):
201188
raise TypeError("{val!r} is not a string".format(val=val))
202189
if val not in self._mapping:
203190
self._mapping[val] = next(self._counter)
@@ -206,6 +193,5 @@ def update(self, data):
206193
# Connects the convertor to matplotlib
207194
units.registry[str] = StrCategoryConverter()
208195
units.registry[np.str_] = StrCategoryConverter()
209-
units.registry[six.text_type] = StrCategoryConverter()
210196
units.registry[bytes] = StrCategoryConverter()
211197
units.registry[np.bytes_] = StrCategoryConverter()

lib/matplotlib/cbook/_backports.py

Lines changed: 0 additions & 78 deletions
This file was deleted.

lib/matplotlib/colors.py

Lines changed: 2 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1485,8 +1485,7 @@ def hsv_to_rgb(hsv):
14851485
g[idx] = v[idx]
14861486
b[idx] = v[idx]
14871487

1488-
# `np.stack([r, g, b], axis=-1)` (numpy 1.10).
1489-
rgb = np.concatenate([r[..., None], g[..., None], b[..., None]], -1)
1488+
rgb = np.stack([r, g, b], axis=-1)
14901489

14911490
if in_ndim == 1:
14921491
rgb.shape = (3,)
@@ -1508,17 +1507,6 @@ def _vector_magnitude(arr):
15081507
return np.sqrt(sum_sq)
15091508

15101509

1511-
def _vector_dot(a, b):
1512-
# things that don't work here:
1513-
# * a.dot(b) - fails on masked arrays until 1.10
1514-
# * np.ma.dot(a, b) - doesn't mask enough things
1515-
# * np.ma.dot(a, b, strict=True) - returns a maskedarray with no mask
1516-
dot = 0
1517-
for i in range(a.shape[-1]):
1518-
dot += a[..., i] * b[..., i]
1519-
return dot
1520-
1521-
15221510
class LightSource(object):
15231511
"""
15241512
Create a light source coming from the specified azimuth and elevation.
@@ -1655,7 +1643,7 @@ def shade_normals(self, normals, fraction=1.):
16551643
completely in shadow and 1 is completely illuminated.
16561644
"""
16571645

1658-
intensity = _vector_dot(normals, self.direction)
1646+
intensity = normals.dot(self.direction)
16591647

16601648
# Apply contrast stretch
16611649
imin, imax = intensity.min(), intensity.max()

lib/matplotlib/tests/test_axes.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@
2525
from numpy.testing import assert_allclose, assert_array_equal
2626
from matplotlib.cbook import (
2727
IgnoredKeywordWarning, MatplotlibDeprecationWarning)
28-
from matplotlib.cbook._backports import broadcast_to
2928

3029
# Note: Some test cases are run twice: once normally and once with labeled data
3130
# These two must be defined in the same test function or need to have
@@ -3187,7 +3186,7 @@ def test_eventplot_colors(colors):
31873186
# NB: ['rgbk'] is not a valid argument for to_rgba_array, while 'rgbk' is.
31883187
if len(expected) == 1:
31893188
expected = expected[0]
3190-
expected = broadcast_to(mcolors.to_rgba_array(expected), (len(data), 4))
3189+
expected = np.broadcast_to(mcolors.to_rgba_array(expected), (len(data), 4))
31913190

31923191
fig, ax = plt.subplots()
31933192
if len(colors) == 1: # tuple with a single string (like '0.5' or 'rgbk')

lib/matplotlib/tests/test_colors.py

Lines changed: 1 addition & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,7 @@
1-
from __future__ import absolute_import, division, print_function
2-
31
import copy
42
import six
53
import itertools
64
import warnings
7-
from distutils.version import LooseVersion as V
85

96
import numpy as np
107
import pytest
@@ -458,17 +455,9 @@ def test_light_source_shading_default():
458455
[1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00]]
459456
]).T
460457

461-
if (V(np.__version__) == V('1.9.0')):
462-
# Numpy 1.9.0 uses a 2. order algorithm on the edges by default
463-
# This was changed back again in 1.9.1
464-
expect = expect[1:-1, 1:-1, :]
465-
rgb = rgb[1:-1, 1:-1, :]
466-
467458
assert_array_almost_equal(rgb, expect, decimal=2)
468459

469460

470-
@pytest.mark.xfail(V('1.7.0') <= V(np.__version__) <= V('1.9.0'),
471-
reason='NumPy version is not buggy')
472461
# Numpy 1.9.1 fixed a bug in masked arrays which resulted in
473462
# additional elements being masked when calculating the gradient thus
474463
# the output is different with earlier numpy versions.
@@ -538,14 +527,7 @@ def alternative_hillshade(azimuth, elev, z):
538527
dy = -dy
539528
dz = np.ones_like(dy)
540529
normals = np.dstack([dx, dy, dz])
541-
dividers = np.zeros_like(z)[..., None]
542-
for i, mat in enumerate(normals):
543-
for j, vec in enumerate(mat):
544-
dividers[i, j, 0] = np.linalg.norm(vec)
545-
normals /= dividers
546-
# once we drop support for numpy 1.7.x the above can be written as
547-
# normals /= np.linalg.norm(normals, axis=2)[..., None]
548-
# aviding the double loop.
530+
normals /= np.linalg.norm(normals, axis=2)[..., None]
549531

550532
intensity = np.tensordot(normals, illum, axes=(2, 0))
551533
intensity -= intensity.min()

0 commit comments

Comments
 (0)