-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
39 lines (33 loc) · 1.14 KB
/
utils.py
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
import sys
import numpy as np
# Computes the outer norm of a matrix A, the sum of the squares of the
# nondiagonal entries
def outer_norm(A):
lt = np.tril_indices(A.shape[0], -1)
ut = np.triu_indices(A.shape[0], 1)
return np.sum(np.square(A[lt])) + np.sum(np.square(A[ut]))
# Returns the index of the largest entry of A, not including
# diagonal entries
def outer_argmax(A):
B = np.abs(A.copy())
B[np.diag_indices(B.shape[0])] = 0
return np.unravel_index(B.argmax(), B.shape)
# Modified version of the mathematical sign operation used by
# the Jacobi method
def sign(x):
if x < 0:
return -1
elif x > 0:
return 1
return 0
# Ensures A is a valid 2D matrix, and optionally square / symmetric
def validate_matrix(A, square=True, symmetric=True):
if len(A.shape) != 2:
die(f"Matrix does not have two dimensions {A.shape}")
if square and A.shape[0] != A.shape[1]:
die(f"Matrix is not square {A.shape}")
if symmetric and np.any(A != A.T):
die("Matrix is not symmetric")
def die(error_msg, exit_code=1):
sys.stderr.write(f"Error: {error_msg}!\n")
sys.exit(exit_code)