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

Skip to content

Remove unnecessary np.{,as}array / astype calls. #24295

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 29, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 3 additions & 8 deletions examples/event_handling/path_editor.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,17 +82,12 @@ def get_ind_under_point(self, event):
Return the index of the point closest to the event position or *None*
if no point is within ``self.epsilon`` to the event position.
"""
# display coords
xy = np.asarray(self.pathpatch.get_path().vertices)
xyt = self.pathpatch.get_transform().transform(xy)
xy = self.pathpatch.get_path().vertices
xyt = self.pathpatch.get_transform().transform(xy) # to display coords
xt, yt = xyt[:, 0], xyt[:, 1]
d = np.sqrt((xt - event.x)**2 + (yt - event.y)**2)
ind = d.argmin()

if d[ind] >= self.epsilon:
ind = None

return ind
return ind if d[ind] < self.epsilon else None

def on_draw(self, event):
"""Callback for draws."""
Expand Down
2 changes: 1 addition & 1 deletion examples/subplots_axes_and_figures/secondary_axis.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ def rad2deg(x):

def one_over(x):
"""Vectorized 1/x, treating x==0 manually"""
x = np.array(x).astype(float)
x = np.array(x, float)
near_zero = np.isclose(x, 0)
x[near_zero] = np.inf
x[~near_zero] = 1 / x[~near_zero]
Expand Down
2 changes: 1 addition & 1 deletion examples/units/basic_units.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ def __getattribute__(self, name):
return object.__getattribute__(self, name)

def __array__(self, dtype=object):
return np.asarray(self.value).astype(dtype)
return np.asarray(self.value, dtype)

def __array_wrap__(self, array, context):
return TaggedValue(array, self.unit)
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/backend_bases.py
Original file line number Diff line number Diff line change
Expand Up @@ -1464,7 +1464,7 @@ def on_pick(event):
line = event.artist
xdata, ydata = line.get_data()
ind = event.ind
print('on pick line:', np.array([xdata[ind], ydata[ind]]).T)
print(f'on pick line: {xdata[ind]:.3f}, {ydata[ind]:.3f}')

cid = fig.canvas.mpl_connect('pick_event', on_pick)
"""
Expand Down
6 changes: 3 additions & 3 deletions lib/matplotlib/collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -547,8 +547,8 @@ def set_offsets(self, offsets):
if offsets.shape == (2,): # Broadcast (2,) -> (1, 2) but nothing else.
offsets = offsets[None, :]
self._offsets = np.column_stack(
(np.asarray(self.convert_xunits(offsets[:, 0]), 'float'),
np.asarray(self.convert_yunits(offsets[:, 1]), 'float')))
(np.asarray(self.convert_xunits(offsets[:, 0]), float),
np.asarray(self.convert_yunits(offsets[:, 1]), float)))
self.stale = True

def get_offsets(self):
Expand All @@ -573,7 +573,7 @@ def set_linewidth(self, lw):
if lw is None:
lw = self._get_default_linewidth()
# get the un-scaled/broadcast lw
self._us_lw = np.atleast_1d(np.asarray(lw))
self._us_lw = np.atleast_1d(lw)

# scale all of the dash patterns.
self._linewidths, self._linestyles = self._bcast_lwls(
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/contour.py
Original file line number Diff line number Diff line change
Expand Up @@ -1144,7 +1144,7 @@ def _process_contour_level_args(self, args):
if isinstance(levels_arg, Integral):
self.levels = self._autolev(levels_arg)
else:
self.levels = np.asarray(levels_arg).astype(np.float64)
self.levels = np.asarray(levels_arg, np.float64)

if not self.filled:
inside = (self.levels > self.zmin) & (self.levels < self.zmax)
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/image.py
Original file line number Diff line number Diff line change
Expand Up @@ -1701,7 +1701,7 @@ def _pil_png_to_float_array(pil_png):
mode = pil_png.mode
rawmode = pil_png.png.im_rawmode
if rawmode == "1": # Grayscale.
return np.asarray(pil_png).astype(np.float32)
return np.asarray(pil_png, np.float32)
if rawmode == "L;2": # Grayscale.
return np.divide(pil_png, 2**2 - 1, dtype=np.float32)
if rawmode == "L;4": # Grayscale.
Expand Down
4 changes: 1 addition & 3 deletions lib/matplotlib/patches.py
Original file line number Diff line number Diff line change
Expand Up @@ -1221,9 +1221,7 @@ def _recompute_path(self):
arc.codes, [connector, connector, Path.CLOSEPOLY]])

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

