Skip to content

Use np.hypot wherever possible. #10322

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 7, 2018
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
2 changes: 1 addition & 1 deletion .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ mpl-run: &mpl-install

doc-run: &doc-build
name: Build documentation
command: make html
command: make html O=-T
working_directory: doc

doc-bundle-run: &doc-bundle
Expand Down
2 changes: 1 addition & 1 deletion .flake8
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ per-file-ignores =
examples/event_handling/poly_editor.py: E501
examples/event_handling/viewlims.py: E501
examples/images_contours_and_fields/affine_image.py: E402
examples/images_contours_and_fields/barb_demo.py: E402, E501
examples/images_contours_and_fields/barb_demo.py: E402
examples/images_contours_and_fields/barcode_demo.py: E402
examples/images_contours_and_fields/contour_corner_mask.py: E402
examples/images_contours_and_fields/contour_demo.py: E402, E501
Expand Down
3 changes: 2 additions & 1 deletion examples/event_handling/pick_event_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,8 @@ def line_picker(line, mouseevent):
xdata = line.get_xdata()
ydata = line.get_ydata()
maxd = 0.05
d = np.sqrt((xdata - mouseevent.xdata)**2. + (ydata - mouseevent.ydata)**2.)
d = np.sqrt(
(xdata - mouseevent.xdata)**2 + (ydata - mouseevent.ydata)**2)

ind = np.nonzero(np.less_equal(d, maxd))
if len(ind):
Expand Down
8 changes: 5 additions & 3 deletions examples/images_contours_and_fields/barb_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,14 @@

# Arbitrary set of vectors, make them longer and change the pivot point
# (point around which they're rotated) to be the middle
axs1[0, 1].barbs(data['x'], data['y'], data['u'], data['v'], length=8, pivot='middle')
axs1[0, 1].barbs(
data['x'], data['y'], data['u'], data['v'], length=8, pivot='middle')

# Showing colormapping with uniform grid. Fill the circle for an empty barb,
# don't round the values, and change some of the size parameters
axs1[1, 0].barbs(X, Y, U, V, np.sqrt(U * U + V * V), fill_empty=True, rounding=False,
sizes=dict(emptybarb=0.25, spacing=0.2, height=0.3))
axs1[1, 0].barbs(
X, Y, U, V, np.sqrt(U ** 2 + V ** 2), fill_empty=True, rounding=False,
sizes=dict(emptybarb=0.25, spacing=0.2, height=0.3))

