Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

""" 

""" 

import numpy as np 

 

 

def vector_norm(data, axis=0): 

"""Return Euclidean norm of ndarray along axis. 

""" 

if isinstance(data, list): 

data = np.array(data) 

assert isinstance(data, np.ndarray), 'data should be a numpy array' 

 

return np.sqrt(np.sum(data * data, axis=axis, keepdims=True)) 

 

 

def unit_vector(data, axis=0): 

"""Return ndarray normalized by length, i.e. Euclidean norm, along axis. 

""" 

if isinstance(data, list): 

data = np.array(data) 

 

assert isinstance(data, np.ndarray), 'data should be a numpy array' 

repetitions = np.array(data.shape) 

repetitions[:] = 1 

repetitions[axis] = data.shape[axis] 

norm = vector_norm(data, axis) 

return data / np.tile(norm, repetitions) 

 

 

def angle_between_vectors(vector_0, vector_1, directed=True, axis=0): 

"""Return angle between vectors. 

 

If directed is False, the input vectors are interpreted as undirected axes, 

i.e. the maximum angle is pi/2. 

""" 

vector_0 = np.array(vector_0, dtype=np.float64, copy=False) 

vector_1 = np.array(vector_1, dtype=np.float64, copy=False) 

dot = np.sum(vector_0 * vector_1, axis=axis, keepdims=True) 

dot /= vector_norm(vector_0, axis=axis) \ 

* vector_norm(vector_1, axis=axis) 

dot = np.squeeze(dot) 

return np.arccos(dot if directed else np.fabs(dot)) 

 

 

def inverse_matrix(matrix): 

"""Return inverse of square transformation matrix. 

""" 

return np.linalg.inv(matrix) 

 

 

def concatenate_matrices(*matrices): 

"""Return concatenation of series of transformation matrices. 

""" 

M = np.identity(4) 

for i in matrices: 

M = np.dot(M, i) 

return M