From 1068a6faa19767724437461bcfb88c6852ec435c Mon Sep 17 00:00:00 2001 From: Antony Lee Date: Fri, 28 Oct 2022 20:27:44 +0200 Subject: [PATCH] Remove unnecessary np.{,as}array / astype calls. Quite often numpy will call asarray for us, saving us the need to call asarray explicitly. When we do call asarray (or array) ourselves, a dtype can directly be passed in, rather than immediately calling astype immediately after. Passing the dtype makes it unnecessary for asarray to infer the dtype of the passed-in container, and can also save an extra array allocation if asarray first has to allocate an array of a type and astype immediately has to allocate an array of another type. --- examples/event_handling/path_editor.py | 11 ++------ .../secondary_axis.py | 2 +- examples/units/basic_units.py | 2 +- lib/matplotlib/backend_bases.py | 2 +- lib/matplotlib/collections.py | 6 ++-- lib/matplotlib/contour.py | 2 +- lib/matplotlib/image.py | 2 +- lib/matplotlib/patches.py | 4 +-- lib/matplotlib/sankey.py | 5 +--- lib/matplotlib/testing/compare.py | 4 +-- lib/matplotlib/tests/test_axes.py | 6 ++-- lib/matplotlib/tests/test_collections.py | 12 ++++---- lib/matplotlib/tests/test_colors.py | 4 +-- lib/matplotlib/tests/test_sankey.py | 28 +++++++++---------- lib/matplotlib/tests/test_transforms.py | 4 +-- lib/matplotlib/tests/test_triangulation.py | 3 +- lib/matplotlib/transforms.py | 2 +- lib/mpl_toolkits/mplot3d/axes3d.py | 2 +- lib/mpl_toolkits/mplot3d/axis3d.py | 3 +- lib/mpl_toolkits/tests/test_axes_grid1.py | 15 +++++----- 20 files changed, 52 insertions(+), 67 deletions(-) diff --git a/examples/event_handling/path_editor.py b/examples/event_handling/path_editor.py index be8d79935db9..105c58bf6e1a 100644 --- a/examples/event_handling/path_editor.py +++ b/examples/event_handling/path_editor.py @@ -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.""" diff --git a/examples/subplots_axes_and_figures/secondary_axis.py b/examples/subplots_axes_and_figures/secondary_axis.py index 8122a211f899..a8ba17d3478b 100644 --- a/examples/subplots_axes_and_figures/secondary_axis.py +++ b/examples/subplots_axes_and_figures/secondary_axis.py @@ -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] diff --git a/examples/units/basic_units.py b/examples/units/basic_units.py index 3b4f13313f50..d4aec86a86b3 100644 --- a/examples/units/basic_units.py +++ b/examples/units/basic_units.py @@ -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) diff --git a/lib/matplotlib/backend_bases.py b/lib/matplotlib/backend_bases.py index 7e62d1a5be1a..e4688f8abb69 100644 --- a/lib/matplotlib/backend_bases.py +++ b/lib/matplotlib/backend_bases.py @@ -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) """ diff --git a/lib/matplotlib/collections.py b/lib/matplotlib/collections.py index 8aba85a67e0a..a66bc73f3fa0 100644 --- a/lib/matplotlib/collections.py +++ b/lib/matplotlib/collections.py @@ -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): @@ -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( diff --git a/lib/matplotlib/contour.py b/lib/matplotlib/contour.py index 67fa754a1765..8a959e5868c4 100644 --- a/lib/matplotlib/contour.py +++ b/lib/matplotlib/contour.py @@ -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) diff --git a/lib/matplotlib/image.py b/lib/matplotlib/image.py index 6401b64dc248..e5d9e68fb945 100644 --- a/lib/matplotlib/image.py +++ b/lib/matplotlib/image.py @@ -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. diff --git a/lib/matplotlib/patches.py b/lib/matplotlib/patches.py index f61524f65597..d4d8179e2a08 100644 --- a/lib/matplotlib/patches.py +++ b/lib/matplotlib/patches.py @@ -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 diff --git a/lib/matplotlib/sankey.py b/lib/matplotlib/sankey.py index 290c67830e14..200fb7e2bd4e 100644 --- a/lib/matplotlib/sankey.py +++ b/lib/matplotlib/sankey.py @@ -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 diff --git a/lib/matplotlib/testing/compare.py b/lib/matplotlib/testing/compare.py index 4c07c7ad7e09..d890c7aefaa5 100644 --- a/lib/matplotlib/testing/compare.py +++ b/lib/matplotlib/testing/compare.py @@ -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: {} " diff --git a/lib/matplotlib/tests/test_axes.py b/lib/matplotlib/tests/test_axes.py index 00091b9f69b4..11ab98994803 100644 --- a/lib/matplotlib/tests/test_axes.py +++ b/lib/matplotlib/tests/test_axes.py @@ -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 @@ -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): @@ -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() diff --git a/lib/matplotlib/tests/test_collections.py b/lib/matplotlib/tests/test_collections.py index 762204c191fc..b624a9093641 100644 --- a/lib/matplotlib/tests/test_collections.py +++ b/lib/matplotlib/tests/test_collections.py @@ -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) @@ -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) @@ -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) diff --git a/lib/matplotlib/tests/test_colors.py b/lib/matplotlib/tests/test_colors.py index 3adfce2833a6..4e6ad9cadcf4 100644 --- a/lib/matplotlib/tests/test_colors.py +++ b/lib/matplotlib/tests/test_colors.py @@ -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(): @@ -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... diff --git a/lib/matplotlib/tests/test_sankey.py b/lib/matplotlib/tests/test_sankey.py index 6cc036a9f1ce..cbb7f516a65c 100644 --- a/lib/matplotlib/tests/test_sankey.py +++ b/lib/matplotlib/tests/test_sankey.py @@ -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 @@ -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']) diff --git a/lib/matplotlib/tests/test_transforms.py b/lib/matplotlib/tests/test_transforms.py index 336200c6e279..6c5b3496bc7c 100644 --- a/lib/matplotlib/tests/test_transforms.py +++ b/lib/matplotlib/tests/test_transforms.py @@ -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) @@ -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 diff --git a/lib/matplotlib/tests/test_triangulation.py b/lib/matplotlib/tests/test_triangulation.py index 6bfd84d9b375..9c6dec71e09f 100644 --- a/lib/matplotlib/tests/test_triangulation.py +++ b/lib/matplotlib/tests/test_triangulation.py @@ -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)) diff --git a/lib/matplotlib/transforms.py b/lib/matplotlib/transforms.py index 1471d4fe672d..1f3a180855b3 100644 --- a/lib/matplotlib/transforms.py +++ b/lib/matplotlib/transforms.py @@ -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) diff --git a/lib/mpl_toolkits/mplot3d/axes3d.py b/lib/mpl_toolkits/mplot3d/axes3d.py index 23b3571a4a38..634829d0db02 100644 --- a/lib/mpl_toolkits/mplot3d/axes3d.py +++ b/lib/mpl_toolkits/mplot3d/axes3d.py @@ -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). diff --git a/lib/mpl_toolkits/mplot3d/axis3d.py b/lib/mpl_toolkits/mplot3d/axis3d.py index 4571b4bffddd..45bd3b4173a5 100644 --- a/lib/mpl_toolkits/mplot3d/axis3d.py +++ b/lib/mpl_toolkits/mplot3d/axis3d.py @@ -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) diff --git a/lib/mpl_toolkits/tests/test_axes_grid1.py b/lib/mpl_toolkits/tests/test_axes_grid1.py index ea9b55de4883..a1a22e027147 100644 --- a/lib/mpl_toolkits/tests/test_axes_grid1.py +++ b/lib/mpl_toolkits/tests/test_axes_grid1.py @@ -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%",