def test_leftright_precond(self): """Check that QMR works with left and right preconditioners""" from scipy.sparse.linalg.dsolve import splu from scipy.sparse.linalg.interface import LinearOperator n = 100 dat = ones(n) A = spdiags([-2*dat, 4*dat, -dat], [-1,0,1] ,n,n) b = arange(n,dtype='d') L = spdiags([-dat/2, dat], [-1,0], n, n) U = spdiags([4*dat, -dat], [ 0,1], n, n) L_solver = splu(L) U_solver = splu(U) def L_solve(b): return L_solver.solve(b) def U_solve(b): return U_solver.solve(b) def LT_solve(b): return L_solver.solve(b,'T') def UT_solve(b): return U_solver.solve(b,'T') M1 = LinearOperator( (n,n), matvec=L_solve, rmatvec=LT_solve ) M2 = LinearOperator( (n,n), matvec=U_solve, rmatvec=UT_solve ) x,info = qmr(A, b, tol=1e-8, maxiter=15, M1=M1, M2=M2) assert_equal(info,0) assert_normclose(A*x, b, tol=1e-8)
def build_sparse_crank_nicolson(s): """(internal) Set up the sparse matrices for the Crank-Nicolson method. """ A = sparse.lil_matrix((s.n, s.n)) C = sparse.lil_matrix((s.n, s.n)) for j in xrange(0, s.n): xd = j+1+s.xs ssxx = (s.sigma * xd) ** 2 A[j,j] = 1.0 - 0.5*s.dt*(ssxx + s.r) C[j,j] = 1.0 + 0.5*s.dt*(ssxx + s.r) if j > 0: A[j,j-1] = 0.25*s.dt*(+ssxx - s.r*xd) C[j,j-1] = 0.25*s.dt*(-ssxx + s.r*xd) if j < s.n-1: A[j,j+1] = 0.25*s.dt*(+ssxx + s.r*xd) C[j,j+1] = 0.25*s.dt*(-ssxx - s.r*xd) s.A = A.tocsr() s.C = linsolve.splu(C) # perform sparse LU decomposition # Buffer to store right-hand side of the linear system Cu = v s.v = empty((n, ))
def test_splu_smoketest(self): with warnings.catch_warnings(): warnings.simplefilter("ignore", category=SparseEfficiencyWarning) # Check that splu works at all x = random.rand(self.n) lu = splu(self.A) r = self.A * lu.solve(x) assert_(abs(x - r).max() < 1e-13)
def _check_non_singular(self): # Make a diagonal dominant, to make sure it is not singular n = 5 a = csc_matrix(random.rand(n, n)) b = ones(n) expected = splu(a).solve(b) assert_array_almost_equal(factorized(a)(b), expected)
def test_leftright_precond(self): """Check that QMR works with left and right preconditioners""" from scipy.sparse.linalg.dsolve import splu from scipy.sparse.linalg.interface import LinearOperator n = 100 dat = ones(n) A = spdiags([-2*dat, 4*dat, -dat], [-1,0,1],n,n) b = arange(n,dtype='d') L = spdiags([-dat/2, dat], [-1,0], n, n) U = spdiags([4*dat, -dat], [0,1], n, n) with suppress_warnings() as sup: sup.filter(SparseEfficiencyWarning, "splu requires CSC matrix format") L_solver = splu(L) U_solver = splu(U) def L_solve(b): return L_solver.solve(b) def U_solve(b): return U_solver.solve(b) def LT_solve(b): return L_solver.solve(b,'T') def UT_solve(b): return U_solver.solve(b,'T') M1 = LinearOperator((n,n), matvec=L_solve, rmatvec=LT_solve) M2 = LinearOperator((n,n), matvec=U_solve, rmatvec=UT_solve) with suppress_warnings() as sup: sup.filter(DeprecationWarning, ".*called without specifying.*") x,info = qmr(A, b, tol=1e-8, maxiter=15, M1=M1, M2=M2) assert_equal(info,0) assert_normclose(A*x, b, tol=1e-8)
def test_splu_perm(self): # Test the permutation vectors exposed by splu. n = 30 a = random.random((n, n)) a[a < 0.95] = 0 # Make a diagonal dominant, to make sure it is not singular a += 4*eye(n) a_ = csc_matrix(a) lu = splu(a_) # Check that the permutation indices do belong to [0, n-1]. for perm in (lu.perm_r, lu.perm_c): assert_(all(perm > -1)) assert_(all(perm < n)) assert_equal(len(unique(perm)), len(perm)) # Now make a symmetric, and test that the two permutation vectors are # the same a += a.T a_ = csc_matrix(a) lu = splu(a_) assert_array_equal(lu.perm_r, lu.perm_c)
def test_bad_inputs(self): A = self.A.tocsc() assert_raises(ValueError, splu, A[:, :4]) assert_raises(ValueError, spilu, A[:, :4]) for lu in [splu(A), spilu(A)]: b = random.rand(42) B = random.rand(42, 3) BB = random.rand(self.n, 3, 9) assert_raises(ValueError, lu.solve, b) assert_raises(ValueError, lu.solve, B) assert_raises(ValueError, lu.solve, BB) assert_raises(TypeError, lu.solve, b.astype(np.complex64)) assert_raises(TypeError, lu.solve, b.astype(np.complex128))
def test_lu_refcount(self): # Test that we are keeping track of the reference count with splu. n = 30 a = random.random((n, n)) a[a < 0.95] = 0 # Make a diagonal dominant, to make sure it is not singular a += 4*eye(n) a_ = csc_matrix(a) lu = splu(a_) # And now test that we don't have a refcount bug rc = sys.getrefcount(lu) for attr in ('perm_r', 'perm_c'): perm = getattr(lu, attr) assert_equal(sys.getrefcount(lu), rc + 1) del perm assert_equal(sys.getrefcount(lu), rc)
def test_lu_refcount(self): # Test that we are keeping track of the reference count with splu. n = 30 a = random.random((n, n)) a[a < 0.95] = 0 # Make a diagonal dominant, to make sure it is not singular a += 4 * eye(n) a_ = csc_matrix(a) lu = splu(a_) # And now test that we don't have a refcount bug rc = sys.getrefcount(lu) for attr in ('perm_r', 'perm_c'): perm = getattr(lu, attr) assert_equal(sys.getrefcount(lu), rc + 1) del perm assert_equal(sys.getrefcount(lu), rc)
def test_bad_inputs(self): A = self.A.tocsc() assert_raises(ValueError, splu, A[:,:4]) assert_raises(ValueError, spilu, A[:,:4]) for lu in [splu(A), spilu(A)]: b = random.rand(42) B = random.rand(42, 3) BB = random.rand(self.n, 3, 9) assert_raises(ValueError, lu.solve, b) assert_raises(ValueError, lu.solve, B) assert_raises(ValueError, lu.solve, BB) assert_raises(TypeError, lu.solve, b.astype(np.complex64)) assert_raises(TypeError, lu.solve, b.astype(np.complex128))
def test_splu_basic(self): # Test basic splu functionality. n = 30 a = random.random((n, n)) a[a < 0.95] = 0 # First test with a singular matrix a[:, 0] = 0 a_ = csc_matrix(a) # Matrix is exactly singular assert_raises(RuntimeError, splu, a_) # Make a diagonal dominant, to make sure it is not singular a += 4*eye(n) a_ = csc_matrix(a) lu = splu(a_) b = ones(n) x = lu.solve(b) assert_almost_equal(dot(a, x), b)
def test_splu_basic(self): # Test basic splu functionality. n = 30 a = random.random((n, n)) a[a < 0.95] = 0 # First test with a singular matrix a[:, 0] = 0 a_ = csc_matrix(a) # Matrix is exactly singular assert_raises(RuntimeError, splu, a_) # Make a diagonal dominant, to make sure it is not singular a += 4 * eye(n) a_ = csc_matrix(a) lu = splu(a_) b = ones(n) x = lu.solve(b) assert_almost_equal(dot(a, x), b)
def test_lu_attr(self): A = self.A n = A.shape[0] lu = splu(A) # Check that the decomposition is as advertized Pc = np.zeros((n, n)) Pc[np.arange(n), lu.perm_c] = 1 Pr = np.zeros((n, n)) Pr[lu.perm_r, np.arange(n)] = 1 Ad = A.toarray() lhs = Pr.dot(Ad).dot(Pc) rhs = (lu.L * lu.U).toarray() assert_allclose(lhs, rhs, atol=1e-10)
def test_lu_attr(self): A = self.A n = A.shape[0] lu = splu(A) # Check that the decomposition is as advertized Pc = np.zeros((n, n)) Pc[np.arange(n), lu.perm_c] = 1 Pr = np.zeros((n, n)) Pr[lu.perm_r, np.arange(n)] = 1 Ad = A.toarray() lhs = Pr.dot(Ad).dot(Pc) rhs = (lu.L * lu.U).toarray() assert_allclose(lhs, rhs, atol=1e-10)
def test_assume_sorted_indices_flag(self): # a sparse matrix with unsorted indices unsorted_inds = np.array([2, 0, 1, 0]) data = np.array([10, 16, 5, 0.4]) indptr = np.array([0, 1, 2, 4]) A = csc_matrix((data, unsorted_inds, indptr), (3, 3)) b = ones(3) # should raise when incorrectly assuming indices are sorted use_solver(useUmfpack=True, assumeSortedIndices=True) assert_raises_regex(RuntimeError, "UMFPACK_ERROR_invalid_matrix", factorized, A) # should sort indices and succeed when not assuming indices are sorted use_solver(useUmfpack=True, assumeSortedIndices=False) expected = splu(A.copy()).solve(b) assert_equal(A.has_sorted_indices, 0) assert_array_almost_equal(factorized(A)(b), expected) assert_equal(A.has_sorted_indices, 1)
def build_sparse_implicit(s): """(internal) Set up the sparse matrix system for the implicit method.""" C = sparse.lil_matrix((s.n, s.n)) for j in xrange(0, s.n): xd = j+1+s.xs ssxx = (s.sigma * xd) ** 2 C[j,j] = 1.0 + s.dt*(ssxx + s.r) if j > 0: C[j,j-1] = 0.5*s.dt*(-ssxx + s.r*xd) if j < s.n-1: C[j,j+1] = 0.5*s.dt*(-ssxx - s.r*xd) # Store matrix with sparse LU decomposition already performed s.C = linsolve.splu(C) # Buffer to store right-hand side of the linear system Cu = v s.v = empty((n, ))
def test_assume_sorted_indices_flag(self): # a sparse matrix with unsorted indices unsorted_inds = np.array([2, 0, 1, 0]) data = np.array([10, 16, 5, 0.4]) indptr = np.array([0, 1, 2, 4]) A = csc_matrix((data, unsorted_inds, indptr), (3, 3)) b = ones(3) # should raise when incorrectly assuming indices are sorted use_solver(useUmfpack=True, assumeSortedIndices=True) with assert_raises(RuntimeError, message="UMFPACK_ERROR_invalid_matrix"): factorized(A) # should sort indices and succeed when not assuming indices are sorted use_solver(useUmfpack=True, assumeSortedIndices=False) expected = splu(A.copy()).solve(b) assert_equal(A.has_sorted_indices, 0) assert_array_almost_equal(factorized(A)(b), expected) assert_equal(A.has_sorted_indices, 1)
def build_sparse_implicit(self, s): """(internal) Set up the sparse matrix system for the implicit method.""" C = sparse.lil_matrix((s.n, s.n)) for j in range(0, s.n): xd = j + 1 + s.xs ssxx = (s.sigma * xd)**2 C[j, j] = 1.0 + s.dt * (ssxx + s.r) if j > 0: C[j, j - 1] = 0.5 * s.dt * (-ssxx + s.r * xd) if j < s.n - 1: C[j, j + 1] = 0.5 * s.dt * (-ssxx - s.r * xd) # Store matrix with sparse LU decomposition already performed s.C = linsolve.splu(sparse.lil_matrix.tocsc(C)) # Buffer to store right-hand side of the linear system Cu = v s.v = empty((n, ))
def check(dtype, complex_2=False): A = self.A.astype(dtype) if complex_2: A = A + 1j * A.T n = A.shape[0] lu = splu(A) # Check that the decomposition is as advertized Pc = np.zeros((n, n)) Pc[np.arange(n), lu.perm_c] = 1 Pr = np.zeros((n, n)) Pr[lu.perm_r, np.arange(n)] = 1 Ad = A.toarray() lhs = Pr.dot(Ad).dot(Pc) rhs = (lu.L * lu.U).toarray() eps = np.finfo(dtype).eps assert_allclose(lhs, rhs, atol=100 * eps)
def build(self): A = sparse.lil_matrix((self.n, self.n)) C = sparse.lil_matrix((self.n, self.n)) for j in xrange(0, self.n): xd = j+1+self.xs ssxx = (self.sigma * xd) ** 2 A[j,j] = 1.0 - 0.5*self.dt*(ssxx + self.r) C[j,j] = 1.0 + 0.5*self.dt*(ssxx + self.r) if j > 0: A[j,j-1] = 0.25*self.dt*(+ssxx - self.r*xd) C[j,j-1] = 0.25*self.dt*(-ssxx + self.r*xd) if j < self.n-1: A[j,j+1] = 0.25*self.dt*(+ssxx + self.r*xd) C[j,j+1] = 0.25*self.dt*(-ssxx - self.r*xd) self.A = A.tocsr() self.C = linsolve.splu(C) # sparse LU decomposition # Buffer to store right-hand side of the linear system Cu = v self.v = empty((n, ))
def check(dtype, complex_2=False): A = self.A.astype(dtype) if complex_2: A = A + 1j*A.T n = A.shape[0] lu = splu(A) # Check that the decomposition is as advertized Pc = np.zeros((n, n)) Pc[np.arange(n), lu.perm_c] = 1 Pr = np.zeros((n, n)) Pr[lu.perm_r, np.arange(n)] = 1 Ad = A.toarray() lhs = Pr.dot(Ad).dot(Pc) rhs = (lu.L * lu.U).toarray() eps = np.finfo(dtype).eps assert_allclose(lhs, rhs, atol=100*eps)
def test_splu_smoketest(self): # Check that splu works at all x = random.rand(self.n) lu = splu(self.A) r = self.A*lu.solve(x) assert_(abs(x - r).max() < 1e-13)
def test_splu_smoketest(self): # Check that splu works at all x = random.rand(self.n) lu = splu(self.A) r = self.A * lu.solve(x) assert_(abs(x - r).max() < 1e-13)