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

Skip to content

Commit c8d1656

Browse files
authored
Merge pull request #24295 from anntzer/ua
Remove unnecessary np.{,as}array / astype calls.
2 parents c8b9eb4 + 1068a6f commit c8d1656

20 files changed

+52
-67
lines changed

examples/event_handling/path_editor.py

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -82,17 +82,12 @@ def get_ind_under_point(self, event):
8282
Return the index of the point closest to the event position or *None*
8383
if no point is within ``self.epsilon`` to the event position.
8484
"""
85-
# display coords
86-
xy = np.asarray(self.pathpatch.get_path().vertices)
87-
xyt = self.pathpatch.get_transform().transform(xy)
85+
xy = self.pathpatch.get_path().vertices
86+
xyt = self.pathpatch.get_transform().transform(xy) # to display coords
8887
xt, yt = xyt[:, 0], xyt[:, 1]
8988
d = np.sqrt((xt - event.x)**2 + (yt - event.y)**2)
9089
ind = d.argmin()
91-
92-
if d[ind] >= self.epsilon:
93-
ind = None
94-
95-
return ind
90+
return ind if d[ind] < self.epsilon else None
9691

9792
def on_draw(self, event):
9893
"""Callback for draws."""

examples/subplots_axes_and_figures/secondary_axis.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ def rad2deg(x):
5959

6060
def one_over(x):
6161
"""Vectorized 1/x, treating x==0 manually"""
62-
x = np.array(x).astype(float)
62+
x = np.array(x, float)
6363
near_zero = np.isclose(x, 0)
6464
x[near_zero] = np.inf
6565
x[~near_zero] = 1 / x[~near_zero]

examples/units/basic_units.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,7 @@ def __getattribute__(self, name):
144144
return object.__getattribute__(self, name)
145145

146146
def __array__(self, dtype=object):
147-
return np.asarray(self.value).astype(dtype)
147+
return np.asarray(self.value, dtype)
148148

149149
def __array_wrap__(self, array, context):
150150
return TaggedValue(array, self.unit)

lib/matplotlib/backend_bases.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1464,7 +1464,7 @@ def on_pick(event):
14641464
line = event.artist
14651465
xdata, ydata = line.get_data()
14661466
ind = event.ind
1467-
print('on pick line:', np.array([xdata[ind], ydata[ind]]).T)
1467+
print(f'on pick line: {xdata[ind]:.3f}, {ydata[ind]:.3f}')
14681468
14691469
cid = fig.canvas.mpl_connect('pick_event', on_pick)
14701470
"""

lib/matplotlib/collections.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -547,8 +547,8 @@ def set_offsets(self, offsets):
547547
if offsets.shape == (2,): # Broadcast (2,) -> (1, 2) but nothing else.
548548
offsets = offsets[None, :]
549549
self._offsets = np.column_stack(
550-
(np.asarray(self.convert_xunits(offsets[:, 0]), 'float'),
551-
np.asarray(self.convert_yunits(offsets[:, 1]), 'float')))
550+
(np.asarray(self.convert_xunits(offsets[:, 0]), float),
551+
np.asarray(self.convert_yunits(offsets[:, 1]), float)))
552552
self.stale = True
553553

554554
def get_offsets(self):
@@ -573,7 +573,7 @@ def set_linewidth(self, lw):
573573
if lw is None:
574574
lw = self._get_default_linewidth()
575575
# get the un-scaled/broadcast lw
576-
self._us_lw = np.atleast_1d(np.asarray(lw))
576+
self._us_lw = np.atleast_1d(lw)
577577

