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

Skip to content

Commit 4478835

Browse files
committed
Use np.hypot whereever possible.
Except examples, where it may be too obscure?
1 parent 4872b79 commit 4478835

22 files changed

+64
-87
lines changed

examples/event_handling/pick_event_demo.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,8 @@ def line_picker(line, mouseevent):
123123
xdata = line.get_xdata()
124124
ydata = line.get_ydata()
125125
maxd = 0.05
126-
d = np.sqrt((xdata - mouseevent.xdata)**2. + (ydata - mouseevent.ydata)**2.)
126+
d = np.sqrt(
127+
(xdata - mouseevent.xdata)**2 + (ydata - mouseevent.ydata)**2)
127128

128129
ind = np.nonzero(np.less_equal(d, maxd))
129130
if len(ind):

examples/images_contours_and_fields/barb_demo.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@
3434
# Showing colormapping with uniform grid. Fill the circle for an empty barb,
3535
# don't round the values, and change some of the size parameters
3636
ax = plt.subplot(2, 2, 3)
37-
ax.barbs(X, Y, U, V, np.sqrt(U * U + V * V), fill_empty=True, rounding=False,
37+
ax.barbs(X, Y, U, V, np.sqrt(U ** 2 + V ** 2), fill_empty=True, rounding=False,
3838
sizes=dict(emptybarb=0.25, spacing=0.2, height=0.3))
3939

4040
# Change colors as well as the increments for parts of the barbs

examples/images_contours_and_fields/contourf_demo.py

Lines changed: 1 addition & 1 deletion
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

Lines changed: 1 addition & 1 deletion
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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717
y = 0.9 * np.random.rand(N)
1818
area = np.pi * (10 * np.random.rand(N))**2 # 0 to 10 point radii
1919
c = np.sqrt(area)
20-
r = np.sqrt(x * x + y * y)
20+
r = np.sqrt(x ** 2 + y ** 2)
2121
area1 = np.ma.masked_where(r < r0, area)
2222
area2 = np.ma.masked_where(r >= r0, area)
2323
plt.scatter(x, y, s=area1, marker='^', c=c)

lib/matplotlib/contour.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -230,11 +230,7 @@ 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+
return any(np.hypot(x - loc[0], y - loc[1]) < 1.2 * lw for loc in self.labelXYs)
238234

239235
def get_label_coords(self, distances, XX, YY, ysize, lw):
240236
"""

lib/matplotlib/lines.py

Lines changed: 8 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,7 @@ def segment_hits(cx, cy, x, y, radius):
8181
"""
8282
# Process single points specially
8383
if len(x) < 2:
84-
res, = np.nonzero((cx - x) ** 2 + (cy - y) ** 2 <= radius ** 2)
84+
res, = np.nonzero(np.hypot(cx - x, cy - y) <= radius)
8585
return res
8686

8787
# We need to lop the last element off a lot.
@@ -93,25 +93,21 @@ def segment_hits(cx, cy, x, y, radius):
9393
Lnorm_sq = dx ** 2 + dy ** 2 # Possibly want to eliminate Lnorm==0
9494
u = ((cx - xr) * dx + (cy - yr) * dy) / Lnorm_sq
9595
candidates = (u >= 0) & (u <= 1)
96-
#if any(candidates): print "candidates",xr[candidates]
9796

9897
# Note that there is a little area near one side of each point
9998
# which will be near neither segment, and another which will
10099
# be near both, depending on the angle of the lines. The
101100
# following radius test eliminates these ambiguities.
102-
point_hits = (cx - x) ** 2 + (cy - y) ** 2 <= radius ** 2
103-
#if any(point_hits): print "points",xr[candidates]
101+
points_hit = np.hypot(cx - x, cy - y) <= radius
104102
candidates = candidates & ~(point_hits[:-1] | point_hits[1:])
105103

106104
# For those candidates which remain, determine how far they lie away
107105
# from the line.
108106
px, py = xr + u * dx, yr + u * dy
109-
line_hits = (cx - px) ** 2 + (cy - py) ** 2 <= radius ** 2
110-
#if any(line_hits): print "lines",xr[candidates]
107+
line_hits = np.hypot(cx - px, cy - py) <= radius
111108
line_hits = line_hits & candidates
112109
points, = point_hits.ravel().nonzero()
113110
lines, = line_hits.ravel().nonzero()
114-
#print points,lines
115111
return np.concatenate((points, lines))
116112

117113

@@ -484,17 +480,15 @@ def contains(self, mouseevent):
484480
else:
485481
pixels = self.figure.dpi / 72. * self.pickradius
486482

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

lib/matplotlib/patches.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1363,10 +1363,8 @@ def get_path(self):
13631363
xb1, yb1, xb2, yb2 = self.getpoints(x1, y1, x2, y2, k1)
13641364

13651365
# a point on the segment 20% of the distance from the tip to the base
1366-
theta = math.atan2(y2 - y1, x2 - x1)
1367-
r = math.sqrt((y2 - y1) ** 2. + (x2 - x1) ** 2.)
1368-
xm = x1 + self.frac * r * math.cos(theta)
1369-
ym = y1 + self.frac * r * math.sin(theta)
1366+
xm = x1 + self.frac * (x2 - x1)
1367+
ym = y1 + self.frac * (y2 - y1)
13701368
xc1, yc1, xc2, yc2 = self.getpoints(x1, y1, xm, ym, k1)
13711369
xd1, yd1, xd2, yd2 = self.getpoints(x1, y1, xm, ym, k2)
13721370

@@ -2950,10 +2948,10 @@ def connect(self, posA, posB):
29502948
codes.append(Path.LINETO)
29512949
else:
29522950
dx1, dy1 = x1 - cx, y1 - cy
2953-
d1 = (dx1 ** 2 + dy1 ** 2) ** .5
2951+
d1 = np.hypot(dx1, dy1)
29542952
f1 = self.rad / d1
29552953
dx2, dy2 = x2 - cx, y2 - cy
2956-
d2 = (dx2 ** 2 + dy2 ** 2) ** .5
2954+
d2 = np.hypot(dx2, dy2)
29572955
f2 = self.rad / d2
29582956
vertices.extend([(cx + dx1 * f1, cy + dy1 * f1),
29592957
(cx, cy),
@@ -3355,7 +3353,7 @@ def transmute(self, path, mutation_size, linewidth):
33553353

33563354
head_length = self.head_length * mutation_size
33573355
head_width = self.head_width * mutation_size
3358-
head_dist = math.sqrt(head_length ** 2 + head_width ** 2)
3356+
head_dist = np.hypot(head_length, head_width)
33593357
cos_t, sin_t = head_length / head_dist, head_width / head_dist
33603358

33613359
# begin arrow

lib/matplotlib/projections/geo.py

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -470,15 +470,12 @@ def transform_non_affine(self, ll):
470470
diff_long = longitude - clong
471471
cos_diff_long = np.cos(diff_long)
472472

473-
inner_k = (1.0 +
474-
np.sin(clat)*sin_lat +
475-
np.cos(clat)*cos_lat*cos_diff_long)
476-
# Prevent divide-by-zero problems
477-
inner_k = np.where(inner_k == 0.0, 1e-15, inner_k)
478-
k = np.sqrt(2.0 / inner_k)
479-
x = k*cos_lat*np.sin(diff_long)
480-
y = k*(np.cos(clat)*sin_lat -
481-
np.sin(clat)*cos_lat*cos_diff_long)
473+
inner_k = np.max( # Prevent divide-by-zero problems
474+
1 + np.sin(clat)*sin_lat + np.cos(clat)*cos_lat*cos_diff_long,
475+
1e-15)
476+
k = np.sqrt(2 / inner_k)
477+
x = k * cos_lat*np.sin(diff_long)
478+
y = k * (np.cos(clat)*sin_lat - np.sin(clat)*cos_lat*cos_diff_long)
482479

483480
return np.concatenate((x, y), 1)
484481
transform_non_affine.__doc__ = Transform.transform_non_affine.__doc__
@@ -502,8 +499,7 @@ def transform_non_affine(self, xy):
502499
y = xy[:, 1:2]
503500
clong = self._center_longitude
504501
clat = self._center_latitude
505-
p = np.sqrt(x*x + y*y)
506-
p = np.where(p == 0.0, 1e-9, p)
502+
p = np.max(np.hypot(x, y), 1e-9)
507503
c = 2.0 * np.arcsin(0.5 * p)
508504
sin_c = np.sin(c)
509505
cos_c = np.cos(c)

lib/matplotlib/projections/polar.py

Lines changed: 2 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -155,15 +155,8 @@ def __str__(self):
155155
def transform_non_affine(self, xy):
156156
x = xy[:, 0:1]
157157
y = xy[:, 1:]
158-
r = np.sqrt(x*x + y*y)
159-
with np.errstate(invalid='ignore'):
160-
# At x=y=r=0 this will raise an
161-
# invalid value warning when doing 0/0
162-
# Divide by zero warnings are only raised when
163-
# the numerator is different from 0. That
164-
# should not happen here.
165-
theta = np.arccos(x / r)
166-
theta = np.where(y < 0, 2 * np.pi - theta, theta)
158+
r = np.hypot(x, y)
159+
theta = np.arctan2(y, x)
167160

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

lib/matplotlib/streamplot.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,7 @@ def streamplot(axes, x, y, u, v, density=1, linewidth=None, color=None,
194194
streamlines.extend(np.hstack([points[:-1], points[1:]]))
195195

196196
# Add arrows half way along each trajectory.
197-
s = np.cumsum(np.sqrt(np.diff(tx) ** 2 + np.diff(ty) ** 2))
197+
s = np.cumsum(np.hypot(np.diff(tx), np.diff(ty)))
198198
n = np.searchsorted(s, s[-1] / 2.)
199199
arrow_tail = (tx[n], ty[n])
200200
arrow_head = (np.mean(tx[n:n + 2]), np.mean(ty[n:n + 2]))
@@ -420,7 +420,7 @@ def get_integrator(u, v, dmap, minlength, maxlength, integration_direction):
420420
# speed (path length) will be in axes-coordinates
421421
u_ax = u / dmap.grid.nx
422422
v_ax = v / dmap.grid.ny
423-
speed = np.ma.sqrt(u_ax ** 2 + v_ax ** 2)
423+
speed = np.ma.hypot(u_ax, v_ax)
424424

425425
def forward_time(xi, yi):
426426
ds_dt = interpgrid(speed, xi, yi)
@@ -543,7 +543,7 @@ def _integrate_rk12(x0, y0, dmap, f, maxlength):
543543

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

548548
# Only save step if within error tolerance
549549
if error < maxerror:

lib/matplotlib/tests/test_axes.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1183,7 +1183,7 @@ def test_pcolorargs():
11831183
x = np.linspace(-1.5, 1.5, n)
11841184
y = np.linspace(-1.5, 1.5, n*2)
11851185
X, Y = np.meshgrid(x, y)
1186-
Z = np.sqrt(X**2 + Y**2)/5
1186+
Z = np.hypot(X, Y) / 5
11871187

11881188
_, ax = plt.subplots()
11891189
with pytest.raises(TypeError):

lib/matplotlib/tests/test_contour.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -289,7 +289,7 @@ def test_corner_mask():
289289
np.random.seed([1])
290290
x, y = np.meshgrid(np.linspace(0, 2.0, n), np.linspace(0, 2.0, n))
291291
z = np.cos(7*x)*np.sin(8*y) + noise_amp*np.random.rand(n, n)
292-
mask = np.where(np.random.rand(n, n) >= mask_level, True, False)
292+
mask = np.random.rand(n, n) >= mask_level
293293
z = np.ma.array(z, mask=mask)
294294

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

365365
plt.figure()
366366
cs = plt.contour(x, y, r)

lib/matplotlib/tests/test_image.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -760,12 +760,11 @@ def test_mask_image():
760760
def test_imshow_endianess():
761761
x = np.arange(10)
762762
X, Y = np.meshgrid(x, x)
763-
Z = ((X-5)**2 + (Y-5)**2)**0.5
763+
Z = np.hypot(X - 5, Y - 5)
764764

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

767-
kwargs = dict(origin="lower", interpolation='nearest',
768-
cmap='viridis')
767+
kwargs = dict(origin="lower", interpolation='nearest', cmap='viridis')
769768

770769
ax1.imshow(Z.astype('<f8'), **kwargs)
771770
ax2.imshow(Z.astype('>f8'), **kwargs)

lib/matplotlib/tests/test_quiver.py

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

lib/matplotlib/tests/test_streamplot.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -50,9 +50,9 @@ def test_colormap():
5050
@image_comparison(baseline_images=['streamplot_linewidth'])
5151
def test_linewidth():
5252
X, Y, U, V = velocity_field()
53-
speed = np.sqrt(U*U + V*V)
54-
lw = 5*speed/speed.max()
55-
df = 25. / 30. # Compatibility factor for old test image
53+
speed = np.hypot(U, V)
54+
lw = 5 * speed / speed.max()
55+
df = 25 / 30 # Compatibility factor for old test image
5656
plt.streamplot(X, Y, U, V, density=[0.5 * df, 1. * df], color='k',
5757
linewidth=lw)
5858

lib/matplotlib/tests/test_triangulation.py

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -664,10 +664,10 @@ def test_triinterp_transformations():
664664
min_radius = 0.15
665665

666666
def z(x, y):
667-
r1 = np.sqrt((0.5-x)**2 + (0.5-y)**2)
668-
theta1 = np.arctan2(0.5-x, 0.5-y)
669-
r2 = np.sqrt((-x-0.2)**2 + (-y-0.2)**2)
670-
theta2 = np.arctan2(-x-0.2, -y-0.2)
667+
r1 = np.hypot(0.5 - x, 0.5 - y)
668+
theta1 = np.arctan2(0.5 - x, 0.5 - y)
669+
r2 = np.hypot(-x - 0.2, -y - 0.2)
670+
theta2 = np.arctan2(-x - 0.2, -y - 0.2)
671671
z = -(2*(np.exp((r1/10)**2)-1)*30. * np.cos(7.*theta1) +
672672
(np.exp((r2/10)**2)-1)*30. * np.cos(11.*theta2) +
673673
0.7*(x**2 + y**2))
@@ -752,10 +752,10 @@ def test_tri_smooth_contouring():
752752
min_radius = 0.15
753753

754754
def z(x, y):
755-
r1 = np.sqrt((0.5-x)**2 + (0.5-y)**2)
756-
theta1 = np.arctan2(0.5-x, 0.5-y)
757-
r2 = np.sqrt((-x-0.2)**2 + (-y-0.2)**2)
758-
theta2 = np.arctan2(-x-0.2, -y-0.2)
755+
r1 = np.hypot(0.5 - x, 0.5 - y)
756+
theta1 = np.arctan2(0.5 - x, 0.5 - y)
757+
r2 = np.hypot(-x - 0.2, -y - 0.2)
758+
theta2 = np.arctan2(-x - 0.2, -y - 0.2)
759759
z = -(2*(np.exp((r1/10)**2)-1)*30. * np.cos(7.*theta1) +
760760
(np.exp((r2/10)**2)-1)*30. * np.cos(11.*theta2) +
761761
0.7*(x**2 + y**2))
@@ -817,8 +817,8 @@ def dipole_potential(x, y):
817817

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

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

lib/matplotlib/tri/tritools.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -95,9 +95,9 @@ def circle_ratios(self, rescale=True):
9595
a = tri_pts[:, 1, :] - tri_pts[:, 0, :]
9696
b = tri_pts[:, 2, :] - tri_pts[:, 1, :]
9797
c = tri_pts[:, 0, :] - tri_pts[:, 2, :]
98-
a = np.sqrt(a[:, 0]**2 + a[:, 1]**2)
99-
b = np.sqrt(b[:, 0]**2 + b[:, 1]**2)
100-
c = np.sqrt(c[:, 0]**2 + c[:, 1]**2)
98+
a = np.hypot(a[:, 0], a[:, 1])
99+
b = np.hypot(b[:, 0], b[:, 1])
100+
c = np.hypot(c[:, 0], c[:, 1])
101101
# circumcircle and incircle radii
102102
s = (a+b+c)*0.5
103103
prod = s*(a+b-s)*(a+c-s)*(b+c-s)

lib/matplotlib/widgets.py

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

lib/mpl_toolkits/mplot3d/proj3d.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ def line2d_dist(l, p):
4343
"""
4444
a, b, c = l
4545
x0, y0 = p
46-
return abs((a*x0 + b*y0 + c)/np.sqrt(a**2+b**2))
46+
return abs((a*x0 + b*y0 + c) / np.hypot(a, b))
4747

4848

4949
def line2d_seg_dist(p1, p2, p0):
@@ -61,9 +61,9 @@ def line2d_seg_dist(p1, p2, p0):
6161
x01 = np.asarray(p0[0]) - p1[0]
6262
y01 = np.asarray(p0[1]) - p1[1]
6363

64-
u = (x01*x21 + y01*y21)/float(abs(x21**2 + y21**2))
64+
u = (x01*x21 + y01*y21) / abs(x21**2 + y21**2)
6565
u = np.clip(u, 0, 1)
66-
d = np.sqrt((x01 - u*x21)**2 + (y01 - u*y21)**2)
66+
d = np.hypot(x01 - u*x21, y01 - u*y21)
6767

6868
return d
6969

0 commit comments

Comments
 (0)