Exemplo n.º 1
0
    def test_compute_entity_collisions_tree_1d(self):

        references = [[set([8, 9, 10, 11, 12, 13, 14, 15]),
                       set([0, 1, 2, 3, 4, 5, 6, 7])],
                      [set([14, 15]),
                       set([0, 1])]]

        points = [Point(0.52), Point(0.9)]

        for i, point in enumerate(points):

            mesh_A = UnitIntervalMesh(16)
            mesh_B = UnitIntervalMesh(16)

            mesh_B.translate(point)

            tree_A = BoundingBoxTree()
            tree_A.build(mesh_A)

            tree_B = BoundingBoxTree()
            tree_B.build(mesh_B)

            entities_A, entities_B = tree_A.compute_entity_collisions(tree_B)

            if MPI.size(mesh_A.mpi_comm()) == 1:
                self.assertEqual(set(entities_A), references[i][0])
                self.assertEqual(set(entities_B), references[i][1])
Exemplo n.º 2
0
def test_compute_collisions_tree_1d():

    references = [[set([8, 9, 10, 11, 12, 13, 14, 15]),
                    set([0, 1, 2, 3, 4, 5, 6, 7])],
                  [set([14, 15]),
                    set([0, 1])]]

    points = [Point(0.52), Point(0.9)]

    for i, point in enumerate(points):

        mesh_A = UnitIntervalMesh(16)
        mesh_B = UnitIntervalMesh(16)

        mesh_B.translate(point)

        tree_A = BoundingBoxTree()
        tree_A.build(mesh_A)

        tree_B = BoundingBoxTree()
        tree_B.build(mesh_B)

        entities_A, entities_B = tree_A.compute_collisions(tree_B)

        assert set(entities_A) == references[i][0]
        assert set(entities_B) == references[i][1]
Exemplo n.º 3
0
    def test_mesh_point_1d(self):
        "Test mesh-point intersection in 1D"

        point = Point(0.1)
        mesh = UnitIntervalMesh(16)

        intersection = intersect(mesh, point)

        if MPI.size(mesh.mpi_comm()) == 1:
            self.assertEqual(intersection.intersected_cells(), [1])
Exemplo n.º 4
0
    def test_compute_collisions_point_1d(self):

        reference = {1: set([4])}

        p = Point(0.3)
        mesh = UnitIntervalMesh(16)
        for dim in range(1, 2):
            tree = BoundingBoxTree()
            tree.build(mesh, dim)
            entities = tree.compute_collisions(p)
            if MPI.size(mesh.mpi_comm()) == 1:
                self.assertEqual(set(entities), reference[dim])
Exemplo n.º 5
0
def test_compute_first_entity_collision_1d():

    reference = [4]

    p = Point(0.3)
    mesh = UnitIntervalMesh(16)
    tree = BoundingBoxTree()
    tree.build(mesh)
    first = tree.compute_first_entity_collision(p)
    assert first in reference

    tree = mesh.bounding_box_tree()
    first = tree.compute_first_entity_collision(p)
    assert first in reference
Exemplo n.º 6
0
def test_compute_entity_collisions_1d():

    reference = set([4])

    p = Point(0.3)
    mesh = UnitIntervalMesh(16)

    tree = BoundingBoxTree()
    tree.build(mesh)
    entities = tree.compute_entity_collisions(p)
    assert set(entities) == reference

    tree = mesh.bounding_box_tree()
    entities = tree.compute_entity_collisions(p)
    assert set(entities) == reference
Exemplo n.º 7
0
def test_compute_first_collision_1d():

    reference = {1: [4]}

    p = Point(0.3)
    mesh = UnitIntervalMesh(16)
    for dim in range(1, 2):
        tree = BoundingBoxTree()
        tree.build(mesh, dim)
        first = tree.compute_first_collision(p)
        assert first in reference[dim]

    tree = mesh.bounding_box_tree()
    first = tree.compute_first_collision(p)
    assert first in reference[mesh.topology().dim()]
