def CARE(A, B, Q, R): '''Returns optimal K matrix For Visualization Purposes Only Otherwise We should make an (n x n) matrix >>> m, n = A.shape >>> np.eye(A.shape) and copy each element into it, in this method we create multiple python objects unnecessarily ''' top = np.concatenate((A, multi_dot(B, inv(R), B.T)), axis=1) bottom = np.concatenate((-Q, -A.T), axis=1) hamiltonian = np.vstack([top, bottom]) T1, U1 = schur(hamiltonian, output='real') T2, U2 = la.rsf2csf(T1, U1) # schur Factorization (conceptually) #>>> eigs = np.diag(T)[:2] #>>> print(np.diag(np.diag(eigs))) m, n = U1.shape P11 = U1[0:int(m / 2), 0:int(n / 2)] P21 = U1[int(m / 2):, 0:int(n / 2)] #print("1:\n",P11) #print("2:\n",P21) return P21.dot(inv(P11))
def test_simple(self): a = [[8,12,3],[2,9,3],[10,3,6]] t,z = schur(a) assert_array_almost_equal(dot(dot(z,t),transp(conj(z))),a) tc,zc = schur(a,'complex') assert_(any(ravel(iscomplex(zc))) and any(ravel(iscomplex(tc)))) assert_array_almost_equal(dot(dot(zc,tc),transp(conj(zc))),a) tc2,zc2 = rsf2csf(tc,zc) assert_array_almost_equal(dot(dot(zc2,tc2),transp(conj(zc2))),a)
def test_simple(self): a = [[8, 12, 3], [2, 9, 3], [10, 3, 6]] t, z = schur(a) assert_array_almost_equal(dot(dot(z, t), transp(conj(z))), a) tc, zc = schur(a, 'complex') assert_(any(ravel(iscomplex(zc))) and any(ravel(iscomplex(tc)))) assert_array_almost_equal(dot(dot(zc, tc), transp(conj(zc))), a) tc2, zc2 = rsf2csf(tc, zc) assert_array_almost_equal(dot(dot(zc2, tc2), transp(conj(zc2))), a)
def check_eigens(): T, Z = schur(A) for i in range(0,T.shape[0]-1): if T[i+1,i]!=0: for eig in np.linalg.eigvals(T[i:i+2,i:i+2]): print eig if eig.real < 0: T, Z = rsf2csf(T,Z) return T,Z return T,Z
def main(): print("Main") A=np.mat('[1 3 2;1 4 5;2 3 6]') T,Z=linalg.schur(A) T1,Z1=linalg.schur(A,'complex') T2,Z2=linalg.rsf2csf(T,Z) print("A: ",A) print("abs(T1-T2): ",abs(T1-T2)) print("abs(Z1-Z2): ",abs(Z1-Z2)) T,Z,T1,Z1,T2,Z2=map(np.mat,(T,Z,T1,Z1,T2,Z2)) print("abs(A-Z*T*Z.H): ",abs(A-Z*T*Z.H)) print("abs(A-Z1*T1*Z1.H): ",abs(A-Z1*T1*Z1.H)) print("abs(A-Z2*T2*Z2.H): ",abs(A-Z2*T2*Z2.H))
def mysqrtm(A): # Schur decomposition and cast to complex array T, Z = lm.schur(A) T, Z = lm.rsf2csf(T, Z) n, n = T.shape # Inner loop of sqrtm algorithm -> call C code R = np.zeros((n, n), dtype=T.dtype) stat = sqrtm_loop(R, T, n) R, Z = lm.all_mat(R, Z) X = (Z * R * Z.H) return X.A
def mysqrtm(A): # Schur decomposition and cast to complex array T, Z = lm.schur(A) T, Z = lm.rsf2csf(T,Z) n,n = T.shape # Inner loop of sqrtm algorithm -> call C code R = np.zeros((n,n), dtype=T.dtype) stat = sqrtm_loop(R, T, n) R, Z = lm.all_mat(R,Z) X = (Z * R * Z.H) return X.A
def cSqrtm(A): """ Computes custom matrix square root using Scipy algorithm with inner loop written in C. """ # Schur decomposition and cast to complex array T, Z = schur(A) T, Z = rsf2csf(T,Z) n,n = T.shape # Inner loop of sqrtm algorithm -> call C code R = np.zeros((n,n), dtype=T.dtype) stat = sqrtm_loop(R, T, n) R, Z = all_mat(R,Z) X = (Z * R * Z.H) return X.A
def sorted_brandts_schur( P: np.ndarray, k: int, z: str = "LM") -> Tuple[np.ndarray, np.ndarray, np.ndarray]: """ Compute a sorted Schur decomposition. This function uses :mod:`scipy` for the decomposition and Brandts' method (see [Brandts02]_) for the sorting. Parameters ---------- %(P)s %(k)s %(z)s Returns ------- Tuple of the following: R %(R_sort)s Q %(Q_sort)s eigenvalues %(eigenvalues_k)s """ # Make a Schur decomposition of P. R, Q = schur(P, output="real") # Sort the Schur matrix and vectors. Q, R, ap = sort_real_schur(Q, R, z=z, b=k) # Warnings if np.any(np.array(ap) > 1.0): warnings.warn("Reordering of Schur matrix was inaccurate.") # compute eigenvalues T, _ = rsf2csf(R, Q) eigenvalues = np.diag(T)[:k] return R, Q, eigenvalues
def sqrtm(A, disp=True): """ Symmetric Matrix square root. modified version of the scipy.linalg sqrtm function for performance: (i) introduced a dot product [based on https://groups.google.com/forum/#!topic/scipy-user/iNzZzkHjlgA] (ii) avoid rsf2csf as the input is expected to be symmetric Parameters ---------- A : (N, N) array_like Matrix whose square root to evaluate disp : bool, optional Print warning if error in the result is estimated large instead of returning estimated error. (Default: True) Returns ------- sgrtm : (N, N) ndarray Value of the sign function at `A` errest : float (if disp == False) Frobenius norm of the estimated error, ||err||_F / ||A||_F Notes ----- Uses algorithm by Nicholas J. Higham """ A = np.asarray(A) if len(A.shape)!=2: raise ValueError("Non-matrix input to matrix function.") T, Z = la.schur(A) # if the matrix is real and symmetric can skip the complex part if not (np.allclose(A,A.T,rtol=0,atol=1e-8) and np.all(A.imag==0)): T, Z = la.rsf2csf(T,Z) n,n = T.shape R = np.zeros((n,n),T.dtype.char) for j in xrange(n): R[j,j] = np.sqrt(T[j,j]) for i in xrange(j-1,-1,-1): #s = 0 #for k in range(i+1,j): # s = s + R[i,k]*R[k,j] s = R[i,(i+1):j].dot(R[(i+1):j,j]) R[i,j] = (T[i,j] - s)/(R[i,i] + R[j,j]) R, Z = la.all_mat(R,Z) X = (Z * R * Z.H) if disp: nzeig = np.any(np.diag(T)==0) if nzeig: print("Matrix is singular and may not have a square root.") return X.A else: arg2 = la.norm(X*X - A,'fro')**2 / la.norm(A,'fro') return X.A, arg2
def sqrtm(A, disp=True): """ Symmetric Matrix square root. modified version of the scipy.linalg sqrtm function for performance: (i) introduced a dot product [based on https://groups.google.com/forum/#!topic/scipy-user/iNzZzkHjlgA] (ii) avoid rsf2csf as the input is expected to be symmetric Parameters ---------- A : (N, N) array_like Matrix whose square root to evaluate disp : bool, optional Print warning if error in the result is estimated large instead of returning estimated error. (Default: True) Returns ------- sgrtm : (N, N) ndarray Value of the sign function at `A` errest : float (if disp == False) Frobenius norm of the estimated error, ||err||_F / ||A||_F Notes ----- Uses algorithm by Nicholas J. Higham """ A = np.asarray(A) if len(A.shape) != 2: raise ValueError("Non-matrix input to matrix function.") T, Z = la.schur(A) # if the matrix is real and symmetric can skip the complex part if not (np.allclose(A, A.T, rtol=0, atol=1e-8) and np.all(A.imag == 0)): T, Z = la.rsf2csf(T, Z) n, n = T.shape R = np.zeros((n, n), T.dtype.char) for j in xrange(n): R[j, j] = np.sqrt(T[j, j]) for i in xrange(j - 1, -1, -1): #s = 0 #for k in range(i+1,j): # s = s + R[i,k]*R[k,j] s = R[i, (i + 1):j].dot(R[(i + 1):j, j]) R[i, j] = (T[i, j] - s) / (R[i, i] + R[j, j]) R, Z = la.all_mat(R, Z) X = (Z * R * Z.H) if disp: nzeig = np.any(np.diag(T) == 0) if nzeig: print("Matrix is singular and may not have a square root.") return X.A else: arg2 = la.norm(X * X - A, 'fro')**2 / la.norm(A, 'fro') return X.A, arg2
U, s, Vh = linalg.svd(svdex) Sig = linalg.diagsvd(s, M, N) U, Vh = U, Vh print(U) print(Sig) print(Vh) print(U.dot(Sig.dot(Vh))) print("Schur decomposition") print("\n") AAA = np.mat('[1 3 2; 1 4 5; 2 3 6]') T, Z = linalg.schur(AAA) T1, Z1 = linalg.schur(AAA, 'complex') T2, Z2 = linalg.rsf2csf(T, Z) print(T) print(T2) print("\n") print(abs(T1 - T2)) # different print("\n") print(abs(Z1 - Z2)) # different T, Z, T1, Z1, T2, Z2 = map(np.mat, (T, Z, T1, Z1, T2, Z2)) print(abs(AAA - Z * T * Z.H)) # same print("\n") print(abs(AAA - Z1 * T1 * Z1.H)) # same print(abs(AAA - Z2 * T2 * Z2.H)) print("\n") hank = np.array([1, 2, 3])