summaryrefslogtreecommitdiff
path: root/transform.py
diff options
context:
space:
mode:
authorAnthony LaTorre <tlatorre9@gmail.com>2011-09-08 16:56:26 -0400
committerAnthony LaTorre <tlatorre9@gmail.com>2011-09-08 16:56:26 -0400
commit1d333302d7756170fb89feece10fe22215cdaa45 (patch)
tree98ab0143186e129efbb3a02f456512ef0d6981ea /transform.py
parentc7c161179a0a26dc9b4e3acdbc61a48803fa00e7 (diff)
downloadchroma-1d333302d7756170fb89feece10fe22215cdaa45.tar.gz
chroma-1d333302d7756170fb89feece10fe22215cdaa45.tar.bz2
chroma-1d333302d7756170fb89feece10fe22215cdaa45.zip
add normalize() function to transform module. np.apply_along_axis(np.linalg.norm,...) is really slow!
Diffstat (limited to 'transform.py')
-rw-r--r--transform.py18
1 files changed, 18 insertions, 0 deletions
diff --git a/transform.py b/transform.py
index 4793c0f..299da46 100644
--- a/transform.py
+++ b/transform.py
@@ -18,3 +18,21 @@ def rotate(x, phi, n):
around the axis `n` (when looking towards +infinity).
"""
return np.inner(np.asarray(x),make_rotation_matrix(phi, n))
+
+def normalize(x):
+ "Returns unit vectors in the direction of `x`."
+ x = np.asarray(x)
+
+ if x.shape[-1] != 3:
+ raise ValueError('dimension of last axis must be 3.')
+
+ d = len(x.shape)
+
+ if d == 1:
+ norm = np.sqrt(x.dot(x))
+ elif d == 2:
+ norm = np.sqrt(np.sum(x*x, axis=1))[:,np.newaxis]
+ else:
+ raise ValueError('len(`x`.shape) must be zero or one.')
+
+ return x/norm