Exemplo n.º 8
0
    def test_compute_first_entity_collision_1d(self):

        reference = [4]

        p = Point(0.3)
        mesh = UnitIntervalMesh(16)
        tree = BoundingBoxTree()
        tree.build(mesh)
        first = tree.compute_first_entity_collision(p)
        if MPI.size(mesh.mpi_comm()) == 1:
            self.assertIn(first, reference)

        tree = mesh.bounding_box_tree()
        first = tree.compute_first_entity_collision(p)
        if MPI.size(mesh.mpi_comm()) == 1:
            self.assertIn(first, reference)
Exemplo n.º 9
0
    def test_compute_first_collision_1d(self):

        reference = {1: [4]}

        p = Point(0.3)
        mesh = UnitIntervalMesh(16)
        for dim in range(1, 2):
            tree = BoundingBoxTree()
            tree.build(mesh, dim)
            first = tree.compute_first_collision(p)
            if MPI.size(mesh.mpi_comm()) == 1:
                self.assertIn(first, reference[dim])

        tree = mesh.bounding_box_tree()
        first = tree.compute_first_collision(p)
        if MPI.size(mesh.mpi_comm()) == 1:
            self.assertIn(first, reference[mesh.topology().dim()])
Exemplo n.º 10
0
    def test_compute_entity_collisions_1d(self):

        reference = [4]

        p = Point(0.3)
        mesh = UnitIntervalMesh(16)
        tree = BoundingBoxTree()
        tree.build(mesh)
        entities = tree.compute_entity_collisions(p, mesh)
        if MPI.num_processes() == 1:
            self.assertEqual(sorted(entities), reference)

        tree = mesh.bounding_box_tree()
        entities = tree.compute_entity_collisions(p, mesh)
        
        if MPI.num_processes() == 1:
            self.assertEqual(sorted(entities), reference)
Exemplo n.º 11
0
def test_compute_closest_entity_1d():

    reference = (0, 1.0)

    p = Point(-1.0)
    mesh = UnitIntervalMesh(16)
    tree = BoundingBoxTree()
    tree.build(mesh)
    entity, distance = tree.compute_closest_entity(p)

    assert entity == reference[0]
    assert round(distance - reference[1], 7) == 0

    tree = mesh.bounding_box_tree()
    entity, distance = tree.compute_closest_entity(p)
    assert entity == reference[0]
    assert round(distance - reference[1], 7) == 0
Exemplo n.º 12
0
    def test_compute_collisions_1d(self):

        reference = {1: [4]}

        p = Point(0.3)
        mesh = UnitIntervalMesh(16)
        for dim in range(1, 2):
            tree = BoundingBoxTree()
            tree.build(mesh, dim)
            entities = tree.compute_collisions(p)
            if MPI.num_processes() == 1:
                self.assertEqual(sorted(entities), reference[dim])

        tree = mesh.bounding_box_tree()
        entities = tree.compute_collisions(p)
        if MPI.num_processes() == 1:
            self.assertEqual(sorted(entities), reference[mesh.topology().dim()])
Exemplo n.º 13
0
    def test_compute_entity_collisions_1d(self):

        reference = set([4])

        p = Point(0.3)
        mesh = UnitIntervalMesh(16)

        tree = BoundingBoxTree()
        tree.build(mesh)
        entities = tree.compute_entity_collisions(p)
        if MPI.size(mesh.mpi_comm()) == 1:
            self.assertEqual(set(entities), reference)

        tree = mesh.bounding_box_tree()
        entities = tree.compute_entity_collisions(p)

        if MPI.size(mesh.mpi_comm()) == 1:
            self.assertEqual(set(entities), reference)
