Example #1
0
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_taylor_hood_cube():
    pytest.xfail("Problem with Mixed Function Spaces")
    meshc = UnitCubeMesh(MPI.comm_world, 2, 2, 2)
    meshf = UnitCubeMesh(MPI.comm_world, 3, 4, 5)

    Ve = VectorElement("CG", meshc.ufl_cell(), 2)
    Qe = FiniteElement("CG", meshc.ufl_cell(), 1)
    Ze = MixedElement([Ve, Qe])

    Zc = FunctionSpace(meshc, Ze)
    Zf = FunctionSpace(meshf, Ze)

    def z(x):
        return np.row_stack((x[0] * x[1],
                             x[1] * x[2],
                             x[2] * x[0],
                             x[0] + 3.0 * x[1] + x[2]))

    zc, zf = Function(Zc), Function(Zf)
    zc.interpolate(z)
    zf.interpolate(z)

    mat = PETScDMCollection.create_transfer_matrix(Zc, Zf)
    Zuc = Function(Zf)
    mat.mult(zc.vector, Zuc.vector)
    Zuc.vector.update_ghost_values()

    diff = Function(Zf)
    diff.assign(Zuc - zf)
    assert diff.vector.norm("l2") < 1.0e-12
Example #3
0
def test_interpolation_function(mesh):
    V = FunctionSpace(mesh, ("CG", 1))
    u = Function(V)
    u.vector.set(1)
    Vh = FunctionSpace(mesh, ("CG", 1))
    uh = Function(Vh)
    uh.interpolate(u)
    assert np.allclose(uh.vector.array, 1)
Example #4
0
def assemble_div_matrix(k, offset):
    mesh = create_quad_mesh(offset)
    V = FunctionSpace(mesh, ("DQ", k))
    W = FunctionSpace(mesh, ("RTCF", k + 1))
    u, w = ufl.TrialFunction(V), ufl.TestFunction(W)
    form = ufl.inner(u, ufl.div(w)) * ufl.dx
    A = fem.assemble_matrix(form)
    A.assemble()
    return A[:, :]
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]:
            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))
            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)

    for i, j in combinations(zip(results, spaces, orders), 2):
        dof_order = []
        for cell in range(2):
            for point in range(len(mesh.geometry.points)):
                point_n = j[2][point]
                cell_points = list(j[1].mesh.cells()[cell])
                if point_n in cell_points:
                    point_n_in_cell = cell_points.index(point_n)
                    dofmap = j[1].dofmap.cell_dofs(cell)
                    j_dof_n = dofmap[point_n_in_cell]
                else:
                    j_dof_n = None

                point_n = i[2][point]
                cell_points = list(i[1].mesh.cells()[cell])
                if point_n in cell_points:
                    point_n_in_cell = cell_points.index(point_n)
                    dofmap = i[1].dofmap.cell_dofs(cell)
                    i_dof_n = dofmap[point_n_in_cell]
                else:
                    i_dof_n = None

                if i_dof_n is None:
                    assert j_dof_n is None
                else:
                    dof_order.append((i_dof_n, j_dof_n))

        for a, b in dof_order:
            assert np.isclose(i[0][a], j[0][b])
Example #6
0
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 = ufl.TestFunction(V)
            a = ufl.inner(f(pm1), v(pm2)) * ufl.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])
Example #7
0
def test_gradient(mesh):
    """Test discrete gradient computation (typically used for curl-curl
    AMG preconditioners"""

    V = FunctionSpace(mesh, ("Lagrange", 1))
    W = FunctionSpace(mesh, ("Nedelec 1st kind H(curl)", 1))
    G = create_discrete_gradient(W._cpp_object, V._cpp_object)
    assert G.getRefCount() == 1
    num_edges = mesh.topology.index_map(1).size_global
    m, n = G.getSize()
    assert m == num_edges
    assert n == mesh.topology.index_map(0).size_global
    assert numpy.isclose(G.norm(PETSc.NormType.FROBENIUS), numpy.sqrt(2.0 * num_edges))
