def test_vector_p1_3d(): meshc = UnitCubeMesh(MPI.comm_world, 2, 3, 4) meshf = UnitCubeMesh(MPI.comm_world, 3, 4, 5) Vc = VectorFunctionSpace(meshc, ("CG", 1)) Vf = VectorFunctionSpace(meshf, ("CG", 1)) def u(x): values0 = x[0] + 2.0 * x[1] values1 = 4.0 * x[0] values2 = 3.0 * x[2] + x[0] return np.stack([values0, values1, values2], axis=0) uc, uf = Function(Vc), Function(Vf) uc.interpolate(u) uf.interpolate(u) mat = PETScDMCollection.create_transfer_matrix(Vc._cpp_object, Vf._cpp_object) Vuc = Function(Vf) mat.mult(uc.vector, Vuc.vector) diff = Vuc.vector diff.axpy(-1, uf.vector) assert diff.norm() < 1.0e-12
def readin_fibers(self, fibarray, V_fib, dx_): # V_fib_input is function space the fiber vector is defined on (only CG1 or DG0 supported, add further depending on your input...) if list(self.fiber_data.keys())[0] == 'nodal': V_fib_input = VectorFunctionSpace(self.mesh, ("CG", 1)) elif list(self.fiber_data.keys())[0] == 'elemental': V_fib_input = VectorFunctionSpace(self.mesh, ("DG", 0)) else: raise AttributeError("Specify 'nodal' or 'elemental' for the fiber data input!") fib_func = [] fib_func_input = [] si = 0 for s in fibarray: fib_func_input.append(Function(V_fib_input, name='Fiber'+str(si+1)+'_input')) self.readfunction(fib_func_input[si], V_fib_input, list(self.fiber_data.values())[0][si], normalize=True) # project to output fiber function space ff = project(fib_func_input[si], V_fib, dx_, bcs=[], nm='fib_'+s+'') # assure that projected field still has unit length (not always necessarily the case) fib_func.append(ff / sqrt(dot(ff,ff))) ## write input fiber field for checking... #outfile = XDMFFile(self.comm, self.output_path+'/fiber'+str(si+1)+'_input.xdmf', 'w') #outfile.write_mesh(self.mesh) #outfile.write_function(fib_func_input[si]) si+=1 return fib_func
def xtest_tetrahedron_integral(space_type, space_order): domain = ufl.Mesh(ufl.VectorElement("Lagrange", "tetrahedron", 1)) temp_points = np.array([[-1., 0., -1.], [0., 0., 0.], [1., 0., 1.], [0., 1., 0.], [0., 0., 1.]]) for repeat in range(10): order = [i for i, j in enumerate(temp_points)] shuffle(order) points = np.zeros(temp_points.shape) for i, j in enumerate(order): points[j] = temp_points[i] cells = [] for cell in [[0, 1, 3, 4], [1, 2, 3, 4]]: # Randomly number the cell cell_order = list(range(4)) shuffle(cell_order) cells.append([order[cell[i]] for i in cell_order]) mesh = create_mesh(MPI.COMM_WORLD, cells, points, domain) V = FunctionSpace(mesh, (space_type, space_order)) Vvec = VectorFunctionSpace(mesh, ("P", 1)) dofs = [i for i in V.dofmap.cell_dofs(0) if i in V.dofmap.cell_dofs(1)] for d in dofs: v = Function(V) v.vector[:] = [1 if i == d else 0 for i in range(V.dim)] if space_type in ["RT", "BDM"]: # Hdiv def normal(x): values = np.zeros((3, x.shape[1])) values[0] = [1 for i in values[0]] return values n = Function(Vvec) n.interpolate(normal) form = ufl.inner(ufl.jump(v), n) * ufl.dS elif space_type in ["N1curl", "N2curl"]: # Hcurl def tangent1(x): values = np.zeros((3, x.shape[1])) values[1] = [1 for i in values[1]] return values def tangent2(x): values = np.zeros((3, x.shape[1])) values[2] = [1 for i in values[2]] return values t1 = Function(Vvec) t1.interpolate(tangent1) t2 = Function(Vvec) t2.interpolate(tangent1) form = ufl.inner(ufl.jump(v), t1) * ufl.dS form += ufl.inner(ufl.jump(v), t2) * ufl.dS else: form = ufl.jump(v) * ufl.dS value = fem.assemble_scalar(form) assert np.isclose(value, 0)
def test_save_3d_vector(tempdir, encoding, cell_type): filename = os.path.join(tempdir, "u_3Dv.xdmf") mesh = UnitCubeMesh(MPI.comm_world, 2, 2, 2, cell_type) u = Function(VectorFunctionSpace(mesh, ("Lagrange", 1))) u.vector.set(1.0 + (1j if has_petsc_complex else 0)) with XDMFFile(mesh.mpi_comm(), filename, encoding=encoding) as file: file.write(u)
def test_save_1d_vector(tempfile, file_options): mesh = UnitIntervalMesh(MPI.COMM_WORLD, 32) u = Function(VectorFunctionSpace(mesh, ("Lagrange", 2))) u.vector.set(1.0) VTKFile(tempfile + "u.pvd").write(u) for file_option in file_options: VTKFile(tempfile + "u.pvd", file_option).write(u)
def test_facet_normals(cell_type): """Test that FacetNormal is outward facing""" for count in range(5): mesh = unit_cell(cell_type) tdim = mesh.topology.dim V = VectorFunctionSpace(mesh, ("Lagrange", 1)) normal = FacetNormal(mesh) v = Function(V) map_f = mesh.topology.index_map(tdim - 1) num_facets = map_f.size_local + map_f.num_ghosts indices = np.arange(0, num_facets) values = np.arange(0, num_facets, dtype=np.intc) marker = MeshTags(mesh, tdim - 1, indices, values) # For each facet, check that the inner product of the normal and # the vector that has a positive normal component on only that facet # is positive for i in range(num_facets): if cell_type == CellType.interval: co = mesh.geometry.x[i] v.interpolate(lambda x: x[0] - co[0]) if cell_type == CellType.triangle: co = mesh.geometry.x[i] # Vector function that is zero at `co` and points away from `co` # so that there is no normal component on two edges and the integral # over the other edge is 1 v.interpolate(lambda x: ((x[0] - co[0]) / 2, (x[1] - co[1]) / 2)) elif cell_type == CellType.tetrahedron: co = mesh.geometry.x[i] # Vector function that is zero at `co` and points away from `co` # so that there is no normal component on three faces and the integral # over the other edge is 1 v.interpolate(lambda x: ((x[0] - co[0]) / 3, (x[1] - co[1]) / 3, (x[2] - co[2]) / 3)) elif cell_type == CellType.quadrilateral: # function that is 0 on one edge and points away from that edge # so that there is no normal component on three edges v.interpolate(lambda x: tuple(x[j] - i % 2 if j == i // 2 else 0 * x[j] for j in range(2))) elif cell_type == CellType.hexahedron: # function that is 0 on one face and points away from that face # so that there is no normal component on five faces v.interpolate(lambda x: tuple(x[j] - i % 2 if j == i // 3 else 0 * x[j] for j in range(3))) # assert that the integrals these functions dotted with the normal over a face # is 1 on one face and 0 on the others ones = 0 for j in range(num_facets): a = inner(v, normal) * ds(subdomain_data=marker, subdomain_id=j) result = fem.assemble_scalar(a) if np.isclose(result, 1): ones += 1 else: assert np.isclose(result, 0) assert ones == 1
def test_vector_interpolation(cell_type, order): """Test that interpolation is correct in a VectorFunctionSpace.""" mesh = one_cell_mesh(cell_type) tdim = mesh.topology.dim V = VectorFunctionSpace(mesh, ("Lagrange", order)) v = Function(V) if tdim == 1: def f(x): return x[0]**order elif tdim == 2: def f(x): return (x[1], 2 * x[0]**order) else: def f(x): return (x[1], 2 * x[0]**order, 3 * x[2]) v.interpolate(f) points = [random_point_in_cell(cell_type) for count in range(5)] cells = [0 for count in range(5)] values = v.eval(points, cells) for p, v in zip(points, values): assert np.allclose(f(p), v)
def test_nullspace_check(mesh, degree): V = VectorFunctionSpace(mesh, ('Lagrange', degree)) u, v = TrialFunction(V), TestFunction(V) E, nu = 2.0e2, 0.3 mu = E / (2.0 * (1.0 + nu)) lmbda = E * nu / ((1.0 + nu) * (1.0 - 2.0 * nu)) def sigma(w, gdim): return 2.0 * mu * ufl.sym(grad(w)) + lmbda * ufl.tr( grad(w)) * ufl.Identity(gdim) a = inner(sigma(u, mesh.geometry.dim), grad(v)) * dx # Assemble matrix and create compatible vector A = assemble_matrix(a) A.assemble() # Create null space basis and test null_space = build_elastic_nullspace(V) assert null_space.in_nullspace(A, tol=1.0e-8) null_space.orthonormalize() assert null_space.in_nullspace(A, tol=1.0e-8) # Create incorrect null space basis and test null_space = build_broken_elastic_nullspace(V) assert not null_space.in_nullspace(A, tol=1.0e-8) null_space.orthonormalize() assert not null_space.in_nullspace(A, tol=1.0e-8)
def xtest_quadrilateral_integral(space_type, space_order): domain = ufl.Mesh(ufl.VectorElement("Lagrange", "quadrilateral", 1)) temp_points = np.array([[-1., -1.], [0., 0.], [1., 0.], [-1., 1.], [0., 1.], [2., 2.]]) for repeat in range(10): order = [i for i, j in enumerate(temp_points)] shuffle(order) points = np.zeros(temp_points.shape) for i, j in enumerate(order): points[j] = temp_points[i] connections = {0: [1, 2], 1: [0, 3], 2: [0, 3], 3: [1, 2]} cells = [] for cell in [[0, 1, 3, 4], [1, 2, 4, 5]]: # Randomly number the cell start = choice(range(4)) cell_order = [start] for i in range(2): diff = choice([ i for i in connections[start] if i not in cell_order ]) - cell_order[0] cell_order += [c + diff for c in cell_order] cells.append([order[cell[i]] for i in cell_order]) mesh = create_mesh(MPI.COMM_WORLD, cells, points, domain) V = FunctionSpace(mesh, (space_type, space_order)) Vvec = VectorFunctionSpace(mesh, ("P", 1)) dofs = [i for i in V.dofmap.cell_dofs(0) if i in V.dofmap.cell_dofs(1)] for d in dofs: v = Function(V) v.vector[:] = [1 if i == d else 0 for i in range(V.dim)] if space_type in ["RTCF"]: # Hdiv def normal(x): values = np.zeros((2, x.shape[1])) values[0] = [1 for i in values[0]] return values n = Function(Vvec) n.interpolate(normal) form = ufl.inner(ufl.jump(v), n) * ufl.dS elif space_type in ["RTCE"]: # Hcurl def tangent(x): values = np.zeros((2, x.shape[1])) values[1] = [1 for i in values[1]] return values t = Function(Vvec) t.interpolate(tangent) form = ufl.inner(ufl.jump(v), t) * ufl.dS else: form = ufl.jump(v) * ufl.dS value = fem.assemble_scalar(form) assert np.isclose(value, 0)
def test_save_2d_vector(tempdir, encoding, cell_type): filename = os.path.join(tempdir, "u_2dv.xdmf") mesh = UnitSquareMesh(MPI.COMM_WORLD, 12, 13, cell_type) V = VectorFunctionSpace(mesh, ("Lagrange", 2)) u = Function(V) u.vector.set(1.0 + (1j if has_petsc_complex else 0)) with XDMFFile(mesh.mpi_comm(), filename, "w", encoding=encoding) as file: file.write_mesh(mesh) file.write_function(u)
def test_save_2d_vector(tempfile, file_options): mesh = UnitSquareMesh(MPI.comm_world, 16, 16) u = Function(VectorFunctionSpace(mesh, "Lagrange", 2)) u.vector.set(1) VTKFile(tempfile + "u.pvd").write(u) f = VTKFile(tempfile + "u.pvd") f.write(u, 0.) f.write(u, 1.) for file_option in file_options: VTKFile(tempfile + "u.pvd", file_option).write(u)
def test_save_3d_vector(tempfile, file_options): mesh = UnitCubeMesh(MPI.COMM_WORLD, 8, 8, 8) u = Function(VectorFunctionSpace(mesh, "Lagrange", 2)) u.vector.set(1) VTKFile(tempfile + "u.pvd").write(u) f = VTKFile(tempfile + "u.pvd") f.write(u, 0.) f.write(u, 1.) for file_option in file_options: VTKFile(tempfile + "u.pvd", file_option).write(u)
def test_nullspace_orthogonal(mesh, degree): """Test that null spaces orthogonalisation""" V = VectorFunctionSpace(mesh, ('Lagrange', degree)) null_space = build_elastic_nullspace(V) assert not null_space.is_orthogonal() assert not null_space.is_orthonormal() null_space.orthonormalize() assert null_space.is_orthogonal() assert null_space.is_orthonormal()
def test_entity_dofs(mesh): """Test that num entity dofs is correctly wrapped to dolfinx::DofMap""" V = FunctionSpace(mesh, ("CG", 1)) assert V.dofmap.dof_layout.num_entity_dofs(0) == 1 assert V.dofmap.dof_layout.num_entity_dofs(1) == 0 assert V.dofmap.dof_layout.num_entity_dofs(2) == 0 V = VectorFunctionSpace(mesh, ("CG", 1)) bs = V.dofmap.dof_layout.block_size() assert V.dofmap.dof_layout.num_entity_dofs(0) * bs == 2 assert V.dofmap.dof_layout.num_entity_dofs(1) * bs == 0 assert V.dofmap.dof_layout.num_entity_dofs(2) * bs == 0 V = FunctionSpace(mesh, ("CG", 2)) assert V.dofmap.dof_layout.num_entity_dofs(0) == 1 assert V.dofmap.dof_layout.num_entity_dofs(1) == 1 assert V.dofmap.dof_layout.num_entity_dofs(2) == 0 V = FunctionSpace(mesh, ("CG", 3)) assert V.dofmap.dof_layout.num_entity_dofs(0) == 1 assert V.dofmap.dof_layout.num_entity_dofs(1) == 2 assert V.dofmap.dof_layout.num_entity_dofs(2) == 1 V = FunctionSpace(mesh, ("DG", 0)) assert V.dofmap.dof_layout.num_entity_dofs(0) == 0 assert V.dofmap.dof_layout.num_entity_dofs(1) == 0 assert V.dofmap.dof_layout.num_entity_dofs(2) == 1 V = FunctionSpace(mesh, ("DG", 1)) assert V.dofmap.dof_layout.num_entity_dofs(0) == 0 assert V.dofmap.dof_layout.num_entity_dofs(1) == 0 assert V.dofmap.dof_layout.num_entity_dofs(2) == 3 V = VectorFunctionSpace(mesh, ("CG", 1)) bs = V.dofmap.dof_layout.block_size() for i, cdofs in enumerate([[0, 1], [2, 3], [4, 5]]): dofs = [ bs * d + b for d in V.dofmap.dof_layout.entity_dofs(0, i) for b in range(bs) ] assert all(d == cd for d, cd in zip(dofs, cdofs))
def test_entity_dofs(mesh): """Test that num entity dofs is correctly wrapped to dolfinx::DofMap""" V = FunctionSpace(mesh, ("CG", 1)) assert V.dofmap.dof_layout.num_entity_dofs(0) == 1 assert V.dofmap.dof_layout.num_entity_dofs(1) == 0 assert V.dofmap.dof_layout.num_entity_dofs(2) == 0 V = VectorFunctionSpace(mesh, ("CG", 1)) assert V.dofmap.dof_layout.num_entity_dofs(0) == 2 assert V.dofmap.dof_layout.num_entity_dofs(1) == 0 assert V.dofmap.dof_layout.num_entity_dofs(2) == 0 V = FunctionSpace(mesh, ("CG", 2)) assert V.dofmap.dof_layout.num_entity_dofs(0) == 1 assert V.dofmap.dof_layout.num_entity_dofs(1) == 1 assert V.dofmap.dof_layout.num_entity_dofs(2) == 0 V = FunctionSpace(mesh, ("CG", 3)) assert V.dofmap.dof_layout.num_entity_dofs(0) == 1 assert V.dofmap.dof_layout.num_entity_dofs(1) == 2 assert V.dofmap.dof_layout.num_entity_dofs(2) == 1 V = FunctionSpace(mesh, ("DG", 0)) assert V.dofmap.dof_layout.num_entity_dofs(0) == 0 assert V.dofmap.dof_layout.num_entity_dofs(1) == 0 assert V.dofmap.dof_layout.num_entity_dofs(2) == 1 V = FunctionSpace(mesh, ("DG", 1)) assert V.dofmap.dof_layout.num_entity_dofs(0) == 0 assert V.dofmap.dof_layout.num_entity_dofs(1) == 0 assert V.dofmap.dof_layout.num_entity_dofs(2) == 3 V = VectorFunctionSpace(mesh, ("CG", 1)) # Note this numbering is dependent on FFCX and can change This test # is here just to check that we get correct numbers mapped from ufc # generated code to dolfinx for i, cdofs in enumerate([[0, 3], [1, 4], [2, 5]]): dofs = V.dofmap.dof_layout.entity_dofs(0, i) assert all(d == cd for d, cd in zip(dofs, cdofs))
def test_vector_p2_2d(): meshc = UnitSquareMesh(MPI.comm_world, 5, 4) meshf = UnitSquareMesh(MPI.comm_world, 5, 8) Vc = VectorFunctionSpace(meshc, ("CG", 2)) Vf = VectorFunctionSpace(meshf, ("CG", 2)) def u(x): return np.stack([x[0] + 2.0 * x[1], 4.0 * x[0] * x[1]], axis=0) uc, uf = Function(Vc), Function(Vf) uc.interpolate(u) uf.interpolate(u) mat = PETScDMCollection.create_transfer_matrix(Vc._cpp_object, Vf._cpp_object) Vuc = Function(Vf) mat.mult(uc.vector, Vuc.vector) diff = Vuc.vector diff.axpy(-1, uf.vector) assert diff.norm() < 1.0e-12
def test_integral(cell_type, space_type, space_order): # TODO: Fix jump integrals in FFC by passing in full info for both cells, then re-enable these tests pytest.xfail() random.seed(4) for repeat in range(10): mesh = random_evaluation_mesh(cell_type) tdim = mesh.topology.dim V = FunctionSpace(mesh, (space_type, space_order)) Vvec = VectorFunctionSpace(mesh, ("P", 1)) dofs = [i for i in V.dofmap.cell_dofs(0) if i in V.dofmap.cell_dofs(1)] for d in dofs: v = Function(V) v.vector[:] = [1 if i == d else 0 for i in range(V.dim)] if space_type in ["RT", "BDM", "RTCF", "NCF"]: # Hdiv def normal(x): values = np.zeros((tdim, x.shape[1])) values[0] = [1 for i in values[0]] return values n = Function(Vvec) n.interpolate(normal) form = ufl.inner(ufl.jump(v), n) * ufl.dS elif space_type in ["N1curl", "N2curl", "RTCE", "NCE"]: # Hcurl def tangent(x): values = np.zeros((tdim, x.shape[1])) values[1] = [1 for i in values[1]] return values t = Function(Vvec) t.interpolate(tangent) form = ufl.inner(ufl.jump(v), t) * ufl.dS if tdim == 3: def tangent2(x): values = np.zeros((3, x.shape[1])) values[2] = [1 for i in values[2]] return values t2 = Function(Vvec) t2.interpolate(tangent2) form += ufl.inner(ufl.jump(v), t2) * ufl.dS else: form = ufl.jump(v) * ufl.dS value = fem.assemble_scalar(form) assert np.isclose(value, 0)
def test_save_3d_vector_series(tempdir, encoding, cell_type): filename = os.path.join(tempdir, "u_3D.xdmf") mesh = UnitCubeMesh(MPI.COMM_WORLD, 2, 2, 2, cell_type) u = Function(VectorFunctionSpace(mesh, ("Lagrange", 2))) with XDMFFile(mesh.mpi_comm(), filename, "w", encoding=encoding) as file: file.write_mesh(mesh) u.vector.set(1.0 + (1j if has_petsc_complex else 0)) file.write_function(u, 0.1) u.vector.set(2.0 + (2j if has_petsc_complex else 0)) file.write_function(u, 0.2) with XDMFFile(mesh.mpi_comm(), filename, "a", encoding=encoding) as file: u.vector.set(3.0 + (3j if has_petsc_complex else 0)) file.write_function(u, 0.3)
def test_argument_equality(mesh, V, V2, W, W2): """Placed this test here because it's mainly about detecting differing function spaces. """ mesh2 = UnitCubeMesh(MPI.COMM_WORLD, 8, 8, 8) V3 = FunctionSpace(mesh2, ('CG', 1)) W3 = VectorFunctionSpace(mesh2, ('CG', 1)) for TF in (TestFunction, TrialFunction): v = TF(V) v2 = TF(V2) v3 = TF(V3) assert v == v2 assert v2 == v assert V != V3 assert V2 != V3 assert not v == v3 assert not v2 == v3 assert v != v3 assert v2 != v3 assert v != v3 assert v2 != v3 w = TF(W) w2 = TF(W2) w3 = TF(W3) assert w == w2 assert w2 == w assert w != w3 assert w2 != w3 assert v != w assert w != v s1 = set((v, w)) s2 = set((v2, w2)) s3 = set((v, v2, w, w2)) assert len(s1) == 2 assert len(s2) == 2 assert len(s3) == 2 assert s1 == s2 assert s1 == s3 assert s2 == s3 # Test that the dolfinx implementation of Argument.__eq__ is # triggered when comparing ufl expressions assert grad(v) == grad(v2) assert grad(v) != grad(v3)
def test_manufactured_vector1(family, degree, filename, datadir): """Projection into H(div/curl) spaces""" with XDMFFile(MPI.COMM_WORLD, os.path.join(datadir, filename), "r", encoding=XDMFFile.Encoding.ASCII) as xdmf: mesh = xdmf.read_mesh(name="Grid") V = FunctionSpace(mesh, (family, degree)) W = VectorFunctionSpace(mesh, ("CG", degree)) u, v = ufl.TrialFunction(V), ufl.TestFunction(V) a = inner(u, v) * dx # Source term x = SpatialCoordinate(mesh) u_ref = x[0]**degree L = inner(u_ref, v[0]) * dx b = assemble_vector(L) b.ghostUpdate(addv=PETSc.InsertMode.ADD, mode=PETSc.ScatterMode.REVERSE) A = assemble_matrix(a) A.assemble() # Create LU linear solver (Note: need to use a solver that # re-orders to handle pivots, e.g. not the PETSc built-in LU # solver) solver = PETSc.KSP().create(MPI.COMM_WORLD) solver.setType("preonly") solver.getPC().setType('lu') solver.setOperators(A) # Solve uh = Function(V) solver.solve(b, uh.vector) uh.vector.ghostUpdate(addv=PETSc.InsertMode.INSERT, mode=PETSc.ScatterMode.FORWARD) u_exact = Function(W) u_exact.interpolate(lambda x: np.array([ x[0]**degree if i == 0 else 0 * x[0] for i in range(mesh.topology.dim) ])) M = inner(uh - u_exact, uh - u_exact) * dx M = fem.Form(M) error = mesh.mpi_comm().allreduce(assemble_scalar(M), op=MPI.SUM) assert np.absolute(error) < 1.0e-14
def test_save_2d_vector(tempdir, cell_type): mesh = UnitSquareMesh(MPI.COMM_WORLD, 16, 16, cell_type=cell_type) u = Function(VectorFunctionSpace(mesh, ("Lagrange", 1))) def f(x): vals = np.zeros((2, x.shape[1])) vals[0] = x[0] vals[1] = 2 * x[0] * x[1] return vals u.interpolate(f) u.vector.ghostUpdate(addv=PETSc.InsertMode.INSERT, mode=PETSc.ScatterMode.FORWARD) filename = os.path.join(tempdir, "u.pvd") with VTKFile(MPI.COMM_WORLD, filename, "w") as vtk: vtk.write_function(u, 0.)
def xtest_read_write_p2_function(tempdir): mesh = cpp.generation.UnitDiscMesh.create(MPI.comm_world, 3, cpp.mesh.GhostMode.none) gdim = mesh.geometry.dim cmap = fem.create_coordinate_map(mesh.ufl_domain()) mesh.geometry.coord_mapping = cmap Q = FunctionSpace(mesh, ("Lagrange", 2)) F = Function(Q) if has_petsc_complex: def expr_eval(x): return x[0] + 1.0j * x[0] F.interpolate(expr_eval) else: def expr_eval(x): return x[0] F.interpolate(expr_eval) filename = os.path.join(tempdir, "tri6_function.xdmf") with XDMFFile(mesh.mpi_comm(), filename, encoding=XDMFFile.Encoding.HDF5) as xdmf: xdmf.write(F) Q = VectorFunctionSpace(mesh, ("Lagrange", 1)) F = Function(Q) if has_petsc_complex: def expr_eval(x): return x[:gdim] + 1.0j * x[:gdim] F.interpolate(expr_eval) else: def expr_eval(x): return x[:gdim] F.interpolate(expr_eval) filename = os.path.join(tempdir, "tri6_vector_function.xdmf") with XDMFFile(mesh.mpi_comm(), filename, encoding=XDMFFile.Encoding.HDF5) as xdmf: xdmf.write(F)
def test_clear_sub_map_data_scalar(mesh): V = FunctionSpace(mesh, ("CG", 2)) with pytest.raises(ValueError): V.sub(1) V = VectorFunctionSpace(mesh, ("CG", 2)) V1 = V.sub(1) assert (V1) # Clean sub-map data V.dofmap.clear_sub_map_data() # Can still get previously computed map V1 = V.sub(1) # New sub-map should throw an error with pytest.raises(RuntimeError): V.sub(0)
def test_save_2d_vector_CG2(tempdir): points = np.array([[0, 0], [1, 0], [1, 2], [0, 2], [1 / 2, 0], [1, 2 / 2], [1 / 2, 2], [0, 2 / 2], [1 / 2, 2 / 2]]) points = np.array([[0, 0], [1, 0], [0, 2], [0.5, 1], [0, 1], [0.5, 0], [1, 2], [0.5, 2], [1, 1]]) cells = np.array([[0, 1, 2, 3, 4, 5], [1, 6, 2, 7, 3, 8]]) domain = ufl.Mesh(ufl.VectorElement("Lagrange", "triangle", 2)) mesh = create_mesh(MPI.COMM_WORLD, cells, points, domain) u = Function(VectorFunctionSpace(mesh, ("Lagrange", 2))) def func(x): vals = np.zeros((2, x.shape[1])) vals[0] = x[0] vals[1] = x[1] return vals u.interpolate(func) filename = os.path.join(tempdir, "u.pvd") with VTKFile(mesh.mpi_comm(), filename, "w") as vtk: vtk.write_function(u, 0.)
def test_block_size(mesh): meshes = [ UnitSquareMesh(8, 8), UnitCubeMesh(4, 4, 4), UnitSquareMesh(8, 8, CellType.quadrilateral), UnitCubeMesh(4, 4, 4, CellType.hexahedron) ] for mesh in meshes: P2 = FiniteElement("Lagrange", mesh.ufl_cell(), 2) V = FunctionSpace(mesh, P2) assert V.dofmap.block_size == 1 V = FunctionSpace(mesh, P2 * P2) assert V.dofmap.index_map.block_size == 2 for i in range(1, 6): W = FunctionSpace(mesh, MixedElement(i * [P2])) assert W.dofmap.index_map.block_size == i V = VectorFunctionSpace(mesh, ("Lagrange", 2)) assert V.dofmap.index_map.block_size == mesh.geometry.dim
def test_vector_P_simplex(family, degree, cell_type, datadir): if cell_type == CellType.tetrahedron and degree == 4: pytest.skip("Skip expensive test on tetrahedron") mesh = get_mesh(cell_type, datadir) V = VectorFunctionSpace(mesh, (family, degree)) run_vector_test(mesh, V, degree)
def test_vector_P_tp(family, degree, cell_type, datadir): mesh = get_mesh(cell_type, datadir) V = VectorFunctionSpace(mesh, (family, degree)) run_vector_test(mesh, V, degree)
def amg_solve(N, method): # Elasticity parameters E = 1.0e9 nu = 0.3 mu = E / (2.0 * (1.0 + nu)) lmbda = E * nu / ((1.0 + nu) * (1.0 - 2.0 * nu)) # Stress computation def sigma(v): return 2.0 * mu * sym(grad(v)) + lmbda * tr(sym( grad(v))) * Identity(2) # Define problem mesh = UnitSquareMesh(MPI.COMM_WORLD, N, N) V = VectorFunctionSpace(mesh, 'Lagrange', 1) bc0 = Function(V) with bc0.vector.localForm() as bc_local: bc_local.set(0.0) def boundary(x): return np.full(x.shape[1], True) facetdim = mesh.topology.dim - 1 bndry_facets = locate_entities_boundary(mesh, facetdim, boundary) bdofs = locate_dofs_topological(V.sub(0), V, facetdim, bndry_facets) bc = DirichletBC(bc0, bdofs, V.sub(0)) u = TrialFunction(V) v = TestFunction(V) # Forms a, L = inner(sigma(u), grad(v)) * dx, dot(ufl.as_vector( (1.0, 1.0)), v) * dx # Assemble linear algebra objects A = assemble_matrix(a, [bc]) A.assemble() b = assemble_vector(L) apply_lifting(b, [a], [[bc]]) b.ghostUpdate(addv=PETSc.InsertMode.ADD, mode=PETSc.ScatterMode.REVERSE) set_bc(b, [bc]) # Create solution function u = Function(V) # Create near null space basis and orthonormalize null_space = build_nullspace(V, u.vector) # Attached near-null space to matrix A.set_near_nullspace(null_space) # Test that basis is orthonormal assert null_space.is_orthonormal() # Create PETSC smoothed aggregation AMG preconditioner, and # create CG solver solver = PETSc.KSP().create(mesh.mpi_comm) solver.setType("cg") # Set matrix operator solver.setOperators(A) # Compute solution and return number of iterations return solver.solve(b, u.vector)
# Elasticity parameters E = 1.0e9 nu = 0.0 mu = E / (2.0 * (1.0 + nu)) lmbda = E * nu / ((1.0 + nu) * (1.0 - 2.0 * nu)) # Stress computation def sigma(v): return 2.0 * mu * sym(grad(v)) + lmbda * tr(sym(grad(v))) * Identity( len(v)) # Create function space V = VectorFunctionSpace(mesh, ("Lagrange", 1)) # Define variational problem u = TrialFunction(V) v = TestFunction(V) a = inner(sigma(u), grad(v)) * dx L = inner(f, v) * dx u0 = Function(V) with u0.vector.localForm() as bc_local: bc_local.set(0.0) # Set up boundary condition on inner surface bc = DirichletBC(u0, locate_dofs_geometrical(V, boundary)) # Assemble system, applying boundary conditions and preserving symmetry)
def W(mesh): return VectorFunctionSpace(mesh, ('CG', 1))