def test_tabulate_matrix_rank(cell):
    fe = LagrangeElement(cell, 2)

    points = np.ones((4, cell.dim))

    t = fe.tabulate(points)

    assert len(t.shape) == 2, \
        "tabulate must return a rank 2 array, not rank %s" % len(t.shape)
def test_tabulate_type(cell):
    fe = LagrangeElement(cell, 2)

    points = np.ones((4, cell.dim))

    t = fe.tabulate(points)

    assert isinstance(t, np.ndarray), \
        "tabulate must return a numpy array, not a %s" % type(t)
def test_tabulate_grad_shape(cell, degree):
    """Check that tabulating at the nodes produces the identity matrix."""
    fe = LagrangeElement(cell, degree)

    vals = fe.tabulate(np.array([[0] * cell.dim]), grad=True)

    correct_shape = (1, fe.nodes.shape[0], cell.dim)

    assert vals.shape == correct_shape, \
        "tabulate should have returned an array of shape %s, not %s"\
        % (correct_shape, vals.shape)
def test_tabulate_matrix_size(cell, degree):
    fe = LagrangeElement(cell, 2)

    points = np.ones((4, cell.dim))

    shape = fe.tabulate(points).shape

    correct_shape = (4, fe.nodes.shape[0])

    assert shape == correct_shape, \
        "tabulate should have returned an array of shape %s, not %s"\
        % (correct_shape, shape)
def test_tabulate_grad_1D():
    """Check that tabulating the gradient of a first degree element is correct."""
    fe = LagrangeElement(ReferenceInterval, 1)

    vals = fe.tabulate(np.array([[0]]), grad=True)

    correct_answer = np.array([[[-1], [1]]], dtype=np.double)

    print "Your answer is:"
    print vals
    print "The correct answer is:"
    print correct_answer

    assert ((vals - correct_answer).round(12) == 0).all()
def test_tabulate_grad_2D():
    """Check that tabulating the gradient of a first degree element is correct."""
    fe = LagrangeElement(ReferenceTriangle, 1)

    vals = fe.tabulate(np.array([[0, 0]]), grad=True)

    # The order of this list depends on the order in which the nodes were defined.
    gradients = np.array([[-1., -1.] if (n == [0., 0.]).all() else n
                          for n in fe.nodes])

    print "Your answer is:"
    print vals
    print "The correct answer is:"
    print gradients

    assert ((vals - gradients).round() == 0).all()
def test_nodes_on_correct_entity(cell, degree):

    fe = LagrangeElement(cell, degree)

    for d in range(cell.dim + 1):
        for e, nodes in fe.entity_nodes[d].items():
            for n in nodes:
                assert cell.point_in_entity(fe.nodes[n], (d, e))
def test_nodes_per_entity(cell, degree):

    fe = LagrangeElement(cell, degree)

    for d in range(cell.dim + 1):
        node_count = comb(degree - 1, d)
        for e in fe.entity_nodes[d].values():
            assert len(e) == node_count
def test_integrate_result_type(degree, mesh):

    fe = LagrangeElement(mesh.cell, degree)
    fs = FunctionSpace(mesh, fe)

    f = Function(fs)

    i = f.integrate()

    assert isinstance(i, float), "Integrate must return a float, not a %s" % \
        str(type(i))
def test_gradient_2d():
    """Ensure the Jacobian produces the correct gradient."""
    m = UnitSquareMesh(2, 2)
    fe = LagrangeElement(m.cell, 1)
    fs = FunctionSpace(m, fe)
    f = Function(fs)
    f.interpolate(lambda x: x[0])

    for c in range(m.entity_counts[-1]):
        df = (f.values[fs.cell_nodes[0]] @ fe.tabulate(
            ((0.333, 0.333), ), grad=True)[0] @ np.linalg.inv(m.jacobian(0)))

        if not np.allclose(df, [1., 0]):
            df_T = (f.values[fs.cell_nodes[0]] @ fe.tabulate(
                ((0.333, 0.333), ), grad=True)[0] @ np.linalg.inv(
                    m.jacobian(0).T))
            if np.allclose(df_T, [1., 0]):
                assert np.allclose(df, [1., 0]), \
                    "Jacobian produces incorrect gradients." \
                    " You may have computed the transposed Jacobian."
            else:
                assert np.allclose(df, [1., 0]), \
                    "Jacobian produces incorrect gradients."