Example #8
0
def test_global_dof_builder(mesh_factory):
    func, args = mesh_factory
    mesh = func(*args)

    V = VectorElement("CG", mesh.ufl_cell(), 1)
    Q = FiniteElement("CG", mesh.ufl_cell(), 1)
    R = FiniteElement("R", mesh.ufl_cell(), 0)

    W = FunctionSpace(mesh, MixedElement([Q, Q, Q, R]))
    W = FunctionSpace(mesh, MixedElement([Q, Q, R, Q]))
    W = FunctionSpace(mesh, V * R)
    W = FunctionSpace(mesh, R * V)
    assert (W)
Example #9
0
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)

    integrals = {IntegralType.cell: ([(-1, tabulate_tensor_b_coeff.address)], None)}
    L = cpp.fem.Form([V._cpp_object], integrals, [vals._cpp_object], [], False)

    b = dolfinx.fem.assemble_vector(L)
    b.ghostUpdate(addv=PETSc.InsertMode.ADD, mode=PETSc.ScatterMode.REVERSE)
    bnorm = b.norm(PETSc.NormType.N2)
    assert (np.isclose(bnorm, 2.0 * 0.0739710713711999))
Example #10
0
def test_clear_sub_map_data_vector(mesh):
    mesh = UnitSquareMesh(8, 8)
    P1 = FiniteElement("Lagrange", mesh.ufl_cell(), 1)
    W = FunctionSpace(mesh, P1 * P1)

    # Check block size
    assert W.dofmap.index_map.block_size == 2

    W.dofmap.clear_sub_map_data()
    with pytest.raises(RuntimeError):
        W0 = W.sub(0)
        assert (W0)
    with pytest.raises(RuntimeError):
        W1 = W.sub(1)
        assert (W1)
Example #11
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_numba_assembly():
    mesh = UnitSquareMesh(MPI.comm_world, 13, 13)
    V = FunctionSpace(mesh, ("Lagrange", 1))

    a = cpp.fem.Form([V._cpp_object, V._cpp_object])
    a.set_tabulate_tensor(FormIntegrals.Type.cell, -1,
                          tabulate_tensor_A.address)
    a.set_tabulate_tensor(FormIntegrals.Type.cell, 12,
                          tabulate_tensor_A.address)
    a.set_tabulate_tensor(FormIntegrals.Type.cell, 2,
                          tabulate_tensor_A.address)

    L = cpp.fem.Form([V._cpp_object])
    L.set_tabulate_tensor(FormIntegrals.Type.cell, -1,
                          tabulate_tensor_b.address)

    A = dolfinx.fem.assemble_matrix(a)
    A.assemble()
    b = dolfinx.fem.assemble_vector(L)
    b.ghostUpdate(addv=PETSc.InsertMode.ADD, mode=PETSc.ScatterMode.REVERSE)

    Anorm = A.norm(PETSc.NormType.FROBENIUS)
    bnorm = b.norm(PETSc.NormType.N2)
    assert (np.isclose(Anorm, 56.124860801609124))
    assert (np.isclose(bnorm, 0.0739710713711999))

    list_timings(MPI.comm_world, [TimingType.wall])
Example #13
0
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)
Example #14
0
def test_evaluation(cell_type, space_type, space_order):
    random.seed(4)
    for repeat in range(10):
        mesh = random_evaluation_mesh(cell_type)
        V = FunctionSpace(mesh, (space_type, space_order))
        dofs = [i for i in V.dofmap.cell_dofs(0) if i in V.dofmap.cell_dofs(1)]

        N = 5
        if cell_type == "tetrahedron":
            eval_points = np.array([[0., i / N, j / N] for i in range(N + 1) for j in range(N + 1 - i)])
        elif cell_type == "hexahedron":
            eval_points = np.array([[0., i / N, j / N] for i in range(N + 1) for j in range(N + 1)])
        else:
            eval_points = np.array([[0., i / N, 0.] for i in range(N + 1)])

        for d in dofs:
            v = Function(V)
            v.vector[:] = [1 if i == d else 0 for i in range(v.vector.local_size)]
            values0 = v.eval(eval_points, [0 for i in eval_points])
            values1 = v.eval(eval_points, [1 for i in eval_points])
            if len(eval_points) == 1:
                values0 = [values0]
                values1 = [values1]
            if space_type in ["RT", "BDM", "RTCF", "NCF"]:
                # Hdiv
                for i, j in zip(values0, values1):
                    assert np.isclose(i[0], j[0])
            elif space_type in ["N1curl", "N2curl", "RTCE", "NCE"]:
                # Hcurl
                for i, j in zip(values0, values1):
                    assert np.allclose(i[1:], j[1:])
            else:
                assert np.allclose(values0, values1)
