Skip to content

Commit fb82ca6

Browse files
committed
Use builtin round instead of np.round for scalars.
Compared to np.round, builtin round is 20x faster for python floats and 2x faster for numpy floats (it's admittedly unlikely that any of the places patched is an actual bottleneck). On Py2 builtin round and np.round were not equivalent because builtin round rounded halves away from zero, but now both round-to-even. Small misc. changes; the rearrangement in backend_agg.draw_text is to make the implementation more similar to draw_mathtext (just above).
1 parent 3bacb5f commit fb82ca6

File tree

15 files changed

+56
-59
lines changed

15 files changed

+56
-59
lines changed

examples/misc/custom_projection.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ def __init__(self, round_to=1.0):
3939
self._round_to = round_to
4040

4141
def __call__(self, x, pos=None):
42-
degrees = np.round(np.rad2deg(x) / self._round_to) * self._round_to
42+
degrees = round(np.rad2deg(x) / self._round_to) * self._round_to
4343
if rcParams['text.usetex'] and not rcParams['text.latex.unicode']:
4444
return r"$%0.0f^\circ$" % degrees
4545
else:

examples/statistics/barchart_demo.py

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,9 @@
2727
Score = namedtuple('Score', ['score', 'percentile'])
2828

2929
# GLOBAL CONSTANTS
30-
testNames = ['Pacer Test', 'Flexed Arm\n Hang', 'Mile Run', 'Agility',
31-
'Push Ups']
32-
testMeta = dict(zip(testNames, ['laps', 'sec', 'min:sec', 'sec', '']))
30+
test_names = ['Pacer Test', 'Flexed Arm\n Hang', 'Mile Run', 'Agility',
31+
'Push Ups']
32+
test_meta = dict(zip(test_names, ['laps', 'sec', 'min:sec', 'sec', '']))
3333

3434

3535
def attach_ordinal(num):
@@ -54,7 +54,7 @@ def format_score(scr, test):
5454
info (like for pushups) then don't add the carriage return to
5555
the string
5656
"""
57-
md = testMeta[test]
57+
md = test_meta[test]
5858
if md:
5959
return '{0}\n{1}'.format(scr, md)
6060
else:
@@ -63,10 +63,10 @@ def format_score(scr, test):
6363

6464
def format_ycursor(y):
6565
y = int(y)
66-
if y < 0 or y >= len(testNames):
66+
if y < 0 or y >= len(test_names):
6767
return ''
6868
else:
69-
return testNames[y]
69+
return test_names[y]
7070

7171

7272
def plot_student_results(student, scores, cohort_size):
@@ -75,12 +75,12 @@ def plot_student_results(student, scores, cohort_size):
7575
fig.subplots_adjust(left=0.115, right=0.88)
7676
fig.canvas.set_window_title('Eldorado K-8 Fitness Chart')
7777

78-
pos = np.arange(len(testNames))
78+
pos = np.arange(len(test_names))
7979

80-
rects = ax1.barh(pos, [scores[k].percentile for k in testNames],
80+
rects = ax1.barh(pos, [scores[k].percentile for k in test_names],
8181
align='center',
8282
height=0.5,
83-
tick_label=testNames)
83+
tick_label=test_names)
8484

8585
ax1.set_title(student.name)
8686

@@ -95,7 +95,7 @@ def plot_student_results(student, scores, cohort_size):
9595
# Set the right-hand Y-axis ticks and labels
9696
ax2 = ax1.twinx()
9797

98-
scoreLabels = [format_score(scores[k].score, k) for k in testNames]
98+
scoreLabels = [format_score(scores[k].score, k) for k in test_names]
9999

100100
# set the tick locations
101101
ax2.set_yticks(pos)
@@ -156,11 +156,11 @@ def plot_student_results(student, scores, cohort_size):
156156

157157

158158
student = Student('Johnny Doe', 2, 'boy')
159-
scores = dict(zip(testNames,
160-
(Score(v, p) for v, p in
161-
zip(['7', '48', '12:52', '17', '14'],
162-
np.round(np.random.uniform(0, 1,
163-
len(testNames)) * 100, 0)))))
159+
scores = dict(zip(
160+
test_names,
161+
(Score(v, p) for v, p in
162+
zip(['7', '48', '12:52', '17', '14'],
163+
np.round(np.random.uniform(0, 100, len(test_names)), 0)))))
164164
cohort_size = 62 # The number of other 2nd grade boys
165165

166166
arts = plot_student_results(student, scores, cohort_size)

examples/statistics/boxplot_demo.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -164,7 +164,7 @@
164164
# X-axis tick labels with the sample medians to aid in comparison
165165
# (just use two decimal places of precision)
166166
pos = np.arange(num_boxes) + 1
167-
upper_labels = [str(np.round(s, 2)) for s in medians]
167+
upper_labels = [str(round(s, 2)) for s in medians]
168168
weights = ['bold', 'semibold']
169169
for tick, label in zip(range(num_boxes), ax1.get_xticklabels()):
170170
k = tick % 2

examples/ticks_and_spines/date_index_formatter2.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ def __init__(self, dates, fmt='%Y-%m-%d'):
3232

3333
def __call__(self, x, pos=0):
3434
'Return the label for time x at position pos'
35-
ind = int(np.round(x))
35+
ind = int(round(x))
3636
if ind >= len(self.dates) or ind < 0:
3737
return ''
3838
return dates.num2date(self.dates[ind]).strftime(self.fmt)

lib/matplotlib/backends/backend_agg.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -163,8 +163,8 @@ def draw_mathtext(self, gc, x, y, s, prop, angle):
163163

164164
xd = descent * sin(radians(angle))
165165
yd = descent * cos(radians(angle))
166-
x = np.round(x + ox + xd)
167-
y = np.round(y - oy + yd)
166+
x = round(x + ox + xd)
167+
y = round(y - oy + yd)
168168
self._renderer.draw_text_image(font_image, x, y + 1, angle, gc)
169169

170170
def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
@@ -190,11 +190,11 @@ def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
190190
xo, yo = font.get_bitmap_offset()
191191
xo /= 64.0
192192
yo /= 64.0
193-
xd = -d * sin(radians(angle))
193+
xd = d * sin(radians(angle))
194194
yd = d * cos(radians(angle))
195-
196-
self._renderer.draw_text_image(
197-
font, np.round(x - xd + xo), np.round(y + yd + yo) + 1, angle, gc)
195+
x = round(x + xo + xd)
196+
y = round(y + yo + yd)
197+
self._renderer.draw_text_image(font, x, y + 1, angle, gc)
198198

199199
def get_text_width_height_descent(self, s, prop, ismath):
200200
# docstring inherited
@@ -235,9 +235,8 @@ def draw_tex(self, gc, x, y, s, prop, angle, ismath='TeX!', mtext=None):
235235
w, h, d = self.get_text_width_height_descent(s, prop, ismath)
236236
xd = d * sin(radians(angle))
237237
yd = d * cos(radians(angle))
238-
x = np.round(x + xd)
239-
y = np.round(y + yd)
240-
238+
x = round(x + xd)
239+
y = round(y + yd)
241240
self._renderer.draw_text_image(Z, x, y, angle, gc)
242241

243242
def get_canvas_width_height(self):

lib/matplotlib/backends/backend_pdf.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -903,9 +903,8 @@ def cvt(length, upe=font.units_per_EM, nearest=True):
903903
"Convert font coordinates to PDF glyph coordinates"
904904
value = length / upe * 1000
905905
if nearest:
906-
return np.round(value)
907-
# Perhaps best to round away from zero for bounding
908-
# boxes and the like
906+
return round(value)
907+
# Best(?) to round away from zero for bounding boxes and the like.
909908
if value < 0:
910909
return math.floor(value)
911910
else:

lib/matplotlib/colors.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -325,16 +325,16 @@ def to_rgb(c):
325325

326326

327327
def to_hex(c, keep_alpha=False):
328-
"""Convert *c* to a hex color.
328+
"""
329+
Convert *c* to a hex color.
329330
330331
Uses the ``#rrggbb`` format if *keep_alpha* is False (the default),
331332
``#rrggbbaa`` otherwise.
332333
"""
333334
c = to_rgba(c)
334335
if not keep_alpha:
335336
c = c[:3]
336-
return "#" + "".join(format(int(np.round(val * 255)), "02x")
337-
for val in c)
337+
return "#" + "".join(format(int(round(val * 255)), "02x") for val in c)
338338

339339

340340
### Backwards-compatible color-conversion API

lib/matplotlib/dates.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -640,7 +640,7 @@ def __init__(self, t, fmt, tz=None):
640640

641641
def __call__(self, x, pos=0):
642642
'Return the label for time *x* at position *pos*'
643-
ind = int(np.round(x))
643+
ind = int(round(x))
644644
if ind >= len(self.t) or ind <= 0:
645645
return ''
646646
return num2date(self.t[ind], self.tz).strftime(self.fmt)

lib/matplotlib/image.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,7 @@ def flush_images():
147147
gc = renderer.new_gc()
148148
gc.set_clip_rectangle(parent.bbox)
149149
gc.set_clip_path(parent.get_clip_path())
150-
renderer.draw_image(gc, np.round(l), np.round(b), data)
150+
renderer.draw_image(gc, round(l), round(b), data)
151151
gc.restore()
152152
del image_group[:]
153153

@@ -971,8 +971,8 @@ def make_image(self, renderer, magnification=1.0, unsampled=False):
971971
self.is_grayscale = False
972972
x0, y0, v_width, v_height = self.axes.viewLim.bounds
973973
l, b, r, t = self.axes.bbox.extents
974-
width = (np.round(r) + 0.5) - (np.round(l) - 0.5)
975-
height = (np.round(t) + 0.5) - (np.round(b) - 0.5)
974+
width = (round(r) + 0.5) - (round(l) - 0.5)
975+
height = (round(t) + 0.5) - (round(b) - 0.5)
976976
width *= magnification
977977
height *= magnification
978978
im = _image.pcolor(self._Ax, self._Ay, A,
@@ -1086,11 +1086,11 @@ def make_image(self, renderer, magnification=1.0, unsampled=False):
10861086
bg = mcolors.to_rgba(fc, 0)
10871087
bg = (np.array(bg)*255).astype(np.uint8)
10881088
l, b, r, t = self.axes.bbox.extents
1089-
width = (np.round(r) + 0.5) - (np.round(l) - 0.5)
1090-
height = (np.round(t) + 0.5) - (np.round(b) - 0.5)
1089+
width = (round(r) + 0.5) - (round(l) - 0.5)
1090+
height = (round(t) + 0.5) - (round(b) - 0.5)
10911091
# The extra cast-to-int is only needed for python2
1092-
width = int(np.round(width * magnification))
1093-
height = int(np.round(height * magnification))
1092+
width = int(round(width * magnification))
1093+
height = int(round(height * magnification))
10941094
if self._rgbacache is None:
10951095
A = self.to_rgba(self._A, bytes=True)
10961096
self._rgbacache = A

lib/matplotlib/patches.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2241,9 +2241,9 @@ def _get_sawtooth_vertices(self, x0, y0, width, height, mutation_size):
22412241

22422242
# the sizes of the vertical and horizontal sawtooth are
22432243
# separately adjusted to fit the given box size.
2244-
dsx_n = int(np.round((width - tooth_size) / (tooth_size * 2))) * 2
2244+
dsx_n = int(round((width - tooth_size) / (tooth_size * 2))) * 2
22452245
dsx = (width - tooth_size) / dsx_n
2246-
dsy_n = int(np.round((height - tooth_size) / (tooth_size * 2))) * 2
2246+
dsy_n = int(round((height - tooth_size) / (tooth_size * 2))) * 2
22472247
dsy = (height - tooth_size) / dsy_n
22482248

22492249
x0, y0 = x0 - pad + tooth_size2, y0 - pad + tooth_size2

0 commit comments

Comments
 (0)