578578
# scale all of the dash patterns.
579579
self._linewidths, self._linestyles = self._bcast_lwls(

lib/matplotlib/contour.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1144,7 +1144,7 @@ def _process_contour_level_args(self, args):
11441144
if isinstance(levels_arg, Integral):
11451145
self.levels = self._autolev(levels_arg)
11461146
else:
1147-
self.levels = np.asarray(levels_arg).astype(np.float64)
1147+
self.levels = np.asarray(levels_arg, np.float64)
11481148

11491149
if not self.filled:
11501150
inside = (self.levels > self.zmin) & (self.levels < self.zmax)

lib/matplotlib/image.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1701,7 +1701,7 @@ def _pil_png_to_float_array(pil_png):
17011701
mode = pil_png.mode
17021702
rawmode = pil_png.png.im_rawmode
17031703
if rawmode == "1": # Grayscale.
1704-
return np.asarray(pil_png).astype(np.float32)
1704+
return np.asarray(pil_png, np.float32)
17051705
if rawmode == "L;2": # Grayscale.
17061706
return np.divide(pil_png, 2**2 - 1, dtype=np.float32)
17071707
if rawmode == "L;4": # Grayscale.

lib/matplotlib/patches.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1221,9 +1221,7 @@ def _recompute_path(self):
12211221
arc.codes, [connector, connector, Path.CLOSEPOLY]])
12221222

12231223
# Shift and scale the wedge to the final location.
1224-
v *= self.r
1225-
v += np.asarray(self.center)
1226-
self._path = Path(v, c)
1224+
self._path = Path(v * self.r + self.center, c)
12271225

12281226
def set_center(self, center):
12291227
self._path = None

