Skip to content

Commit dd1c386

Browse files
committed
Use np.hypot whereever possible.
Except examples, where it may be too obscure? Also added -T to CI sphinx-build invocation, to help troubleshooting e.g. https://circleci.com/gh/anntzer/matplotlib/2505?utm_campaign=vcs-integration-link&utm_medium=referral&utm_source=github-build-link (show traceback on sphinx failure).
1 parent 9869fd7 commit dd1c386

23 files changed

+66
-80
lines changed

.circleci/config.yml

+1-1
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ mpl-run: &mpl-install
7474

7575
doc-run: &doc-build
7676
name: Build documentation
77-
command: make html
77+
command: make html O=-T
7878
working_directory: doc
7979

8080
doc-bundle-run: &doc-bundle

.flake8

+1-1
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ per-file-ignores =
108108
examples/event_handling/poly_editor.py: E501
109109
examples/event_handling/viewlims.py: E501
110110
examples/images_contours_and_fields/affine_image.py: E402
111-
examples/images_contours_and_fields/barb_demo.py: E402, E501
111+
examples/images_contours_and_fields/barb_demo.py: E402
112112
examples/images_contours_and_fields/barcode_demo.py: E402
113113
examples/images_contours_and_fields/contour_corner_mask.py: E402
114114
examples/images_contours_and_fields/contour_demo.py: E402, E501

examples/event_handling/pick_event_demo.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,8 @@ def line_picker(line, mouseevent):
126126
xdata = line.get_xdata()
127127
ydata = line.get_ydata()
128128
maxd = 0.05
129-
d = np.sqrt((xdata - mouseevent.xdata)**2. + (ydata - mouseevent.ydata)**2.)
129+
d = np.sqrt(
130+
(xdata - mouseevent.xdata)**2 + (ydata - mouseevent.ydata)**2)
130131

131132
ind = np.nonzero(np.less_equal(d, maxd))
132133
if len(ind):

examples/images_contours_and_fields/barb_demo.py

+5-3
Original file line numberDiff line numberDiff line change
@@ -28,12 +28,14 @@
2828

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

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

