def setUp(self):
     """
     Prepare for tests.
     """
     mesh = UnitCubeMesh(10, 10, 10)
     V = FunctionSpace(mesh, 'CG', 1)
     self.problem = MockProblem(mesh, V)
Ejemplo n.º 2
0
 def setUp(self):
     """
     Setup the mesh and function space.
     """
     self.m = UnitCubeMesh(10, 10, 10)
     self.V = FunctionSpace(self.m, 'CG', 1)
     self.out_dir = TemporaryDirectory()
Ejemplo n.º 3
0
def fdrake_mesh(request):
    mesh_name = request.param
    if mesh_name == "FiredrakeUnitIntervalMesh":
        return UnitIntervalMesh(100)
    elif mesh_name == "FiredrakeUnitSquareMesh":
        return UnitSquareMesh(10, 10)
    elif mesh_name == "FiredrakeUnitSquareMesh-order2":
        m = UnitSquareMesh(10, 10)
        fspace = VectorFunctionSpace(m, "CG", 2)
        coords = Function(fspace).interpolate(SpatialCoordinate(m))
        from firedrake.mesh import Mesh
        return Mesh(coords)
    elif mesh_name == "FiredrakeUnitCubeMesh":
        return UnitCubeMesh(5, 5, 5)
    elif mesh_name not in ("annulus.msh", "blob2d-order1-h4e-2.msh",
                           "blob2d-order1-h6e-2.msh",
                           "blob2d-order1-h8e-2.msh"):
        raise ValueError("Unexpected value for request.param")

    # Firedrake can't read in higher order meshes from gmsh,
    # so we can only use the order1 blobs
    from firedrake import Mesh
    fd_mesh = Mesh(mesh_name)
    fd_mesh.init()
    return fd_mesh
Ejemplo n.º 4
0
 def setUp(self):
     """
     Create a factory.
     """
     self.mesh = UnitCubeMesh(10, 10, 10)
     self.V = FunctionSpace(self.mesh, 'CG', 1)
     self.factory = FunctionBuilderFactory(self.mesh, self.V)
 def setUp(self):
     """
     Create the parser.
     """
     mesh = UnitCubeMesh(10, 10, 10)
     V = FunctionSpace(mesh, 'CG', 1)
     self.parser = InitialValParser(mesh=mesh, V=V)
 def setUp(self):
     """
     Create the parser.
     """
     mesh = UnitCubeMesh(10, 10, 10)
     V = FunctionSpace(mesh, 'CG', 1)
     self.parser = BoundaryCondsParser(mesh=mesh, V=V)
 def setUp(self):
     """
     Define the function builder.
     """
     m = UnitCubeMesh(10, 10, 10)
     V = FunctionSpace(m, 'CG', 1)
     self.func_builder = DummyFunctionBuilder(m, V)
Ejemplo n.º 8
0
    def test_can_initialise(self):
        """
        Test that the TimeDependantProblem can be instantiated.
        """
        m = UnitCubeMesh(10, 10, 10)
        V = FunctionSpace(m, 'CG', 1)

        _ = problem.TimeDependantProblem(m, V)
Ejemplo n.º 9
0
    def setUp(self):
        """
        Create a blank problem.
        """
        self.mesh = UnitCubeMesh(10, 10, 10)
        self.V = FunctionSpace(self.mesh, 'CG', 1)

        self.prob = problem.Problem(mesh=self.mesh, V=self.V)
Ejemplo n.º 10
0
    def setUp(self):
        """
        Create a problem.
        """
        m = UnitCubeMesh(10, 10, 10)
        V = FunctionSpace(m, 'CG', 1)

        self.problem = MockProblem(m, V)
Ejemplo n.º 11
0
 def setUp(self):
     """
     Prepare for tests.
     """
     self.mesh = UnitCubeMesh(10, 10, 10)
     self.V = FunctionSpace(self.mesh, 'CG', 1)
     self.problem = MockProblem(self.mesh, self.V)
     self.norm = FacetNormal(self.mesh)
Ejemplo n.º 12
0
    def test_can_initialise(self):
        """
        Test that the SteadyStateProblems can be instantiated.
        """
        m = UnitCubeMesh(10, 10, 10)
        V = FunctionSpace(m, 'CG', 1)

        _ = problem.SteadyStateProblem(m, V)
Ejemplo n.º 13
0
    def setUp(self):
        """
        Create the problem.
        """
        m = UnitCubeMesh(10, 10, 10)
        V = FunctionSpace(m, 'CG', 1)

        self.problem = MockProblem(m, V)
        self.stashed_args = ([], {})
