Skip to content

Commit f931734

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

File tree

22 files changed

+65
-85
lines changed

22 files changed

+65
-85
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: 3 additions & 5 deletions
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

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -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 = (cx - x) ** 2 + (cy - y) ** 2 <= radius ** 2
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
109107
line_hits = (cx - px) ** 2 + (cy - py) ** 2 <= radius ** 2
110-
#if any(line_hits): print "lines",xr[candidates]
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,16 @@ 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+
(xt - mouseevent.x) ** 2 + (yt - mouseevent.y) ** 2
492+
<= pixels ** 2)
498493
else:
499494
# If line, return the nearby segment(s)
500495
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.

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy