def test_3d(tempdir, cell_type, encoding): filename = os.path.join(tempdir, "meshtags_3d.xdmf") comm = MPI.COMM_WORLD mesh = UnitCubeMesh(comm, 4, 4, 4, cell_type) bottom_facets = locate_entities(mesh, 2, lambda x: np.isclose(x[1], 0.0)) bottom_values = np.full(bottom_facets.shape, 1, dtype=np.intc) left_facets = locate_entities(mesh, 2, lambda x: np.isclose(x[0], 0.0)) left_values = np.full(left_facets.shape, 2, dtype=np.intc) indices, pos = np.unique(np.hstack((bottom_facets, left_facets)), return_index=True) mt = MeshTags(mesh, 2, indices, np.hstack((bottom_values, left_values))[pos]) mt.name = "facets" top_lines = locate_entities(mesh, 1, lambda x: np.isclose(x[2], 1.0)) top_values = np.full(top_lines.shape, 3, dtype=np.intc) right_lines = locate_entities(mesh, 1, lambda x: np.isclose(x[0], 1.0)) right_values = np.full(right_lines.shape, 4, dtype=np.intc) indices, pos = np.unique(np.hstack((top_lines, right_lines)), return_index=True) mt_lines = MeshTags(mesh, 1, indices, np.hstack((top_values, right_values))[pos]) mt_lines.name = "lines" with XDMFFile(comm, filename, "w", encoding=encoding) as file: mesh.topology.create_connectivity_all() file.write_mesh(mesh) file.write_meshtags(mt) file.write_meshtags(mt_lines) file.write_information("units", "mm") with XDMFFile(comm, filename, "r", encoding=encoding) as file: mesh_in = file.read_mesh() mesh_in.topology.create_connectivity_all() mt_in = file.read_meshtags(mesh_in, "facets") mt_lines_in = file.read_meshtags(mesh_in, "lines") units = file.read_information("units") assert units == "mm" assert mt_in.name == "facets" assert mt_lines_in.name == "lines" with XDMFFile(comm, os.path.join(tempdir, "meshtags_3d_out.xdmf"), "w", encoding=encoding) as file: file.write_mesh(mesh_in) file.write_meshtags(mt_lines_in) file.write_meshtags(mt_in) # Check number of owned and marked entities lines_local = comm.allreduce((mt_lines.indices < mesh.topology.index_map(1).size_local).sum(), op=MPI.SUM) lines_local_in = comm.allreduce( (mt_lines_in.indices < mesh_in.topology.index_map(1).size_local).sum(), op=MPI.SUM) assert lines_local == lines_local_in # Check that only owned data is written to file facets_local = comm.allreduce((mt.indices < mesh.topology.index_map(2).size_local).sum(), op=MPI.SUM) parser = ElementTree.XMLParser() tree = ElementTree.parse(os.path.join(tempdir, "meshtags_3d_out.xdmf"), parser) num_lines = int(tree.findall(".//Grid[@Name='lines']/Topology")[0].get("NumberOfElements")) num_facets = int(tree.findall(".//Grid[@Name='facets']/Topology")[0].get("NumberOfElements")) assert(num_lines == lines_local) assert(num_facets == facets_local)
def test_create(cell_type): comm = MPI.COMM_WORLD mesh = UnitCubeMesh(comm, 6, 6, 6, cell_type) marked_lines = locate_entities(mesh, 1, lambda x: numpy.isclose(x[1], 0.5)) f_v = mesh.topology.connectivity(1, 0).array.reshape(-1, 2) entities = cpp.graph.AdjacencyList_int32(f_v[marked_lines]) values = numpy.full(marked_lines.shape[0], 2, dtype=numpy.int32) mt = create_meshtags(mesh, 1, entities, values) assert mt.indices.shape == marked_lines.shape
def test_3d(tempdir, cell_type, encoding): filename = os.path.join(tempdir, "meshtags_3d.xdmf") comm = MPI.COMM_WORLD mesh = UnitCubeMesh(comm, 4, 4, 4, cell_type) bottom_facets = locate_entities(mesh, 2, lambda x: np.isclose(x[1], 0.0)) bottom_values = np.full(bottom_facets.shape, 1, dtype=np.intc) left_facets = locate_entities(mesh, 2, lambda x: np.isclose(x[0], 0.0)) left_values = np.full(left_facets.shape, 2, dtype=np.intc) indices, pos = np.unique(np.hstack((bottom_facets, left_facets)), return_index=True) mt = MeshTags(mesh, 2, indices, np.hstack((bottom_values, left_values))[pos]) mt.name = "facets" top_lines = locate_entities(mesh, 1, lambda x: np.isclose(x[2], 1.0)) top_values = np.full(top_lines.shape, 3, dtype=np.intc) right_lines = locate_entities(mesh, 1, lambda x: np.isclose(x[0], 1.0)) right_values = np.full(right_lines.shape, 4, dtype=np.intc) indices, pos = np.unique(np.hstack((top_lines, right_lines)), return_index=True) mt_lines = MeshTags(mesh, 1, indices, np.hstack((top_values, right_values))[pos]) mt_lines.name = "lines" with XDMFFile(comm, filename, "w", encoding=encoding) as file: mesh.topology.create_connectivity_all() file.write_mesh(mesh) file.write_meshtags(mt) file.write_meshtags(mt_lines) with XDMFFile(comm, filename, "r", encoding=encoding) as file: mesh_in = file.read_mesh() mesh_in.topology.create_connectivity_all() mt_in = file.read_meshtags(mesh_in, "facets") mt_lines_in = file.read_meshtags(mesh_in, "lines") assert mt_in.name == "facets" assert mt_lines_in.name == "lines" with XDMFFile(comm, os.path.join(tempdir, "meshtags_3d_out.xdmf"), "w", encoding=encoding) as file: file.write_mesh(mesh_in) file.write_meshtags(mt_lines_in) file.write_meshtags(mt_in) # Check number of owned and marked entities lines_local = comm.allreduce((mt_lines.indices < mesh.topology.index_map(1).size_local).sum(), op=MPI.SUM) lines_local_in = comm.allreduce( (mt_lines_in.indices < mesh_in.topology.index_map(1).size_local).sum(), op=MPI.SUM) assert lines_local == lines_local_in
ksp.getPC().setType('jacobi') ksp.setTolerances(rtol=1.0e-12) ksp.setFromOptions() ksp.solve(b2, x2) x2norm = x2.norm() assert x2norm == pytest.approx(x0norm, 1.0e-10) @pytest.mark.parametrize("mesh", [ UnitSquareMesh( MPI.COMM_WORLD, 12, 11, ghost_mode=dolfinx.cpp.mesh.GhostMode.none), UnitSquareMesh(MPI.COMM_WORLD, 12, 11, ghost_mode=dolfinx.cpp.mesh.GhostMode.shared_facet), UnitCubeMesh( MPI.COMM_WORLD, 3, 7, 3, ghost_mode=dolfinx.cpp.mesh.GhostMode.none), UnitCubeMesh(MPI.COMM_WORLD, 3, 7, 3, ghost_mode=dolfinx.cpp.mesh.GhostMode.shared_facet) ]) def test_assembly_solve_taylor_hood(mesh): """Assemble Stokes problem with Taylor-Hood elements and solve.""" P2 = fem.VectorFunctionSpace(mesh, ("Lagrange", 2)) P1 = fem.FunctionSpace(mesh, ("Lagrange", 1)) def boundary0(x): """Define boundary x = 0""" return x[0] < 10 * numpy.finfo(float).eps
def ode_1st_nonlinear_odeint(a=1.0, b=1.0, c=1.0, nT=10, dt=0.1, **kwargs): """ Create 1st order ODE problem and solve with `ODEInt` time integrator. First order nonlinear non-autonomous ODE: t * dot u - a * cos(c*t) * u^2 - 2 * u - a * b^2 * t^4 * cos(c*t) = 0 with initial condition u(t=1) = 0 """ mesh = UnitCubeMesh(MPI.COMM_WORLD, 1, 1, 1) U = FunctionSpace(mesh, ("DG", 0)) u = Function(U, name="u") ut = Function(U, name="ut") u.vector.set(0.0) # initial condition ut.vector.set( a * b**2 * numpy.cos(c)) # exact initial rate of this ODE for generalised alpha u.vector.ghostUpdate() ut.vector.ghostUpdate() δu = ufl.TestFunction(U) dx = ufl.Measure("dx", domain=mesh) # Global time t = dolfinx.Constant(mesh, 1.0) # Time step size dt = dolfinx.Constant(mesh, dt) # Time integrator odeint = dolfiny.odeint.ODEInt(t=t, dt=dt, x=u, xt=ut, **kwargs) # Weak form (as one-form) f = δu * (t * ut - a * ufl.cos(c * t) * u**2 - 2 * u - a * b**2 * t**4 * ufl.cos(c * t)) * dx # Overall form (as one-form) F = odeint.discretise_in_time(f) # Overall form (as list of forms) F = dolfiny.function.extract_blocks(F, [δu]) # # Options for PETSc backend from petsc4py import PETSc opts = PETSc.Options() opts["snes_type"] = "newtonls" opts["snes_linesearch_type"] = "basic" opts["snes_atol"] = 1.0e-10 opts["snes_rtol"] = 1.0e-12 # Silence SNES monitoring during test dolfiny.snesblockproblem.SNESBlockProblem.print_norms = lambda self, it: 1 # Create nonlinear problem problem = dolfiny.snesblockproblem.SNESBlockProblem(F, [u]) # Book-keeping of results u_avg = numpy.zeros(nT + 1) u_avg[0] = u.vector.sum() / u.vector.getSize() dolfiny.utils.pprint(f"+++ Processing time steps = {nT}") # Process time steps for time_step in range(1, nT + 1): # Stage next time step odeint.stage() # Solve nonlinear problem u, = problem.solve() # Assert convergence of nonlinear solver assert problem.snes.getConvergedReason( ) > 0, "Nonlinear solver did not converge!" # Update solution states for time integration odeint.update() # Store result u_avg[time_step] = u.vector.sum() / u.vector.getSize() return u_avg
def ode_1st_linear_odeint(a=1.0, b=0.5, u_0=1.0, nT=10, dt=0.1, **kwargs): """ Create 1st order ODE problem and solve with `ODEInt` time integrator. First order linear ODE: dot u + a * u - b = 0 with initial condition u(t=0) = u_0 """ mesh = UnitCubeMesh(MPI.COMM_WORLD, 1, 1, 1) U = FunctionSpace(mesh, ("DG", 0)) u = Function(U, name="u") ut = Function(U, name="ut") u.vector.set(u_0) # initial condition ut.vector.set( b - a * u_0) # exact initial rate of this ODE for generalised alpha u.vector.ghostUpdate() ut.vector.ghostUpdate() δu = ufl.TestFunction(U) dx = ufl.Measure("dx", domain=mesh) # Global time time = dolfinx.Constant(mesh, 0.0) # Time step size dt = dolfinx.Constant(mesh, dt) # Time integrator odeint = dolfiny.odeint.ODEInt(t=time, dt=dt, x=u, xt=ut, **kwargs) # Weak form (as one-form) f = δu * (ut + a * u - b) * dx # Overall form (as one-form) F = odeint.discretise_in_time(f) # Overall form (as list of forms) F = dolfiny.function.extract_blocks(F, [δu]) # Silence SNES monitoring during test dolfiny.snesblockproblem.SNESBlockProblem.print_norms = lambda self, it: 1 # Create problem (although having a linear ODE we use the dolfiny.snesblockproblem API) problem = dolfiny.snesblockproblem.SNESBlockProblem(F, [u]) # Book-keeping of results u_avg = numpy.zeros(nT + 1) u_avg[0] = u.vector.sum() / u.vector.getSize() dolfiny.utils.pprint(f"+++ Processing time steps = {nT}") # Process time steps for time_step in range(1, nT + 1): # Stage next time step odeint.stage() # Solve (linear) problem u, = problem.solve() # Update solution states for time integration odeint.update() # Store result u_avg[time_step] = u.vector.sum() / u.vector.getSize() return u_avg
def test_neohooke(): mesh = UnitCubeMesh(MPI.COMM_WORLD, 7, 7, 7) V = VectorFunctionSpace(mesh, ("P", 1)) P = FunctionSpace(mesh, ("P", 1)) L = FunctionSpace(mesh, ("R", 0)) u = Function(V, name="u") v = ufl.TestFunction(V) p = Function(P, name="p") q = ufl.TestFunction(P) lmbda0 = Function(L) d = mesh.topology.dim Id = ufl.Identity(d) F = Id + ufl.grad(u) C = F.T * F J = ufl.det(F) E_, nu_ = 10.0, 0.3 mu, lmbda = E_ / (2 * (1 + nu_)), E_ * nu_ / ((1 + nu_) * (1 - 2 * nu_)) psi = (mu / 2) * (ufl.tr(C) - 3) - mu * ufl.ln(J) + lmbda / 2 * ufl.ln(J)**2 + (p - 1.0)**2 pi = psi * ufl.dx F0 = ufl.derivative(pi, u, v) F1 = ufl.derivative(pi, p, q) # Number of eigenvalues to find nev = 8 opts = PETSc.Options("neohooke") opts["eps_smallest_magnitude"] = True opts["eps_nev"] = nev opts["eps_ncv"] = 50 * nev opts["eps_conv_abs"] = True # opts["eps_non_hermitian"] = True opts["eps_tol"] = 1.0e-14 opts["eps_max_it"] = 1000 opts["eps_error_relative"] = "::ascii_info_detail" opts["eps_monitor"] = "::ascii_info_detail" slepcp = dolfiny.slepcblockproblem.SLEPcBlockProblem([F0, F1], [u, p], lmbda0, prefix="neohooke") slepcp.solve() # mat = dolfiny.la.petsc_to_scipy(slepcp.eps.getOperators()[0]) # eigvals, eigvecs = linalg.eigsh(mat, which="SM", k=nev) with XDMFFile(MPI.COMM_WORLD, "eigvec.xdmf", "w") as ofile: ofile.write_mesh(mesh) for i in range(nev): eigval, ur, ui = slepcp.getEigenpair(i) # Expect first 6 eignevalues 0, i.e. rigid body modes if i < 6: assert np.isclose(eigval, 0.0) for func in ur: name = func.name func.name = f"{name}_eigvec_{i}_real" ofile.write_function(func) func.name = name