def test_entity_closure_dofs(mesh_factory): func, args = mesh_factory mesh = func(*args) tdim = mesh.topology.dim for degree in (1, 2, 3): V = FunctionSpace(mesh, ("CG", degree)) for d in range(tdim + 1): map = mesh.topology.index_map(d) num_entities = map.size_local + map.num_ghosts covered = set() covered2 = set() all_entities = np.array([entity for entity in range(num_entities)], dtype=np.uintp) for entity in all_entities: entities = np.array([entity], dtype=np.uintp) dofs_on_this_entity = V.dofmap.entity_dofs(mesh, d, entities) closure_dofs = V.dofmap.entity_closure_dofs( mesh, d, entities) assert len(dofs_on_this_entity) == V.dofmap.dof_layout.num_entity_dofs(d) assert len(dofs_on_this_entity) <= len(closure_dofs) covered.update(dofs_on_this_entity) covered2.update(closure_dofs) dofs_on_all_entities = V.dofmap.entity_dofs( mesh, d, all_entities) closure_dofs_on_all_entities = V.dofmap.entity_closure_dofs( mesh, d, all_entities) assert len(dofs_on_all_entities) == V.dofmap.dof_layout.num_entity_dofs(d) * num_entities assert covered == set(dofs_on_all_entities) assert covered2 == set(closure_dofs_on_all_entities) d = tdim map = mesh.topology.index_map(d) num_entities = map.size_local + map.num_ghosts all_cells = np.array([entity for entity in range(num_entities)], dtype=np.uintp) assert set(V.dofmap.entity_closure_dofs(mesh, d, all_cells)) == set(range(V.dim))
def test_higher_order_coordinate_map(points, celltype, order): """Computes physical coordinates of a cell, based on the coordinate map.""" cells = np.array([range(len(points))]) mesh = Mesh(MPI.COMM_WORLD, celltype, points, cells, [], degree=order) V = FunctionSpace(mesh, ("Lagrange", 2)) X = V.element.dof_reference_coordinates() coord_dofs = mesh.geometry.dofmap x_g = mesh.geometry.x cmap = fem.create_coordinate_map(mesh.ufl_domain()) x_coord_new = np.zeros([len(points), mesh.geometry.dim]) i = 0 for node in range(len(points)): x_coord_new[i] = x_g[coord_dofs.links(0)[node], :mesh.geometry.dim] i += 1 x = np.zeros(X.shape) cmap.push_forward(x, X, x_coord_new) assert(np.allclose(x[:, 0], X[:, 0])) assert(np.allclose(x[:, 1], 2 * X[:, 1])) if mesh.geometry.dim == 3: assert(np.allclose(x[:, 2], 3 * X[:, 2]))
def test_mixed_element(ElementType, space, cell, order): if cell == ufl.triangle: mesh = UnitSquareMesh(MPI.COMM_WORLD, 1, 1, CellType.triangle, dolfinx.cpp.mesh.GhostMode.shared_facet) else: mesh = UnitCubeMesh(MPI.COMM_WORLD, 1, 1, 1, CellType.tetrahedron, dolfinx.cpp.mesh.GhostMode.shared_facet) norms = [] U_el = ufl.FiniteElement(space, cell, order) for i in range(3): U = FunctionSpace(mesh, U_el) u = ufl.TrialFunction(U) v = ufl.TestFunction(U) a = ufl.inner(u, v) * ufl.dx A = dolfinx.fem.assemble_matrix(a) A.assemble() norms.append(A.norm()) U_el = ufl.MixedElement(U_el) for i in norms[1:]: assert np.isclose(norms[0], i)
def test_scatter_reverse(element): comm = MPI.COMM_WORLD mesh = UnitSquareMesh(MPI.COMM_WORLD, 5, 5) V = FunctionSpace(mesh, element) u = Function(V) bs = V.dofmap.bs u.interpolate(lambda x: [x[i] for i in range(bs)]) # Reverse scatter (insert) should have no effect w0 = u.x.array.copy() cpp.la.scatter_reverse(u.x, cpp.common.ScatterMode.insert) assert np.allclose(w0, u.x.array) # Fill with MPI rank, and sum all entries in the vector (including ghosts) u.x.array.fill(comm.rank) all_count0 = MPI.COMM_WORLD.allreduce(u.x.array.sum(), op=MPI.SUM) # Reverse scatter (add) cpp.la.scatter_reverse(u.x, cpp.common.ScatterMode.add) num_ghosts = V.dofmap.index_map.num_ghosts ghost_count = MPI.COMM_WORLD.allreduce(num_ghosts * comm.rank, op=MPI.SUM) # New count should have gone up by the number of ghosts times their rank # on all processes all_count1 = MPI.COMM_WORLD.allreduce(u.x.array.sum(), op=MPI.SUM) assert all_count1 == (all_count0 + bs * ghost_count)
def test_higher_order_coordinate_map(points, celltype): """ Computes physical coordinates of a cell, based on the coordinate map. """ cells = np.array([range(len(points))]) mesh = Mesh(MPI.comm_world, celltype, points, cells, [], GhostMode.none) V = FunctionSpace(mesh, ("Lagrange", mesh.degree())) X = V.element.dof_reference_coordinates() coord_dofs = mesh.coordinate_dofs().entity_points() x_g = mesh.geometry.points cmap = fem.create_coordinate_map(mesh.ufl_domain()) x_coord_new = np.zeros([len(points), mesh.geometry.dim]) i = 0 for node in range(len(points)): x_coord_new[i] = x_g[coord_dofs[0, node], :mesh.geometry.dim] i += 1 x = np.zeros(X.shape) cmap.push_forward(x, X, x_coord_new) assert (np.allclose(x[:, 0], X[:, 0])) assert (np.allclose(x[:, 1], 2 * X[:, 1])) if mesh.geometry.dim == 3: assert (np.allclose(x[:, 2], 3 * X[:, 2]))
def test_higher_order_coordinate_map(points, celltype, order): """Computes physical coordinates of a cell, based on the coordinate map.""" print(celltype) cells = np.array([range(len(points))]) domain = ufl.Mesh( ufl.VectorElement("Lagrange", cpp.mesh.to_string(celltype), order)) mesh = create_mesh(MPI.COMM_WORLD, cells, points, domain) V = FunctionSpace(mesh, ("Lagrange", 2)) X = V.element.interpolation_points() coord_dofs = mesh.geometry.dofmap x_g = mesh.geometry.x cmap = fem.create_coordinate_map(mesh.mpi_comm(), mesh.ufl_domain()) x_coord_new = np.zeros([len(points), mesh.geometry.dim]) i = 0 for node in range(len(points)): x_coord_new[i] = x_g[coord_dofs.links(0)[node], :mesh.geometry.dim] i += 1 x = cmap.push_forward(X, x_coord_new) assert np.allclose(x[:, 0], X[:, 0]) assert np.allclose(x[:, 1], 2 * X[:, 1]) if mesh.geometry.dim == 3: assert np.allclose(x[:, 2], 3 * X[:, 2])
def test_facet_integral(cell_type): """Test that the integral of a function over a facet is correct""" for count in range(5): mesh = unit_cell(cell_type) tdim = mesh.topology.dim V = FunctionSpace(mesh, ("Lagrange", 2)) 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) # Functions that will have the same integral over each facet if cell_type == CellType.triangle: root = 3 ** 0.25 # 4th root of 3 v.interpolate(lambda x: (x[0] - 1 / root) ** 2 + (x[1] - root / 3) ** 2) elif cell_type == CellType.quadrilateral: v.interpolate(lambda x: x[0] * (1 - x[0]) + x[1] * (1 - x[1])) elif cell_type == CellType.tetrahedron: s = 2 ** 0.5 * 3 ** (1 / 3) # side length v.interpolate(lambda x: (x[0] - s / 2) ** 2 + (x[1] - s / 2 / np.sqrt(3)) ** 2 + (x[2] - s * np.sqrt(2 / 3) / 4) ** 2) elif cell_type == CellType.hexahedron: v.interpolate(lambda x: x[0] * (1 - x[0]) + x[1] * (1 - x[1]) + x[2] * (1 - x[2])) # assert that the integral of these functions over each face are equal out = [] for j in range(num_facets): a = v * ds(subdomain_data=marker, subdomain_id=j) result = fem.assemble_scalar(a) out.append(result) assert np.isclose(result, out[0])
def test_krylov_solver_lu(): mesh = UnitSquareMesh(MPI.COMM_WORLD, 12, 12) V = FunctionSpace(mesh, ("Lagrange", 1)) u, v = TrialFunction(V), TestFunction(V) a = inner(u, v) * dx L = inner(1.0, v) * dx A = assemble_matrix(a) A.assemble() b = assemble_vector(L) b.ghostUpdate(addv=PETSc.InsertMode.ADD, mode=PETSc.ScatterMode.REVERSE) norm = 13.0 solver = PETSc.KSP().create(mesh.mpi_comm()) solver.setOptionsPrefix("test_lu_") opts = PETSc.Options("test_lu_") opts["ksp_type"] = "preonly" opts["pc_type"] = "lu" solver.setFromOptions() x = A.createVecRight() solver.setOperators(A) solver.solve(b, x) # *Tight* tolerance for LU solves assert x.norm(PETSc.NormType.N2) == pytest.approx(norm, abs=1.0e-12)
def test_scatter_forward(element): mesh = UnitSquareMesh(MPI.COMM_WORLD, 5, 5) V = FunctionSpace(mesh, element) u = Function(V) bs = V.dofmap.bs u.interpolate(lambda x: [x[i] for i in range(bs)]) # Forward scatter should have no effect w0 = u.x.array.copy() cpp.la.scatter_forward(u.x) assert np.allclose(w0, u.x.array) # Fill local array with the mpi rank u.x.array.fill(MPI.COMM_WORLD.rank) w0 = u.x.array.copy() cpp.la.scatter_forward(u.x) # Now the ghosts should have the value of the rank of # the owning process ghost_owners = u.function_space.dofmap.index_map.ghost_owner_rank() ghost_owners = np.repeat(ghost_owners, bs) local_size = u.function_space.dofmap.index_map.size_local * bs assert np.allclose(u.x.array[local_size:], ghost_owners)
def test_P_simplex_built_in(family, degree, cell_type, datadir): if cell_type == CellType.tetrahedron: mesh = UnitCubeMesh(MPI.COMM_WORLD, 5, 5, 5) elif cell_type == CellType.triangle: mesh = UnitSquareMesh(MPI.COMM_WORLD, 5, 5) V = FunctionSpace(mesh, (family, degree)) run_scalar_test(mesh, V, degree)
def test_save_and_read_function(tempdir): filename = os.path.join(tempdir, "function.h5") mesh = UnitSquareMesh(MPI.comm_world, 10, 10) Q = FunctionSpace(mesh, ("CG", 3)) F0 = Function(Q) F1 = Function(Q) def E(x): return x[0] F0.interpolate(E) # Save to HDF5 File hdf5_file = HDF5File(mesh.mpi_comm(), filename, "w") hdf5_file.write(F0, "/function") hdf5_file.close() # Read back from file hdf5_file = HDF5File(mesh.mpi_comm(), filename, "r") F1 = hdf5_file.read_function(Q, "/function") F0.vector.axpy(-1.0, F1.vector) assert F0.vector.norm() < 1.0e-12 hdf5_file.close()
def test_save_2d_mixed(tempdir): mesh = UnitCubeMesh(MPI.COMM_WORLD, 3, 3, 3) P2 = ufl.VectorElement("Lagrange", mesh.ufl_cell(), 2) P1 = ufl.FiniteElement("Lagrange", mesh.ufl_cell(), 1) TH = P2 * P1 W = FunctionSpace(mesh, TH) def vec_func(x): vals = np.zeros((3, x.shape[1])) vals[0] = x[0] vals[1] = 0.2 * x[1] return vals def scal_func(x): return 0.5 * x[0] U = Function(W) U.sub(0).interpolate(vec_func) U.sub(1).interpolate(scal_func) U.vector.ghostUpdate(addv=PETSc.InsertMode.INSERT, mode=PETSc.ScatterMode.FORWARD) filename = os.path.join(tempdir, "u.pvd") with VTKFile(mesh.mpi_comm(), filename, "w") as vtk: vtk.write_function([U.sub(i) for i in range(W.num_sub_spaces())], 0.)
def test_incompatible_spaces(): """Test that error is thrown when function spaces are not compatible""" mesh = UnitSquareMesh(MPI.COMM_WORLD, 13, 7) V = FunctionSpace(mesh, ("Lagrange", 1)) W = FunctionSpace(mesh, ("Nedelec 1st kind H(curl)", 1)) with pytest.raises(RuntimeError): create_discrete_gradient(V._cpp_object, W._cpp_object) with pytest.raises(RuntimeError): create_discrete_gradient(V._cpp_object, V._cpp_object) with pytest.raises(RuntimeError): create_discrete_gradient(W._cpp_object, W._cpp_object) V = FunctionSpace(mesh, ("Lagrange", 2)) with pytest.raises(RuntimeError): create_discrete_gradient(W._cpp_object, V._cpp_object)
def test_scalar_interpolation(cell_type, order): """Test that interpolation is correct in a FunctionSpace""" mesh = one_cell_mesh(cell_type) tdim = mesh.topology.dim V = FunctionSpace(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]**order + 2 * x[0] else: def f(x): return x[1]**order + 2 * x[0] - 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(v, f(p))
def test_mixed_interpolation(cell_type, order): """Test that interpolation is correct in a MixedElement.""" mesh = one_cell_mesh(cell_type) tdim = mesh.topology.dim A = ufl.FiniteElement("Lagrange", mesh.ufl_cell(), order) B = ufl.VectorElement("Lagrange", mesh.ufl_cell(), order) V = FunctionSpace(mesh, ufl.MixedElement([A, B])) v = Function(V) if tdim == 1: def f(x): return (x[0]**order, 2 * x[0]) elif tdim == 2: def f(x): return (x[1], 2 * x[0]**order, 3 * x[1]) else: def f(x): return (x[1], 2 * x[0]**order, 3 * x[2], 4 * x[0]) 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(v, f(p))
def test_plus_minus_vector(cell_type, pm1, pm2): """Test that ('+') and ('-') match up with the correct DOFs for DG functions""" results = [] orders = [] spaces = [] for count in range(3): for agree in [True, False]: # Two cell mesh with randomly numbered points mesh, order = two_unit_cells(cell_type, agree, return_order=True) if cell_type in [CellType.interval, CellType.triangle, CellType.tetrahedron]: V = FunctionSpace(mesh, ("DG", 1)) else: V = FunctionSpace(mesh, ("DQ", 1)) # Assemble vectors with combinations of + and - for a few different numberings f = Function(V) f.interpolate(lambda x: x[0] - 2 * x[1]) v = TestFunction(V) a = inner(f(pm1), v(pm2)) * dS result = fem.assemble_vector(a) result.assemble() spaces.append(V) results.append(result) orders.append(order) # Check that the above vectors all have the same values as the first one, # but permuted due to differently ordered dofs dofmap0 = spaces[0].mesh.geometry.dofmap for result, space in zip(results[1:], spaces[1:]): # Get the data relating to two results dofmap1 = space.mesh.geometry.dofmap # For each cell for cell in range(2): # For each point in cell 0 in the the first mesh for dof0, point0 in zip(spaces[0].dofmap.cell_dofs(cell), dofmap0.links(cell)): # Find the point in the cell 0 in the second mesh for dof1, point1 in zip(space.dofmap.cell_dofs(cell), dofmap1.links(cell)): if np.allclose(spaces[0].mesh.geometry.x[point0], space.mesh.geometry.x[point1]): break else: # If no matching point found, fail assert False assert np.isclose(results[0][dof0], result[dof1])
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_quadrilateral_dof_positions(space_type): """Checks that dofs on shared quadrilateral edges match up""" domain = ufl.Mesh(ufl.VectorElement("Lagrange", "quadrilateral", 1)) if MPI.COMM_WORLD.rank == 0: # Create a quadrilateral mesh N = 6 temp_points = np.array([[x / 2, y / 2] for x in range(N) for y in range(N)]) 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 x in range(N - 1): for y in range(N - 1): a = N * y + x cell = [order[i] for i in [a, a + 1, a + N, a + N + 1]] cells.append(cell) # On process 0, input mesh data and distribute to other # processes mesh = create_mesh(MPI.COMM_WORLD, cells, points, domain) else: mesh = create_mesh(MPI.COMM_WORLD, np.ndarray((0, 4)), np.ndarray((0, 2)), domain) V = FunctionSpace(mesh, space_type) dofmap = V.dofmap edges = {} # Get coordinates of dofs and edges and check that they are the same # for each global dof number X = V.element.dof_reference_coordinates() coord_dofs = mesh.geometry.dofmap x_g = mesh.geometry.x cmap = fem.create_coordinate_map(mesh.ufl_domain()) for cell_n in range(coord_dofs.num_nodes): dofs = dofmap.cell_dofs(cell_n) x_coord_new = np.zeros([4, 2]) for v in range(4): x_coord_new[v] = x_g[coord_dofs.links(cell_n)[v], :2] x = X.copy() cmap.push_forward(x, X, x_coord_new) edge_dofs_local = [] for i in range(4): edge_dofs_local += list(dofmap.dof_layout.entity_dofs(1, i)) edge_dofs = [dofs[i] for i in edge_dofs_local] for i, j in zip(edge_dofs, x[edge_dofs_local]): if i in edges: assert np.allclose(j, edges[i]) else: edges[i] = j
def test_fourth_order_quad(L, H, Z): """Test by comparing integration of z+x*y against sympy/scipy integration of a quad element. Z>0 implies curved element. *---------* 20-21-22-23-24-41--42--43--44 | | | | | | | 15 16 17 18 19 37 38 39 40 | | | | | | | 10 11 12 13 14 33 34 35 36 | | | | | | | 5 6 7 8 9 29 30 31 32 | | | | | *---------* 0--1--2--3--4--25--26--27--28 """ points = np.array([[0, 0, 0], [L / 4, 0, 0], [L / 2, 0, 0], # 0 1 2 [3 * L / 4, 0, 0], [L, 0, 0], # 3 4 [0, H / 4, -Z / 3], [L / 4, H / 4, -Z / 3], [L / 2, H / 4, -Z / 3], # 5 6 7 [3 * L / 4, H / 4, -Z / 3], [L, H / 4, -Z / 3], # 8 9 [0, H / 2, 0], [L / 4, H / 2, 0], [L / 2, H / 2, 0], # 10 11 12 [3 * L / 4, H / 2, 0], [L, H / 2, 0], # 13 14 [0, (3 / 4) * H, 0], [L / 4, (3 / 4) * H, 0], # 15 16 [L / 2, (3 / 4) * H, 0], [3 * L / 4, (3 / 4) * H, 0], # 17 18 [L, (3 / 4) * H, 0], [0, H, Z], [L / 4, H, Z], # 19 20 21 [L / 2, H, Z], [3 * L / 4, H, Z], [L, H, Z], # 22 23 24 [(5 / 4) * L, 0, 0], [(6 / 4) * L, 0, 0], # 25 26 [(7 / 4) * L, 0, 0], [2 * L, 0, 0], # 27 28 [(5 / 4) * L, H / 4, -Z / 3], [(6 / 4) * L, H / 4, -Z / 3], # 29 30 [(7 / 4) * L, H / 4, -Z / 3], [2 * L, H / 4, -Z / 3], # 31 32 [(5 / 4) * L, H / 2, 0], [(6 / 4) * L, H / 2, 0], # 33 34 [(7 / 4) * L, H / 2, 0], [2 * L, H / 2, 0], # 35 36 [(5 / 4) * L, 3 / 4 * H, 0], # 37 [(6 / 4) * L, 3 / 4 * H, 0], # 38 [(7 / 4) * L, 3 / 4 * H, 0], [2 * L, 3 / 4 * H, 0], # 39 40 [(5 / 4) * L, H, Z], [(6 / 4) * L, H, Z], # 41 42 [(7 / 4) * L, H, Z], [2 * L, H, Z]]) # 43 44 # VTK ordering cells = np.array([[0, 4, 24, 20, 1, 2, 3, 9, 14, 19, 21, 22, 23, 5, 10, 15, 6, 7, 8, 11, 12, 13, 16, 17, 18], [4, 28, 44, 24, 25, 26, 27, 32, 36, 40, 41, 42, 43, 9, 14, 19, 29, 30, 31, 33, 34, 35, 37, 38, 39]]) cells = cells[:, perm_vtk(CellType.quadrilateral, cells.shape[1])] cell = ufl.Cell("quadrilateral", geometric_dimension=points.shape[1]) domain = ufl.Mesh(ufl.VectorElement("Lagrange", cell, 4)) mesh = create_mesh(MPI.COMM_WORLD, cells, points, domain) def e2(x): return x[2] + x[0] * x[1] V = FunctionSpace(mesh, ("CG", 4)) u = Function(V) u.interpolate(e2) intu = assemble_scalar(u * dx(mesh)) intu = mesh.mpi_comm().allreduce(intu, op=MPI.SUM) nodes = [0, 5, 10, 15, 20] ref = sympy_scipy(points, nodes, 2 * L, H) assert ref == pytest.approx(intu, rel=1e-5)
def test_mixed_interpolation(): """Test that interpolation raised an exception.""" mesh = one_cell_mesh(CellType.triangle) A = ufl.FiniteElement("Lagrange", mesh.ufl_cell(), 1) B = ufl.VectorElement("Lagrange", mesh.ufl_cell(), 1) v = Function(FunctionSpace(mesh, ufl.MixedElement([A, B]))) with pytest.raises(RuntimeError): v.interpolate(lambda x: (x[1], 2 * x[0], 3 * x[1]))
def test_save_3d_scalar(tempdir, encoding, cell_type): filename = os.path.join(tempdir, "u3.xdmf") mesh = UnitCubeMesh(MPI.comm_world, 4, 4, 4, cell_type) V = FunctionSpace(mesh, ("Lagrange", 2)) u = Function(V) 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_P_tp_built_in_mesh(family, degree, cell_type, datadir): if cell_type == CellType.hexahedron: mesh = UnitCubeMesh(MPI.COMM_WORLD, 5, 5, 5, cell_type) elif cell_type == CellType.quadrilateral: mesh = UnitSquareMesh(MPI.COMM_WORLD, 5, 5, cell_type) mesh = get_mesh(cell_type, datadir) V = FunctionSpace(mesh, (family, degree)) run_scalar_test(mesh, V, degree)
def test_coefficient(): mesh = UnitSquareMesh(MPI.COMM_WORLD, 13, 13) V = FunctionSpace(mesh, ("Lagrange", 1)) DG0 = FunctionSpace(mesh, ("DG", 0)) vals = Function(DG0) vals.vector.set(2.0) L = cpp.fem.Form([V._cpp_object]) L.set_tabulate_tensor(IntegralType.cell, -1, tabulate_tensor_b_coeff.address) L.set_coefficient(0, vals._cpp_object) b = dolfinx.fem.assemble_vector(L) b.ghostUpdate(addv=PETSc.InsertMode.ADD, mode=PETSc.ScatterMode.REVERSE) bnorm = b.norm(PETSc.NormType.N2) print(bnorm) assert (np.isclose(bnorm, 2.0 * 0.0739710713711999))
def test_tabulate_all_coordinates(mesh_factory): func, args = mesh_factory mesh = func(*args) V = FunctionSpace(mesh, ("Lagrange", 1)) W0 = FiniteElement("Lagrange", mesh.ufl_cell(), 1) W1 = VectorElement("Lagrange", mesh.ufl_cell(), 1) W = FunctionSpace(mesh, W0 * W1) D = mesh.geometry.dim V_dofmap = V.dofmap W_dofmap = W.dofmap all_coords_V = V.tabulate_dof_coordinates() all_coords_W = W.tabulate_dof_coordinates() local_size_V = V_dofmap().index_map.size_local * V_dofmap().index_map.block_size local_size_W = W_dofmap().index_map.size_local * W_dofmap().index_map.block_size all_coords_V = all_coords_V.reshape(local_size_V, D) all_coords_W = all_coords_W.reshape(local_size_W, D) checked_V = [False] * local_size_V checked_W = [False] * local_size_W # Check that all coordinates are within the cell it should be map = mesh.topology.index_map(mesh.topology.dim) num_cells = map.size_local + map.num_ghosts for c in range(num_cells): cell = MeshEntity(mesh, mesh.topology.dim, c) dofs_V = V_dofmap.cell_dofs(c) for di in dofs_V: if di >= local_size_V: continue assert cell.contains(all_coords_V[di]) checked_V[di] = True dofs_W = W_dofmap.cell_dofs(c) for di in dofs_W: if di >= local_size_W: continue assert cell.contains(all_coords_W[di]) checked_W[di] = True # Assert that all dofs have been checked by the above assert all(checked_V) assert all(checked_W)
def test_RefineUnitCubeMesh_keep_partition(): """Refine mesh of unit cube.""" mesh = UnitCubeMesh(MPI.COMM_WORLD, 5, 7, 9, ghost_mode=GhostMode.none) mesh.topology.create_entities(1) mesh = refine(mesh, redistribute=False) assert mesh.topology.index_map(0).size_global == 3135 assert mesh.topology.index_map(3).size_global == 15120 Q = FunctionSpace(mesh, ("CG", 1)) assert (Q)
def test_save_2d_scalar(tempdir, encoding, cell_type): filename = os.path.join(tempdir, "u2.xdmf") mesh = UnitSquareMesh(MPI.comm_world, 16, 16, cell_type) # FIXME: This randomly hangs in parallel V = FunctionSpace(mesh, ("Lagrange", 2)) u = Function(V) 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_RefineUnitCubeMesh_keep_partition(): """Refine mesh of unit cube.""" mesh = UnitCubeMesh(MPI.comm_world, 5, 7, 9) mesh.create_entities(1) mesh = refine(mesh, False) assert mesh.num_entities_global(0) == 3135 assert mesh.num_entities_global(3) == 15120 Q = FunctionSpace(mesh, ("CG", 1)) assert(Q)
def test_NC_hex(family, degree, cell_type, datadir): # TODO: Implement higher order NCE/NCF spaces if family == "NCE" and degree >= 3: return if family == "NCF" and degree >= 2: return mesh = get_mesh(cell_type, datadir) V = FunctionSpace(mesh, (family, degree)) run_vector_test(mesh, V, degree - 1)
def test_save_3d_scalar(tempdir, encoding, cell_type): filename = os.path.join(tempdir, "u3.xdmf") mesh = UnitCubeMesh(MPI.COMM_WORLD, 4, 3, 4, cell_type) V = FunctionSpace(mesh, ("Lagrange", 2)) u = Function(V) u.vector.set(1.0) with XDMFFile(mesh.mpi_comm(), filename, "w", encoding=encoding) as file: file.write_mesh(mesh) file.write_function(u)
def test_save_1d_scalar(tempdir, encoding): filename2 = os.path.join(tempdir, "u1_.xdmf") mesh = UnitIntervalMesh(MPI.COMM_WORLD, 32) V = FunctionSpace(mesh, ("Lagrange", 2)) u = Function(V) u.vector.set(1.0 + (1j if has_petsc_complex else 0)) with XDMFFile(mesh.mpi_comm(), filename2, "w", encoding=encoding) as file: file.write_mesh(mesh) file.write_function(u)