def test_integrate_function(degree, mesh):

    fe = LagrangeElement(mesh.cell, degree)
    fs = FunctionSpace(mesh, fe)

    f = Function(fs)

    f.interpolate(lambda x: x[0]**degree)

    numeric = f.integrate()

    analytic = 1. / (degree + 1)

    assert round(numeric - analytic, 12) == 0, \
        "Integration error, analytic solution %g, your solution %g" % \
        (analytic, numeric)
def test_edge_orientation(cell, degree):
    """Test that the nodes on edges go in edge order"""

    fe = LagrangeElement(cell, degree)

    # Only test edges.
    d = 1

    for e, nodes in fe.entity_nodes[d].items():
        vertices = [np.array(cell.vertices[v]) for v in cell.topology[d][e]]

        # Project the nodes onto the edge.
        p = [
            np.dot(fe.nodes[n] - vertices[0], vertices[1] - vertices[0])
            for n in nodes
        ]

        assert np.all(p[:-1] < p[1:])
def test_tabulate_at_nodes(cell, degree):
    """Check that tabulating at the nodes produces the identity matrix."""
    fe = LagrangeElement(cell, degree)

    assert (np.round(fe.tabulate(fe.nodes) - np.eye(len(fe.nodes)),
                     10) == 0).all()
Esempio n. 14
0
                    type=int,
                    nargs=1,
                    help="The number of cells in each direction on the mesh.")
parser.add_argument(
    "degree",
    type=int,
    nargs=1,
    help="The degree of the polynomial basis for the function space.")

if __name__ == "__main__":
    args = parser.parse_args()
    resolution = args.resolution[0]
    degree = args.degree[0]
    cell = (None, ReferenceInterval, ReferenceTriangle)[args.dimension[0]]

    fe = LagrangeElement(cell, degree)
    if cell is ReferenceTriangle:
        mesh = UnitSquareMesh(resolution, resolution)
    else:
        mesh = UnitIntervalMesh(resolution)
    fs = FunctionSpace(mesh, fe)

    nodes = np.empty((fs.node_count, cell.dim))
    cg1 = LagrangeElement(cell, 1)
    cg1fs = FunctionSpace(mesh, cg1)
    coord_map = cg1.tabulate(fe.nodes)
    for c in range(mesh.entity_counts[-1]):
        # Interpolate the coordinates to the cell nodes.
        vertex_coords = mesh.vertex_coords[cg1fs.cell_nodes[c, :], :]
        lcoords = np.dot(coord_map, vertex_coords)
                    nargs=1,
                    choices=(1, 2),
                    help="Dimension of the reference cell.")
parser.add_argument("degree",
                    type=int,
                    nargs=1,
                    help="Degree of polynomial basis.")

if __name__ == "__main__":
    args = parser.parse_args()
    dim = args.dimension[0]
    degree = args.degree[0]

    cells = (None, ReferenceInterval, ReferenceTriangle)

    fe = LagrangeElement(cells[dim], degree)

    if dim == 1:
        x = np.linspace(0, 1, 100)
        x.shape = (100, 1)
        fig = plt.figure()
        ax = fig.add_subplot(111)

        y = fe.tabulate(x)

        for y_ in y.T:
            plt.plot(x, y_)

    if dim == 2:
        x = lagrange_points(ReferenceTriangle, 20)
        z = fe.tabulate(x)
Esempio n. 16
0
                    nargs=1,
                    choices=(1, 2),
                    help="Dimension of reference cell.")
parser.add_argument("degree",
                    type=int,
                    nargs=1,
                    help="Degree of basis functions.")
if __name__ == "__main__":
    args = parser.parse_args()
    dim = args.dimension[0]
    degree = args.degree[0]
    fn = eval('lambda x: ' + args.function[0])

    cells = (None, ReferenceInterval, ReferenceTriangle)

    fe = LagrangeElement(cells[dim], degree)
    coefs = fe.interpolate(fn)

    if dim == 1:
        x = np.linspace(0, 1, 100)
        x.shape = (100, 1)
        fig = plt.figure()
        ax = fig.add_subplot(111)

        y = fe.tabulate(x)

        for c, y_ in zip(coefs, y.T):
            plt.plot(x, c * y_, "--")
        plt.plot(x, np.dot(y, coefs), 'k')

    if dim == 2: