def test_save_mesh_value_collection(tempdir, encoding, data_type, cell_type): dtype_str, dtype = data_type mesh = UnitCubeMesh(MPI.comm_world, 4, 4, 4, cell_type) tdim = mesh.topology.dim meshfn = MeshFunction(dtype_str, mesh, mesh.topology.dim, False) meshfn.name = "volume_marker" mp = cpp.mesh.midpoints(mesh, tdim, range(mesh.num_entities(tdim))) for i in range(mesh.num_cells()): if mp[i, 1] > 0.1: meshfn.values[i] = 1 if mp[i, 1] > 0.9: meshfn.values[i] = 2 for mvc_dim in range(0, tdim + 1): mvc = MeshValueCollection(dtype_str, mesh, mvc_dim) tag = "dim_{}_marker".format(mvc_dim) mvc.name = tag mesh.create_connectivity(mvc_dim, tdim) mp = cpp.mesh.midpoints(mesh, mvc_dim, range(mesh.num_entities(mvc_dim))) for e in range(mesh.num_entities(mvc_dim)): if (mp[e, 0] > 0.5): mvc.set_value(e, dtype(1)) filename = os.path.join(tempdir, "mvc_{}.xdmf".format(mvc_dim)) with XDMFFile(mesh.mpi_comm(), filename, encoding=encoding) as xdmf: xdmf.write(meshfn) xdmf.write(mvc) with XDMFFile(mesh.mpi_comm(), filename) as xdmf: read_function = getattr(xdmf, "read_mvc_" + dtype_str) mvc = read_function(mesh, tag)
def test_save_1d_mesh(tempdir, encoding): filename = os.path.join(tempdir, "mf_1D.xdmf") mesh = UnitIntervalMesh(MPI.comm_world, 32) mf = MeshFunction("size_t", mesh, mesh.topology.dim, 0) mf.values[:] = np.arange(mesh.num_entities(1)) with XDMFFile(mesh.mpi_comm(), filename, encoding=encoding) as file: file.write(mf)
def test_save_and_read_meshfunction_3D(tempdir): filename = os.path.join(tempdir, "meshfn-3d.h5") # Write to file mesh = UnitCubeMesh(MPI.comm_world, 2, 2, 2) mf_file = HDF5File(mesh.mpi_comm(), filename, "w") # save meshfuns to compare when reading back meshfunctions = [] for i in range(0, 4): mf = MeshFunction('double', mesh, i, 0.0) mp = cpp.mesh.midpoints(mesh, i, range(mesh.num_entities(i))) # NB choose a value to set which will be the same on every # process for each entity mf.values[:] = mp[:, 0] meshfunctions.append(mf) mf_file.write(mf, "/meshfunction/group/%d/meshfun" % i) mf_file.close() # Read back from file mf_file = HDF5File(mesh.mpi_comm(), filename, "r") for i in range(0, 4): mf2 = mf_file.read_mf_double(mesh, "/meshfunction/group/%d/meshfun" % i) assert numpy.all(meshfunctions[i].values == mf2.values) mf_file.close()
def test_mesh_function_assign_2D_facets(): mesh = UnitSquareMesh(MPI.comm_world, 3, 3) mesh.create_entities(1) tdim = mesh.topology.dim num_cell_facets = cpp.mesh.cell_num_entities(mesh.topology.cell_type, tdim - 1) f = MeshFunction("int", mesh, tdim - 1, 25) connectivity = mesh.topology.connectivity(tdim, tdim - 1) for c in range(mesh.num_cells()): facets = connectivity.links(c) for i in range(num_cell_facets): assert 25 == f.values[facets[i]] g = MeshValueCollection("int", mesh, 1) g.assign(f) assert mesh.num_entities(tdim - 1) == len(f.values) assert mesh.num_cells() * 3 == g.size() for c in range(mesh.num_cells()): for i in range(num_cell_facets): assert 25 == g.get_value(c, i) f2 = MeshFunction("int", mesh, g, 0) connectivity = mesh.topology.connectivity(tdim, tdim - 1) for c in range(mesh.num_cells()): facets = connectivity.links(c) for i in range(num_cell_facets): assert f2.values[facets[i]] == g.get_value(c, i)
def test_mesh_function_assign_2D_cells(): mesh = UnitSquareMesh(MPI.comm_world, 3, 3) ncells = mesh.num_cells() f = MeshFunction("int", mesh, mesh.topology.dim, 0) for c in range(ncells): f.values[c] = ncells - c g = MeshValueCollection("int", mesh, 2) g.assign(f) assert ncells == len(f.values) assert ncells == g.size() f2 = MeshFunction("int", mesh, g, 0) for c in range(mesh.num_cells()): value = ncells - c assert value == g.get_value(c, 0) assert f2.values[c] == g.get_value(c, 0) h = MeshValueCollection("int", mesh, 2) global_indices = mesh.topology.index_map(2).global_indices(True) ncells_global = mesh.num_entities_global(2) for c in range(mesh.num_cells()): if global_indices[c] in [5, 8, 10]: continue value = ncells_global - global_indices[c] h.set_value(c, int(value)) f3 = MeshFunction("int", mesh, h, 0) values = f3.values values[values > ncells_global] = 0. assert MPI.sum(mesh.mpi_comm(), values.sum() * 1.0) == 140.
def test_save_3D_vertex_function(tempdir, encoding, data_type, cell_type): dtype_str, dtype = data_type filename = os.path.join(tempdir, "mf_vertex_3D_%s.xdmf" % dtype_str) mesh = UnitCubeMesh(MPI.comm_world, 4, 4, 4, cell_type) mf = MeshFunction(dtype_str, mesh, 0, 0) mf.values[:] = np.arange(mesh.num_entities(0), dtype=dtype) with XDMFFile(mesh.mpi_comm(), filename, encoding=encoding) as file: file.write(mf)
def test_facet_normals(cell_type): """Test that FacetNormal is outward facing""" for count in range(5): mesh = unit_cell(cell_type) V = VectorFunctionSpace(mesh, ("Lagrange", 1)) normal = FacetNormal(mesh) num_facets = mesh.num_entities(mesh.topology.dim - 1) v = Function(V) facet_function = MeshFunction("size_t", mesh, mesh.topology.dim - 1, 1) facet_function.values[:] = range(num_facets) # 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.points[i] v.interpolate(lambda x: x[0] - co[0]) if cell_type == CellType.triangle: co = mesh.geometry.points[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.points[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=facet_function, 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_append_and_load_mesh_value_collections(tempdir, encoding, data_type, cell_type): dtype_str, dtype = data_type mesh = UnitCubeMesh(MPI.comm_world, 2, 2, 2, cell_type) mesh.create_connectivity_all() mvc_v = MeshValueCollection(dtype_str, mesh, 0) mvc_v.name = "vertices" mvc_e = MeshValueCollection(dtype_str, mesh, 1) mvc_e.name = "edges" mvc_f = MeshValueCollection(dtype_str, mesh, 2) mvc_f.name = "facets" mvc_c = MeshValueCollection(dtype_str, mesh, 3) mvc_c.name = "cells" mvcs = [mvc_v, mvc_e, mvc_f, mvc_c] filename = os.path.join(tempdir, "appended_mvcs.xdmf") with XDMFFile(mesh.mpi_comm(), filename) as xdmf: for mvc in mvcs: # global_indices = mesh.topology.global_indices(mvc.dim) map = mesh.topology.index_map(mvc.dim) global_indices = map.global_indices(True) for ent in range(mesh.num_entities(mvc.dim)): assert (mvc.set_value(ent, global_indices[ent])) xdmf.write(mvc) mvc_v_in = MeshValueCollection(dtype_str, mesh, 0) mvc_e_in = MeshValueCollection(dtype_str, mesh, 1) mvc_f_in = MeshValueCollection(dtype_str, mesh, 2) mvc_c_in = MeshValueCollection(dtype_str, mesh, 3) with XDMFFile(mesh.mpi_comm(), filename) as xdmf: read_function = getattr(xdmf, "read_mvc_" + dtype_str) mvc_v_in = read_function(mesh, "vertices") mvc_e_in = read_function(mesh, "edges") mvc_f_in = read_function(mesh, "facets") mvc_c_in = read_function(mesh, "cells") mvcs_in = [mvc_v_in, mvc_e_in, mvc_f_in, mvc_c_in] for (mvc, mvc_in) in zip(mvcs, mvcs_in): mf = MeshFunction(dtype_str, mesh, mvc, 0) mf_in = MeshFunction(dtype_str, mesh, mvc_in, 0) diff = mf_in.values - mf.values assert np.all(diff == 0)
def test_save_3D_cell_function(tempdir, encoding, data_type, cell_type): dtype_str, dtype = data_type mesh = UnitCubeMesh(MPI.comm_world, 4, 4, 4, cell_type) mf = MeshFunction(dtype_str, mesh, mesh.topology.dim, 0) mf.name = "cells" mf.values[:] = np.arange(mesh.num_entities(3), dtype=dtype) filename = os.path.join(tempdir, "mf_3D_%s.xdmf" % dtype_str) with XDMFFile(mesh.mpi_comm(), filename, encoding=encoding) as file: file.write(mf) with XDMFFile(mesh.mpi_comm(), filename) as xdmf: read_function = getattr(xdmf, "read_mf_" + dtype_str) mf_in = read_function(mesh, "cells") diff = mf_in.values - mf.values assert np.all(diff == 0)
def test_save_2D_vertex_function(tempdir, encoding, data_type, cell_type): dtype_str, dtype = data_type mesh = UnitSquareMesh(MPI.comm_world, 32, 32, cell_type) mf = MeshFunction(dtype_str, mesh, 0, 0) mf.name = "vertices" global_indices = mesh.topology.index_map(0).global_indices(False) mf.values[:] = global_indices[:] filename = os.path.join(tempdir, "mf_vertex_2D_%s.xdmf" % dtype_str) with XDMFFile(mesh.mpi_comm(), filename, encoding=encoding) as file: file.write(mf) with XDMFFile(mesh.mpi_comm(), filename) as xdmf: read_function = getattr(xdmf, "read_mf_" + dtype_str) mf_in = read_function(mesh, "vertices") diff = mf_in.values - mf.values assert np.all(diff == 0)
def test_save_3D_facet_function(tempdir, encoding, data_type, cell_type): dtype_str, dtype = data_type mesh = UnitCubeMesh(MPI.comm_world, 4, 4, 4, cell_type) tdim = mesh.topology.dim mf = MeshFunction(dtype_str, mesh, tdim - 1, 0) mf.name = "facets" global_indices = mesh.topology.global_indices(tdim - 1) mf.values[:] = global_indices[:] filename = os.path.join(tempdir, "mf_facet_3D_%s.xdmf" % dtype_str) with XDMFFile(mesh.mpi_comm(), filename, encoding=encoding) as xdmf: xdmf.write(mf) with XDMFFile(mesh.mpi_comm(), filename) as xdmf: read_function = getattr(xdmf, "read_mf_" + dtype_str) mf_in = read_function(mesh, "facets") diff = mf_in.values - mf.values assert np.all(diff == 0)
def test_mesh_function_assign_2D_vertices(): mesh = UnitSquareMesh(MPI.comm_world, 3, 3) mesh.create_entities(0) f = MeshFunction("int", mesh, 0, 25) g = MeshValueCollection("int", mesh, 0) g.assign(f) assert mesh.num_entities(0) == len(f.values) assert mesh.num_cells() * 3 == g.size() f2 = MeshFunction("int", mesh, g, 0) num_cell_vertices = cpp.mesh.cell_num_vertices(mesh.topology.cell_type) tdim = mesh.topology.dim connectivity = mesh.topology.connectivity(tdim, 0) for c in range(mesh.num_cells()): vertices = connectivity.links(c) for i in range(num_cell_vertices): assert 25 == g.get_value(c, i) assert f2.values[vertices[i]] == g.get_value(c, i)
def test_save_1d_meshfunctions(tempfile, mesh_function_types, file_options, type_conv): mesh = UnitIntervalMesh(MPI.comm_world, 32) for d in range(mesh.topology.dim + 1): for t in mesh_function_types: mf = MeshFunction(t, mesh, mesh.topology.dim - d, type_conv[t](1)) VTKFile(tempfile + "mf.pvd").write(mf) f = VTKFile(tempfile + "mf.pvd") f.write(mf, 0.) f.write(mf, 1.)
def test_save_3d_meshfunctions(tempfile, mesh_function_types, file_options, type_conv, cell_types_3D): mesh = UnitCubeMesh(MPI.comm_world, 8, 8, 8) for d in range(mesh.topology.dim + 1): for t in mesh_function_types: for cell_type in cell_types_3D: mf = MeshFunction(t, mesh, mesh.topology.dim - d, type_conv[t](1)) VTKFile(tempfile + "mf_{0:d}_{1:s}.pvd".format(mesh.topology.dim - d, str(cell_type).split(".")[-1])).write(mf) f = VTKFile(tempfile + "mf{0:d}_{1:s}.pvd".format(mesh.topology.dim - d, str(cell_type).split(".")[-1])) f.write(mf, 0.) f.write(mf, 1.)
def test_save_and_read_meshfunction_2D(tempdir): filename = os.path.join(tempdir, "meshfn-2d.h5") # Write to file mesh = UnitSquareMesh(MPI.comm_world, 20, 20) with HDF5File(mesh.mpi_comm(), filename, "w") as mf_file: # save meshfuns to compare when reading back meshfunctions = [] for i in range(0, 3): mf = MeshFunction('double', mesh, i, 0.0) # NB choose a value to set which will be the same on every # process for each entity mf.values[:] = cpp.mesh.midpoints(mesh, i, range(mesh.num_entities(i)))[:, 0] meshfunctions.append(mf) mf_file.write(mf, "/meshfunction/meshfun%d" % i) # Read back from file with HDF5File(mesh.mpi_comm(), filename, "r") as mf_file: for i in range(0, 3): mf2 = mf_file.read_mf_double(mesh, "/meshfunction/meshfun%d" % i) assert numpy.all(meshfunctions[i].values == mf2.values)
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) V = FunctionSpace(mesh, ("Lagrange", 2)) num_facets = mesh.num_entities(mesh.topology.dim - 1) v = Function(V) facet_function = MeshFunction("size_t", mesh, mesh.topology.dim - 1, 1) facet_function.values[:] = range(num_facets) # 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=facet_function, subdomain_id=j) result = fem.assemble_scalar(a) out.append(result) assert np.isclose(result, out[0])
def test_multiple_datasets(tempdir, encoding, cell_type): mesh = UnitSquareMesh(MPI.comm_world, 4, 4, cell_type) cf0 = MeshFunction('size_t', mesh, 2, 11) cf0.name = 'cf0' cf1 = MeshFunction('size_t', mesh, 2, 22) cf1.name = 'cf1' filename = os.path.join(tempdir, "multiple_mf.xdmf") with XDMFFile(mesh.mpi_comm(), filename, encoding=encoding) as xdmf: xdmf.write(mesh) xdmf.write(cf0) xdmf.write(cf1) with XDMFFile(mesh.mpi_comm(), filename) as xdmf: mesh = xdmf.read_mesh(cpp.mesh.GhostMode.none) cf0 = xdmf.read_mf_size_t(mesh, "cf0") cf1 = xdmf.read_mf_size_t(mesh, "cf1") assert (cf0.values[0] == 11 and cf1.values[0] == 22)
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 mf = MeshFunction("size_t", mesh, facetdim, 0) mf.mark(boundary, 1) bndry_facets = np.where(mf.values == 1)[0] 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)
def test_data_types(dtype, mesh): dtype_str, dtype = dtype mf = MeshFunction(dtype_str, mesh, 0, 0) assert isinstance(mf.values[0], dtype)
def f(mesh): return MeshFunction('int', mesh, 0, 0)
def test_numpy_access(dtype, mesh): dtype_str, dtype = dtype mf = MeshFunction(dtype_str, mesh, 0, 0) values = mf.values values[:] = numpy.random.rand(len(values)) assert numpy.all(values == mf.values)
def dx_from_measure(mesh): subdomains = MeshFunction("size_t", mesh, mesh.topology.dim, 1) dx = Measure("dx")(subdomain_data=subdomains, domain=mesh) dx = dx(1) return dx
def dS_from_measure(mesh): boundaries = MeshFunction("size_t", mesh, mesh.topology.dim - 1, 1) dS = Measure("dS")(subdomain_data=boundaries, domain=mesh) return dS
def test_append_and_load_mesh_functions(tempdir, encoding, data_type): dtype_str, dtype = data_type meshes = [ UnitSquareMesh(MPI.comm_world, 12, 12), UnitCubeMesh(MPI.comm_world, 2, 2, 2), UnitSquareMesh(MPI.comm_world, 12, 12, CellType.quadrilateral), UnitCubeMesh(MPI.comm_world, 2, 2, 2, CellType.hexahedron) ] for mesh in meshes: dim = mesh.topology.dim vf = MeshFunction(dtype_str, mesh, 0, 0) vf.name = "vertices" ff = MeshFunction(dtype_str, mesh, mesh.topology.dim - 1, 0) ff.name = "facets" cf = MeshFunction(dtype_str, mesh, mesh.topology.dim, 0) cf.name = "cells" # vf.values[:] = mesh.topology.global_indices(0)[:] map = mesh.topology.index_map(0) vf.values[:] = map.global_indices(True) map = mesh.topology.index_map(dim - 1) ff.values[:] = map.global_indices(True) map = mesh.topology.index_map(dim) cf.values[:] = map.global_indices(True) filename = os.path.join( tempdir, "appended_mf_{0:d}_{1:s}.xdmf".format( dim, str(mesh.topology.cell_type))) with XDMFFile(mesh.mpi_comm(), filename, encoding=encoding) as xdmf: xdmf.write(mesh) xdmf.write(vf) xdmf.write(ff) xdmf.write(cf) with XDMFFile(mesh.mpi_comm(), filename) as xdmf: read_function = getattr(xdmf, "read_mf_" + dtype_str) vf_in = read_function(mesh, "vertices") ff_in = read_function(mesh, "facets") cf_in = read_function(mesh, "cells") diff_vf = vf_in.values - vf.values diff_ff = ff_in.values - ff.values diff_cf = cf_in.values - cf.values assert np.all(diff_vf == 0) assert np.all(diff_ff == 0) assert np.all(diff_cf == 0)