Example #15
0
def test_save_and_checkpoint_timeseries(tempdir, encoding, cell_type):
    mesh = UnitSquareMesh(MPI.comm_world, 16, 16, cell_type)
    filename = os.path.join(tempdir, "u2_checkpoint.xdmf")
    FE = FiniteElement("CG", mesh.ufl_cell(), 2)
    V = FunctionSpace(mesh, FE)

    times = [0.5, 0.2, 0.1]
    u_out = [None] * len(times)
    u_in = [None] * len(times)

    p = 0.0

    def expr_eval(x):
        return x[0] * p

    with XDMFFile(mesh.mpi_comm(), filename, encoding=encoding) as file:
        for i, p in enumerate(times):
            u_out[i] = Function(V)
            u_out[i].interpolate(expr_eval)
            file.write_checkpoint(u_out[i], "u_out", p)

    with XDMFFile(mesh.mpi_comm(), filename) as file:
        for i, p in enumerate(times):
            u_in[i] = file.read_checkpoint(V, "u_out", i)

    for i, p in enumerate(times):
        u_in[i].vector.axpy(-1.0, u_out[i].vector)
        assert u_in[i].vector.norm() < 1.0e-12

    # test reading last
    with XDMFFile(mesh.mpi_comm(), filename) as file:
        u_in_last = file.read_checkpoint(V, "u_out", -1)

    u_out[-1].vector.axpy(-1.0, u_in_last.vector)
    assert u_out[-1].vector.norm() < 1.0e-12
Example #16
0
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))
Example #17
0
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()
    u.x.scatter_forward()
    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()
    u.x.scatter_forward()

    # 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)
Example #18
0
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))
Example #19
0
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 = mesh.geometry.cmap

    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])
Example #20
0
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()
    u.x.scatter_reverse(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)
    u.x.scatter_reverse(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)
Example #21
0
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))
Example #22
0
def test_N2curl_interpolation(cell_type, order):
    mesh = one_cell_mesh(cell_type)
    tdim = mesh.topology.dim

    # TODO: fix higher order elements
    if tdim == 2 and order > 1:
        pytest.skip("N2curl order > 1 in 2D needs fixing")

    V = FunctionSpace(mesh, ("Nedelec 2nd kind H(curl)", order))
    v = Function(V)

    if tdim == 2:

        def f(x):
            return (x[1]**order, 2 * x[0])
    else:

        def f(x):
            return (x[1]**order + 2 * x[0], x[2]**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)
    assert np.allclose(values, [f(p) for p in points])
Example #23
0
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_numba_assembly():
    mesh = UnitSquareMesh(MPI.COMM_WORLD, 13, 13)
    V = FunctionSpace(mesh, ("Lagrange", 1))

    integrals = {
        IntegralType.cell: ([(-1, tabulate_tensor_A.address),
                             (12, tabulate_tensor_A.address),
                             (2, tabulate_tensor_A.address)], None)
    }
    a = cpp.fem.Form([V._cpp_object, V._cpp_object], integrals, [], [], False)

    integrals = {IntegralType.cell: ([(-1, tabulate_tensor_b.address)], None)}
    L = cpp.fem.Form([V._cpp_object], integrals, [], [], False)

    A = dolfinx.fem.assemble_matrix(a)
    A.assemble()
    b = dolfinx.fem.assemble_vector(L)
    b.ghostUpdate(addv=PETSc.InsertMode.ADD, mode=PETSc.ScatterMode.REVERSE)

    Anorm = A.norm(PETSc.NormType.FROBENIUS)
    bnorm = b.norm(PETSc.NormType.N2)
    assert (np.isclose(Anorm, 56.124860801609124))
    assert (np.isclose(bnorm, 0.0739710713711999))

    list_timings(MPI.COMM_WORLD, [TimingType.wall])