Ejemplo n.º 14
0
    def setUp(self):
        """
        Define 2 functions and create an IterationMethod.
        """
        m = UnitCubeMesh(10, 10, 10)
        V = FunctionSpace(m, 'CG', 1)

        self.problem = MockProblem(m, V)
        self.im = IterationMethod(self.problem)
Ejemplo n.º 15
0
    def setUp(self):
        """
        Set up a problem and IterationMethod as all tests need these.
        """
        m = UnitCubeMesh(10, 10, 10)
        V = FunctionSpace(m, 'CG', 1)

        self.problem = MockProblem(m, V)
        self.im = IterationMethod(self.problem)
Ejemplo n.º 16
0
def run(problem, tensor, size_factor, degree):
    formname = problem.__name__
    cellname = 'cube' if tensor else 'simplex'
    PETSc.Sys.Print("%s: %s, degree=%d" % (formname, cellname, degree))
    num_cells = COMM_WORLD.size * max(1, 1e7 * size_factor / (degree + 1)**{'spectral': 4, 'coffee': 6}[args.mode])
    h = int(floor(cbrt(num_cells / COMM_WORLD.size)))
    w = int(floor(sqrt(num_cells / h)))
    d = int(round(num_cells / (w * h)))
    num_cells = w * d * h

    if tensor:
        mesh = ExtrudedMesh(UnitSquareMesh(w, d, quadrilateral=True), h)
    else:
        mesh = UnitCubeMesh(w, d, h)
    comm = mesh.comm
    J = problem(mesh, int(degree))

    # Warmup and allocate
    A = assemble(J, mat_type="matfree", form_compiler_parameters={'mode': args.mode})
    A.force_evaluation()
    Ap = A.petscmat
    x, y = Ap.createVecs()
    assert x.size == y.size
    num_dofs = x.size
    Ap.mult(x, y)
    stage = PETSc.Log.Stage("%s(%d) %s" % (formname, degree, cellname))
    with stage:
        assemble(J, mat_type="matfree", form_compiler_parameters={'mode': args.mode}, tensor=A)
        A.force_evaluation()
        Ap = A.petscmat
        for _ in range(num_matvecs):
            Ap.mult(x, y)

        parloop = parloop_event.getPerfInfo()
        matmult = matmult_event.getPerfInfo()
        assert parloop["count"] == 2 * num_matvecs
        assert matmult["count"] == num_matvecs
        parloop_time = comm.allreduce(parloop["time"], op=MPI.SUM) / (comm.size * num_matvecs)
        matmult_time = comm.allreduce(matmult["time"], op=MPI.SUM) / (comm.size * num_matvecs)

        matfree_overhead = (1 - parloop_time / matmult_time)
        PETSc.Sys.Print("Matrix-free action overhead: %.1f%%" % (matfree_overhead * 100,))

    if COMM_WORLD.rank == 0:
        header = not os.path.exists(filepath)
        data = {"num_cells": num_cells,
                "num_dofs": num_dofs,
                "num_procs": comm.size,
                "tsfc_mode": args.mode,
                "problem": formname,
                "cell_type": cellname,
                "degree": degree,
                "matmult_time": matmult_time,
                "parloop_time": parloop_time}
        df = pandas.DataFrame(data, index=[0])
        df.to_csv(filepath, index=False, mode='a', header=header)
Ejemplo n.º 17
0
    def test_spatial_coord_x_2(self):
        """
        Test spatial coords are correctly parsed.
        """
        mesh = UnitCubeMesh(10, 10, 10)
        V = FunctionSpace(mesh, 'CG', 1)

        x = Terminal('x[2]').evaluate(mesh, V)
        self.assertIsInstance(x, Function)
        self.assertAlmostEqual(x([0.12, 0.84, 0.61]).item(), 0.61)
Ejemplo n.º 18
0
    def setUp(self):
        """
        Create a function builder and input file.
        """
        self.mesh = UnitCubeMesh(10, 10, 10)
        self.V = FunctionSpace(self.mesh, 'CG', 1)
        self.fb = FileBuilder(self.mesh, self.V)

        self.input = NamedTemporaryFile(mode='w+')
        self.fb.assign('path', self.input.name)
Ejemplo n.º 19
0
    def setUp(self):
        """
        Create a problem and function to set bounds on.
        """
        self.mesh = UnitCubeMesh(10, 10, 10)
        self.V = FunctionSpace(self.mesh, 'CG', 1)

        self.prob = problem.Problem(mesh=self.mesh, V=self.V)

        self.prob.to_bound = Function(self.V)
        self.prob.test_func = self.prob.to_bound + 1