Exemplo n.º 14
0
    def test_compute_closest_entity_1d(self):

        reference = (0, 1.0)

        p = Point(-1.0)
        mesh = UnitIntervalMesh(16)
        tree = BoundingBoxTree()
        tree.build(mesh)
        entity, distance = tree.compute_closest_entity(p)

        if MPI.size(mesh.mpi_comm()) == 1:
            self.assertEqual(entity, reference[0])
            self.assertAlmostEqual(distance, reference[1])

        tree = mesh.bounding_box_tree()
        entity, distance = tree.compute_closest_entity(p)
        if MPI.size(mesh.mpi_comm()) == 1:
            self.assertEqual(entity, reference[0])
            self.assertAlmostEqual(distance, reference[1])
Exemplo n.º 15
0
    def test_transport_rectangle(self):
        m, n = 10, 100
        v = 0.1 * np.ones((m, n))

        # Define mesh.
        mesh = UnitIntervalMesh(n - 1)

        # Define function spaces
        V = FunctionSpace(mesh, 'CG', 1)

        f0 = Rectangle(degree=1)
        f0 = interpolate(f0, V)

        # Compute transport
        f = transport1d(v, np.zeros_like(v), f0.vector().get_local())

        fig, ax = plt.subplots(figsize=(10, 5))
        cax = ax.imshow(f, cmap=cm.coolwarm)
        fig.colorbar(cax, orientation='vertical')
        plt.show()
        plt.close(fig)

        np.testing.assert_equal(f.shape, (m + 1, n))
Exemplo n.º 16
0
def test_block_size_real(mesh):
    mesh = UnitIntervalMesh(12)
    V = FiniteElement('DG', mesh.ufl_cell(), 0)
    R = FiniteElement('R', mesh.ufl_cell(), 0)
    X = FunctionSpace(mesh, V * R)
    assert X.dofmap().index_map.block_size == 1
Exemplo n.º 17
0
def interval():
    return UnitIntervalMesh(MPI.comm_world, 10)
Exemplo n.º 18
0
def mesh1d():
    # Create 1D mesh with degenerate cell
    mesh1d = UnitIntervalMesh(MPI.comm_world, 4)
    mesh1d.geometry.points[4] = mesh1d.geometry.points[3]
    return mesh1d
Exemplo n.º 19
0
 def initMesh(self, n):
     self.mesh = UnitIntervalMesh(n)
Exemplo n.º 20
0
def test_structured(tol=1E-15):
    'Test with structured non-uniform mesh. Fenicstools vs matrix.'
    passed = []
    for d in [1, 2, 3]:
        if d == 1:
            mesh = UnitIntervalMesh(20)
            mesh.coordinates()[:] = np.cos(2*pi*mesh.coordinates())
        elif d == 2:
            mesh = UnitSquareMesh(20, 20)
            mesh.coordinates()[:] = np.cos(2*pi*mesh.coordinates())
        else:
            mesh = UnitCubeMesh(5, 5, 5)
            mesh.coordinates()[:, 0] = mesh.coordinates()[:, 0]**3
            mesh.coordinates()[:, 1] = mesh.coordinates()[:, 1]**2
            mesh.coordinates()[:, 2] = mesh.coordinates()[:, 2]**2

        for j in range(d):
            WP = build_WP(mesh, 'harmonic', i=j).array()
            F_WP = f_build_WP(mesh, i=j).array()
            e = np.linalg.norm(WP - F_WP)/WP.shape[0]
            passed.append(e < tol)
    assert(all(passed))
Exemplo n.º 21
0
def structured_mesh_1d():
    return UnitIntervalMesh(24)
Exemplo n.º 22
0
def test_dolfin():
    from dolfin import FiniteElement, FunctionSpace, UnitIntervalMesh, interval

    mesh = UnitIntervalMesh(20)
    elem = FiniteElement("CG", interval, 1)
    W = FunctionSpace(mesh, elem)
Exemplo n.º 23
0
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writeheader()

    for step in range(steps):

        if model == 'SmoothSol':

            fac = 2**(step)
            # Set discretization level
            nt = 30 * fac
            nx = 5 * fac
            ny = 5 * fac
            T = [0, 1]

            # Mesh for stochastic part
            mx = UnitIntervalMesh(nx)
            x = SpatialCoordinate(mx)[0]

            # Mesh for deterministic part
            my = UnitIntervalMesh(ny)
            y = SpatialCoordinate(my)[0]

            # Set up coefficients as described above
            # Diffusion in x direction
            ax = as_matrix([[1]])

            # Convection in x direction
            bx = as_vector([0])

            # Convection in y direction
            def by(t, x, y):
Exemplo n.º 24
0
def meshes_p1():
    return UnitIntervalMesh(10), UnitSquareMesh(3, 3), UnitCubeMesh(2, 2, 2)
Exemplo n.º 25
0
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with DOLFIN. If not, see <http://www.gnu.org/licenses/>.

import pytest
import numpy as np
from dolfin import (UnitIntervalMesh, UnitSquareMesh, UnitCubeMesh, Point, MPI,
                    FunctionSpace, TestFunction, TrialFunction, assemble,
                    Constant, PointSource, dx, Cell, VectorFunctionSpace, near,
                    vertex_to_dof_map, vertices, dot, FiniteElement, Function,
                    VectorElement, MixedElement)

meshes = [UnitIntervalMesh(10), UnitSquareMesh(10, 10), UnitCubeMesh(4, 4, 4)]
data = [(UnitIntervalMesh(10), Point(0.5)),
        (UnitSquareMesh(10, 10), Point(0.5, 0.5)),
        (UnitCubeMesh(3, 3, 3), Point(0.5, 0.5, 0.5))]


@pytest.mark.parametrize("mesh, point", data)
def test_pointsource_vector_node(mesh, point):
    """Tests point source when given constructor PointSource(V, point,
    mag) with a vector and when placed at a node for 1D, 2D and
    3D. Global points given to constructor from rank 0 processor.

    """

    rank = MPI.rank(mesh.mpi_comm())
    V = FunctionSpace(mesh, "CG", 1)
Exemplo n.º 26
0
 def mesh_generator(n):
     return UnitIntervalMesh(n)
Exemplo n.º 27
0
m, n = 40, 200

# Define parameters of artificial velocity field.
c0 = 0.05
v0 = 0.5
tau0 = 0.5
tau1 = 0.5

# Create artificial velocity.
v = velocity(m, n, c0, v0, tau0, tau1)

# Convert to array.
v = funvec2img(v.vector().get_local(), m, n)

# Define mesh.
mesh = UnitIntervalMesh(n - 1)

# Define function spaces
V = FunctionSpace(mesh, 'CG', 1)


class DoubleHat(UserExpression):
    def eval(self, value, x):
        value[0] = max(0, 0.1 - abs(x[0] - 0.4)) \
            + max(0, 0.1 - abs(x[0] - 0.6))

    def value_shape(self):
        return ()


class InitialData(UserExpression):
Exemplo n.º 28
0
def test_ghost_facet_1d():
    mesh = UnitIntervalMesh(MPI.comm_world,
                            20,
                            ghost_mode=cpp.mesh.GhostMode.shared_facet)
    assert mesh.num_entities_global(0) == 21
    assert mesh.num_entities_global(1) == 20
Exemplo n.º 29
0
import numpy as np
from dolfin import (
    interpolate,
    Constant,
    Expression,
    FunctionSpace,
    UnitIntervalMesh,
)

from tests.utils.solves import assert_solves
from tests.utils.types import assemble_with_mixed_types

MESH = UnitIntervalMesh(32)
EXACT_EXPRESSION = "sin(DOLFIN_PI * x[0])"
EXACT = Expression(EXACT_EXPRESSION, degree=4)

DIFFUSIVITY = 1.0 / (np.pi * np.pi)
DIFFUSION_TERM = f"DOLFIN_PI * DOLFIN_PI * {DIFFUSIVITY} * {EXACT_EXPRESSION}"

CONVECTIVITY = [1.0 / np.pi]
CONVECTION_TERM = "-cos(DOLFIN_PI * x[0])"

REACTIVITY = 1.0
REACTION_TERM = EXACT_EXPRESSION


def test_1d_types():
    mesh = UnitIntervalMesh(4)
    CG = FunctionSpace(mesh, "CG", 1)
    DG = FunctionSpace(mesh, "DG", 0)
    diffusion = Expression("1. + x[0] * (1. - x[0])", degree=2)
Exemplo n.º 30
0
from dolfin import Expression, plot, UnitIntervalMesh
from ufl.algorithms import estimate_total_polynomial_degree as get_degree


class MyExpr(Expression):
    def __init__(self, a, **kwargs):
        self.a = a

    def eval(self, value, x):
        value[0] = x[0] + self.a


f = MyExpr(10, degree=10)
assert get_degree(f) == 10

mesh = UnitIntervalMesh(100)
plot(f, mesh=mesh, interactive=True)
Exemplo n.º 31
0
def test_diff_then_integrate():

    # Define 1D geometry
    n = 21
    mesh = UnitIntervalMesh(MPI.comm_world, n)

    # Shift and scale mesh
    x0, x1 = 1.5, 3.14
    mesh.coordinates()[:] *= (x1 - x0)
    mesh.coordinates()[:] += x0

    x = SpatialCoordinate(mesh)[0]
    xs = 0.1 + 0.8 * x / x1  # scaled to be within [0.1,0.9]

    # Define list of expressions to test, and configure
    # accuracies these expressions are known to pass with.
    # The reason some functions are less accurately integrated is
    # likely that the default choice of quadrature rule is not perfect
    F_list = []

    def reg(exprs, acc=10):
        for expr in exprs:
            F_list.append((expr, acc))

    # FIXME: 0*dx and 1*dx fails in the ufl-ffc-jit framework somewhere
    # reg([Constant(0.0, cell=cell)])
    # reg([Constant(1.0, cell=cell)])
    monomial_list = [x**q for q in range(2, 6)]
    reg(monomial_list)
    reg([2.3 * p + 4.5 * q for p in monomial_list for q in monomial_list])
    reg([x**x])
    reg([x**(x**2)], 8)
    reg([x**(x**3)], 6)
    reg([x**(x**4)], 2)
    # Special functions:
    reg([atan(xs)], 8)
    reg([sin(x), cos(x), exp(x)], 5)
    reg([ln(xs), pow(x, 2.7), pow(2.7, x)], 3)
    reg([asin(xs), acos(xs)], 1)
    reg([tan(xs)], 7)

    try:
        import scipy
    except ImportError:
        scipy = None

    if hasattr(math, 'erf') or scipy is not None:
        reg([erf(xs)])
    else:
        print(
            "Warning: skipping test of erf, old python version and no scipy.")

    # if 0:
    #     print("Warning: skipping tests of bessel functions, doesn't build on all platforms.")
    # elif scipy is None:
    #     print("Warning: skipping tests of bessel functions, missing scipy.")
    # else:
    #     for nu in (0, 1, 2):
    #         # Many of these are possibly more accurately integrated,
    #         # but 4 covers all and is sufficient for this test
    #         reg([bessel_J(nu, xs), bessel_Y(nu, xs), bessel_I(nu, xs), bessel_K(nu, xs)], 4)

    # To handle tensor algebra, make an x dependent input tensor
    # xx and square all expressions
    def reg2(exprs, acc=10):
        for expr in exprs:
            F_list.append((inner(expr, expr), acc))

    xx = as_matrix([[2 * x**2, 3 * x**3], [11 * x**5, 7 * x**4]])
    x3v = as_vector([3 * x**2, 5 * x**3, 7 * x**4])
    cc = as_matrix([[2, 3], [4, 5]])
    reg2([xx])
    reg2([x3v])
    reg2([cross(3 * x3v, as_vector([-x3v[1], x3v[0], x3v[2]]))])
    reg2([xx.T])
    reg2([tr(xx)])
    reg2([det(xx)])
    reg2([dot(xx, 0.1 * xx)])
    reg2([outer(xx, xx.T)])
    reg2([dev(xx)])
    reg2([sym(xx)])
    reg2([skew(xx)])
    reg2([elem_mult(7 * xx, cc)])
    reg2([elem_div(7 * xx, xx + cc)])
    reg2([elem_pow(1e-3 * xx, 1e-3 * cc)])
    reg2([elem_pow(1e-3 * cc, 1e-3 * xx)])
    reg2([elem_op(lambda z: sin(z) + 2, 0.03 * xx)], 2)  # pretty inaccurate...

    # FIXME: Add tests for all UFL operators:
    # These cause discontinuities and may be harder to test in the
    # above fashion:
    # 'inv', 'cofac',
    # 'eq', 'ne', 'le', 'ge', 'lt', 'gt', 'And', 'Or', 'Not',
    # 'conditional', 'sign',
    # 'jump', 'avg',
    # 'LiftingFunction', 'LiftingOperator',

    # FIXME: Test other derivatives: (but algorithms for operator
    # derivatives are the same!):
    # 'variable', 'diff',
    # 'Dx', 'grad', 'div', 'curl', 'rot', 'Dn', 'exterior_derivative',

    # Run through all operators defined above and compare integrals
    debug = 0
    for F, acc in F_list:
        # Apply UFL differentiation
        f = diff(F, SpatialCoordinate(mesh))[..., 0]
        if debug:
            print(F)
            print(x)
            print(f)

        # Apply integration with DOLFIN
        # (also passes through form compilation and jit)
        M = f * dx
        f_integral = assemble_scalar(M)  # noqa
        f_integral = MPI.sum(mesh.mpi_comm(), f_integral)

        # Compute integral of f manually from anti-derivative F
        # (passes through PyDOLFIN interface and uses UFL evaluation)
        F_diff = F((x1, )) - F((x0, ))

        # Compare results. Using custom relative delta instead
        # of decimal digits here because some numbers are >> 1.
        delta = min(abs(f_integral), abs(F_diff)) * 10**-acc
        assert f_integral - F_diff <= delta
Exemplo n.º 32
0
def test_distance_tetrahedron():
    mesh = UnitCubeMesh(MPI.comm_self, 1, 1, 1)
    cell = MeshEntity(mesh, mesh.topology.dim, 5)
    assert cpp.geometry.squared_distance(cell,
                                         numpy.array([-1.0, -1.0, -1.0
                                                      ])) == pytest.approx(3.0)
    assert cpp.geometry.squared_distance(cell,
                                         numpy.array([-1.0, 0.5, 0.5
                                                      ])) == pytest.approx(1.0)
    assert cpp.geometry.squared_distance(cell,
                                         numpy.array([0.5, 0.5, 0.5
                                                      ])) == pytest.approx(0.0)


@pytest.mark.parametrize('mesh', [
    UnitIntervalMesh(MPI.comm_world, 8),
    UnitSquareMesh(MPI.comm_world, 8, 9, CellType.triangle),
    UnitSquareMesh(MPI.comm_world, 8, 9, CellType.quadrilateral),
    UnitCubeMesh(MPI.comm_world, 8, 9, 5, CellType.tetrahedron)
])
def test_volume_cells(mesh):
    num_cells = mesh.num_entities(mesh.topology.dim)
    v = cpp.mesh.volume_entities(mesh, range(num_cells), mesh.topology.dim)
    v = MPI.sum(mesh.mpi_comm(), v.sum())
    assert v == pytest.approx(1.0, rel=1e-9)


def test_volume_quadrilateralR2():
    mesh = UnitSquareMesh(MPI.comm_self, 1, 1, CellType.quadrilateral)
    assert cpp.mesh.volume_entities(mesh, [0], mesh.topology.dim) == 1.0