def test_regular_3D(backend, forward_output): if (backend == 'netcdf4' and forward_output is True) or skip[backend]: return K0 = FunctionSpace(N[0], 'F', dtype='D', domain=(0, np.pi)) K1 = FunctionSpace(N[1], 'F', dtype='d', domain=(0, 2 * np.pi)) K2 = FunctionSpace(N[2], 'C', dtype='d', bc=(0, 0)) T = TensorProductSpace(comm, (K0, K1, K2)) filename = 'test3Dr_{}'.format(ex[forward_output]) hfile = writer(filename, T, backend=backend) if forward_output: u = Function(T) else: u = Array(T) u[:] = np.random.random(u.shape) for i in range(3): hfile.write(i, { 'u': [u, (u, [slice(None), 4, slice(None)]), (u, [slice(None), 4, 4])] }, forward_output=forward_output) if not forward_output and backend == 'hdf5' and comm.Get_rank() == 0: generate_xdmf(filename + '.h5') u0 = Function(T) if forward_output else Array(T) read = reader(filename, T, backend=backend) read.read(u0, 'u', forward_output=forward_output, step=1) assert np.allclose(u0, u) cleanup()
def test_biharmonic2D(family, axis): la = lla if family == 'chebyshev': la = cla N = (16, 16) SD = FunctionSpace(N[axis], family=family, bc='Biharmonic') K1 = FunctionSpace(N[(axis + 1) % 2], family='F', dtype='d') subcomms = mpi4py_fft.pencil.Subcomm(MPI.COMM_WORLD, allaxes2D[axis]) bases = [K1] bases.insert(axis, SD) T = TensorProductSpace(subcomms, bases, axes=allaxes2D[axis]) u = shenfun.TrialFunction(T) v = shenfun.TestFunction(T) if family == 'chebyshev': mat = inner(v, div(grad(div(grad(u))))) else: mat = inner(div(grad(v)), div(grad(u))) H = la.Biharmonic(*mat) u = Function(T) u[:] = np.random.random(u.shape) + 1j * np.random.random(u.shape) f = Function(T) f = H.matvec(u, f) g0 = Function(T) g1 = Function(T) g2 = Function(T) M = {d.get_key(): d for d in mat} g0 = M['SBBmat'].matvec(u, g0) g1 = M['ABBmat'].matvec(u, g1) g2 = M['BBBmat'].matvec(u, g2) assert np.linalg.norm(f - (g0 + g1 + g2)) < 1e-8
def test_solve(quad): SD = Basis(N, 'C', bc=(0, 0), quad=quad, plan=True) u = TrialFunction(SD) v = TestFunction(SD) A = inner(div(grad(u)), v) b = np.ones(N) u_hat = Function(SD) u_hat = A.solve(b, u=u_hat) w_hat = Function(SD) B = SparseMatrix(dict(A), (N - 2, N - 2)) w_hat[:-2] = B.solve(b[:-2], w_hat[:-2]) assert np.all(abs(w_hat[:-2] - u_hat[:-2]) < 1e-8) ww = w_hat[:-2].repeat(N - 2).reshape((N - 2, N - 2)) bb = b[:-2].repeat(N - 2).reshape((N - 2, N - 2)) ww = B.solve(bb, ww, axis=0) assert np.all( abs(ww - u_hat[:-2].repeat(N - 2).reshape((N - 2, N - 2))) < 1e-8) bb = bb.transpose() ww = B.solve(bb, ww, axis=1) assert np.all( abs(ww - u_hat[:-2].repeat(N - 2).reshape( (N - 2, N - 2)).transpose()) < 1e-8)
def test_quasiGalerkin(basis): N = 40 T = FunctionSpace(N, 'C') S = FunctionSpace(N, 'C', basis=basis) u = TrialFunction(S) v = TestFunction(T) A = inner(v, div(grad(u))) B = inner(v, u) Q = chebyshev.quasi.QIGmat(N) A = Q*A B = Q*B M = B-A sol = la.Solve(M, S) f_hat = inner(v, Array(T, buffer=fe)) f_hat[:-2] = Q.diags('csc')*f_hat[:-2] u_hat = Function(S) u_hat = sol(f_hat, u_hat) uj = u_hat.backward() ua = Array(S, buffer=ue) bb = Q*np.ones(N) assert abs(np.sum(bb[:8])) < 1e-8 if S.boundary_condition().lower() == 'neumann': xj, wj = S.points_and_weights() ua -= np.sum(ua*wj)/np.pi # normalize uj -= np.sum(uj*wj)/np.pi # normalize assert np.sqrt(inner(1, (uj-ua)**2)) < 1e-5
def interp(self, y, eigvals, eigvectors, eigval=1, verbose=False): """Interpolate solution eigenvector and it's derivative onto y Parameters ---------- y : array Interpolation points eigvals : array All computed eigenvalues eigvectors : array All computed eigenvectors eigval : int, optional The chosen eigenvalue, ranked with descending imaginary part. The largest imaginary part is 1, the second largest is 2, etc. verbose : bool, optional Print information or not """ nx, eigval = self.get_eigval(eigval, eigvals, verbose) SB = Basis(self.N, 'C', bc='Biharmonic', quad=self.quad, dtype='D') phi_hat = Function(SB) phi_hat[:-4] = np.squeeze(eigvectors[:, nx]) phi = phi_hat.eval(y) dphidy = Dx(phi_hat, 0, 1).eval(y) return eigval, phi, dphidy
def test_curl_cc(): theta, phi = sp.symbols('x,y', real=True, positive=True) psi = (theta, phi) r = 1 rv = (r * sp.sin(theta) * sp.cos(phi), r * sp.sin(theta) * sp.sin(phi), r * sp.cos(theta)) # Manufactured solution sph = sp.functions.special.spherical_harmonics.Ynm ue = sph(6, 3, theta, phi) N, M = 16, 12 L0 = FunctionSpace(N, 'C', domain=(0, np.pi)) F1 = FunctionSpace(M, 'F', dtype='D') T = TensorProductSpace(comm, (L0, F1), coordinates=(psi, rv)) u_hat = Function(T, buffer=ue) du = curl(grad(u_hat)) du.terms() == [[]] r, theta, z = psi = sp.symbols('x,y,z', real=True, positive=True) rv = (r * sp.cos(theta), r * sp.sin(theta), z) # Manufactured solution ue = (r * (1 - r) * sp.cos(4 * theta) - 1 * (r - 1)) * sp.cos(4 * z) N = 12 F0 = FunctionSpace(N, 'F', dtype='D') F1 = FunctionSpace(N, 'F', dtype='d') L = FunctionSpace(N, 'L', bc='Dirichlet', domain=(0, 1)) T = TensorProductSpace(comm, (L, F0, F1), coordinates=(psi, rv)) T1 = T.get_orthogonal() V = VectorSpace(T1) u_hat = Function(T, buffer=ue) du = project(curl(grad(u_hat)), V) assert np.linalg.norm(du) < 1e-10
def test_project_2dirichlet(quad): x, y = symbols("x,y") ue = (cos(4*y)*sin(2*x))*(1-x**2)*(1-y**2) sizes = (18, 17) D0 = lbases.ShenDirichlet(sizes[0], quad=quad) D1 = lbases.ShenDirichlet(sizes[1], quad=quad) B0 = lbases.Orthogonal(sizes[0], quad=quad) B1 = lbases.Orthogonal(sizes[1], quad=quad) DD = TensorProductSpace(comm, (D0, D1)) BD = TensorProductSpace(comm, (B0, D1)) DB = TensorProductSpace(comm, (D0, B1)) BB = TensorProductSpace(comm, (B0, B1)) X = DD.local_mesh(True) uh = Function(DD, buffer=ue) dudx_hat = project(Dx(uh, 0, 1), BD) dx = Function(BD, buffer=ue.diff(x, 1)) assert np.allclose(dx, dudx_hat, 0, 1e-5) dudy = project(Dx(uh, 1, 1), DB).backward() duedy = Array(DB, buffer=ue.diff(y, 1)) assert np.allclose(duedy, dudy, 0, 1e-5) us_hat = Function(BB) uq = uh.backward() us = project(uq, BB, output_array=us_hat).backward() assert np.allclose(us, uq, 0, 1e-5) dudxy = project(Dx(us_hat, 0, 1) + Dx(us_hat, 1, 1), BB).backward() dxy = Array(BB, buffer=ue.diff(x, 1) + ue.diff(y, 1)) assert np.allclose(dxy, dudxy, 0, 1e-5), np.linalg.norm(dxy-dudxy)
def divergenceConvection(rhs, u_dealias, u_hat, K, VFSp, FSTp, FSBp, FCTp, work, mat, la, add=False): """c_i = div(u_i u_j)""" if not add: rhs.fill(0) F_tmp = Function(VFSp, buffer=work[(rhs, 0, True)]) F_tmp2 = Function(VFSp, buffer=work[(rhs, 1, True)]) U = u_dealias F_tmp[0] = FSTp.forward(U[0]*U[0], F_tmp[0]) F_tmp[1] = FSTp.forward(U[0]*U[1], F_tmp[1]) F_tmp[2] = FSTp.forward(U[0]*U[2], F_tmp[2]) F_tmp2 = project(Dx(F_tmp, 0, 1), VFSp, output_array=F_tmp2) rhs += F_tmp2 F_tmp2[0] = FSTp.forward(U[0]*U[1], F_tmp2[0]) F_tmp2[1] = FSTp.forward(U[0]*U[2], F_tmp2[1]) rhs[0] += 1j*K[1]*F_tmp2[0] # duvdy rhs[0] += 1j*K[2]*F_tmp2[1] # duwdz F_tmp[0] = FSTp.forward(U[1]*U[1], F_tmp[0]) F_tmp[1] = FSTp.forward(U[1]*U[2], F_tmp[1]) F_tmp[2] = FSTp.forward(U[2]*U[2], F_tmp[2]) rhs[1] += 1j*K[1]*F_tmp[0] # dvvdy rhs[1] += 1j*K[2]*F_tmp[1] # dvwdz rhs[2] += 1j*K[1]*F_tmp[1] # dvwdy rhs[2] += 1j*K[2]*F_tmp[2] # dwwdz return rhs
def test_mixed_2D(backend, forward_output, as_scalar): if (backend == 'netcdf4' and forward_output is True) or skip[backend]: return K0 = FunctionSpace(N[0], 'F') K1 = FunctionSpace(N[1], 'C') T = TensorProductSpace(comm, (K0, K1)) TT = CompositeSpace([T, T]) filename = 'test2Dm_{}'.format(ex[forward_output]) hfile = writer(filename, TT, backend=backend) if forward_output: uf = Function(TT, val=2) else: uf = Array(TT, val=2) hfile.write(0, {'uf': [uf]}, as_scalar=as_scalar) hfile.write(1, {'uf': [uf]}, as_scalar=as_scalar) if not forward_output and backend == 'hdf5' and comm.Get_rank() == 0: generate_xdmf(filename + '.h5') if as_scalar is False: u0 = Function(TT) if forward_output else Array(TT) read = reader(filename, TT, backend=backend) read.read(u0, 'uf', step=1) assert np.allclose(u0, uf) else: u0 = Function(T) if forward_output else Array(T) read = reader(filename, T, backend=backend) read.read(u0, 'uf0', step=1) assert np.allclose(u0, uf[0]) cleanup()
def test_helmholtz2D(family, axis): la = lla if family == 'chebyshev': la = cla N = (8, 9) SD = FunctionSpace(N[axis], family=family, bc=(0, 0)) K1 = FunctionSpace(N[(axis+1)%2], family='F', dtype='d') subcomms = mpi4py_fft.pencil.Subcomm(MPI.COMM_WORLD, allaxes2D[axis]) bases = [K1] bases.insert(axis, SD) T = TensorProductSpace(subcomms, bases, axes=allaxes2D[axis], modify_spaces_inplace=True) u = shenfun.TrialFunction(T) v = shenfun.TestFunction(T) if family == 'chebyshev': mat = inner(v, div(grad(u))) else: mat = inner(grad(v), grad(u)) H = la.Helmholtz(*mat) u = Function(T) s = SD.sl[SD.slice()] u[s] = np.random.random(u[s].shape) + 1j*np.random.random(u[s].shape) f = Function(T) f = H.matvec(u, f) g0 = Function(T) g1 = Function(T) M = {d.get_key(): d for d in mat} g0 = M['ADDmat'].matvec(u, g0) g1 = M['BDDmat'].matvec(u, g1) assert np.linalg.norm(f-(g0+g1)) < 1e-12, np.linalg.norm(f-(g0+g1)) uc = Function(T) uc = H(uc, f) assert np.linalg.norm(uc-u) < 1e-12
def test_mixed_3D(backend, forward_output, as_scalar): if (backend == 'netcdf4' and forward_output is True) or skip[backend]: return K0 = FunctionSpace(N[0], 'F', dtype='D', domain=(0, np.pi)) K1 = FunctionSpace(N[1], 'F', dtype='d', domain=(0, 2 * np.pi)) K2 = FunctionSpace(N[2], 'C') T = TensorProductSpace(comm, (K0, K1, K2)) TT = VectorSpace(T) filename = 'test3Dm_{}'.format(ex[forward_output]) hfile = writer(filename, TT, backend=backend) uf = Function(TT, val=2) if forward_output else Array(TT, val=2) uf[0] = 1 data = { 'ux': (uf[0], (uf[0], [slice(None), 4, slice(None)]), (uf[0], [slice(None), 4, 4])), 'uy': (uf[1], (uf[1], [slice(None), 4, slice(None)]), (uf[1], [slice(None), 4, 4])), 'u': [uf, (uf, [slice(None), 4, slice(None)])] } hfile.write(0, data, as_scalar=as_scalar) hfile.write(1, data, as_scalar=as_scalar) if not forward_output and backend == 'hdf5' and comm.Get_rank() == 0: generate_xdmf(filename + '.h5') if as_scalar is False: u0 = Function(TT) if forward_output else Array(TT) read = reader(filename, TT, backend=backend) read.read(u0, 'u', step=1) assert np.allclose(u0, uf) else: u0 = Function(T) if forward_output else Array(T) read = reader(filename, T, backend=backend) read.read(u0, 'u0', step=1) assert np.allclose(u0, uf[0]) cleanup()
def __init__(self, T, L=None, N=None, update=None, **params): IntegratorBase.__init__(self, T, L=L, N=N, update=update, **params) self.U_hat0 = Function(T) self.U_hat1 = Function(T) self.dU = Function(T) self.a = np.array([1. / 6., 1. / 3., 1. / 3., 1. / 6.]) self.b = np.array([0.5, 0.5, 1.])
def test_backward_uniform(family): T = FunctionSpace(N, family) uT = Function(T, buffer=f) ub = uT.backward(kind='uniform') xj = T.mesh(uniform=True) fj = sp.lambdify(x, f)(xj) assert np.linalg.norm(fj - ub) < 1e-8
def __init__(self, T, L=None, N=None, update=None, **params): IntegratorBase.__init__(self, T, L=L, N=N, update=update, **params) self.dU = Function(T) self.dU1 = Function(T) self.a = (8. / 15., 5. / 12., 3. / 4.) self.b = (0.0, -17. / 60., -5. / 12.) self.c = (0., 8. / 15., 2. / 3., 1) self.solver = None self.rhs_mats = None self.w0 = Function(self.T).v self.mask = self.T.get_mask_nyquist()
def __init__(self, T, L=None, N=None, update=None, **params): IntegratorBase.__init__(self, T, L=L, N=N, update=update, **params) self.U_hat0 = Function(T) self.U_hat1 = Function(T) self.dU = Function(T) self.dU0 = Function(T) self.V2 = Function(T) self.psi = np.zeros((4, ) + self.U_hat0.shape, dtype=np.float) self.a = None self.b = [0.5, 0.5, 0.5] self.ehL = None self.ehL_h = None
def test_backward2ND(): T0 = FunctionSpace(N, 'C') L0 = FunctionSpace(N, 'L') T1 = FunctionSpace(N, 'C') L1 = FunctionSpace(N, 'L') TT = TensorProductSpace(comm, (T0, T1)) LL = TensorProductSpace(comm, (L0, L1)) uT = Function(TT, buffer=h) uL = Function(LL, buffer=h) u2 = uL.backward(kind=TT) uT2 = project(u2, TT) assert np.linalg.norm(uT2 - uT)
def test_curl2(): # Test projection of curl K0 = FunctionSpace(N[0], 'C', bc=(0, 0)) K1 = FunctionSpace(N[1], 'F', dtype='D') K2 = FunctionSpace(N[2], 'F', dtype='d') K3 = FunctionSpace(N[0], 'C') T = TensorProductSpace(comm, (K0, K1, K2)) TT = TensorProductSpace(comm, (K3, K1, K2)) X = T.local_mesh(True) K = T.local_wavenumbers(False) Tk = VectorSpace(T) TTk = VectorSpace([T, T, TT]) U = Array(Tk) U_hat = Function(Tk) curl_hat = Function(TTk) curl_ = Array(TTk) # Initialize a Taylor Green vortex U[0] = np.sin(X[0]) * np.cos(X[1]) * np.cos(X[2]) * (1 - X[0]**2) U[1] = -np.cos(X[0]) * np.sin(X[1]) * np.cos(X[2]) * (1 - X[0]**2) U[2] = 0 U_hat = Tk.forward(U, U_hat) Uc = U_hat.copy() U = Tk.backward(U_hat, U) U_hat = Tk.forward(U, U_hat) assert allclose(U_hat, Uc) # Compute curl first by computing each term individually curl_hat[0] = 1j * (K[1] * U_hat[2] - K[2] * U_hat[1]) curl_[0] = T.backward( curl_hat[0], curl_[0]) # No x-derivatives, still in Dirichlet space dwdx_hat = project(Dx(U_hat[2], 0, 1), TT) # Need to use space without bc dvdx_hat = project(Dx(U_hat[1], 0, 1), TT) # Need to use space without bc dwdx = Array(TT) dvdx = Array(TT) dwdx = TT.backward(dwdx_hat, dwdx) dvdx = TT.backward(dvdx_hat, dvdx) curl_hat[1] = 1j * K[2] * U_hat[0] curl_hat[2] = -1j * K[1] * U_hat[0] curl_[1] = T.backward(curl_hat[1], curl_[1]) curl_[2] = T.backward(curl_hat[2], curl_[2]) curl_[1] -= dwdx curl_[2] += dvdx # Now do it with project w_hat = project(curl(U_hat), TTk) w = Array(TTk) w = TTk.backward(w_hat, w) assert allclose(w, curl_)
def test_backward3D(): T = FunctionSpace(N, 'C') L = FunctionSpace(N, 'L') F0 = FunctionSpace(N, 'F', dtype='D') F1 = FunctionSpace(N, 'F', dtype='d') TT = TensorProductSpace(comm, (F0, T, F1)) TL = TensorProductSpace(comm, (F0, L, F1)) uT = Function(TT, buffer=h) uL = Function(TL, buffer=h) u2 = uL.backward(kind=TT) uT2 = project(u2, TT) assert np.linalg.norm(uT2 - uT)
def test_project_2dirichlet(quad): x, y = symbols("x,y") ue = (cos(4 * y) * sin(2 * x)) * (1 - x**2) * (1 - y**2) sizes = (25, 24) D0 = lbases.ShenDirichletBasis(sizes[0], quad=quad) D1 = lbases.ShenDirichletBasis(sizes[1], quad=quad) B0 = lbases.Basis(sizes[0], quad=quad) B1 = lbases.Basis(sizes[1], quad=quad) DD = TensorProductSpace(comm, (D0, D1)) BD = TensorProductSpace(comm, (B0, D1)) DB = TensorProductSpace(comm, (D0, B1)) BB = TensorProductSpace(comm, (B0, B1)) X = DD.local_mesh(True) ul = lambdify((x, y), ue, 'numpy') uq = Array(DD) uq[:] = ul(*X) uh = Function(DD) uh = DD.forward(uq, uh) dudx_hat = project(Dx(uh, 0, 1), BD) dudx = Array(BD) dudx = BD.backward(dudx_hat, dudx) duedx = ue.diff(x, 1) duxl = lambdify((x, y), duedx, 'numpy') dx = duxl(*X) assert np.allclose(dx, dudx) dudy_hat = project(Dx(uh, 1, 1), DB) dudy = Array(DB) dudy = DB.backward(dudy_hat, dudy) duedy = ue.diff(y, 1) duyl = lambdify((x, y), duedy, 'numpy') dy = duyl(*X) assert np.allclose(dy, dudy) us_hat = Function(BB) us_hat = project(uq, BB, output_array=us_hat) us = Array(BB) us = BB.backward(us_hat, us) assert np.allclose(us, uq) dudxy_hat = project(Dx(us_hat, 0, 1) + Dx(us_hat, 1, 1), BB) dudxy = Array(BB) dudxy = BB.backward(dudxy_hat, dudxy) duedxy = ue.diff(x, 1) + ue.diff(y, 1) duxyl = lambdify((x, y), duedxy, 'numpy') dxy = duxyl(*X) assert np.allclose(dxy, dudxy)
def test_refine(): assert comm.Get_size() < 7 N = (8, 9, 10) F0 = Basis(8, 'F', dtype='D') F1 = Basis(9, 'F', dtype='D') F2 = Basis(10, 'F', dtype='d') T = TensorProductSpace(comm, (F0, F1, F2), slab=True, collapse_fourier=True) u_hat = Function(T) u = Array(T) u[:] = np.random.random(u.shape) u_hat = u.forward(u_hat) Tp = T.get_dealiased(padding_factor=(2, 2, 2)) u_ = Array(Tp) up_hat = Function(Tp) assert up_hat.commsizes == u_hat.commsizes u2 = u_hat.refine(2*np.array(N)) V = VectorTensorProductSpace(T) u_hat = Function(V) u = Array(V) u[:] = np.random.random(u.shape) u_hat = u.forward(u_hat) Vp = V.get_dealiased(padding_factor=(2, 2, 2)) u_ = Array(Vp) up_hat = Function(Vp) assert up_hat.commsizes == u_hat.commsizes u3 = u_hat.refine(2*np.array(N))
def test_eval_expression(): import sympy as sp from shenfun import div, grad x, y, z = sp.symbols('x,y,z') B0 = FunctionSpace(16, 'C') B1 = FunctionSpace(17, 'C') B2 = FunctionSpace(20, 'F', dtype='d') TB = TensorProductSpace(comm, (B0, B1, B2)) f = sp.sin(x)+sp.sin(y)+sp.sin(z) dfx = f.diff(x, 2) + f.diff(y, 2) + f.diff(z, 2) fa = Function(TB, buffer=f) dfe = div(grad(fa)) dfa = project(dfe, TB) xyz = np.array([[0.25, 0.5, 0.75], [0.25, 0.5, 0.75], [0.25, 0.5, 0.75]]) f0 = lambdify((x, y, z), dfx)(*xyz) f1 = dfe.eval(xyz) f2 = dfa.eval(xyz) assert np.allclose(f0, f1, 1e-7) assert np.allclose(f1, f2, 1e-7)
def test_energy_fourier(N): B0 = FunctionSpace(N[0], 'F', dtype='D') B1 = FunctionSpace(N[1], 'F', dtype='D') B2 = FunctionSpace(N[2], 'F', dtype='d') for bases, axes in zip(((B0, B1, B2), (B0, B2, B1)), ((0, 1, 2), (2, 0, 1))): T = TensorProductSpace(comm, bases, axes=axes) u_hat = Function(T) u_hat[:] = np.random.random( u_hat.shape) + 1j * np.random.random(u_hat.shape) u = u_hat.backward() u_hat = u.forward(u_hat) u = u_hat.backward(u) e0 = comm.allreduce(np.sum(u.v * u.v) / np.prod(N)) e1 = fourier.energy_fourier(u_hat, T) assert abs(e0 - e1) < 1e-10
def get_adaptive(self, fun=None, reltol=1e-12, abstol=1e-15): """Return space (otherwise as self) with number of quadrature points determined by fitting `fun` Returns ------- SpectralBase A new space with adaptively found number of quadrature points """ from shenfun import Function assert isinstance(fun, sp.Expr) assert self.N == 0 T = self.get_refined(5) converged = False count = 0 points = np.random.random(8) points = T.domain[0] + points * (T.domain[1] - T.domain[0]) sym = fun.free_symbols assert len(sym) == 1 x = sym.pop() fx = sp.lambdify(x, fun) while (not converged) and count < 12: T = T.get_refined(int(1.7 * T.N)) u = Function(T, buffer=fun) res = T.eval(points, u) exact = fx(points) energy = np.linalg.norm(res - exact) #print(T.N, energy) converged = energy**2 < abstol count += 1 # trim trailing zeros (if any) trailing_zeros = T.count_trailing_zeros(u, reltol, abstol) T = T.get_refined(T.N - trailing_zeros) return T
def test_project(typecode, dim, ST, quad): # Using sympy to compute an analytical solution x, y, z = symbols("x,y,z") sizes = (25, 24) funcs = { (1, 0): (cos(4 * y) * sin(2 * np.pi * x)) * (1 - x**2), (1, 1): (cos(4 * x) * sin(2 * np.pi * y)) * (1 - y**2), (2, 0): (sin(6 * z) * cos(4 * y) * sin(2 * np.pi * x)) * (1 - x**2), (2, 1): (sin(2 * z) * cos(4 * x) * sin(2 * np.pi * y)) * (1 - y**2), (2, 2): (sin(2 * x) * cos(4 * y) * sin(2 * np.pi * z)) * (1 - z**2) } syms = {1: (x, y), 2: (x, y, z)} xs = {0: x, 1: y, 2: z} for shape in product(*([sizes] * dim)): bases = [] for n in shape[:-1]: bases.append(Basis(n, 'F', dtype=typecode.upper())) bases.append(Basis(shape[-1], 'F', dtype=typecode)) if dim < 3: n = min(shape) if typecode in 'fdg': n //= 2 n += 1 if n < comm.size: continue for axis in range(dim + 1): ST0 = ST(shape[-1], quad=quad) bases.insert(axis, ST0) fft = TensorProductSpace(comm, bases, dtype=typecode, axes=axes[dim][axis]) X = fft.local_mesh(True) ue = funcs[(dim, axis)] ul = lambdify(syms[dim], ue, 'numpy') uq = ul(*X).astype(typecode) uh = Function(fft) uh = fft.forward(uq, uh) due = ue.diff(xs[axis], 1) dul = lambdify(syms[dim], due, 'numpy') duq = dul(*X).astype(typecode) uf = project(Dx(uh, axis, 1), fft) uy = Array(fft) uy = fft.backward(uf, uy) assert np.allclose(uy, duq, 0, 1e-6) for ax in (x for x in range(dim + 1) if x is not axis): due = ue.diff(xs[axis], 1, xs[ax], 1) dul = lambdify(syms[dim], due, 'numpy') duq = dul(*X).astype(typecode) uf = project(Dx(Dx(uh, axis, 1), ax, 1), fft) uy = Array(fft) uy = fft.backward(uf, uy) assert np.allclose(uy, duq, 0, 1e-6) bases.pop(axis) fft.destroy()
def test_padding_biharmonic(family): N = 8 B = FunctionSpace(N, family, bc=(0, 0, 0, 0)) Bp = B.get_dealiased(1.5) u = Function(B) u[:(N - 4)] = np.random.random(N - 4) up = Array(Bp) up = Bp.backward(u, fast_transform=False) uf = Bp.forward(up, fast_transform=False) assert np.linalg.norm(uf - u) < 1e-12 if family == 'C': up = Bp.backward(u) uf = Bp.forward(up) assert np.linalg.norm(uf - u) < 1e-12 # Test padding 2D F = FunctionSpace(N, 'F', dtype='d') T = TensorProductSpace(comm, (B, F)) Tp = T.get_dealiased(1.5) u = Function(T) u[:-4, :-1] = np.random.random(u[:-4, :-1].shape) up = Tp.backward(u) uc = Tp.forward(up) assert np.linalg.norm(u - uc) < 1e-8 # Test padding 3D F1 = FunctionSpace(N, 'F', dtype='D') T = TensorProductSpace(comm, (F1, F, B)) Tp = T.get_dealiased(1.5) u = Function(T) u[:, :, :-4] = np.random.random(u[:, :, :-4].shape) u = u.backward().forward() # Clean up = Tp.backward(u) uc = Tp.forward(up) assert np.linalg.norm(u - uc) < 1e-8
def test_padding_neumann(family): N = 8 B = FunctionSpace(N, family, bc={'left': ('N', 0), 'right': ('N', 0)}) Bp = B.get_dealiased(1.5) u = Function(B) u[1:-2] = np.random.random(N - 3) up = Array(Bp) up = Bp.backward(u, fast_transform=False) uf = Bp.forward(up, fast_transform=False) assert np.linalg.norm(uf - u) < 1e-12 if family == 'C': up = Bp.backward(u) uf = Bp.forward(up) assert np.linalg.norm(uf - u) < 1e-12 # Test padding 2D F = FunctionSpace(N, 'F', dtype='d') T = TensorProductSpace(comm, (B, F)) Tp = T.get_dealiased(1.5) u = Function(T) u[1:-2, :-1] = np.random.random(u[1:-2, :-1].shape) up = Tp.backward(u) uc = Tp.forward(up) assert np.linalg.norm(u - uc) < 1e-8 # Test padding 3D F1 = FunctionSpace(N, 'F', dtype='D') T = TensorProductSpace(comm, (F1, F, B)) Tp = T.get_dealiased(1.5) u = Function(T) u[:, :, 1:-2] = np.random.random(u[:, :, 1:-2].shape) u = u.backward().forward() # Clean up = Tp.backward(u) uc = Tp.forward(up) assert np.linalg.norm(u - uc) < 1e-8
def __init__(self, T, L=None, N=None, update=None, **params): IntegratorBase.__init__(self, T, L=L, N=N, update=update, **params) self.dU = Function(T) self.psi = None self.ehL = None
def test_PDMA(quad): SB = FunctionSpace(N, 'C', bc=(0, 0, 0, 0), quad=quad) u = TrialFunction(SB) v = TestFunction(SB) points, weights = SB.points_and_weights(N) fj = Array(SB, buffer=np.random.randn(N)) f_hat = Function(SB) f_hat = inner(v, fj, output_array=f_hat) A = inner(v, div(grad(u))) B = inner(v, u) s = SB.slice() H = A + B P = PDMA(A, B, A.scale, B.scale, solver='cython') u_hat = Function(SB) u_hat[s] = solve(H.diags().toarray()[s, s], f_hat[s]) u_hat2 = Function(SB) u_hat2 = P(u_hat2, f_hat) assert np.allclose(u_hat2, u_hat)
def test_TwoDMA(): N = 12 SD = FunctionSpace(N, 'C', basis='ShenDirichlet') HH = FunctionSpace(N, 'C', basis='Heinrichs') u = TrialFunction(HH) v = TestFunction(SD) points, weights = SD.points_and_weights(N) fj = Array(SD, buffer=np.random.randn(N)) f_hat = Function(SD) f_hat = inner(v, fj, output_array=f_hat) A = inner(v, div(grad(u))) sol = TwoDMA(A) u_hat = Function(HH) u_hat = sol(f_hat, u_hat) sol2 = la.Solve(A, HH) u_hat2 = Function(HH) u_hat2 = sol2(f_hat, u_hat2) assert np.allclose(u_hat2, u_hat)
def main(N, family, bci, bcj, plotting=False): global fe, ue BX = FunctionSpace(N, family=family, bc=bcx[bci], domain=xdomain) BY = FunctionSpace(N, family=family, bc=bcy[bcj], domain=ydomain) T = TensorProductSpace(comm, (BX, BY)) u = TrialFunction(T) v = TestFunction(T) # Get f on quad points fj = Array(T, buffer=fe) # Compare with analytical solution ua = Array(T, buffer=ue) if T.use_fixed_gauge: mean = dx(ua, weighted=True) / inner(1, Array(T, val=1)) # Compute right hand side of Poisson equation f_hat = Function(T) f_hat = inner(v, fj, output_array=f_hat) # Get left hand side of Poisson equation A = inner(v, -div(grad(u))) u_hat = Function(T) sol = la.Solver2D(A, fixed_gauge=mean if T.use_fixed_gauge else None) u_hat = sol(f_hat, u_hat) uj = u_hat.backward() assert np.allclose(uj, ua), np.linalg.norm(uj - ua) print("Error=%2.16e" % (np.sqrt(dx((uj - ua)**2)))) if 'pytest' not in os.environ and plotting is True: import matplotlib.pyplot as plt X, Y = T.local_mesh(True) plt.contourf(X, Y, uj, 100) plt.colorbar() plt.figure() plt.contourf(X, Y, ua, 100) plt.colorbar() plt.figure() plt.contourf(X, Y, ua - uj, 100) plt.colorbar()