Ejemplo n.º 20
0
    def setUp(self):
        """
        Create mesh and function space.
        """
        class MockProblem(FluxLimiterMixin, Problem):
            """
            Fake problem to test the flux limiter mixin.
            """

        self.cls = MockProblem

        self.mesh = UnitCubeMesh(10, 10, 10)
        self.V = FunctionSpace(self.mesh, 'CG', 1)
Ejemplo n.º 21
0
    def setUp(self):
        """
        Create mesh and function space.
        """
        class MockProblem(ConductivityLimiterMixin, Problem):
            """
            Fake problem to test the spitzer harm mixin.
            """

        self.cls = MockProblem

        self.mesh = UnitCubeMesh(10, 10, 10)
        self.V = FunctionSpace(self.mesh, 'CG', 1)
Ejemplo n.º 22
0
    def get_fdrake_mesh_and_h_from_par(mesh_par):
        if fdrake_mesh_name == "UnitInterval":
            assert dim == 1
            n = mesh_par
            fdrake_mesh = UnitIntervalMesh(n)
            h = 1 / n
        elif fdrake_mesh_name == "UnitSquare":
            assert dim == 2
            n = mesh_par
            fdrake_mesh = UnitSquareMesh(n, n)
            h = 1 / n
        elif fdrake_mesh_name == "UnitCube":
            assert dim == 3
            n = mesh_par
            fdrake_mesh = UnitCubeMesh(n, n, n)
            h = 1 / n
        elif fdrake_mesh_name in ("blob2d-order1", "blob2d-order4"):
            assert dim == 2
            if fdrake_mesh_name == "blob2d-order1":
                from firedrake import Mesh
                fdrake_mesh = Mesh(f"{fdrake_mesh_name}-h{mesh_par}.msh",
                                   dim=dim)
            else:
                from meshmode.mesh.io import read_gmsh
                from meshmode.interop.firedrake import export_mesh_to_firedrake
                mm_mesh = read_gmsh(f"{fdrake_mesh_name}-h{mesh_par}.msh",
                                    force_ambient_dim=dim)
                fdrake_mesh, _, _ = export_mesh_to_firedrake(mm_mesh)
            h = float(mesh_par)
        elif fdrake_mesh_name == "warp":
            from meshmode.mesh.generation import generate_warped_rect_mesh
            from meshmode.interop.firedrake import export_mesh_to_firedrake
            mm_mesh = generate_warped_rect_mesh(dim,
                                                order=4,
                                                nelements_side=mesh_par)
            fdrake_mesh, _, _ = export_mesh_to_firedrake(mm_mesh)
            h = 1 / mesh_par
        else:
            raise ValueError("fdrake_mesh_name not recognized")

        return (fdrake_mesh, h)
Ejemplo n.º 23
0
 def setUp(self):
     """
     Setup the mesh and function space.
     """
     self.m = UnitCubeMesh(10, 10, 10)
     self.V = FunctionSpace(self.m, 'CG', 1)
Ejemplo n.º 24
0
    # Ensure the discretization and the firedrake function space reference element
    # agree on some basic properties
    finat_elt = fdrake_fspace.finat_element
    assert len(discr.groups) == 1
    assert discr.groups[0].order == finat_elt.degree
    assert discr.groups[0].nunit_dofs == finat_elt.space_dimension()


# }}}

# {{{ Boundary tags checking

bdy_tests = [
    (UnitSquareMesh(10, 10), [1, 2, 3, 4], [0, 0, 1, 1], [0.0, 1.0, 0.0, 1.0]),
    (UnitCubeMesh(5, 5, 5), [1, 2, 3, 4, 5,
                             6], [0, 0, 1, 1, 2,
                                  2], [0.0, 1.0, 0.0, 1.0, 0.0, 1.0]),
]


@pytest.mark.parametrize(
    "square_or_cube_mesh,bdy_ids,coord_indices,coord_values", bdy_tests)
