def test_cg_2x2(): A = np.array([4.0, 1.0, 1.0, 3.0]) A = A.reshape((2, 2)) def Ax(x): return np.dot(A, x) b = np.array([1.0, 2.0]) x, niter = cg(Ax, b) assert niter <= 2 assert (np.round(x, decimals=4) == np.array([0.0909, 0.6364])).all()
def test_cg_20x20(): n = 20 A = np.random.rand(n, n) A = (A + A.T) / 2.0 def Ax(x): return np.dot(A, x) b = np.random.rand(n) x, niter = cg(Ax, b) np_x = np.linalg.solve(A, b) assert np.allclose(x, np_x, atol=1e-8)
def test_single_element_cg_sin_3d(): N = 10 n = N + 1 mesh = load_mesh("box001.msh") mesh.find_physical_coordinates(N) mesh.calc_geometric_factors() mesh.establish_global_numbering() mesh.setup_mask() G = mesh.get_geom() J = mesh.get_jaco() B = mesh.get_mass() def mask(W): W = W.reshape((n, n, n)) W[0, :, :] = 0 W[n - 1, :, :] = 0 W[:, 0, :] = 0 W[:, n - 1, :] = 0 W[:, :, 0] = 0 W[:, :, n - 1] = 0 W = W.reshape((n * n * n,)) return W def Ax(x): Ux, Uy, Uz = gradient(x, n) Wx = G[0, 0, 0, :] * Ux + G[0, 0, 1, :] * Uy + G[0, 0, 2, :] * Uz Wy = G[0, 1, 0, :] * Ux + G[0, 1, 1, :] * Uy + G[0, 1, 2, :] * Uz Wz = G[0, 2, 0, :] * Ux + G[0, 2, 1, :] * Uy + G[0, 2, 2, :] * Uz W = gradient_transpose(Wx, Wy, Wz, n) return mask(W) X = mesh.get_x() Y = mesh.get_y() Z = mesh.get_z() x = np.sin(np.pi * X) * np.sin(np.pi * Y) * np.sin(np.pi * Z) x = mask(x) b = 3 * np.pi * np.pi * np.sin(np.pi * X) * np.sin(np.pi * Y) * np.sin(np.pi * Z) b = b * B * J b = mask(b) x_cg, niter = cg(Ax, b, tol=1e-8, maxit=100, verbose=0) assert np.allclose(x, x_cg, 1e-8)
def test_cg_3x3(): A = np.array([1.0, 2.0, -1.0, 2.0, 2.0, 2.0, 1.0, -1.0, 2.0]) A = A.reshape((3, 3)) A = (A + A.T) / 2.0 def Ax(x): return np.dot(A, x) b = np.array([2.0, 12.0, 5.0]) x, niter = cg(Ax, b) np_x = np.linalg.solve(A, b) assert niter <= 3 assert np.allclose(x, np_x, atol=1e-8)
if example_2d: b = np.exp(10 * Y) * np.sin(10 * X) b = mask(b.reshape((n * n, )) * B * J) else: b = np.exp(10 * Y * Z) * np.sin(10 * X) b = mask(b.reshape((n * n * n, )) * B * J) tol = 1.0e-8 maxit = 1000 verbose = 0 t = time.process_time() if example_2d: x_cg, niter_cg = cg(Ax_2d, b, tol, maxit, verbose) x_mass, niter_mass = pcg(Ax_2d, precon_mass, b, tol, maxit, verbose) x_jacobi, niter_jacobi = pcg(Ax_2d, precon_jacobi_2d, b, tol, maxit, verbose) x_fdm, niter_fdm = pcg(Ax_2d, precon_fdm_2d, b, tol, maxit, verbose) else: x_cg, niter_cg = cg(Ax, b, tol, maxit, verbose) tt = time.process_time() - t elapsed_cg.append(tt) # x_mass ,niter_mass =pcg(Ax,precon_mass ,b,tol,maxit,verbose) # x_jacobi,niter_jacobi=pcg(Ax,precon_jacobi,b,tol,maxit,verbose) t = time.process_time() x_fdm, niter_fdm = pcg(Ax, precon_fdm, b, tol, maxit, verbose) tt = time.process_time() - t elapsed_fdm.append(tt)