# Change colors as well as the increments for parts of the barbs
axs1[1, 1].barbs(data['x'], data['y'], data['u'], data['v'], flagcolor='r',
Expand Down
2 changes: 1 addition & 1 deletion examples/images_contours_and_fields/contourf_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
Z[:nr // 6, :nc // 6] = np.ma.masked

# mask a circle in the middle:
interior = np.sqrt((X**2) + (Y**2)) < 0.5
interior = np.sqrt(X**2 + Y**2) < 0.5
Z[interior] = np.ma.masked

# We are using automatic selection of contour levels;
Expand Down
2 changes: 1 addition & 1 deletion examples/images_contours_and_fields/plot_streamplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
Y, X = np.mgrid[-w:w:100j, -w:w:100j]
U = -1 - X**2 + Y
V = 1 + X - Y**2
speed = np.sqrt(U*U + V*V)
speed = np.sqrt(U**2 + V**2)

fig = plt.figure(figsize=(7, 9))
gs = gridspec.GridSpec(nrows=3, ncols=2, height_ratios=[1, 1, 2])
Expand Down
2 changes: 1 addition & 1 deletion examples/lines_bars_and_markers/scatter_masked.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
y = 0.9 * np.random.rand(N)
area = (20 * np.random.rand(N))**2 # 0 to 10 point radii
c = np.sqrt(area)
r = np.sqrt(x * x + y * y)
r = np.sqrt(x ** 2 + y ** 2)
area1 = np.ma.masked_where(r < r0, area)
area2 = np.ma.masked_where(r >= r0, area)
plt.scatter(x, y, s=area1, marker='^', c=c)
Expand Down
8 changes: 3 additions & 5 deletions lib/matplotlib/contour.py
Original file line number Diff line number Diff line change
Expand Up @@ -230,11 +230,9 @@ def print_label(self, linecontour, labelwidth):

def too_close(self, x, y, lw):
"Return *True* if a label is already near this location."
for loc in self.labelXYs:
d = np.sqrt((x - loc[0]) ** 2 + (y - loc[1]) ** 2)
if d < 1.2 * lw:
return True
return False
thresh = (1.2 * lw) ** 2
return any((x - loc[0]) ** 2 + (y - loc[1]) ** 2 < thresh
for loc in self.labelXYs)

def get_label_coords(self, distances, XX, YY, ysize, lw):
"""
Expand Down
13 changes: 6 additions & 7 deletions lib/matplotlib/lines.py
Original file line number Diff line number Diff line change
Expand Up @@ -477,17 +477,16 @@ def contains(self, mouseevent):
else:
pixels = self.figure.dpi / 72. * self.pickradius

# the math involved in checking for containment (here and inside of
# segment_hits) assumes that it is OK to overflow. In case the
# application has set the error flags such that an exception is raised
# on overflow, we temporarily set the appropriate error flags here and
# set them back when we are finished.
# The math involved in checking for containment (here and inside of
# segment_hits) assumes that it is OK to overflow, so temporarily set
# the error flags accordingly.
with np.errstate(all='ignore'):
# Check for collision
if self._linestyle in ['None', None]:
# If no line, return the nearby point(s)
d = (xt - mouseevent.x) ** 2 + (yt - mouseevent.y) ** 2
ind, = np.nonzero(np.less_equal(d, pixels ** 2))
ind, = np.nonzero(
(xt - mouseevent.x) ** 2 + (yt - mouseevent.y) ** 2
<= pixels ** 2)
else:
# If line, return the nearby segment(s)
ind = segment_hits(mouseevent.x, mouseevent.y, xt, yt, pixels)
Expand Down
12 changes: 5 additions & 7 deletions lib/matplotlib/patches.py
Original file line number Diff line number Diff line change
Expand Up @@ -1359,10 +1359,8 @@ def get_path(self):
xb1, yb1, xb2, yb2 = self.getpoints(x1, y1, x2, y2, k1)

# a point on the segment 20% of the distance from the tip to the base
theta = math.atan2(y2 - y1, x2 - x1)
r = math.sqrt((y2 - y1) ** 2. + (x2 - x1) ** 2.)
xm = x1 + self.frac * r * math.cos(theta)
ym = y1 + self.frac * r * math.sin(theta)
xm = x1 + self.frac * (x2 - x1)
ym = y1 + self.frac * (y2 - y1)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice catch :).

xc1, yc1, xc2, yc2 = self.getpoints(x1, y1, xm, ym, k1)
xd1, yd1, xd2, yd2 = self.getpoints(x1, y1, xm, ym, k2)

Expand Down Expand Up @@ -2915,10 +2913,10 @@ def connect(self, posA, posB):
codes.append(Path.LINETO)
else:
dx1, dy1 = x1 - cx, y1 - cy
d1 = (dx1 ** 2 + dy1 ** 2) ** .5
d1 = np.hypot(dx1, dy1)
f1 = self.rad / d1
dx2, dy2 = x2 - cx, y2 - cy
d2 = (dx2 ** 2 + dy2 ** 2) ** .5
d2 = np.hypot(dx2, dy2)
f2 = self.rad / d2
vertices.extend([(cx + dx1 * f1, cy + dy1 * f1),
(cx, cy),
Expand Down Expand Up @@ -3302,7 +3300,7 @@ def transmute(self, path, mutation_size, linewidth):

head_length = self.head_length * mutation_size
head_width = self.head_width * mutation_size
head_dist = math.sqrt(head_length ** 2 + head_width ** 2)
head_dist = np.hypot(head_length, head_width)
cos_t, sin_t = head_length / head_dist, head_width / head_dist

# begin arrow
Expand Down
20 changes: 8 additions & 12 deletions lib/matplotlib/projections/geo.py
Original file line number Diff line number Diff line change
Expand Up @@ -462,15 +462,12 @@ def transform_non_affine(self, ll):
diff_long = longitude - clong
cos_diff_long = np.cos(diff_long)

inner_k = (1.0 +
np.sin(clat)*sin_lat +
np.cos(clat)*cos_lat*cos_diff_long)
# Prevent divide-by-zero problems
inner_k = np.where(inner_k == 0.0, 1e-15, inner_k)
k = np.sqrt(2.0 / inner_k)
x = k*cos_lat*np.sin(diff_long)
y = k*(np.cos(clat)*sin_lat -
np.sin(clat)*cos_lat*cos_diff_long)
inner_k = np.maximum( # Prevent divide-by-zero problems
1 + np.sin(clat)*sin_lat + np.cos(clat)*cos_lat*cos_diff_long,
1e-15)
k = np.sqrt(2 / inner_k)
x = k * cos_lat*np.sin(diff_long)
y = k * (np.cos(clat)*sin_lat - np.sin(clat)*cos_lat*cos_diff_long)

return np.concatenate((x, y), 1)
transform_non_affine.__doc__ = Transform.transform_non_affine.__doc__
Expand All @@ -494,9 +491,8 @@ def transform_non_affine(self, xy):
y = xy[:, 1:2]
clong = self._center_longitude
clat = self._center_latitude
p = np.sqrt(x*x + y*y)
p = np.where(p == 0.0, 1e-9, p)
c = 2.0 * np.arcsin(0.5 * p)
p = np.maximum(np.hypot(x, y), 1e-9)
c = 2 * np.arcsin(0.5 * p)
sin_c = np.sin(c)
cos_c = np.cos(c)

Expand Down
11 changes: 2 additions & 9 deletions lib/matplotlib/projections/polar.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,15 +149,8 @@ def __str__(self):
def transform_non_affine(self, xy):
x = xy[:, 0:1]
y = xy[:, 1:]
r = np.sqrt(x*x + y*y)
with np.errstate(invalid='ignore'):
# At x=y=r=0 this will raise an
# invalid value warning when doing 0/0
# Divide by zero warnings are only raised when
# the numerator is different from 0. That
# should not happen here.
theta = np.arccos(x / r)
theta = np.where(y < 0, 2 * np.pi - theta, theta)
r = np.hypot(x, y)
theta = (np.arctan2(y, x) + 2 * np.pi) % (2 * np.pi)

# PolarAxes does not use the theta transforms here, but apply them for
# backwards-compatibility if not being used by it.
Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/streamplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ def streamplot(axes, x, y, u, v, density=1, linewidth=None, color=None,
streamlines.extend(np.hstack([points[:-1], points[1:]]))

# Add arrows half way along each trajectory.
s = np.cumsum(np.sqrt(np.diff(tx) ** 2 + np.diff(ty) ** 2))
s = np.cumsum(np.hypot(np.diff(tx), np.diff(ty)))
n = np.searchsorted(s, s[-1] / 2.)
arrow_tail = (tx[n], ty[n])
arrow_head = (np.mean(tx[n:n + 2]), np.mean(ty[n:n + 2]))
Expand Down Expand Up @@ -536,7 +536,7 @@ def _integrate_rk12(x0, y0, dmap, f, maxlength):

nx, ny = dmap.grid.shape
# Error is normalized to the axes coordinates
error = np.sqrt(((dx2 - dx1) / nx) ** 2 + ((dy2 - dy1) / ny) ** 2)
error = np.hypot((dx2 - dx1) / nx, (dy2 - dy1) / ny)

# Only save step if within error tolerance
if error < maxerror:
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/tests/test_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -1173,7 +1173,7 @@ def test_pcolorargs():
x = np.linspace(-1.5, 1.5, n)
y = np.linspace(-1.5, 1.5, n*2)
X, Y = np.meshgrid(x, y)
Z = np.sqrt(X**2 + Y**2)/5
Z = np.hypot(X, Y) / 5

_, ax = plt.subplots()
with pytest.raises(TypeError):
Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/tests/test_contour.py
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,7 @@ def test_corner_mask():
np.random.seed([1])
x, y = np.meshgrid(np.linspace(0, 2.0, n), np.linspace(0, 2.0, n))
z = np.cos(7*x)*np.sin(8*y) + noise_amp*np.random.rand(n, n)
mask = np.where(np.random.rand(n, n) >= mask_level, True, False)
mask = np.random.rand(n, n) >= mask_level
z = np.ma.array(z, mask=mask)

for corner_mask in [False, True]:
Expand Down Expand Up @@ -362,7 +362,7 @@ def test_circular_contour_warning():
# Check that almost circular contours don't throw a warning
with pytest.warns(None) as record:
x, y = np.meshgrid(np.linspace(-2, 2, 4), np.linspace(-2, 2, 4))
r = np.sqrt(x ** 2 + y ** 2)
r = np.hypot(x, y)

plt.figure()
cs = plt.contour(x, y, r)
Expand Down
5 changes: 2 additions & 3 deletions lib/matplotlib/tests/test_image.py
Original file line number Diff line number Diff line change
Expand Up @@ -745,12 +745,11 @@ def test_mask_image():
def test_imshow_endianess():
x = np.arange(10)
X, Y = np.meshgrid(x, x)
Z = ((X-5)**2 + (Y-5)**2)**0.5
Z = np.hypot(X - 5, Y - 5)

fig, (ax1, ax2) = plt.subplots(1, 2)

kwargs = dict(origin="lower", interpolation='nearest',
cmap='viridis')
kwargs = dict(origin="lower", interpolation='nearest', cmap='viridis')

ax1.imshow(Z.astype('<f8'), **kwargs)
ax2.imshow(Z.astype('>f8'), **kwargs)
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/tests/test_quiver.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ def test_barbs():
X, Y = np.meshgrid(x, x)
U, V = 12*X, 12*Y
fig, ax = plt.subplots()
ax.barbs(X, Y, U, V, np.sqrt(U*U + V*V), fill_empty=True, rounding=False,
ax.barbs(X, Y, U, V, np.hypot(U, V), fill_empty=True, rounding=False,
sizes=dict(emptybarb=0.25, spacing=0.2, height=0.3),
cmap='viridis')

Expand Down
6 changes: 3 additions & 3 deletions lib/matplotlib/tests/test_streamplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,9 @@ def test_colormap():
remove_text=True, style='mpl20')
def test_linewidth():
X, Y, U, V = velocity_field()
speed = np.sqrt(U*U + V*V)
lw = 5*speed/speed.max()
df = 25. / 30. # Compatibility factor for old test image
speed = np.hypot(U, V)
lw = 5 * speed / speed.max()
df = 25 / 30 # Compatibility factor for old test image
plt.streamplot(X, Y, U, V, density=[0.5 * df, 1. * df], color='k',
linewidth=lw)

Expand Down
22 changes: 11 additions & 11 deletions lib/matplotlib/tests/test_triangulation.py
Original file line number Diff line number Diff line change
Expand Up @@ -662,10 +662,10 @@ def test_triinterp_transformations():
min_radius = 0.15

def z(x, y):
r1 = np.sqrt((0.5-x)**2 + (0.5-y)**2)
theta1 = np.arctan2(0.5-x, 0.5-y)
r2 = np.sqrt((-x-0.2)**2 + (-y-0.2)**2)
theta2 = np.arctan2(-x-0.2, -y-0.2)
r1 = np.hypot(0.5 - x, 0.5 - y)
theta1 = np.arctan2(0.5 - x, 0.5 - y)
r2 = np.hypot(-x - 0.2, -y - 0.2)
theta2 = np.arctan2(-x - 0.2, -y - 0.2)
z = -(2*(np.exp((r1/10)**2)-1)*30. * np.cos(7.*theta1) +
(np.exp((r2/10)**2)-1)*30. * np.cos(11.*theta2) +
0.7*(x**2 + y**2))
Expand Down Expand Up @@ -750,10 +750,10 @@ def test_tri_smooth_contouring():
min_radius = 0.15

def z(x, y):
r1 = np.sqrt((0.5-x)**2 + (0.5-y)**2)
theta1 = np.arctan2(0.5-x, 0.5-y)
r2 = np.sqrt((-x-0.2)**2 + (-y-0.2)**2)
theta2 = np.arctan2(-x-0.2, -y-0.2)
r1 = np.hypot(0.5 - x, 0.5 - y)
theta1 = np.arctan2(0.5 - x, 0.5 - y)
r2 = np.hypot(-x - 0.2, -y - 0.2)
theta2 = np.arctan2(-x - 0.2, -y - 0.2)
z = -(2*(np.exp((r1/10)**2)-1)*30. * np.cos(7.*theta1) +
(np.exp((r2/10)**2)-1)*30. * np.cos(11.*theta2) +
0.7*(x**2 + y**2))
Expand Down Expand Up @@ -815,8 +815,8 @@ def dipole_potential(x, y):

# Computes the electrical field (Ex, Ey) as gradient of -V
tci = mtri.CubicTriInterpolator(triang, -V)
(Ex, Ey) = tci.gradient(triang.x, triang.y)
E_norm = np.sqrt(Ex**2 + Ey**2)
Ex, Ey = tci.gradient(triang.x, triang.y)
E_norm = np.hypot(Ex, Ey)

# Plot the triangulation, the potential iso-contours and the vector field
plt.figure()
Expand Down Expand Up @@ -936,7 +936,7 @@ def test_trirefine():
y = np.asarray([0.0, 0.0, 1.0, 1.0])
triang = [mtri.Triangulation(x, y, [[0, 1, 3], [3, 2, 0]]),
mtri.Triangulation(x, y, [[0, 1, 3], [2, 0, 3]])]
z = np.sqrt((x-0.3)*(x-0.3) + (y-0.4)*(y-0.4))
z = np.hypot(x - 0.3, y - 0.4)
# Refining the 2 triangulations and reordering the points
xyz_data = []
for i in range(2):
Expand Down
6 changes: 3 additions & 3 deletions lib/matplotlib/tri/tritools.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,9 +92,9 @@ def circle_ratios(self, rescale=True):
a = tri_pts[:, 1, :] - tri_pts[:, 0, :]
b = tri_pts[:, 2, :] - tri_pts[:, 1, :]
c = tri_pts[:, 0, :] - tri_pts[:, 2, :]
a = np.sqrt(a[:, 0]**2 + a[:, 1]**2)
b = np.sqrt(b[:, 0]**2 + b[:, 1]**2)
c = np.sqrt(c[:, 0]**2 + c[:, 1]**2)
a = np.hypot(a[:, 0], a[:, 1])
b = np.hypot(b[:, 0], b[:, 1])
c = np.hypot(c[:, 0], c[:, 1])
# circumcircle and incircle radii
s = (a+b+c)*0.5
prod = s*(a+b-s)*(a+c-s)*(b+c-s)
Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/widgets.py
Original file line number Diff line number Diff line change
Expand Up @@ -2685,7 +2685,7 @@ def _onmove(self, event):
# Calculate distance to the start vertex.
x0, y0 = self.line.get_transform().transform((self._xs[0],
self._ys[0]))
v0_dist = np.sqrt((x0 - event.x) ** 2 + (y0 - event.y) ** 2)
v0_dist = np.hypot(x0 - event.x, y0 - event.y)
# Lock on to the start vertex if near it and ready to complete.
if len(self._xs) > 3 and v0_dist < self.vertex_select_radius:
self._xs[-1], self._ys[-1] = self._xs[0], self._ys[0]
Expand Down
4 changes: 2 additions & 2 deletions lib/mpl_toolkits/mplot3d/proj3d.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def line2d_dist(l, p):
"""
a, b, c = l
x0, y0 = p
return abs((a*x0 + b*y0 + c) / np.sqrt(a**2+b**2))
return abs((a*x0 + b*y0 + c) / np.hypot(a, b))


def line2d_seg_dist(p1, p2, p0):
Expand All @@ -57,7 +57,7 @@ def line2d_seg_dist(p1, p2, p0):

u = (x01*x21 + y01*y21) / (x21**2 + y21**2)
u = np.clip(u, 0, 1)
d = np.sqrt((x01 - u*x21)**2 + (y01 - u*y21)**2)
d = np.hypot(x01 - u*x21, y01 - u*y21)

return d

Expand Down
4 changes: 2 additions & 2 deletions lib/mpl_toolkits/tests/test_mplot3d.py
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ def f(t):

ax = fig.add_subplot(2, 1, 2, projection='3d')
X, Y = np.meshgrid(np.arange(-5, 5, 0.25), np.arange(-5, 5, 0.25))
R = np.sqrt(X ** 2 + Y ** 2)
R = np.hypot(X, Y)
Z = np.sin(R)

surf = ax.plot_surface(X, Y, Z, rcount=40, ccount=40,
Expand Down Expand Up @@ -202,7 +202,7 @@ def test_surface3d():
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X ** 2 + Y ** 2)
R = np.hypot(X, Y)
Z = np.sin(R)
surf = ax.plot_surface(X, Y, Z, rcount=40, ccount=40, cmap=cm.coolwarm,
lw=0, antialiased=False)
Expand Down