@pytest.mark.parametrize("only_convert_bdy", (True, False))
def test_bdy_tags(square_or_cube_mesh, bdy_ids, coord_indices, coord_values,
                  only_convert_bdy):
    """
    Make sure the given boundary ids cover the converted mesh.
    Make sure that the given coordinate have the given value for the
    corresponding boundary tag (see :mod:`firedrake.utility_meshes`'s
    documentation to see how the boundary tags for its utility meshes are
    # agree on some basic properties
    finat_elt = fdrake_fspace.finat_element
    assert len(discr.groups) == 1
    assert discr.groups[0].order == finat_elt.degree
    assert discr.groups[0].nunit_dofs == finat_elt.space_dimension()

# }}}


# {{{ Boundary tags checking

bdy_tests = [(UnitSquareMesh(10, 10),
             [1, 2, 3, 4],
             [0, 0, 1, 1],
             [0.0, 1.0, 0.0, 1.0]),
             (UnitCubeMesh(5, 5, 5),
              [1, 2, 3, 4, 5, 6],
              [0, 0, 1, 1, 2, 2],
              [0.0, 1.0, 0.0, 1.0, 0.0, 1.0]),
             ]


@pytest.mark.parametrize("square_or_cube_mesh,bdy_ids,coord_indices,coord_values",
                         bdy_tests)
@pytest.mark.parametrize("only_convert_bdy", (True, False))
def test_bdy_tags(square_or_cube_mesh, bdy_ids, coord_indices, coord_values,
                  only_convert_bdy):
    """
    Make sure the given boundary ids cover the converted mesh.
    Make sure that the given coordinate have the given value for the
    corresponding boundary tag (see :mod:`firedrake.utility_meshes`'s
Ejemplo n.º 26
0
 def setUp(self):
     mesh = UnitCubeMesh(10, 10, 10)
     V = FunctionSpace(mesh, 'CG', 1)
     self.factory = FunctionBuilderFactory(mesh=mesh, V=V)
Ejemplo n.º 27
0
def main():
    # make function space and function
    dim = 2  # 2 or 3
    order = 1

    logger.info(f"building {dim}D source and solution exprs")
    if dim == 2:
        m = UnitSquareMesh(32, 32)
    elif dim == 3:
        m = UnitCubeMesh(16, 16, 16)
    else:
        raise ValueError("dim must be 2 or 3, not %s" % dim)
    # get spatial coordinate, shifted so that [0,1]^2 -> [-0.5,0.5]^2
    xx = SpatialCoordinate(m)
    shifted_xx = as_tensor([xx_i - 0.5 for xx_i in xx])
    norm2 = sum([xx_i * xx_i for xx_i in shifted_xx])
    alpha = 10
    source_expr = -(4 * alpha**2 * norm2 - 2 * dim * alpha) * exp(
        -alpha * norm2)
    sol_expr = exp(-alpha * norm2)

    logger.info("source_expr : %s" % source_expr)
    logger.info("sol_expr : %s" % sol_expr)

    logger.info(f"Building FunctionSpace of order {order}")
    fspace = FunctionSpace(m, 'DG', order)
    logger.info("interpolating source and solution")
    source = Function(fspace).interpolate(source_expr)
    sol = Function(fspace).interpolate(sol_expr)

    from sumpy.kernel import LaplaceKernel
    kernel = LaplaceKernel(m.geometric_dimension())

    # We could set to a custom group factory if we wanted to,
    # defaults to recursive nodes with 'lgl' nodes
    #
    # from meshmode.discretization.poly_element import (
    #     PolynomialWarpAndBlendGroupFactory)
    # grp_factory = PolynomialWarpAndBlendGroupFactory(order)
    grp_factory = None

    # Build VolumePotential external operator
    cl_ctx = cl.create_some_context()
    queue = cl.CommandQueue(cl_ctx)
    potential_data = {
        'kernel': kernel,
        'kernel_type': "Laplace",
        'cl_ctx': cl_ctx,
        'queue': queue,
        'nlevels': 6,
        'm_order': 20,
        'dataset_filename': f"laplace-order{order}-{dim}D.hdf5",
        'grp_factory': grp_factory,
        'root_extent': 2,
        'table_compute_method': "DrosteSum",
        'table_kwargs': {
            'force_recompute': False,
            'n_brick_quad_points': 100,
            'adaptive_level': False,
            'use_symmetry': True,
            'alpha': 0.1,
            'nlevels': 15,
        },
        'fmm_kwargs': {},
    }

    logger.info("Creating volume potential")
    # pot = VolumePotential(source, function_space=source.function_space(), operator_data=potential_data)

    # logger.info("Evaluating potential and assembling L^2 Error")
    # ell2_difference = sqrt(assemble(inner(pot - sol, pot - sol) * dx))

    # print("L^2 difference: %e" % ell2_difference)
    print("interpolation error: %e" % errornorm(sol_expr, sol))