def test_basic(self): h3 = array([[1.0, 1 / 2.0, 1 / 3.0], [1 / 2.0, 1 / 3.0, 1 / 4.0], [1 / 3.0, 1 / 4.0, 1 / 5.0]]) assert_array_almost_equal(hilbert(3), h3) assert_array_equal(hilbert(1), [[1.0]]) h0 = hilbert(0) assert_equal(h0.shape, (0, 0))
def test_basic(self): h3 = array([[1.0, 1 / 2., 1 / 3.], [1 / 2., 1 / 3., 1 / 4.], [1 / 3., 1 / 4., 1 / 5.]]) assert_array_almost_equal(hilbert(3), h3) assert_array_equal(hilbert(1), [[1.0]]) h0 = hilbert(0) assert_equal(h0.shape, (0, 0))
def setUp(self): super().setUp() random = np.abs(np.hstack([np.random.rand(30), np.zeros(10)])) random[::-1].sort() random[0] += np.abs(random[1:]).sum() def up(x): return np.diag(np.arange(x) + 1) def down(x): return up(x)[::-1, ::-1] self.eigtol = 1e-3 self.raw_examples = [ # Square [up(1), down(1)], [up(3), down(2)], [up(2), down(3)], [la.hilbert(3), la.hilbert(3)], [self._rpsd(3), np.identity(2)], [self._rpsd(2), self._rpsd(3)], [up(3), Toeplitz(np.arange(10)[::-1] + 1)], [Toeplitz(random), self._rpsd(5)], [self._rpsd(100), self._rpsd(5)], [np.identity(2), np.identity(3) * self.eigtol / 2], [np.identity(2), np.identity(3) * self.eigtol], [np.identity(2), np.identity(3) * self.eigtol * 2], [self._rpsd(5), Toeplitz(utils.exp_decr_toep(10))], [self._rpsd(5), Toeplitz(utils.exp_decr_toep(100))], [ Toeplitz(utils.exp_decr_toep(10)), Toeplitz(utils.exp_decr_toep(10)) ], [np.random.rand(2, 2) for _ in range(4)], [up(2), down(2), up(2)], # Rectangle [np.random.rand(2, 3), up(1)], [np.random.rand(2, 3), np.random.rand(3, 2)], [np.random.rand(4, 3), np.random.rand(5, 2), np.random.rand(1, 2)] ] self.raw_examples = [[ x if isinstance(x, Matrix) else NumpyMatrix(x) for x in ls ] for ls in self.raw_examples] self.examples = [reduce(Kronecker, x) for x in self.raw_examples]
def test_svd_maxiter(self): # check that maxiter works as expected: should not return accurate # solution after 1 iteration, but should with default `maxiter` if self.solver == 'propack': if not has_propack: pytest.skip("PROPACK not available") A = hilbert(6) k = 1 u, s, vh = sorted_svd(A, k) if self.solver == 'arpack': message = "ARPACK error -1: No convergence" with pytest.raises(ArpackNoConvergence, match=message): svds(A, k, ncv=3, maxiter=1, solver=self.solver) elif self.solver == 'lobpcg': message = "Not equal to tolerance" with pytest.raises(AssertionError, match=message): with pytest.warns(UserWarning, match="Exited at iteration"): u2, s2, vh2 = svds(A, k, maxiter=1, solver=self.solver) assert_allclose(np.abs(u2), np.abs(u)) elif self.solver == 'propack': message = "k=1 singular triplets did not converge within" with pytest.raises(np.linalg.LinAlgError, match=message): svds(A, k, maxiter=1, solver=self.solver) u, s, vh = svds(A, k, solver=self.solver) # default maxiter _check_svds(A, k, u, s, vh)
def uloha1(n): from scipy import linalg import numpy A = linalg.hilbert(n) xexact = numpy.ones((n, 1)) b = A.dot(xexact) return A, b
def test_badcall(self): A = hilbert(5).astype(np.float32) assert_raises(ValueError, pymatrixid.interp_decomp, A, 1e-6, rand=False)
def problem4(): n = 50 H = splin.hilbert(n) Hi = splin.invhilbert(n) U, S, V = splin.svd(H) b = U[:, 0] * S[0] db = U[:, -1] * S[-1] print(S[-1]) x = Hi.dot(b) dx = Hi.dot(db) k = S[0] / S[-1] print('Condition number of H50: {}'.format(k)) dxx = np.linalg.norm(dx) / np.linalg.norm(x) dbb = np.linalg.norm(db) / np.linalg.norm(b) q = dxx / dbb print('Quotient of pertubations: {}'.format(q)) print('Quotient: {}'.format(q / k)) maxq = 0 for j in range(0, 100): num_vecs = 1000 b_collection = np.random.rand(n, num_vecs) db_collection = np.random.rand(n, num_vecs) * 1e-16 x_collection = Hi.dot(b_collection) dx_collection = Hi.dot(db_collection) q_collection = np.zeros((num_vecs, 1)) for k in range(0, num_vecs): q_collection[k] = np.linalg.norm( dx_collection[:, k]) * np.linalg.norm(b_collection[:, k]) q_collection[k] /= np.linalg.norm( db_collection[:, k]) * np.linalg.norm(x_collection[:, k]) maxq = max(maxq, max(q_collection)) print(j) print(max(maxq))
def test_initialize_A_condition(self): dummy = hilbert(14) dummy = dummy[:, :-1] dummy[:, 0] = 1.0 with pytest.raises(ValueError, match="The condition number .*"): _initialize_rot_matrix(dummy)
def main(): np.set_printoptions(precision=4) A = hilbert(4) print("\nA = \n", A) # without Wilkinson shift eigvals = get_eigvals(A, 'hilbert4') print_eigvals(eigvals) # with Wilkinson shift eigvals = get_eigvals(A, 'hilbert4_Wilkinson', True) print_eigvals(eigvals, True) v = np.array([i for i in range(15, 0, -1)]) A = np.diag(v) + np.ones((15, 15)) print("\nA = \n", A) # without Wilkinson shift eigvals = get_eigvals(A, 'diagones15') print_eigvals(eigvals) # with Wilkinson shift eigvals = get_eigvals(A, 'diagones15_Wilkinson', True) print_eigvals(eigvals, True)
def test_conjgrad_solver(n): H = linalg.hilbert(n) x0 = matlib.ones([n, 1]) b = H @ x0 x = [0, 1] y1 = [] y2 = [] for xi in tqdm(x): x1, niter = conjgrad(H, b, ind=xi, eps=1e-15) y1.append(linalg.norm(x0 - x1, ord=np.inf)) y2.append(niter) sleep(0.01) fig, left_axis = plt.subplots() right_axis = left_axis.twinx() plt.title("Conjugate gradient results for "+ \ "$H_{"+str(n)+"}\bf{x}=\bf{b}$") left_axis.plot(x, y1, 'ro-') left_axis.set_xlabel("Preprocessing index") left_axis.set_ylabel("Infinite-norm error", color='r') left_axis.tick_params(axis='y', colors='r') right_axis.plot(x, y2, 'bo-') right_axis.set_xlabel("Same") right_axis.set_ylabel("Iteration step", color='b') right_axis.tick_params(axis='y', colors='b') plt.show()
def test_simpleit_solver(n): H = linalg.hilbert(n) x0 = matlib.ones([n, 1]) b = H @ x0 x = np.arange(0.1, 2.0, 0.1) y1 = [] y2 = [] #x1, niter = jacobi(H,b) #print(x1,niter) for xi in tqdm(x): x1, niter = gs_sor(H, b, omg=xi, eps=1e-15) y1.append(math.log(linalg.norm(x0 - x1, ord=np.inf), 10)) y2.append(niter) sleep(0.01) fig, left_axis = plt.subplots() right_axis = left_axis.twinx() plt.title("SOR results for $H_{" + str(n) + "}\bf{x}=\bf{b}$") left_axis.plot(x, y1, 'ro-') left_axis.set_xlabel("Relaxation coefficient") left_axis.set_ylabel("log(Infinite-norm error)", color='r') left_axis.tick_params(axis='y', colors='r') right_axis.plot(x, y2, 'bo-') right_axis.set_xlabel("Same") right_axis.set_ylabel("Iteration step", color='b') right_axis.tick_params(axis='y', colors='b') plt.show()
def bench(Observations, Features): N = max(Observations, Features) k = 40 # Create a known ill-conditionned matrix for testing # This requires 20k * 20k * 4 bytes (float32) = 1.6 GB start = time.time() H = hilbert(N)[:Observations, :Features] stop = time.time() print(f'Hilbert matrix creation too: {stop-start:>4.4f} seconds.') print(f'Matrix of shape: [{Observations}, {Features}]') print(f'Target SVD: [{Observations}, {k}]') start = time.time() (U, S, Vh) = pca(H, k=k, raw=True, n_iter=2, l=k + 5) # Raw=True for SVD stop = time.time() print(f'Randomized SVD took: {stop-start:>4.4f} seconds') print("U: ", U.shape) print("S: ", S.shape) print("Vh: ", Vh.shape) print( "---------------------------------------------------------------------------------" )
def test_initialize_A_condition_warning(self): dummy = hilbert(6) dummy = dummy[:, :-1] dummy[:, 0] = 1.0 with pytest.warns(UserWarning): _ = _initialize_rot_matrix(dummy)
def test_inverse(self): for n in xrange(1, 10): a = hilbert(n) b = invhilbert(n) # The Hilbert matrix is increasingly badly conditioned, # so take that into account in the test c = cond(a) assert_allclose(a.dot(b), eye(n), atol=1e-15*c, rtol=1e-15*c)
def test_svd_which(): # check that the which parameter works as expected x = hilbert(6) for which in ['LM', 'SM']: _, s, _ = sorted_svd(x, 2, which=which) ss = svds(x, 2, which=which, return_singular_vectors=False) ss.sort() assert_allclose(s, ss, atol=np.sqrt(1e-15))
def test_inverse(self): for n in xrange(1, 10): a = hilbert(n) b = invhilbert(n) # The Hilbert matrix is increasingly badly conditioned, # so take that into account in the test c = cond(a) assert_allclose(a.dot(b), eye(n), atol=1e-15 * c, rtol=1e-15 * c)
def Norm_Wska(n): c = hilbert(n) norm = np.linalg.norm(c) wska = np.linalg.cond(c) print("Wskażnik uwarunkowania = ", wska) print("Norma = ", norm)
def main(): a = np.asmatrix(la.hilbert(4)) h = tridiag(a) h_std = la.hessenberg(a) print("Solution:") print(h) print('\n') print("Standard Solution:") print(h_std)
def test_svd_maxiter(): # check that maxiter works as expected x = hilbert(6) # ARPACK shouldn't converge on such an ill-conditioned matrix with just # one iteration assert_raises(ArpackNoConvergence, svds, x, 1, maxiter=1, ncv=3) # but 100 iterations should be more than enough u, s, vt = svds(x, 1, maxiter=100, ncv=3) assert_allclose(s, [1.7], atol=0.5)
def funkcja(n): h = hilbert(n) norm = np.linalg.norm(h) cond = np.linalg.cond(h) print("Dla macierzy Hilberta " + str(n) + "x" + str(n)) print("Norma " + " = " + str(norm)) print("Wskaznik uwarunkowania " + " = " + str(cond))
def test_svd_maxiter(): # check that maxiter works as expected x = hilbert(6) # ARPACK shouldn't converge on such an ill-conditioned matrix with just # one iteration assert_raises(ArpackNoConvergence, svds, x, 1, maxiter=1) # but 100 iterations should be more than enough u, s, vt = svds(x, 1, maxiter=100) assert_allclose(s, [1.7], atol=0.5)
def main(): # create the matrix and the right hand sides N = 1000 A = sp.coo_matrix( hilbert(N) + np.identity(N) ) # a well-condition, symmetric, positive-definite matrix with off-diagonal entries true_x1 = np.arange(N) true_x2 = np.array(list(reversed(np.arange(N)))) b1 = A * true_x1 b2 = A * true_x2 # solve solver = MumpsCentralizedAssembledLinearSolver() x1, res = solver.solve(A, b1) x2, res = solver.solve(A, b2) assert np.allclose(x1, true_x1) assert np.allclose(x2, true_x2) # only perform factorization once solver = MumpsCentralizedAssembledLinearSolver() solver.do_symbolic_factorization(A) solver.do_numeric_factorization(A) x1, res = solver.do_back_solve(b1) x2, res = solver.do_back_solve(b2) assert np.allclose(x1, true_x1) assert np.allclose(x2, true_x2) # Tell Mumps the matrix is symmetric # Note that the answer will be incorrect if both the lower # and upper portions of the matrix are given. solver = MumpsCentralizedAssembledLinearSolver(sym=2) A_lower_triangular = sp.tril(A) x1, res = solver.solve(A_lower_triangular, b1) assert np.allclose(x1, true_x1) # Tell Mumps the matrix is symmetric and positive-definite solver = MumpsCentralizedAssembledLinearSolver(sym=1) A_lower_triangular = sp.tril(A) x1, res = solver.solve(A_lower_triangular, b1) assert np.allclose(x1, true_x1) # Set options solver = MumpsCentralizedAssembledLinearSolver( icntl_options={11: 2}) # compute error stats solver.set_cntl(2, 1e-4) # set the stopping criteria for iterative refinement solver.set_icntl( 10, 5 ) # set the maximum number of iterations for iterative refinement to 5 x1, res = solver.solve(A, b1) assert np.allclose(x1, true_x1) # Get information after the solve print('Number of iterations of iterative refinement performed: ', solver.get_infog(15)) print('scaled residual: ', solver.get_rinfog(6))
def solve(size, delta=0): print(f'size = {size}, delta = {delta}') H = hilbert(size) x = np.zeros(size) + delta + 1 b = H.dot(x) _H = cholesky(H, size) xp = np.linalg.solve(_H.T, np.linalg.solve(_H, b)) print(f'||r||_inf: {abs(b - H.dot(xp)).max()}') print(f'||delta||_inf: {abs(xp - x).max()}')
def createHilbertFractionMatrix(sq_size): fract_hill = [] hill = hilbert(sq_size) # for decimals just use this line (from library) for h in hill: for i in h: fract_hill.append(Fraction(str(i))) reshaped_array = np.split(np.asarray(fract_hill), sq_size) print "The Hilbert Matrix shape: " + str( np.asarray(reshaped_array).shape) + "\n" return np.asmatrix(reshaped_array)
def hilbertLA(n): """ Utilisise scipy.linalg for populating an nxn hilbert matrix Param: n : int square size of matrix Returns: H : matrix The hilbert matrix """ return lasc.hilbert(n)
def test_arlsgt(): x = np.array([6.0, 5.0, 4.0, 3.0]) A = hilbert(5) A = np.delete(A, 4, 1) # delete last column b = A @ x G = np.array([0.0, 0.0, 0.0, 1.0]) h = 5 x = arlsgt(A, b, G, h)[0] res = A @ x - b assert_(norm(res) < 0.002, "Residual too large in arlsgt hilbert test.") return
def get_hilbert_cond2(n): x = [] y = [] for i in range(2, n): cur_mat = hilbert(i) cur_cond = cond(cur_mat, 2) x.append(i) y.append(math.log(cur_cond)) plt.scatter(x, y) plt.xlabel('order') plt.ylabel('log(cond2)') plt.show()
def testIllConditioned(self): # Modified G-S handles ill-conditioned matrices much better (numerically) # than original G-S. dim = 200 mat = tf.eye(200, dtype=tf.float64) * 1e-5 + scipy_linalg.hilbert(dim) mat = tf.math.l2_normalize(mat, axis=-1) ortho = tfp.math.gram_schmidt(mat) xtx = tf.matmul(ortho, ortho, transpose_a=True) self.assertAllClose( 0., tf.linalg.norm(tf.eye(dim, dtype=tf.float64) - xtx, ord='fro', axis=(-1, -2)))
def Hilbert_test(dim, func): A = hilbert(dim) eigenvec, eigenval, iterations = func(A) residue = np.linalg.norm(A.dot(eigenvec) - eigenval * eigenvec) eigenval_real, eigenvec_real = Hilbert_dominant_eigenpair_dict[dim][ 1], Hilbert_dominant_eigenpair_dict[dim][0] eigenvec_real = eigenvec_real / np.linalg.norm(eigenvec_real) dist = np.linalg.norm(eigenvec_real - eigenvec) residue_real_val = np.linalg.norm( A.dot(eigenvec) - eigenval_real * eigenvec) return residue, dist, residue_real_val
def draw_hilbert_cond(max_n=15): """ This function draws the condition for the Hilbert matrix. Parameters ---------- max_n : int The plot is drawn from 3 upto this int. """ condition = [] for i in range(3, max_n): condition.append(np.linalg.cond(hilbert(i), np.inf)) plt.loglog(range(3, max_n), [np.linalg.cond(hilbert(i), np.inf) for i in range(3, max_n)], label="Condition of the Hilbert Matrix", linewidth=3) axis = plt.gca() axis.set_yscale('log') plt.xlabel("Number of Rows/Columns of the Hilbert Matrix", fontsize=18) plt.ylabel("Condition", fontsize=18) plt.legend(fontsize=24) plt.show()
def p1(): cond = [] est = [] ratio = [] for n in range(5, 20): H = la.hilbert(n) K = np.linalg.cond(H, p=np.inf) cond.append(K) E = (1 + np.sqrt(2))**(4 * n) / np.sqrt(n) est.append(E) ratio.append(K / E) latex_table((range(5, len(cond) + 5), cond, est, ratio), ('$n$', '$K(H_n)$', 'est', '$K(H_n)/$est'))
def solve(n, delta=0): print('n =', n, ', delta =', delta) H = hilbert(n) x = np.zeros(n) + 1 + delta b = H.dot(x) L = cholesky(H) # Hx = b, H = LL' # LL'x = b # x = L'^-1 L^-1 b xp = np.linalg.solve(L.T, np.linalg.solve(L, b)) r = b - H.dot(xp) dx = xp - x print('||r||_inf:', abs(r).max()) print('||dx||_inf:', abs(dx).max())
def __init__(self, dim, r_s=None): """ Initialisiert ein neues Hilbert-Objekt. Input: dim (int): Dimension der Hilbertmatrix. Return: - """ self.dim = dim self.hil_matr = lina.hilbert(self.dim) self.inv_hil_matr = lina.invhilbert(self.dim) self.r_s = r_s
def run_stats(dimension): matrices = {} # Generation of the 4 relevant matrices matrices['normal'] = np.matrix(np.random.randn(dimension, dimension)) matrices['hilbert'] = np.matrix(sp.hilbert(dimension)) matrices['pascal'] = np.matrix(pascal(dimension)) if dimension != 100: matrices['magic'] = np.matrix(magic(dimension)) else: matrices['magic'] = np.matrix(np.identity(100)) x = np.matrix(np.ones((dimension,1))) data = {} # these are just bookkeeping things that keep track of variables for future use for name, matr in matrices.items(): this_matrix_data = {} b = matr * x try: xhat = sp.solve(matr, b) xhat1 = np.linalg.inv(matr) * b except np.linalg.LinAlgError: xhat = x xhat1 = x this_matrix_data['delta_b'] = matr * xhat - b norm_data = {} # Loop through the three norms we're asked to do for norm_type in [1, 2, np.inf]: values = {} values['x_relative_error'] = sp.norm(x - xhat, norm_type) / sp.norm(x, norm_type) values['x_relative_error_inv'] = sp.norm(x - xhat1, norm_type) / sp.norm(x, norm_type) try: values['condition_no'] = np.linalg.cond(matr, norm_type) except: values['condition_no'] = 0 values['cond_rel_b_err'] = values['condition_no'] * (sp.norm(this_matrix_data['delta_b'], norm_type) / sp.norm(b, norm_type)) norm_data[norm_type] = values this_matrix_data['norm_dep_vals'] = norm_data data[name] = this_matrix_data return data
def demo(n): from numpy import random from scipy import linalg A = random.randn(n, n) x = random.randn(n) print('\n\t\t Random matrix of dimension', n) showerr(A, x) A = linalg.hilbert(n) print('\n\t\t Hilbert matrix of dimension', n) showerr(A, x) from . import cond A = cond.laplace(n) print('\n\t\t Disc Laplacian of dimension', n) showerr(A, x)
def main(): for n in range(12, 20): H = hilbert(n) x = [1000 for _ in range(n)] b = H.dot(x) x = np.linalg.solve(H, b) Hx = H.dot(x) r = b - Hx print np.linalg.norm(r, np.inf) iter = 0 while np.linalg.norm(r, np.inf) > 1e-5 and iter < 50: z = np.linalg.solve(H, r) x = x + z Ax = H.dot(x) r = b - Ax iter += 1 print iter, x
def time_hilbert(self, size): sl.hilbert(size)
def test_svd_return(): # check that the return_singular_vectors parameter works as expected x = hilbert(6) _, s, _ = sorted_svd(x, 2) ss = svds(x, 2, return_singular_vectors=False) assert_allclose(s, ss)
# -*- coding: utf-8 -*- """ Created on Wed Sep 25 19:08:23 2013 @author: jschulz1 """ import numpy as np # NumPy (multidimensional arrays, linear algebra, ...) import scipy as sp # SciPy (signal and image processing library) import matplotlib as mpl # Matplotlib (2D/3D plotting library) import matplotlib.pyplot as plt # Matplotlib's pyplot: MATLAB-like syntax from pylab import * # Matplotlib's pylab interface from scipy.linalg import hilbert A = hilbert(50) print dot(A[:,2].T,ones((len(A[:,2]),))) # alternativ print sum(A[:,2])
if isspmatrix(m): m = m.todense() u, s, vh = svd(m) if which == 'LM': ii = np.argsort(s)[-k:] elif which == 'SM': ii = np.argsort(s)[:k] else: raise ValueError("unknown which=%r" % (which,)) return u[:, ii], s[ii], vh[ii] def svd_estimate(u, s, vh): return np.dot(u, np.dot(np.diag(s), vh)) n = 5 x = hilbert(n) # u,s,vh = svd(x) # s[2:-1] = 0 # x = svd_estimate(u, s, vh) which = 'SM' k = 2 u, s, vh = sorted_svd(x, k, which=which) su,ss,svh = old_svds(x, k, which=which) ssu,sss,ssvh = new_svds(x, k, which=which) m_hat = svd_estimate(u, s, vh) sm_hat = svd_estimate(su, ss, svh) ssm_hat = svd_estimate(ssu, sss, ssvh)
np.linalg.cond(A) np.linalg.cond(A_delta) b=np.matrix('1;1;1') #noise free right hand side l=.01 k=100 ip.invert(A_delta,b,k,l) np.linalg.pinv(A_delta)*b ##################### #Example 3 Hilbert A ##################### from scipy.linalg import hilbert A=hilbert(3) np.linalg.cond(A) x=np.matrix('1;1;1') b=A*x #Now add noise to b of size ro # dimension of A r= np.matrix(A.shape)[0,0] nb= np.random.normal(0, .50, r) #compute vector of normal variants mean=0,std=0.1 #nb= np.random.normal(0, 50, r) #compute vector of normal variants mean=0,std=50 #note that nb is 3 by 1, so we need to flip it be=b+np.matrix(nb).transpose() #add noise l=1 k=100
for k in range(n-1,-1,-1): b[k] = (b[k] - np.dot(L[k+1:n,k],b[k+1:n]))/L[k,k] return b choleski(a2) print ("The answer for problem 11 is:") print (choleskiSol(a2,b2)) """ #Problem 15 #Code is not working correctly. I did not have enough time to finish it. a3 = hilbert(2) b3 = [] x = [] i = 0 actNorm = 1*10**-6 while True: b3.append(a3[i].sum()) x.append([1]) xNorm = np.linalg.norm(x, np.inf) xApprox = np.linalg.solve(a3, b3) xHat = np.linalg.norm(xApprox, np.inf) approxErr = xNorm - xHat if abs(approxErr) < actNorm: break i = i + 1
B # Out[3]: # array([[ 1., 2., 3., 4.], # [ 2., 3., 4., 5.], # [ 3., 4., 5., 6.], # [ 4., 5., 6., 7.]]) # In[4]: A = 1/B from scipy.linalg import hilbert A2 = hilbert(n) print "difference: %g" % la.norm(A-A2) print "cond: %g" % np.linalg.cond(A) # Out[4]: # difference: 0 # cond: 15513.7 # # /usr/lib/pymodules/python2.7/numpy/oldnumeric/__init__.py:11: ModuleDeprecationWarning: The oldnumeric module will be dropped in Numpy 1.9 # warnings.warn(_msg, ModuleDeprecationWarning) #
def check_id(self, dtype): # Test ID routines on a Hilbert matrix. # set parameters n = 300 eps = 1e-12 # construct Hilbert matrix A = hilbert(n).astype(dtype) if np.issubdtype(dtype, np.complexfloating): A = A * (1 + 1j) L = aslinearoperator(A) # find rank S = np.linalg.svd(A, compute_uv=False) try: rank = np.nonzero(S < eps)[0][0] except: rank = n # print input summary _debug_print("Hilbert matrix dimension: %8i" % n) _debug_print("Working precision: %8.2e" % eps) _debug_print("Rank to working precision: %8i" % rank) # set print format fmt = "%8.2e (s) / %5s" # test real ID routines _debug_print("-----------------------------------------") _debug_print("Real ID routines") _debug_print("-----------------------------------------") # fixed precision _debug_print("Calling iddp_id / idzp_id ...",) t0 = time.clock() k, idx, proj = pymatrixid.interp_decomp(A, eps, rand=False) t = time.clock() - t0 B = pymatrixid.reconstruct_matrix_from_id(A[:, idx[:k]], idx, proj) _debug_print(fmt % (t, np.allclose(A, B, eps))) assert_(np.allclose(A, B, eps)) _debug_print("Calling iddp_aid / idzp_aid ...",) t0 = time.clock() k, idx, proj = pymatrixid.interp_decomp(A, eps) t = time.clock() - t0 B = pymatrixid.reconstruct_matrix_from_id(A[:, idx[:k]], idx, proj) _debug_print(fmt % (t, np.allclose(A, B, eps))) assert_(np.allclose(A, B, eps)) _debug_print("Calling iddp_rid / idzp_rid ...",) t0 = time.clock() k, idx, proj = pymatrixid.interp_decomp(L, eps) t = time.clock() - t0 B = pymatrixid.reconstruct_matrix_from_id(A[:, idx[:k]], idx, proj) _debug_print(fmt % (t, np.allclose(A, B, eps))) assert_(np.allclose(A, B, eps)) # fixed rank k = rank _debug_print("Calling iddr_id / idzr_id ...",) t0 = time.clock() idx, proj = pymatrixid.interp_decomp(A, k, rand=False) t = time.clock() - t0 B = pymatrixid.reconstruct_matrix_from_id(A[:, idx[:k]], idx, proj) _debug_print(fmt % (t, np.allclose(A, B, eps))) assert_(np.allclose(A, B, eps)) _debug_print("Calling iddr_aid / idzr_aid ...",) t0 = time.clock() idx, proj = pymatrixid.interp_decomp(A, k) t = time.clock() - t0 B = pymatrixid.reconstruct_matrix_from_id(A[:, idx[:k]], idx, proj) _debug_print(fmt % (t, np.allclose(A, B, eps))) assert_(np.allclose(A, B, eps)) _debug_print("Calling iddr_rid / idzr_rid ...",) t0 = time.clock() idx, proj = pymatrixid.interp_decomp(L, k) t = time.clock() - t0 B = pymatrixid.reconstruct_matrix_from_id(A[:, idx[:k]], idx, proj) _debug_print(fmt % (t, np.allclose(A, B, eps))) assert_(np.allclose(A, B, eps)) # check skeleton and interpolation matrices idx, proj = pymatrixid.interp_decomp(A, k, rand=False) P = pymatrixid.reconstruct_interp_matrix(idx, proj) B = pymatrixid.reconstruct_skel_matrix(A, k, idx) assert_(np.allclose(B, A[:,idx[:k]], eps)) assert_(np.allclose(B.dot(P), A, eps)) # test SVD routines _debug_print("-----------------------------------------") _debug_print("SVD routines") _debug_print("-----------------------------------------") # fixed precision _debug_print("Calling iddp_svd / idzp_svd ...",) t0 = time.clock() U, S, V = pymatrixid.svd(A, eps, rand=False) t = time.clock() - t0 B = np.dot(U, np.dot(np.diag(S), V.T.conj())) _debug_print(fmt % (t, np.allclose(A, B, eps))) assert_(np.allclose(A, B, eps)) _debug_print("Calling iddp_asvd / idzp_asvd...",) t0 = time.clock() U, S, V = pymatrixid.svd(A, eps) t = time.clock() - t0 B = np.dot(U, np.dot(np.diag(S), V.T.conj())) _debug_print(fmt % (t, np.allclose(A, B, eps))) assert_(np.allclose(A, B, eps)) _debug_print("Calling iddp_rsvd / idzp_rsvd...",) t0 = time.clock() U, S, V = pymatrixid.svd(L, eps) t = time.clock() - t0 B = np.dot(U, np.dot(np.diag(S), V.T.conj())) _debug_print(fmt % (t, np.allclose(A, B, eps))) assert_(np.allclose(A, B, eps)) # fixed rank k = rank _debug_print("Calling iddr_svd / idzr_svd ...",) t0 = time.clock() U, S, V = pymatrixid.svd(A, k, rand=False) t = time.clock() - t0 B = np.dot(U, np.dot(np.diag(S), V.T.conj())) _debug_print(fmt % (t, np.allclose(A, B, eps))) assert_(np.allclose(A, B, eps)) _debug_print("Calling iddr_asvd / idzr_asvd ...",) t0 = time.clock() U, S, V = pymatrixid.svd(A, k) t = time.clock() - t0 B = np.dot(U, np.dot(np.diag(S), V.T.conj())) _debug_print(fmt % (t, np.allclose(A, B, eps))) assert_(np.allclose(A, B, eps)) _debug_print("Calling iddr_rsvd / idzr_rsvd ...",) t0 = time.clock() U, S, V = pymatrixid.svd(L, k) t = time.clock() - t0 B = np.dot(U, np.dot(np.diag(S), V.T.conj())) _debug_print(fmt % (t, np.allclose(A, B, eps))) assert_(np.allclose(A, B, eps)) # ID to SVD idx, proj = pymatrixid.interp_decomp(A, k, rand=False) Up, Sp, Vp = pymatrixid.id_to_svd(A[:, idx[:k]], idx, proj) B = U.dot(np.diag(S).dot(V.T.conj())) assert_(np.allclose(A, B, eps)) # Norm estimates s = svdvals(A) norm_2_est = pymatrixid.estimate_spectral_norm(A) assert_(np.allclose(norm_2_est, s[0], 1e-6)) B = A.copy() B[:,0] *= 1.2 s = svdvals(A - B) norm_2_est = pymatrixid.estimate_spectral_norm_diff(A, B) assert_(np.allclose(norm_2_est, s[0], 1e-6)) # Rank estimates B = np.array([[1, 1, 0], [0, 0, 1], [0, 0, 1]], dtype=dtype) for M in [A, B]: ML = aslinearoperator(M) rank_np = np.linalg.matrix_rank(M, 1e-9) rank_est = pymatrixid.estimate_rank(M, 1e-9) rank_est_2 = pymatrixid.estimate_rank(ML, 1e-9) assert_(rank_est >= rank_np) assert_(rank_est <= rank_np + 10) assert_(rank_est_2 >= rank_np) assert_(rank_est_2 <= rank_np + 10)
print(A) #b) b=np.array([npr.rand(),npr.rand(),npr.rand()]) print(b) #c) x=solve(A,b) print(x) #sprawdzenie poprawności rozwiązania print(npl.norm(np.dot(A,x)-b)) # powinno wyjść coś bliskiego zeru #d) H=sclin.hilbert(4) print(H) #e) c=np.array([npr.rand(),npr.rand(),npr.rand(),npr.rand()]) print(c) #f) y=solve(H,c) print(y) #sprawdzenie poprawności rozwiązania print(npl.norm(np.dot(H,y)-c)) # powinno wyjść coś bliskiego zeru #g
r = linalg.norm([ A[j , k] , A[j + 1, k] ], 2) if r>0: c=A[j, k]/r; s=A[j + 1, k]/r A[[j, j + 1],(k + 1):(n+1)] = \ mat([[c, s],[-s, c]])* \ A[[j, j + 1],(k + 1):(n+1)] A[j, k] = r; A[j+1,k] = 0 z = A[:, n].copy() rbacksolve(A[:, :n], z, n) return z if __name__ == '__main__': N = 20 H_ = hilbert(N) xe_ = mat(ones(N)).T err = empty(N) errAlt = empty(N) iterations = arange(N) for n in iterations: # H = H_[:n+1, :n+1]; xe = xe_[:n+1] H = hilbert(n+1); xe = mat(ones(n+1)).T b = H*xe x = rotsolve(H, b) err[n] = linalg.norm(x - xe, 2) y = rotsolveAlt(H, b) errAlt[n] = linalg.norm(y - xe, 2) plt.plot(1+iterations, err, 'b') plt.plot(1 +iterations, errAlt, 'r')