def set_center(self, center):
self._path = None
Expand Down
5 changes: 1 addition & 4 deletions lib/matplotlib/sankey.py
Original file line number Diff line number Diff line change
Expand Up @@ -434,10 +434,7 @@ def add(self, patchlabel='', flows=None, orientations=None, labels='',
Sankey.finish
"""
# Check and preprocess the arguments.
if flows is None:
flows = np.array([1.0, -1.0])
else:
flows = np.array(flows)
flows = np.array([1.0, -1.0]) if flows is None else np.array(flows)
n = flows.shape[0] # Number of flows
if rotation is None:
rotation = 0
Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/testing/compare.py
Original file line number Diff line number Diff line change
Expand Up @@ -500,8 +500,8 @@ def save_diff_image(expected, actual, output):
actual_image = _load_image(actual)
actual_image, expected_image = crop_to_same(
actual, actual_image, expected, expected_image)
expected_image = np.array(expected_image).astype(float)
actual_image = np.array(actual_image).astype(float)
expected_image = np.array(expected_image, float)
actual_image = np.array(actual_image, float)
if expected_image.shape != actual_image.shape:
raise ImageComparisonFailure(
"Image sizes do not match expected size: {} "
Expand Down
6 changes: 3 additions & 3 deletions lib/matplotlib/tests/test_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -1499,7 +1499,7 @@ def test_arc_ellipse():
[np.cos(rtheta), -np.sin(rtheta)],
[np.sin(rtheta), np.cos(rtheta)]])

x, y = np.dot(R, np.array([x, y]))
x, y = np.dot(R, [x, y])
x += xcenter
y += ycenter

Expand Down Expand Up @@ -2097,7 +2097,7 @@ def test_hist_datetime_datasets():
@pytest.mark.parametrize("bins_preprocess",
[mpl.dates.date2num,
lambda bins: bins,
lambda bins: np.asarray(bins).astype('datetime64')],
lambda bins: np.asarray(bins, 'datetime64')],
ids=['date2num', 'datetime.datetime',
'np.datetime64'])
def test_hist_datetime_datasets_bins(bins_preprocess):
Expand Down Expand Up @@ -6409,7 +6409,7 @@ def test_pandas_pcolormesh(pd):

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

ax = plt.gca()
Expand Down
12 changes: 5 additions & 7 deletions lib/matplotlib/tests/test_collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -696,7 +696,7 @@ def test_pathcollection_legend_elements():

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

h, l = sc.legend_elements(prop="sizes", alpha=0.5, color="red")
alpha = np.array([line.get_alpha() for line in h])
assert_array_equal(alpha, 0.5)
color = np.array([line.get_markerfacecolor() for line in h])
assert_array_equal(color, "red")
assert all(line.get_alpha() == 0.5 for line in h)
assert all(line.get_markerfacecolor() == "red" for line in h)
l3 = ax.legend(h, l, loc=4)

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

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

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

for l in [l1, l2, l3, l4]:
ax.add_artist(l)
Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/tests/test_colors.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@ def test_colormap_invalid():
# Test scalar representations
assert_array_equal(cmap(-np.inf), cmap(0))
assert_array_equal(cmap(np.inf), cmap(1.0))
assert_array_equal(cmap(np.nan), np.array([0., 0., 0., 0.]))
assert_array_equal(cmap(np.nan), [0., 0., 0., 0.])


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

# Don't lose precision on longdoubles (float128 on Linux):
# for array inputs...
Expand Down
28 changes: 14 additions & 14 deletions lib/matplotlib/tests/test_sankey.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import pytest
import numpy as np
from numpy.testing import assert_allclose, assert_array_equal

from matplotlib.sankey import Sankey
from matplotlib.testing.decorators import check_figures_equal
Expand Down Expand Up @@ -67,28 +67,28 @@ def test_sankey2():
s = Sankey(flows=[0.25, -0.25, 0.5, -0.5], labels=['Foo'],
orientations=[-1], unit='Bar')
sf = s.finish()
assert np.all(np.equal(np.array((0.25, -0.25, 0.5, -0.5)), sf[0].flows))
assert_array_equal(sf[0].flows, [0.25, -0.25, 0.5, -0.5])
assert sf[0].angles == [1, 3, 1, 3]
assert all([text.get_text()[0:3] == 'Foo' for text in sf[0].texts])
assert all([text.get_text()[-3:] == 'Bar' for text in sf[0].texts])
assert sf[0].text.get_text() == ''
assert np.allclose(np.array(((-1.375, -0.52011255),
(1.375, -0.75506044),
(-0.75, -0.41522509),
(0.75, -0.8599479))),
sf[0].tips)
assert_allclose(sf[0].tips,
[(-1.375, -0.52011255),
(1.375, -0.75506044),
(-0.75, -0.41522509),
(0.75, -0.8599479)])

s = Sankey(flows=[0.25, -0.25, 0, 0.5, -0.5], labels=['Foo'],
orientations=[-1], unit='Bar')
sf = s.finish()
assert np.all(np.equal(np.array((0.25, -0.25, 0, 0.5, -0.5)), sf[0].flows))
assert_array_equal(sf[0].flows, [0.25, -0.25, 0, 0.5, -0.5])
assert sf[0].angles == [1, 3, None, 1, 3]
assert np.allclose(np.array(((-1.375, -0.52011255),
(1.375, -0.75506044),
(0, 0),
(-0.75, -0.41522509),
(0.75, -0.8599479))),
sf[0].tips)
assert_allclose(sf[0].tips,
[(-1.375, -0.52011255),
(1.375, -0.75506044),
(0, 0),
(-0.75, -0.41522509),
(0.75, -0.8599479)])


@check_figures_equal(extensions=['png'])
Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/tests/test_transforms.py
Original file line number Diff line number Diff line change
Expand Up @@ -422,7 +422,7 @@ def test_pathc_extents_non_affine(self):
ax = plt.axes()
offset = mtransforms.Affine2D().translate(10, 10)
na_offset = NonAffineForTest(mtransforms.Affine2D().translate(10, 10))
pth = Path(np.array([[0, 0], [0, 10], [10, 10], [10, 0]]))
pth = Path([[0, 0], [0, 10], [10, 10], [10, 0]])
patch = mpatches.PathPatch(pth,
transform=offset + na_offset + ax.transData)
ax.add_patch(patch)
Expand All @@ -432,7 +432,7 @@ def test_pathc_extents_non_affine(self):
def test_pathc_extents_affine(self):
ax = plt.axes()
offset = mtransforms.Affine2D().translate(10, 10)
pth = Path(np.array([[0, 0], [0, 10], [10, 10], [10, 0]]))
pth = Path([[0, 0], [0, 10], [10, 10], [10, 0]])
patch = mpatches.PathPatch(pth, transform=offset + ax.transData)
ax.add_patch(patch)
expected_data_lim = np.array([[0., 0.], [10., 10.]]) + 10
Expand Down
3 changes: 1 addition & 2 deletions lib/matplotlib/tests/test_triangulation.py
Original file line number Diff line number Diff line change
Expand Up @@ -944,8 +944,7 @@ def test_tritools():
mask = np.array([False, False, True], dtype=bool)
triang = mtri.Triangulation(x, y, triangles, mask=mask)
analyser = mtri.TriAnalyzer(triang)
assert_array_almost_equal(analyser.scale_factors,
np.array([1., 1./(1.+0.5*np.sqrt(3.))]))
assert_array_almost_equal(analyser.scale_factors, [1, 1/(1+3**.5/2)])
assert_array_almost_equal(
analyser.circle_ratios(rescale=False),
np.ma.masked_array([0.5, 1./(1.+np.sqrt(2.)), np.nan], mask))
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/transforms.py
Original file line number Diff line number Diff line change
Expand Up @@ -925,7 +925,7 @@ def update_from_data_y(self, y, ignore=None):
- When ``False``, include the existing bounds of the `Bbox`.
- When ``None``, use the last value passed to :meth:`ignore`.
"""
y = np.array(y).ravel()
y = np.ravel(y)
self.update_from_data_xy(np.column_stack([np.ones(y.size), y]),
ignore=ignore, updatex=False)

Expand Down
2 changes: 1 addition & 1 deletion lib/mpl_toolkits/mplot3d/axes3d.py
Original file line number Diff line number Diff line change
Expand Up @@ -3207,7 +3207,7 @@ def _extract_errs(err, data, lomask, himask):
invM = np.linalg.inv(self.get_proj())
# elev=azim=roll=0 produces the Y-Z plane, so quiversize in 2D 'x' is
# 'y' in 3D, hence the 1 index.
quiversize = np.dot(invM, np.array([quiversize, 0, 0, 0]))[1]
quiversize = np.dot(invM, [quiversize, 0, 0, 0])[1]
# Quivers use a fixed 15-degree arrow head, so scale up the length so
# that the size corresponds to the base. In other words, this constant
# corresponds to the equation tan(15) = (base / 2) / (arrow length).
Expand Down
3 changes: 1 addition & 2 deletions lib/mpl_toolkits/mplot3d/axis3d.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,8 +164,7 @@ def _init3d(self):
antialiased=True)

