8000 Micro-optimize rotation transform. · matplotlib/matplotlib@ff120cd · GitHub
[go: up one dir, main page]

Skip to content

Commit ff120cd

Browse files
committed
Micro-optimize rotation transform.
The following test script shows a ~3x speedup. ```python import math, numpy as np mtx = np.array([[.1, .2, .3], [.4, .5, .6], [0, 0, 1]]) theta = np.pi / 4 def rotate(mtx, theta): a = math.cos(theta) b = math.sin(theta) rotate_mtx = np.array([[a, -b, 0.0], [b, a, 0.0], [0.0, 0.0, 1.0]], float) return np.dot(rotate_mtx, mtx) def rfast(mtx, theta): a = math.cos(theta) b = math.sin(theta) (xx, xy, x0), (yx, yy, y0), _ = mtx.tolist() # mtx = [[a -b 0], [b a 0], [0 0 1]] * mtx mtx[0, 0] = a * xx - b * yx mtx[0, 1] = a * xy - b * yy mtx[0, 2] = a * x0 - b * y0 mtx[1, 0] = b * xx + a * yx mtx[1, 1] = b * xy + a * yy mtx[1, 2] = b * x0 + a * y0 return mtx %timeit rotate(mtx, theta) %timeit rfast(mtx, theta) ```
1 parent 68d6b79 commit ff120cd

File tree

1 file changed

+10
-3
lines changed

1 file changed

+10
-3
lines changed

lib/matplotlib/transforms.py

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2002,9 +2002,16 @@ def rotate(self, theta):
20022002
"""
20032003
a = math.cos(theta)
20042004
b = math.sin(theta)
2005-
rotate_mtx = np.array([[a, -b, 0.0], [b, a, 0.0], [0.0, 0.0, 1.0]],
2006-
float)
2007-
self._mtx = np.dot(rotate_mtx, self._mtx)
2005+
mtx = self._mtx
2006+
# Operating and assigning one scalar at a time is much faster.
2007+
(xx, xy, x0), (yx, yy, y0), _ = mtx.tolist()
2008+
# mtx = [[a -b 0], [b a 0], [0 0 1]] * mtx
2009+
mtx[0, 0] = a * xx - b * yx
2010+
mtx[0, 1] = a * xy - b * yy
2011+
mtx[0, 2] = a * x0 - b * y0
2012+
mtx[1, 0] = b * xx + a * yx
2013+
mtx[1, 1] = b * xy + a * yy
2014+
mtx[1, 2] = b * x0 + a * y0
20082015
self.invalidate()
20092016
return self
20102017

0 commit comments

Comments
 (0)
0