Example #25
0
def test_lhs_rhs_simple():
    """Test taking lhs/rhs of DOLFINX specific forms (constants
    without cell). """

    mesh = RectangleMesh(
        MPI.COMM_WORLD,
        [numpy.array([0.0, 0.0, 0.0]),
         numpy.array([2.0, 1.0, 0.0])], [3, 5], CellType.triangle)
    V = FunctionSpace(mesh, "CG", 1)
    f = 2.0
    g = 3.0
    v = TestFunction(V)
    u = TrialFunction(V)

    F = inner(g * grad(f * v), grad(u)) * dx + f * v * dx
    a, L = system(F)

    Fl = lhs(F)
    Fr = rhs(F)
    assert (Fr)

    a0 = inner(grad(v), grad(u)) * dx

    n = assemble(a).norm("frobenius")  # noqa
    nl = assemble(Fl).norm("frobenius")  # noqa
    n0 = 6.0 * assemble(a0).norm("frobenius")  # noqa

    assert round(n - n0, 7) == 0
    assert round(n - nl, 7) == 0
def test_save_and_read_function_timeseries(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)

    t = 0.0

    def E(x):
        return t * x[0]

    F0.interpolate(E)

    # Save to HDF5 File
    hdf5_file = HDF5File(mesh.mpi_comm(), filename, "w")
    for t in range(10):
        F0.interpolate(E)
        hdf5_file.write(F0, "/function", t)
    hdf5_file.close()

    # Read back from file
    hdf5_file = HDF5File(mesh.mpi_comm(), filename, "r")
    for t in range(10):
        F1.interpolate(E)
        vec_name = "/function/vector_{}".format(t)
        F0 = hdf5_file.read_function(Q, vec_name)
        # timestamp = hdf5_file.attributes(vec_name)["timestamp"]
        # assert timestamp == t
        F0.vector.axpy(-1.0, F1.vector)
        assert F0.vector.norm() < 1.0e-12
    hdf5_file.close()
Example #27
0
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]))
Example #28
0
def test_save_and_checkpoint_scalar(tempdir, encoding, fe_degree, fe_family,
                                    tdim, n):
    if invalid_fe(fe_family, fe_degree):
        pytest.skip("Trivial finite element")

    filename = os.path.join(tempdir, "u1_checkpoint.xdmf")
    mesh = mesh_factory(tdim, n)
    FE = FiniteElement(fe_family, mesh.ufl_cell(), fe_degree)
    V = FunctionSpace(mesh, FE)
    u_in = Function(V)
    u_out = Function(V)

    if has_petsc_complex:

        def expr_eval(x):
            return x[0] + 1.0j * x[0]

        u_out.interpolate(expr_eval)
    else:

        def expr_eval(x):
            return x[0]

        u_out.interpolate(expr_eval)

    with XDMFFile(mesh.mpi_comm(), filename, encoding=encoding) as file:
        file.write_checkpoint(u_out, "u_out", 0)

    with XDMFFile(mesh.mpi_comm(), filename) as file:
        u_in = file.read_checkpoint(V, "u_out", 0)

    u_in.vector.axpy(-1.0, u_out.vector)
    assert u_in.vector.norm() < 1.0e-12
Example #29
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)
Example #30
0
def assemble_div_vector(k, offset):
    mesh = create_quad_mesh(offset)
    V = FunctionSpace(mesh, ("RTCF", k + 1))
    v = ufl.TestFunction(V)
    form = ufl.inner(Constant(mesh, 1), ufl.div(v)) * ufl.dx
    L = fem.assemble_vector(form)
    return L[:]