lib/matplotlib/sankey.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -434,10 +434,7 @@ def add(self, patchlabel='', flows=None, orientations=None, labels='',
434434
Sankey.finish
435435
"""
436436
# Check and preprocess the arguments.
437-
if flows is None:
438-
flows = np.array([1.0, -1.0])
439-
else:
440-
flows = np.array(flows)
437+
flows = np.array([1.0, -1.0]) if flows is None else np.array(flows)
441438
n = flows.shape[0] # Number of flows
442439
if rotation is None:
443440
rotation = 0

lib/matplotlib/testing/compare.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -500,8 +500,8 @@ def save_diff_image(expected, actual, output):
500500
actual_image = _load_image(actual)
501501
actual_image, expected_image = crop_to_same(
502502
actual, actual_image, expected, expected_image)
503-
expected_image = np.array(expected_image).astype(float)
504-
actual_image = np.array(actual_image).astype(float)
503+
expected_image = np.array(expected_image, float)
504+
actual_image = np.array(actual_image, float)
505505
if expected_image.shape != actual_image.shape:
506506
raise ImageComparisonFailure(
507507
"Image sizes do not match expected size: {} "

lib/matplotlib/tests/test_axes.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1499,7 +1499,7 @@ def test_arc_ellipse():
14991499
[np.cos(rtheta), -np.sin(rtheta)],
15001500
[np.sin(rtheta), np.cos(rtheta)]])
15011501

1502-
x, y = np.dot(R, np.array([x, y]))
1502+
x, y = np.dot(R, [x, y])
15031503
x += xcenter
15041504
y += ycenter
15051505

@@ -2097,7 +2097,7 @@ def test_hist_datetime_datasets():
20972097
@pytest.mark.parametrize("bins_preprocess",
20982098
[mpl.dates.date2num,
20992099
lambda bins: bins,
2100-
lambda bins: np.asarray(bins).astype('datetime64')],
2100+
lambda bins: np.asarray(bins, 'datetime64')],
21012101
ids=['date2num', 'datetime.datetime',
21022102
'np.datetime64'])
21032103
def test_hist_datetime_datasets_bins(bins_preprocess):
@@ -6409,7 +6409,7 @@ def test_pandas_pcolormesh(pd):
64096409

64106410
def test_pandas_indexing_dates(pd):
64116411
dates = np.arange('2005-02', '2005-03', dtype='datetime64[D]')
6412-
values = np.sin(np.array(range(len(dates))))
6412+
values = np.sin(range(len(dates)))
64136413
df = pd.DataFrame({'dates': dates, 'values': values})
64146414

64156415
ax = plt.gca()

lib/matplotlib/tests/test_collections.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -696,7 +696,7 @@ def test_pathcollection_legend_elements():
696696

697697
h, l = sc.legend_elements(fmt="{x:g}")
698698
assert len(h) == 5
699-
assert_array_equal(np.array(l).astype(float), np.arange(5))
699+
assert l == ["0", "1", "2", "3", "4"]
700700
colors = np.array([line.get_color() for line in h])
701701
colors2 = sc.cmap(np.arange(5)/4)
702702
assert_array_equal(colors, colors2)
@@ -707,16 +707,14 @@ def test_pathcollection_legend_elements():
707707
l2 = ax.legend(h2, lab2, loc=2)
708708

709709
h, l = sc.legend_elements(prop="sizes", alpha=0.5, color="red")
710-
alpha = np.array([line.get_alpha() for line in h])
711-
assert_array_equal(alpha, 0.5)
712-
color = np.array([line.get_markerfacecolor() for line in h])
713-
assert_array_equal(color, "red")
710+
assert all(line.get_alpha() == 0.5 for line in h)
711+
assert all(line.get_markerfacecolor() == "red" for line in h)
714712
l3 = ax.legend(h, l, loc=4)
715713

716714
h, l = sc.legend_elements(prop="sizes", num=4, fmt="{x:.2f}",
717715
func=lambda x: 2*x)
718716
actsizes = [line.get_markersize() for line in h]
719-
labeledsizes = np.sqrt(np.array(l).astype(float)/2)
717+
labeledsizes = np.sqrt(np.array(l, float) / 2)
720718
assert_array_almost_equal(actsizes, labeledsizes)
721719
l4 = ax.legend(h, l, loc=3)
722720

@@ -727,7 +725,7 @@ def test_pathcollection_legend_elements():
727725

728726
levels = [-1, 0, 55.4, 260]
729727
h6, lab6 = sc.legend_elements(num=levels, prop="sizes", fmt="{x:g}")
730-
assert_array_equal(np.array(lab6).astype(float), levels[2:])
728+
assert [float(l) for l in lab6] == levels[2:]
731729

732730
for l in [l1, l2, l3, l4]:
733731
ax.add_artist(l)

lib/matplotlib/tests/test_colors.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -243,7 +243,7 @@ def test_colormap_invalid():
243243
# Test scalar representations
244244
assert_array_equal(cmap(-np.inf), cmap(0))
245245
assert_array_equal(cmap(np.inf), cmap(1.0))
246-
assert_array_equal(cmap(np.nan), np.array([0., 0., 0., 0.]))
246+
assert_array_equal(cmap(np.nan), [0., 0., 0., 0.])
247247

248248

249249
def test_colormap_return_types():
@@ -574,7 +574,7 @@ def test_Normalize():
574574
# i.e. 127-(-128) here).
575575
vals = np.array([-128, 127], dtype=np.int8)
576576
norm = mcolors.Normalize(vals.min(), vals.max())
577-
assert_array_equal(np.asarray(norm(vals)), [0, 1])
577+
assert_array_equal(norm(vals), [0, 1])
578578

579579
# Don't lose precision on longdoubles (float128 on Linux):
580580
# for array inputs...

lib/matplotlib/tests/test_sankey.py

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import pytest
2-
import numpy as np
2+
from numpy.testing import assert_allclose, assert_array_equal
33

44
from matplotlib.sankey import Sankey
55
from matplotlib.testing.decorators import check_figures_equal
@@ -67,28 +67,28 @@ def test_sankey2():
6767
s = Sankey(flows=[0.25, -0.25, 0.5, -0.5], labels=['Foo'],
6868
orientations=[-1], unit='Bar')
6969
sf = s.finish()
70-
assert np.all(np.equal(np.array((0.25, -0.25, 0.5, -0.5)), sf[0].flows))
70+
assert_array_equal(sf[0].flows, [0.25, -0.25, 0.5, -0.5])
7171
assert sf[0].angles == [1, 3, 1, 3]
7272
assert all([text.get_text()[0:3] == 'Foo' for text in sf[0].texts])
7373
assert all([text.get_text()[-3:] == 'Bar' for text in sf[0].texts])
7474
assert sf[0].text.get_text() == ''
75-
assert np.allclose(np.array(((-1.375, -0.52011255),
76-
(1.375, -0.75506044),
77-
(-0.75, -0.41522509),
78-
(0.75, -0.8599479))),
79-
sf[0].tips)
75+
assert_allclose(sf[0].tips,
76+
[(-1.375, -0.52011255),
77+
(1.375, -0.75506044),
78+
(-0.75, -0.41522509),
79+
(0.75, -0.8599479)])
8080

8181
s = Sankey(flows=[0.25, -0.25, 0, 0.5, -0.5], labels=['Foo'],
8282
orientations=[-1], unit='Bar')
8383
sf = s.finish()
84-
assert np.all(np.equal(np.array((0.25, -0.25, 0, 0.5, -0.5)), sf[0].flows))
84+
assert_array_equal(sf[0].flows, [0.25, -0.25, 0, 0.5, -0.5])
8585
assert sf[0].angles == [1, 3, None, 1, 3]
86-
assert np.allclose(np.array(((-1.375, -0.52011255),
87-
(1.375, -0.75506044),
88-
(0, 0),
89-
(-0.75, -0.41522509),
90-
(0.75, -0.8599479))),
91-
sf[0].tips)
86+
assert_allclose(sf[0].tips,
87+
[(-1.375, -0.52011255),
88+
(1.375, -0.75506044),
89+
(0, 0),
90+
(-0.75, -0.41522509),
91+
(0.75, -0.8599479)])
9292

9393

9494
@check_figures_equal(extensions=['png'])

lib/matplotlib/tests/test_transforms.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -422,7 +422,7 @@ def test_pathc_extents_non_affine(self):
422422
ax = plt.axes()
423423
offset = mtransforms.Affine2D().translate(10, 10)
424424
na_offset = NonAffineForTest(mtransforms.Affine2D().translate(10, 10))
425-
pth = Path(np.array([[0, 0], [0, 10], [10, 10], [10, 0]]))
425+
pth = Path([[0, 0], [0, 10], [10, 10], [10, 0]])
426426
patch = mpatches.PathPatch(pth,
427427
transform=offset + na_offset + ax.transData)
428428
ax.add_patch(patch)
@@ -432,7 +432,7 @@ def test_pathc_extents_non_affine(self):
432432
def test_pathc_extents_affine(self):
433433
ax = plt.axes()
434434
offset = mtransforms.Affine2D().translate(10, 10)
435-
pth = Path(np.array([[0, 0], [0, 10], [10, 10], [10, 0]]))
435+
pth = Path([[0, 0], [0, 10], [10, 10], [10, 0]])
436436
patch = mpatches.PathPatch(pth, transform=offset + ax.transData)
437437
ax.add_patch(patch)
438438
expected_data_lim = np.array([[0., 0.], [10., 10.]]) + 10

lib/matplotlib/tests/test_triangulation.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -944,8 +944,7 @@ def test_tritools():
944944
mask = np.array([False, False, True], dtype=bool)
945945
triang = mtri.Triangulation(x, y, triangles, mask=mask)
946946
analyser = mtri.TriAnalyzer(triang)
947-
assert_array_almost_equal(analyser.scale_factors,
948-
np.array([1., 1./(1.+0.5*np.sqrt(3.))]))
947+
assert_array_almost_equal(analyser.scale_factors, [1, 1/(1+3**.5/2)])
949948
assert_array_almost_equal(
950949
analyser.circle_ratios(rescale=False),
951950
np.ma.masked_array([0.5, 1./(1.+np.sqrt(2.)), np.nan], mask))

lib/matplotlib/transforms.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -925,7 +925,7 @@ def update_from_data_y(self, y, ignore=None):
925925
- When ``False``, include the existing bounds of the `Bbox`.
926926
- When ``None``, use the last value passed to :meth:`ignore`.
927927
"""
928-
y = np.array(y).ravel()
928+
y = np.ravel(y)
929929
self.update_from_data_xy(np.column_stack([np.ones(y.size), y]),
930930
ignore=ignore, updatex=False)
931931

lib/mpl_toolkits/mplot3d/axes3d.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3207,7 +3207,7 @@ def _extract_errs(err, data, lomask, himask):
32073207
invM = np.linalg.inv(self.get_proj())
32083208
# elev=azim=roll=0 produces the Y-Z plane, so quiversize in 2D 'x' is
32093209
# 'y' in 3D, hence the 1 index.
3210-
quiversize = np.dot(invM, np.array([quiversize, 0, 0, 0]))[1]
3210+
quiversize = np.dot(invM, [quiversize, 0, 0, 0])[1]
32113211
# Quivers use a fixed 15-degree arrow head, so scale up the length so
32123212
# that the size corresponds to the base. In other words, this constant
32133213
# corresponds to the equation tan(15) = (base / 2) / (arrow length).

lib/mpl_toolkits/mplot3d/axis3d.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -164,8 +164,7 @@ def _init3d(self):
164164
antialiased=True)
165165

