Skip to content

Use np.full{,_like} where appropriate. [requires numpy>=1.12] #10571

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

Closed
wants to merge 1 commit into from
Closed
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
2 changes: 1 addition & 1 deletion examples/animation/animated_histogram.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@
# in the ``verts`` array to keep the codes aligned with the vertices.
nverts = nrects * (1 + 3 + 1)
verts = np.zeros((nverts, 2))
codes = np.ones(nverts, int) * path.Path.LINETO
codes = np.full(nverts, path.Path.LINETO)
codes[0::5] = path.Path.MOVETO
codes[4::5] = path.Path.CLOSEPOLY
verts[0::5, 0] = left
Expand Down
3 changes: 1 addition & 2 deletions examples/api/donut.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,7 @@ def make_circle(r):

inside_vertices = make_circle(0.5)
outside_vertices = make_circle(1.0)
codes = np.ones(
len(inside_vertices), dtype=mpath.Path.code_type) * mpath.Path.LINETO
codes = np.full(len(inside_vertices), mpath.Path.LINETO)
codes[0] = mpath.Path.MOVETO

for i, (inside, outside) in enumerate(((1, 1), (1, -1), (-1, 1), (-1, -1))):
Expand Down
2 changes: 1 addition & 1 deletion examples/api/filled_step.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ def filled_hist(ax, edges, values, bottoms=None, orientation='v',
if bottoms is None:
bottoms = np.zeros_like(values)
if np.isscalar(bottoms):
bottoms = np.ones_like(values) * bottoms
bottoms = np.full_like(values, bottoms)

values = np.r_[values, values[-1]]
bottoms = np.r_[bottoms, bottoms[-1]]
Expand Down
4 changes: 2 additions & 2 deletions examples/pyplots/boxplot_demo_pyplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@

# fake up some data
spread = np.random.rand(50) * 100
center = np.ones(25) * 50
center = np.full(25, 50)
flier_high = np.random.rand(10) * 100 + 100
flier_low = np.random.rand(10) * -100
data = np.concatenate((spread, center, flier_high, flier_low))
Expand Down Expand Up @@ -61,7 +61,7 @@
# Fake up some more data

spread = np.random.rand(50) * 100
center = np.ones(25) * 40
center = np.full(25, 40)
flier_high = np.random.rand(10) * 100 + 100
flier_low = np.random.rand(10) * -100
d2 = np.concatenate((spread, center, flier_high, flier_low))
Expand Down
2 changes: 1 addition & 1 deletion examples/pyplots/compound_path_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@

nverts = nrects*(1+3+1)
verts = np.zeros((nverts, 2))
codes = np.ones(nverts, int) * path.Path.LINETO
codes = np.full(nverts, path.Path.LINETO)
codes[0::5] = path.Path.MOVETO
codes[4::5] = path.Path.CLOSEPOLY
verts[0::5,0] = left
Expand Down
8 changes: 4 additions & 4 deletions examples/specialty_plots/leftventricle_bulleye.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ def bullseye_plot(ax, data, segBold=None, cmap=None, norm=None):
# First segment start at 60 degrees
theta0 = theta[i * 128:i * 128 + 128] + np.deg2rad(60)
theta0 = np.repeat(theta0[:, np.newaxis], 2, axis=1)
z = np.ones((128, 2)) * data[i]
z = np.full((128, 2), data[i])
ax.pcolormesh(theta0, r0, z, cmap=cmap, norm=norm)
if i + 1 in segBold:
ax.plot(theta0, r0, '-k', lw=linewidth + 2)
Expand All @@ -92,7 +92,7 @@ def bullseye_plot(ax, data, segBold=None, cmap=None, norm=None):
# First segment start at 60 degrees
theta0 = theta[i * 128:i * 128 + 128] + np.deg2rad(60)
theta0 = np.repeat(theta0[:, np.newaxis], 2, axis=1)
z = np.ones((128, 2)) * data[i + 6]
z = np.full((128, 2), data[i + 6])
ax.pcolormesh(theta0, r0, z, cmap=cmap, norm=norm)
if i + 7 in segBold:
ax.plot(theta0, r0, '-k', lw=linewidth + 2)
Expand All @@ -106,7 +106,7 @@ def bullseye_plot(ax, data, segBold=None, cmap=None, norm=None):
# First segment start at 45 degrees
theta0 = theta[i * 192:i * 192 + 192] + np.deg2rad(45)
theta0 = np.repeat(theta0[:, np.newaxis], 2, axis=1)
z = np.ones((192, 2)) * data[i + 12]
z = np.full((192, 2), data[i + 12])
ax.pcolormesh(theta0, r0, z, cmap=cmap, norm=norm)
if i + 13 in segBold:
ax.plot(theta0, r0, '-k', lw=linewidth + 2)
Expand All @@ -118,7 +118,7 @@ def bullseye_plot(ax, data, segBold=None, cmap=None, norm=None):
r0 = np.array([0, r[0]])
r0 = np.repeat(r0[:, np.newaxis], theta.size, axis=1).T
theta0 = np.repeat(theta[:, np.newaxis], 2, axis=1)
z = np.ones((theta.size, 2)) * data[16]
z = np.full((theta.size, 2), data[16])
ax.pcolormesh(theta0, r0, z, cmap=cmap, norm=norm)
if 17 in segBold:
ax.plot(theta0, r0, '-k', lw=linewidth + 2)
Expand Down
4 changes: 2 additions & 2 deletions examples/statistics/boxplot_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@

# fake up some data
spread = np.random.rand(50) * 100
center = np.ones(25) * 50
center = np.full(25, 50)
flier_high = np.random.rand(10) * 100 + 100
flier_low = np.random.rand(10) * -100
data = np.concatenate((spread, center, flier_high, flier_low))
Expand Down Expand Up @@ -56,7 +56,7 @@

# fake up some more data
spread = np.random.rand(50) * 100
center = np.ones(25) * 40
center = np.full(25, 40)
flier_high = np.random.rand(10) * 100 + 100
flier_low = np.random.rand(10) * -100
d2 = np.concatenate((spread, center, flier_high, flier_low))
Expand Down
2 changes: 1 addition & 1 deletion examples/text_labels_and_annotations/legend_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ def create_artists(self, legend, orig_handle,
leglines = []
# divide the vertical space where the lines will go
# into equal parts based on the number of lines
ydata = ((height) / (numlines + 1)) * np.ones(xdata.shape, float)
ydata = np.full_like(xdata, height / (numlines + 1))
# for each line, create the line at the proper location
# and set the dash pattern
for i in range(numlines):
Expand Down
8 changes: 4 additions & 4 deletions lib/matplotlib/axes/_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -3801,16 +3801,16 @@ def dopatch(xs, ys, **kwargs):
datalabels.append(stats.get('label', pos))

# whisker coords
whisker_x = np.ones(2) * pos
whisker_x = np.full(2, pos)
whiskerlo_y = np.array([stats['q1'], stats['whislo']])
whiskerhi_y = np.array([stats['q3'], stats['whishi']])

# cap coords
cap_left = pos - width * 0.25
cap_right = pos + width * 0.25
cap_x = np.array([cap_left, cap_right])
cap_lo = np.ones(2) * stats['whislo']
cap_hi = np.ones(2) * stats['whishi']
cap_lo = np.full(2, stats['whislo'])
cap_hi = np.full(2, stats['whishi'])

# box and median coords
box_left = pos - width * 0.5
Expand Down Expand Up @@ -3873,7 +3873,7 @@ def dopatch(xs, ys, **kwargs):
# maybe draw the fliers
if showfliers:
# fliers coords
flier_x = np.ones(len(stats['fliers'])) * pos
flier_x = np.full(len(stats['fliers']), pos)
flier_y = stats['fliers']

fliers.extend(doplot(
Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -941,8 +941,8 @@ def set_verts(self, verts, closed=True):
else:
xy = np.asarray(xy)
xy = np.concatenate([xy, xy[0:1]])
codes = np.empty(xy.shape[0], dtype=mpath.Path.code_type)
codes[:] = mpath.Path.LINETO
codes = np.full(xy.shape[0], mpath.Path.LINETO,
dtype=mpath.Path.code_type)
codes[0] = mpath.Path.MOVETO
codes[-1] = mpath.Path.CLOSEPOLY
self._paths.append(mpath.Path(xy, codes))
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/hatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ def __init__(self, hatch, density):
self.num_rows = (hatch.count('*')) * density
path = Path.unit_regular_star(5)
self.shape_vertices = path.vertices
self.shape_codes = np.ones(len(self.shape_vertices)) * Path.LINETO
self.shape_codes = np.full(len(self.shape_vertices), Path.LINETO)
self.shape_codes[0] = Path.MOVETO
Shapes.__init__(self, hatch, density)

Expand Down
6 changes: 3 additions & 3 deletions lib/matplotlib/legend_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ def create_artists(self, legend, orig_handle,
xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent,
width, height, fontsize)

ydata = ((height - ydescent) / 2.) * np.ones(xdata.shape, float)
ydata = np.full_like(xdata, (height - ydescent) / 2)
legline = Line2D(xdata, ydata)

self.update_prop(legline, orig_handle, legend)
Expand Down Expand Up @@ -324,7 +324,7 @@ def create_artists(self, legend, orig_handle,

xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent,
width, height, fontsize)
ydata = ((height - ydescent) / 2.) * np.ones(xdata.shape, float)
ydata = np.full_like(xdata, (height - ydescent) / 2)
legline = Line2D(xdata, ydata)

self.update_prop(legline, orig_handle, legend)
Expand Down Expand Up @@ -466,7 +466,7 @@ def create_artists(self, legend, orig_handle,
xdata, xdata_marker = self.get_xdata(legend, xdescent, ydescent,
width, height, fontsize)

ydata = ((height - ydescent) / 2.) * np.ones(xdata.shape, float)
ydata = np.full_like(xdata, (height - ydescent) / 2)
legline = Line2D(xdata, ydata)

xdata_marker = np.asarray(xdata_marker)
Expand Down
14 changes: 7 additions & 7 deletions lib/matplotlib/path.py
Original file line number Diff line number Diff line change
Expand Up @@ -315,10 +315,10 @@ def make_compound_path_from_polys(cls, XY):
raise ValueError("The third dimension of 'XY' must be 2")
stride = numsides + 1
nverts = numpolys * stride
verts = np.zeros((nverts, 2))
codes = np.ones(nverts, int) * cls.LINETO
codes = np.full(nverts, cls.LINETO)
codes[0::stride] = cls.MOVETO
codes[numsides::stride] = cls.CLOSEPOLY
verts = np.zeros((nverts, 2))
for i in range(numsides):
verts[i::stride] = XY[:, i]

Expand Down Expand Up @@ -566,7 +566,7 @@ def interpolated(self, steps):
vertices = simple_linear_interpolation(self.vertices, steps)
codes = self.codes
if codes is not None:
new_codes = Path.LINETO * np.ones(((len(codes) - 1) * steps + 1, ))
new_codes = np.full((len(codes) - 1) * steps + 1, Path.LINETO)
new_codes[0::steps] = codes
else:
new_codes = None
Expand Down Expand Up @@ -886,17 +886,17 @@ def arc(cls, theta1, theta2, n=None, is_wedge=False):

if is_wedge:
length = n * 3 + 4
vertices = np.zeros((length, 2), float)
codes = cls.CURVE4 * np.ones((length, ), cls.code_type)
vertices = np.zeros((length, 2))
codes = np.full(length, cls.CURVE4, cls.code_type)
vertices[1] = [xA[0], yA[0]]
codes[0:2] = [cls.MOVETO, cls.LINETO]
codes[-2:] = [cls.LINETO, cls.CLOSEPOLY]
vertex_offset = 2
end = length - 2
else:
length = n * 3 + 1
vertices = np.empty((length, 2), float)
codes = cls.CURVE4 * np.ones((length, ), cls.code_type)
vertices = np.empty((length, 2))
codes = np.full(length, cls.CURVE4, cls.code_type)
vertices[0] = [xA[0], yA[0]]
codes[0] = cls.MOVETO
vertex_offset = 1
Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/tests/test_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -1517,7 +1517,7 @@ def test_hist_steplog():
data += -2.0 - np.min(data)
data_pos = data + 2.1
data_big = data_pos + 30
weights = np.ones_like(data) * 1.e-5
weights = np.full_like(data, 1e-5)

ax = plt.subplot(4, 1, 1)
plt.hist(data, 100, histtype='stepfilled', log=True)
Expand Down Expand Up @@ -4948,7 +4948,7 @@ def test_violin_point_mass():


def generate_errorbar_inputs():
base_xy = cycler('x', [np.arange(5)]) + cycler('y', [np.ones((5, ))])
base_xy = cycler('x', [np.arange(5)]) + cycler('y', [np.ones(5)])
err_cycler = cycler('err', [1,
[1, 1, 1, 1, 1],
[[1, 1, 1, 1, 1],
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/tests/test_collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -454,7 +454,7 @@ def test_EllipseCollection():

ww = X / x[-1]
hh = Y / y[-1]
aa = np.ones_like(ww) * 20 # first axis is 20 degrees CCW from x axis
aa = np.full_like(ww, 20) # first axis is 20 degrees CCW from x axis

ec = mcollections.EllipseCollection(ww, hh, aa,
units='x',
Expand Down
5 changes: 1 addition & 4 deletions lib/matplotlib/tests/test_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -910,12 +910,9 @@ def test_imshow_bool():


def test_full_invalid():
x = np.ones((10, 10))
x[:] = np.nan

x = np.full((10, 10), np.nan)
f, ax = plt.subplots()
ax.imshow(x)

f.canvas.draw()


Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/tests/test_legend.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ def test_labels_first():
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(np.arange(10), '-o', label=1)
ax.plot(np.ones(10)*5, ':x', label="x")
ax.plot(np.full(10, 5), ':x', label="x")
ax.plot(np.arange(20, 10, -1), 'd', label="diamond")
ax.legend(loc=0, markerfirst=False)

Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/tests/test_lines.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ def test_lw_scaling():
cy = cycler(matplotlib.rcParams['axes.prop_cycle'])
for j, (ls, sty) in enumerate(zip(lins_styles, cy)):
for lw in np.linspace(.5, 10, 10):
ax.plot(th, j*np.ones(50) + .1 * lw, linestyle=ls, lw=lw, **sty)
ax.plot(th, np.full(50, j) + .1 * lw, linestyle=ls, lw=lw, **sty)


def test_nan_is_sorted():
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/tests/test_path.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ def test_marker_paths_pdf():
N = 7

plt.errorbar(np.arange(N),
np.ones(N) + 4,
np.full(N, 5),
np.ones(N))
plt.xlim(-1, N)
plt.ylim(-1, 7)
Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/tests/test_quiver.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,8 +158,8 @@ def test_bad_masked_sizes():
'Test error handling when given differing sized masked arrays'
x = np.arange(3)
y = np.arange(3)
u = np.ma.array(15. * np.ones((4,)))
v = np.ma.array(15. * np.ones_like(u))
u = np.ma.array(np.full(4, 15.))
v = np.ma.array(np.full(4, 15.))
u[1] = np.ma.masked
v[1] = np.ma.masked
fig, ax = plt.subplots()
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/tests/test_triangulation.py
Original file line number Diff line number Diff line change
Expand Up @@ -645,7 +645,7 @@ def test_triinterp_colinear():
zs_target = 1.23*xs - 4.79*ys
for interp in (linear_interp, cubic_min_E, cubic_geom):
zs, = interp._interpolate_multikeys(
xs, ys, tri_index=itri*np.ones(10, dtype=np.int32))
xs, ys, tri_index=np.full(10, itri, dtype=np.int32))
assert_array_almost_equal(zs_target, zs)


Expand Down
3 changes: 1 addition & 2 deletions lib/matplotlib/text.py
Original file line number Diff line number Diff line change
Expand Up @@ -343,8 +343,7 @@ def _get_layout(self, renderer):
# get the rotation matrix
M = Affine2D().rotate_deg(self.get_rotation())

offsetLayout = np.zeros((len(lines), 2))
offsetLayout[:] = horizLayout[:, 0:2]
offsetLayout = horizLayout[:, 0:2].copy()
# now offset the individual text lines within the box
if len(lines) > 1: # do the multiline aligment
malign = self._get_multialignment()
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/tri/triinterpolate.py
Original file line number Diff line number Diff line change
Expand Up @@ -679,7 +679,7 @@ class _ReducedHCT_Element():
[ 4./18., 1./18., 13./18.],
[13./18., 1./18., 4./18.],
[ 7./18., 4./18., 7./18.]], dtype=np.float64)
gauss_w = np.ones([9], dtype=np.float64) / 9.
gauss_w = np.full(9, 1 / 9)

# 4) Stiffness matrix for curvature energy
E = np.array([[1., 0., 0.], [0., 1., 0.], [0., 0., 2.]])
Expand Down
4 changes: 2 additions & 2 deletions tutorials/advanced/path_tutorial.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@
#
# nverts = nrects*(1+3+1)
# verts = np.zeros((nverts, 2))
# codes = np.ones(nverts, int) * path.Path.LINETO
# codes = np.full(nverts, path.Path.LINETO)
# codes[0::5] = path.Path.MOVETO
# codes[4::5] = path.Path.CLOSEPOLY
# verts[0::5,0] = left
Expand Down Expand Up @@ -201,7 +201,7 @@

nverts = nrects*(1+3+1)
verts = np.zeros((nverts, 2))
codes = np.ones(nverts, int) * path.Path.LINETO
codes = np.full(nverts, path.Path.LINETO)
codes[0::5] = path.Path.MOVETO
codes[4::5] = path.Path.CLOSEPOLY
verts[0::5, 0] = left
Expand Down