3840
# Change colors as well as the increments for parts of the barbs
3941
axs1[1, 1].barbs(data['x'], data['y'], data['u'], data['v'], flagcolor='r',

examples/images_contours_and_fields/contourf_demo.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
Z[:nr // 6, :nc // 6] = np.ma.masked
3131

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

3636
# We are using automatic selection of contour levels;

examples/images_contours_and_fields/plot_streamplot.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
Y, X = np.mgrid[-w:w:100j, -w:w:100j]
2121
U = -1 - X**2 + Y
2222
V = 1 + X - Y**2
23-
speed = np.sqrt(U*U + V*V)
23+
speed = np.sqrt(U**2 + V**2)
2424

2525
fig = plt.figure(figsize=(7, 9))
2626
gs = gridspec.GridSpec(nrows=3, ncols=2, height_ratios=[1, 1, 2])

examples/lines_bars_and_markers/scatter_masked.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
y = 0.9 * np.random.rand(N)
2121
area = (20 * np.random.rand(N))**2 # 0 to 10 point radii
2222
c = np.sqrt(area)
23-
r = np.sqrt(x * x + y * y)
23+
r = np.sqrt(x ** 2 + y ** 2)
2424
area1 = np.ma.masked_where(r < r0, area)
2525
area2 = np.ma.masked_where(r >= r0, area)
2626
plt.scatter(x, y, s=area1, marker='^', c=c)

lib/matplotlib/contour.py

+3-5
Original file line numberDiff line numberDiff line change
@@ -230,11 +230,9 @@ def print_label(self, linecontour, labelwidth):
230230

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

239237
def get_label_coords(self, distances, XX, YY, ysize, lw):
240238
"""

lib/matplotlib/lines.py

+6-7
Original file line numberDiff line numberDiff line change
@@ -477,17 +477,16 @@ def contains(self, mouseevent):
477477
else:
478478
pixels = self.figure.dpi / 72. * self.pickradius
479479

480-
# the math involved in checking for containment (here and inside of
481-
# segment_hits) assumes that it is OK to overflow. In case the
482-
# application has set the error flags such that an exception is raised
483-
# on overflow, we temporarily set the appropriate error flags here and
484-
# set them back when we are finished.
480+
# The math involved in checking for containment (here and inside of
481+
# segment_hits) assumes that it is OK to overflow, so temporarily set
482+
# the error flags accordingly.
485483
with np.errstate(all='ignore'):
486484
# Check for collision
487485
if self._linestyle in ['None', None]:
488486
# If no line, return the nearby point(s)
489-
d = (xt - mouseevent.x) ** 2 + (yt - mouseevent.y) ** 2
490-
ind, = np.nonzero(np.less_equal(d, pixels ** 2))
487+
ind, = np.nonzero(
488+
(xt - mouseevent.x) ** 2 + (yt - mouseevent.y) ** 2
489+
<= pixels ** 2)
491490
else:
492491
# If line, return the nearby segment(s)
493492
ind = segment_hits(mouseevent.x, mouseevent.y, xt, yt, pixels)

lib/matplotlib/patches.py

+5-7
Original file line numberDiff line numberDiff line change
@@ -1359,10 +1359,8 @@ def get_path(self):
13591359
xb1, yb1, xb2, yb2 = self.getpoints(x1, y1, x2, y2, k1)
13601360

13611361
# a point on the segment 20% of the distance from the tip to the base
1362-
theta = math.atan2(y2 - y1, x2 - x1)
1363-
r = math.sqrt((y2 - y1) ** 2. + (x2 - x1) ** 2.)
1364-
xm = x1 + self.frac * r * math.cos(theta)
1365-
ym = y1 + self.frac * r * math.sin(theta)
1362+
xm = x1 + self.frac * (x2 - x1)
1363+
ym = y1 + self.frac * (y2 - y1)
13661364
xc1, yc1, xc2, yc2 = self.getpoints(x1, y1, xm, ym, k1)
13671365
xd1, yd1, xd2, yd2 = self.getpoints(x1, y1, xm, ym, k2)
13681366

@@ -2915,10 +2913,10 @@ def connect(self, posA, posB):
29152913
codes.append(Path.LINETO)
29162914
else:
29172915
dx1, dy1 = x1 - cx, y1 - cy
2918-
d1 = (dx1 ** 2 + dy1 ** 2) ** .5
2916+
d1 = np.hypot(dx1, dy1)
29192917
f1 = self.rad / d1
29202918
dx2, dy2 = x2 - cx, y2 - cy
2921-
d2 = (dx2 ** 2 + dy2 ** 2) ** .5
2919+
d2 = np.hypot(dx2, dy2)
29222920
f2 = self.rad / d2
29232921
vertices.extend([(cx + dx1 * f1, cy + dy1 * f1),
29242922
(cx, cy),
@@ -3302,7 +3300,7 @@ def transmute(self, path, mutation_size, linewidth):
33023300

33033301
head_length = self.head_length * mutation_size
33043302
head_width = self.head_width * mutation_size
3305-
head_dist = math.sqrt(head_length ** 2 + head_width ** 2)
3303+
head_dist = np.hypot(head_length, head_width)
33063304
cos_t, sin_t = head_length / head_dist, head_width / head_dist
33073305

33083306
# begin arrow

lib/matplotlib/projections/geo.py

+8-12
Original file line numberDiff line numberDiff line change
@@ -462,15 +462,12 @@ def transform_non_affine(self, ll):
462462
diff_long = longitude - clong
463463
cos_diff_long = np.cos(diff_long)
464464

465-
inner_k = (1.0 +
466-
np.sin(clat)*sin_lat +
467-
np.cos(clat)*cos_lat*cos_diff_long)
468-
# Prevent divide-by-zero problems
469-
inner_k = np.where(inner_k == 0.0, 1e-15, inner_k)
470-
k = np.sqrt(2.0 / inner_k)
471-
x = k*cos_lat*np.sin(diff_long)
472-
y = k*(np.cos(clat)*sin_lat -
473-
np.sin(clat)*cos_lat*cos_diff_long)
465+
inner_k = np.maximum( # Prevent divide-by-zero problems
466+
1 + np.sin(clat)*sin_lat + np.cos(clat)*cos_lat*cos_diff_long,
467+
1e-15)
468+
k = np.sqrt(2 / inner_k)
469+
x = k * cos_lat*np.sin(diff_long)
470+
y = k * (np.cos(clat)*sin_lat - np.sin(clat)*cos_lat*cos_diff_long)
474471

475472
return np.concatenate((x, y), 1)
476473
transform_non_affine.__doc__ = Transform.transform_non_affine.__doc__
@@ -494,9 +491,8 @@ def transform_non_affine(self, xy):
494491
y = xy[:, 1:2]
495492
clong = self._center_longitude
496493
clat = self._center_latitude
497-
p = np.sqrt(x*x + y*y)
498-
p = np.where(p == 0.0, 1e-9, p)
499-
c = 2.0 * np.arcsin(0.5 * p)
494+
p = np.maximum(np.hypot(x, y), 1e-9)
495+
c = 2 * np.arcsin(0.5 * p)
500496
sin_c = np.sin(c)
501497
cos_c = np.cos(c)
502498

lib/matplotlib/projections/polar.py

+2-9
Original file line numberDiff line numberDiff line change
@@ -149,15 +149,8 @@ def __str__(self):
149149
def transform_non_affine(self, xy):
150150
x = xy[:, 0:1]
151151
y = xy[:, 1:]
152-
r = np.sqrt(x*x + y*y)
153-
with np.errstate(invalid='ignore'):
154-
# At x=y=r=0 this will raise an
155-
# invalid value warning when doing 0/0
156-
# Divide by zero warnings are only raised when
157-
# the numerator is different from 0. That
158-
# should not happen here.
159-
theta = np.arccos(x / r)
160-
theta = np.where(y < 0, 2 * np.pi - theta, theta)
152+
r = np.hypot(x, y)
153+
theta = (np.arctan2(y, x) + 2 * np.pi) % (2 * np.pi)
161154

162155
# PolarAxes does not use the theta transforms here, but apply them for
163156
# backwards-compatibility if not being used by it.

lib/matplotlib/streamplot.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -190,7 +190,7 @@ def streamplot(axes, x, y, u, v, density=1, linewidth=None, color=None,
190190
streamlines.extend(np.hstack([points[:-1], points[1:]]))
191191

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

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

541541
# Only save step if within error tolerance
542542
if error < maxerror:

lib/matplotlib/tests/test_axes.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1173,7 +1173,7 @@ def test_pcolorargs():
11731173
x = np.linspace(-1.5, 1.5, n)
11741174
y = np.linspace(-1.5, 1.5, n*2)
11751175
X, Y = np.meshgrid(x, y)
1176-
Z = np.sqrt(X**2 + Y**2)/5
1176+
Z = np.hypot(X, Y) / 5
11771177

11781178
_, ax = plt.subplots()
11791179
with pytest.raises(TypeError):

lib/matplotlib/tests/test_contour.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -291,7 +291,7 @@ def test_corner_mask():
291291
np.random.seed([1])
292292
x, y = np.meshgrid(np.linspace(0, 2.0, n), np.linspace(0, 2.0, n))
293293
z = np.cos(7*x)*np.sin(8*y) + noise_amp*np.random.rand(n, n)
294-
mask = np.where(np.random.rand(n, n) >= mask_level, True, False)
294+
mask = np.random.rand(n, n) >= mask_level
295295
z = np.ma.array(z, mask=mask)
296296

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

367367
plt.figure()
368368
cs = plt.contour(x, y, r)

lib/matplotlib/tests/test_image.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -745,12 +745,11 @@ def test_mask_image():
745745
def test_imshow_endianess():
746746
x = np.arange(10)
747747
X, Y = np.meshgrid(x, x)
748-
Z = ((X-5)**2 + (Y-5)**2)**0.5
748+
Z = np.hypot(X - 5, Y - 5)
749749

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

752-
kwargs = dict(origin="lower", interpolation='nearest',
753-
cmap='viridis')
752+
kwargs = dict(origin="lower", interpolation='nearest', cmap='viridis')
754753

755754
ax1.imshow(Z.astype('<f8'), **kwargs)
756755
ax2.imshow(Z.astype('>f8'), **kwargs)

lib/matplotlib/tests/test_quiver.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@ def test_barbs():
136136
X, Y = np.meshgrid(x, x)
137137
U, V = 12*X, 12*Y
138138
fig, ax = plt.subplots()
139-
ax.barbs(X, Y, U, V, np.sqrt(U*U + V*V), fill_empty=True, rounding=False,
139+
ax.barbs(X, Y, U, V, np.hypot(U, V), fill_empty=True, rounding=False,
140140
sizes=dict(emptybarb=0.25, spacing=0.2, height=0.3),
141141
cmap='viridis')
142142

lib/matplotlib/tests/test_streamplot.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -53,9 +53,9 @@ def test_colormap():
5353
remove_text=True, style='mpl20')
5454
def test_linewidth():
5555
X, Y, U, V = velocity_field()
56-
speed = np.sqrt(U*U + V*V)
57-
lw = 5*speed/speed.max()
58-
df = 25. / 30. # Compatibility factor for old test image
56+
speed = np.hypot(U, V)
57+
lw = 5 * speed / speed.max()
58+
df = 25 / 30 # Compatibility factor for old test image
5959
plt.streamplot(X, Y, U, V, density=[0.5 * df, 1. * df], color='k',
6060
linewidth=lw)
6161

lib/matplotlib/tests/test_triangulation.py

+11-11
Original file line numberDiff line numberDiff line change
@@ -662,10 +662,10 @@ def test_triinterp_transformations():
662662
min_radius = 0.15
663663

664664
def z(x, y):
665-
r1 = np.sqrt((0.5-x)**2 + (0.5-y)**2)
666-
theta1 = np.arctan2(0.5-x, 0.5-y)
667-
r2 = np.sqrt((-x-0.2)**2 + (-y-0.2)**2)
668-
theta2 = np.arctan2(-x-0.2, -y-0.2)
665+
r1 = np.hypot(0.5 - x, 0.5 - y)
666+
theta1 = np.arctan2(0.5 - x, 0.5 - y)
667+
r2 = np.hypot(-x - 0.2, -y - 0.2)
668+
theta2 = np.arctan2(-x - 0.2, -y - 0.2)
669669
z = -(2*(np.exp((r1/10)**2)-1)*30. * np.cos(7.*theta1) +
670670
(np.exp((r2/10)**2)-1)*30. * np.cos(11.*theta2) +
671671
0.7*(x**2 + y**2))
@@ -750,10 +750,10 @@ def test_tri_smooth_contouring():
750750
min_radius = 0.15
751751

752752
def z(x, y):
753-
r1 = np.sqrt((0.5-x)**2 + (0.5-y)**2)
754-
theta1 = np.arctan2(0.5-x, 0.5-y)
755-
r2 = np.sqrt((-x-0.2)**2 + (-y-0.2)**2)
756-
theta2 = np.arctan2(-x-0.2, -y-0.2)
753+
r1 = np.hypot(0.5 - x, 0.5 - y)
754+
theta1 = np.arctan2(0.5 - x, 0.5 - y)
755+
r2 = np.hypot(-x - 0.2, -y - 0.2)
756+
theta2 = np.arctan2(-x - 0.2, -y - 0.2)
757757
z = -(2*(np.exp((r1/10)**2)-1)*30. * np.cos(7.*theta1) +
758758
(np.exp((r2/10)**2)-1)*30. * np.cos(11.*theta2) +
759759
0.7*(x**2 + y**2))
@@ -815,8 +815,8 @@ def dipole_potential(x, y):
815815

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

821821
# Plot the triangulation, the potential iso-contours and the vector field
822822
plt.figure()
@@ -936,7 +936,7 @@ def test_trirefine():
936936
y = np.asarray([0.0, 0.0, 1.0, 1.0])
937937
triang = [mtri.Triangulation(x, y, [[0, 1, 3], [3, 2, 0]]),
938938
mtri.Triangulation(x, y, [[0, 1, 3], [2, 0, 3]])]
939-
z = np.sqrt((x-0.3)*(x-0.3) + (y-0.4)*(y-0.4))
939+
z = np.hypot(x - 0.3, y - 0.4)
940940
# Refining the 2 triangulations and reordering the points
941941
xyz_data = []
942942
for i in range(2):

lib/matplotlib/tri/tritools.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -92,9 +92,9 @@ def circle_ratios(self, rescale=True):
9292
a = tri_pts[:, 1, :] - tri_pts[:, 0, :]
9393
b = tri_pts[:, 2, :] - tri_pts[:, 1, :]
9494
c = tri_pts[:, 0, :] - tri_pts[:, 2, :]
95-
a = np.sqrt(a[:, 0]**2 + a[:, 1]**2)
96-
b = np.sqrt(b[:, 0]**2 + b[:, 1]**2)
97-
c = np.sqrt(c[:, 0]**2 + c[:, 1]**2)
95+
a = np.hypot(a[:, 0], a[:, 1])
96+
b = np.hypot(b[:, 0], b[:, 1])
97+
c = np.hypot(c[:, 0], c[:, 1])
9898
# circumcircle and incircle radii
9999
s = (a+b+c)*0.5
100100
prod = s*(a+b-s)*(a+c-s)*(b+c-s)

lib/matplotlib/widgets.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -2685,7 +2685,7 @@ def _onmove(self, event):
26852685
# Calculate distance to the start vertex.
26862686
x0, y0 = self.line.get_transform().transform((self._xs[0],
26872687
self._ys[0]))
2688-
v0_dist = np.sqrt((x0 - event.x) ** 2 + (y0 - event.y) ** 2)
2688+
v0_dist = np.hypot(x0 - event.x, y0 - event.y)
26892689
# Lock on to the start vertex if near it and ready to complete.
26902690
if len(self._xs) > 3 and v0_dist < self.vertex_select_radius:
26912691
self._xs[-1], self._ys[-1] = self._xs[0], self._ys[0]

lib/mpl_toolkits/mplot3d/proj3d.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ def line2d_dist(l, p):
3737
"""
3838
a, b, c = l
3939
x0, y0 = p
40-
return abs((a*x0 + b*y0 + c) / np.sqrt(a**2+b**2))
40+
return abs((a*x0 + b*y0 + c) / np.hypot(a, b))
4141

4242

4343
def line2d_seg_dist(p1, p2, p0):
@@ -57,7 +57,7 @@ def line2d_seg_dist(p1, p2, p0):
5757

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

6262
return d
6363

lib/mpl_toolkits/tests/test_mplot3d.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,7 @@ def f(t):
154154

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

160160
surf = ax.plot_surface(X, Y, Z, rcount=40, ccount=40,
@@ -202,7 +202,7 @@ def test_surface3d():
202202
X = np.arange(-5, 5, 0.25)
203203
Y = np.arange(-5, 5, 0.25)
204204
X, Y = np.meshgrid(X, Y)
205-
R = np.sqrt(X ** 2 + Y ** 2)
205+
R = np.hypot(X, Y)
206206
Z = np.sin(R)
207207
surf = ax.plot_surface(X, Y, Z, rcount=40, ccount=40, cmap=cm.coolwarm,
208208
lw=0, antialiased=False)

0 commit comments

Comments
 (0)