# Store dummy data in Polygon object
self.pane = mpatches.Polygon(
np.array([[0, 0], [0, 1]]), closed=False)
self.pane = mpatches.Polygon([[0, 0], [0, 1]], closed=False)
self.set_pane_color(self._axinfo['color'])

self.axes._set_artist_props(self.line)
Expand Down
15 changes: 7 additions & 8 deletions lib/mpl_toolkits/tests/test_axes_grid1.py
Original file line number Diff line number Diff line change
Expand Up @@ -208,23 +208,22 @@ def test_inset_axes_complete():
ins = inset_axes(ax, width=2., height=2., borderpad=0)
fig.canvas.draw()
assert_array_almost_equal(
ins.get_position().extents,
np.array(((0.9*figsize[0]-2.)/figsize[0],
(0.9*figsize[1]-2.)/figsize[1], 0.9, 0.9)))
ins.get_position().extents,
[(0.9*figsize[0]-2.)/figsize[0], (0.9*figsize[1]-2.)/figsize[1],
0.9, 0.9])

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

ins = inset_axes(ax, width=1., height=1.2, bbox_to_anchor=(200, 100),
loc=3, borderpad=0)
fig.canvas.draw()
assert_array_almost_equal(
ins.get_position().extents,
np.array((200./dpi/figsize[0], 100./dpi/figsize[1],
(200./dpi+1)/figsize[0], (100./dpi+1.2)/figsize[1])))
ins.get_position().extents,
[200/dpi/figsize[0], 100/dpi/figsize[1],
(200/dpi+1)/figsize[0], (100/dpi+1.2)/figsize[1]])

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