166166
# Store dummy data in Polygon object
167-
self.pane = mpatches.Polygon(
168-
np.array([[0, 0], [0, 1]]), closed=False)
167+
self.pane = mpatches.Polygon([[0, 0], [0, 1]], closed=False)
169168
self.set_pane_color(self._axinfo['color'])
170169

171170
self.axes._set_artist_props(self.line)

lib/mpl_toolkits/tests/test_axes_grid1.py

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -209,23 +209,22 @@ def test_inset_axes_complete():
209209
ins = inset_axes(ax, width=2., height=2., borderpad=0)
210210
fig.canvas.draw()
211211
assert_array_almost_equal(
212-
ins.get_position().extents,
213-
np.array(((0.9*figsize[0]-2.)/figsize[0],
214-
(0.9*figsize[1]-2.)/figsize[1], 0.9, 0.9)))
212+
ins.get_position().extents,
213+
[(0.9*figsize[0]-2.)/figsize[0], (0.9*figsize[1]-2.)/figsize[1],
214+
0.9, 0.9])
215215

216216
ins = inset_axes(ax, width="40%", height="30%", borderpad=0)
217217
fig.canvas.draw()
218218
assert_array_almost_equal(
219-
ins.get_position().extents,
220-
np.array((.9-.8*.4, .9-.8*.3, 0.9, 0.9)))
219+
ins.get_position().extents, [.9-.8*.4, .9-.8*.3, 0.9, 0.9])
221220

222221
ins = inset_axes(ax, width=1., height=1.2, bbox_to_anchor=(200, 100),
223222
loc=3, borderpad=0)
224223
fig.canvas.draw()
225224
assert_array_almost_equal(
226-
ins.get_position().extents,
227-
np.array((200./dpi/figsize[0], 100./dpi/figsize[1],
228-
(200./dpi+1)/figsize[0], (100./dpi+1.2)/figsize[1])))
225+
ins.get_position().extents,
226+
[200/dpi/figsize[0], 100/dpi/figsize[1],
227+
(200/dpi+1)/figsize[0], (100/dpi+1.2)/figsize[1]])
229228

230229
ins1 = inset_axes(ax, width="35%", height="60%", loc=3, borderpad=1)
231230
ins2 = inset_axes(ax, width="100%", height="100%",

0 commit comments

Comments
 (0)