from fuse import *
import sympy as sp
import numpy as np

np.set_printoptions(legacy="1.25")


def construct_dg0():
    # [test_dg0 0]
    vert = Point(0)
    xs = [DOF(DeltaPairing(), PointKernel(()))]
    dg0 = ElementTriple(vert, (P0, C0), DOFGenerator(xs, S1))
    # [test_dg0 1]
    return dg0


def construct_dg0_int():
    edge = Point(1, [Point(0), Point(0)], vertex_num=2)
    xs = [DOF(DeltaPairing(), PointKernel((0,)))]
    dg1 = ElementTriple(edge, (P0, C0), DOFGenerator(xs, S1))
    return dg1


def construct_dg1():
    # [test_dg1_int 0]
    edge = Point(1, [Point(0), Point(0)], vertex_num=2)
    xs = [DOF(DeltaPairing(), PointKernel((-1,)))]
    dg1 = ElementTriple(edge, (P1, C0), DOFGenerator(xs, S2))
    # [test_dg1_int 1]
    return dg1


def plot_dg1():
    dg1 = construct_dg1()
    dg1.plot()


def construct_dg1_tri():
    # [test_dg1_tri 0]
    tri = polygon(3)
    xs = [DOF(DeltaPairing(), PointKernel((-1, -np.sqrt(3)/3)))]
    dg1 = ElementTriple(tri, (P1, C0), DOFGenerator(xs, S3/S2))
    # [test_dg1_tri 1]
    return dg1


def plot_dg1_tri():
    dg1 = construct_dg1_tri()
    dg1.plot()


def test_dg_examples():
    dg0 = construct_dg0()
    test_func = FuseFunction(lambda: 3)

    for dof in dg0.generate():
        assert np.allclose(dof.eval(test_func), 3)

    dg1 = construct_dg1()
    x = sp.Symbol("x")
    test_func = FuseFunction(2*x, symbols=(x,))

    dof_vals = [-2, 2]

    for dof in dg1.generate():
        # Avoiding assuming order of generation
        assert any(np.isclose(val, dof.eval(test_func)) for val in dof_vals)

    dg1 = construct_dg1_tri()

    dof_vals = [-11, 2, 9]

    x = sp.Symbol("x")
    y = sp.Symbol("y")
    test_func = FuseFunction(10*x + 3*y/np.sqrt(3), symbols=(x, y))

    for dof in dg1.generate():
        assert any(np.isclose(val, dof.eval(test_func)) for val in dof_vals)


def construct_cg1():
    # [test_cg1 0]
    edge = Point(1, [Point(0), Point(0)], vertex_num=2)
    vert = edge.vertices()[0]

    xs = [DOF(DeltaPairing(), PointKernel(()))]
    dg0 = ElementTriple(vert, (P0, C0), DOFGenerator(xs, S1))

    xs = [immerse(edge, dg0)]
    cg1 = ElementTriple(edge, (P1, C0),
                        DOFGenerator(xs, S2))
    # [test_cg1 1]

    return cg1


def plot_cg1():
    cg1 = construct_cg1()
    cg1.plot()


def construct_cg3(tri=None):
    # [test_cg3 0]
    tri = polygon(3)
    edge = tri.edges()[0]
    vert = tri.vertices()[0]

    xs = [DOF(DeltaPairing(), PointKernel(()))]
    dg0 = ElementTriple(vert, (P0, C0), DOFGenerator(xs, S1))

    v_xs = [immerse(tri, dg0)]
    v_dofs = DOFGenerator(v_xs, C3)

    xs = [DOF(DeltaPairing(), PointKernel((-1/np.sqrt(5),)))]
    dg0_int = ElementTriple(edge, (P1, C0), DOFGenerator(xs, S2))

    e_xs = [immerse(tri, dg0_int)]
    e_dofs = DOFGenerator(e_xs, C3)

    i_xs = [DOF(DeltaPairing(), PointKernel((0, 0)))]
    i_dofs = DOFGenerator(i_xs, S1)

    cg3 = ElementTriple(tri, (P3, C0), [v_dofs, e_dofs, i_dofs])
    # [test_cg3 1]
    return cg3


def plot_cg3():
    cg3 = construct_cg3()
    cg3.plot()


def test_cg_examples():

    cg1 = construct_cg1()

    x = sp.Symbol("x")
    test_func = FuseFunction(2*x, symbols=(x,))

    val_set = set([-2, 2])

    for dof in cg1.generate():
        # Avoiding assuming order of generation
        assert any(np.isclose(val, dof.eval(test_func)) for val in val_set)

    cg3 = construct_cg3()

    x = sp.Symbol("x")
    y = sp.Symbol("y")
    test_func = FuseFunction(sp.Matrix([10*x, 3*y/np.sqrt(3)]), symbols=(x, y))
    identity = FuseFunction(sp.Matrix([x, y]), symbols=(x, y))

    for dof in cg3.generate():
        val = dof.eval(test_func)
        position = dof.eval(identity)
        assert np.allclose([[10*position[0], 3*position[1]/np.sqrt(3)]], val)


def construct_nd(tri=None):
    if tri is None:
        tri = polygon(3)
    deg = 1
    edge = tri.edges()[0]
    x = sp.Symbol("x")
    y = sp.Symbol("y")

    xs = [DOF(L2Pairing(), VectorKernel(1, action=HCurl))]

    dofs = DOFGenerator(xs, S1)
    int_ned = ElementTriple(edge, (P0, L2), dofs)

    xs = [immerse(tri, int_ned)]
    tri_dofs = DOFGenerator(xs, C3)

    M = sp.Matrix([[y, -x]])
    vec_Pk = PolynomialSpace(deg - 1, shape=2)
    Pk = PolynomialSpace(deg - 1)
    nd = vec_Pk + (Pk.restrict(deg - 2, deg - 1))*M

    ned = ElementTriple(tri, (nd, C0), [tri_dofs])
    return ned


def construct_nd_2nd_kind(tri=None):
    if tri is None:
        tri = polygon(3)
    deg = 1
    edge = tri.edges()[0]
    x = sp.Symbol("x")

    xs = [DOF(L2Pairing(), PolynomialKernel((1/2)*(x + 1), symbols=(x,), action=HCurl))]
    dofs = DOFGenerator(xs, S2)
    int_ned = ElementTriple(edge, (P1, L2), dofs)

    xs = [immerse(tri, int_ned)]
    tri_dofs = DOFGenerator(xs, C3)

    nd = PolynomialSpace(deg, shape=2)

    ned = ElementTriple(tri, (nd, C0), [tri_dofs])
    return ned


def construct_nd2_2nd_kind(tri=None):
    if tri is None:
        tri = polygon(3)
    deg = 2
    edge = tri.edges()[0]

    s_0 = sp.Symbol("s_0")
    xs = [DOF(L2Pairing(), BarycentricPolynomialKernel(s_0*(2*s_0 - 1), symbols=(s_0,), action=HCurl))]
    centre = [DOF(L2Pairing(), BarycentricPolynomialKernel(4*s_0*(1 - s_0), symbols=(s_0,), action=HCurl))]
    dofs = [DOFGenerator(xs, S2), DOFGenerator(centre, S1)]
    int_ned = ElementTriple(edge, (PolynomialSpace(deg), L2), dofs)

    xs = [immerse(tri, int_ned)]
    edge_dofs = DOFGenerator(xs, C3)

    # moments against the Whitney field of the edge (0, 1) rotated by a right angle,
    # in the barycentric coordinates of this triangle, and its rotations
    s_1 = sp.Symbol("s_1")
    s_2 = sp.Symbol("s_2")
    phi_0 = [(np.sqrt(3)/6)*s_0 + (np.sqrt(3)/3)*s_1, -s_0/2]
    xs = [DOF(L2Pairing(), BarycentricPolynomialKernel(phi_0, symbols=(s_0, s_1, s_2), action=HCurl))]
    face_dofs = DOFGenerator(xs, C3)

    nd = PolynomialSpace(deg, shape=2)

    ned = ElementTriple(tri, (nd, C0), [edge_dofs, face_dofs])
    return ned


def construct_bdm(tri=None):
    if tri is None:
        tri = polygon(3)
    deg = 1
    edge = tri.edges()[0]
    x = sp.Symbol("x")

    xs = [DOF(L2Pairing(), PolynomialKernel((1/2)*(x + 1), symbols=(x,), action=HDiv))]
    dofs = DOFGenerator(xs, S2)
    int_rt = ElementTriple(edge, (PolynomialSpace(deg), L2), dofs)

    xs = [immerse(tri, int_rt)]
    tri_dofs = DOFGenerator(xs, C3)

    nd = PolynomialSpace(deg, shape=2)

    rt = ElementTriple(tri, (nd, C0), [tri_dofs])
    return rt


def construct_bdm_bary(tri=None):
    if tri is None:
        tri = polygon(3)
    deg = 1
    edge = tri.edges()[0]
    s_0 = sp.Symbol("s_0")

    xs = [DOF(L2Pairing(), BarycentricPolynomialKernel(s_0, symbols=(s_0,), action=HDiv))]
    dofs = DOFGenerator(xs, S2)
    int_rt = ElementTriple(edge, (PolynomialSpace(deg), L2), dofs)

    xs = [immerse(tri, int_rt)]
    tri_dofs = DOFGenerator(xs, C3)

    nd = PolynomialSpace(deg, shape=2)

    rt = ElementTriple(tri, (nd, C0), [tri_dofs])
    return rt


def construct_bdm2(tri=None):
    if tri is None:
        tri = polygon(3)
    deg = 2
    edge = tri.edges()[0]
    x = sp.Symbol("x")

    xs = [DOF(L2Pairing(), PolynomialKernel((x/2)*(x + 1), symbols=(x,), action=HDiv))]
    centre = [DOF(L2Pairing(), PolynomialKernel((1 - x**2), symbols=(x,), action=HDiv))]

    dofs = [DOFGenerator(xs, S2), DOFGenerator(centre, S1)]
    int_rt = ElementTriple(edge, (PolynomialSpace(deg), L2), dofs)

    xs = [immerse(tri, int_rt)]
    tri_dofs = DOFGenerator(xs, C3)

    # moments against the Whitney field of the edge (0, 1), l_0 grad(l_1) - l_1 grad(l_0)
    # in the barycentric coordinates l_i of this triangle, and its rotations
    s_0, s_1, s_2 = sp.symbols("s_0 s_1 s_2")
    phi_0 = [-s_0/2, -(np.sqrt(3)/6)*s_0 - (np.sqrt(3)/3)*s_1]
    xs = [DOF(L2Pairing(), BarycentricPolynomialKernel(phi_0, symbols=(s_0, s_1, s_2), action=HDiv))]
    interior = DOFGenerator(xs, C3)

    space = PolynomialSpace(deg, shape=2)

    bdm2 = ElementTriple(tri, (space, C0), [tri_dofs, interior])
    dofs = bdm2.generate()
    return bdm2


def construct_bdm2_bary(tri=None):
    if tri is None:
        tri = polygon(3)
    deg = 2
    edge = tri.edges()[0]

    s_0 = sp.Symbol("s_0")
    s_1 = sp.Symbol("s_1")
    vertex_basis = s_0*(2*s_0 - 1)
    edge_basis = 4*s_0*s_1
    xs = [DOF(L2Pairing(), BarycentricPolynomialKernel(vertex_basis, symbols=(s_0, s_1), action=HDiv))]
    centre = [DOF(L2Pairing(), BarycentricPolynomialKernel(edge_basis, symbols=(s_0, s_1), action=HDiv))]

    dofs = [DOFGenerator(xs, S2), DOFGenerator(centre, S1)]
    int_rt = ElementTriple(edge, (PolynomialSpace(deg), L2), dofs)

    xs = [immerse(tri, int_rt)]
    tri_dofs = DOFGenerator(xs, C3)

    # moments against the Whitney field of the edge (0, 1), l_0 grad(l_1) - l_1 grad(l_0)
    # in the barycentric coordinates l_i of this triangle, and its rotations
    s_0, s_1, s_2 = sp.symbols("s_0 s_1 s_2")
    phi_0 = [-s_0/2, -(np.sqrt(3)/6)*s_0 - (np.sqrt(3)/3)*s_1]
    xs = [DOF(L2Pairing(), BarycentricPolynomialKernel(phi_0, symbols=(s_0, s_1, s_2), action=HDiv))]
    interior = DOFGenerator(xs, C3)

    space = PolynomialSpace(deg, shape=2)

    bdm2 = ElementTriple(tri, (space, C0), [tri_dofs, interior])
    dofs = bdm2.generate()
    return bdm2


def test_nd_example():
    tri = polygon(3)

    ned = construct_nd(tri)

    x = sp.Symbol("x")
    y = sp.Symbol("y")

    phi_2 = FuseFunction(sp.Matrix([1/3 - (np.sqrt(3)/6)*y, (np.sqrt(3)/6)*x]), symbols=(x, y))
    phi_0 = FuseFunction(sp.Matrix([-1/6 - (np.sqrt(3)/6)*y, (-np.sqrt(3)/6) + (np.sqrt(3)/6)*x]), symbols=(x, y))
    phi_1 = FuseFunction(sp.Matrix([-1/6 - (np.sqrt(3)/6)*y,
                                    (np.sqrt(3)/6) + (np.sqrt(3)/6)*x]), symbols=(x, y))
    basis_funcs = [phi_0, phi_1, phi_2]

    for dof in ned.generate():
        assert [np.allclose(1, dof.eval(basis_func).flatten()) for basis_func in basis_funcs].count(True) == 1
        assert [np.allclose(0, dof.eval(basis_func).flatten()) for basis_func in basis_funcs].count(True) == 2


def construct_rt(tri=None):
    if tri is None:
        tri = polygon(3)
    deg = 1
    edge = tri.edges()[0]

    x = sp.Symbol("x")
    y = sp.Symbol("y")

    M = sp.Matrix([[x, y]])
    vec_Pd = PolynomialSpace(deg - 1, shape=2)
    Pd = PolynomialSpace(deg - 1)
    rt_space = vec_Pd + (Pd.restrict(deg - 2, deg - 1))*M

    xs = [DOF(L2Pairing(), VectorKernel(1, action=HDiv))]
    dofs = DOFGenerator(xs, S1)

    int_rt = ElementTriple(edge, (P0, L2), dofs)

    xs = [immerse(tri, int_rt)]
    tri_dofs = DOFGenerator(xs, C3)

    rt = ElementTriple(tri, (rt_space, C0), [tri_dofs])
    return rt


def test_rt_example():
    x = sp.Symbol("x")
    y = sp.Symbol("y")
    phi_2 = FuseFunction(sp.Matrix([(np.sqrt(3)/6)*x,
                                    -1/3 + (np.sqrt(3)/6)*y]), symbols=(x, y))
    phi_0 = FuseFunction(sp.Matrix([(-np.sqrt(3)/6) + (np.sqrt(3)/6)*x,
                                    1/6 + (np.sqrt(3)/6)*y]), symbols=(x, y))
    phi_1 = FuseFunction(sp.Matrix([(np.sqrt(3)/6) + (np.sqrt(3)/6)*x,
                                    1/6 + (np.sqrt(3)/6)*y]), symbols=(x, y))

    rt = construct_rt()

    basis_funcs = [phi_0, phi_1, phi_2]

    for dof in rt.generate():
        assert [np.allclose(1, dof.eval(basis_func).flatten()) for basis_func in basis_funcs].count(True) == 1
        assert [np.allclose(0, dof.eval(basis_func).flatten()) for basis_func in basis_funcs].count(True) == 2
    rt.to_fiat()


def construct_hermite():
    tri = polygon(3)
    vert = tri.vertices()[0]

    xs = [DOF(DeltaPairing(), PointKernel(()))]
    dg0 = ElementTriple(vert, (P0, C0), DOFGenerator(xs, S1))

    v_xs = [immerse(tri, dg0)]
    v_dofs = DOFGenerator(v_xs, S3/S2)

    v_derv_xs = [immerse(tri, dg0, TrGrad)]
    v_derv_dofs = DOFGenerator(v_derv_xs, S3/S2)

    v_derv2_xs = [immerse(tri, dg0, TrHess)]
    v_derv2_dofs = DOFGenerator(v_derv2_xs, S3/S2)

    i_xs = [DOF(DeltaPairing(), PointKernel((0, 0)))]
    i_dofs = DOFGenerator(i_xs, S1)

    her = ElementTriple(tri, (P3, C0),
                        [v_dofs, v_derv_dofs, v_derv2_dofs, i_dofs])
    return her

# draft of hermite test, immersions need work
# def test_hermite_example():
#    her = construct_hermite()
#
#    # TODO improve this test
#    x = sp.Symbol("x")
#    y = sp.Symbol("y")
#    phi_0 = FuseFunction(x**2 + 3*y**3 + 4*x*y, symbols=(x, y))
#    ls = her.generate()
#    print("num dofs ", her.num_dofs())
#    for dof in ls:
#        print(dof)
#        print("dof eval", dof.eval(phi_0))


def test_square_cg():
    square = polygon(4)

    vert = square.d_entities(0)[0]
    edge = square.d_entities(1)[0]

    xs = [DOF(DeltaPairing(), PointKernel(()))]
    dg0 = ElementTriple(vert, (P0, C0),
                        DOFGenerator(xs, S1))

    xs = [DOF(DeltaPairing(), PointKernel((0,)))]
    dg0_int = ElementTriple(edge, (P0, C0),
                            DOFGenerator(xs, S1))

    v_xs = [immerse(square, dg0)]
    v_dofs = DOFGenerator(v_xs, C4)

    e_xs = [immerse(square, dg0_int)]
    e_dofs = DOFGenerator(e_xs, sq_edges)

    i_xs = [DOF(DeltaPairing(), PointKernel((0, 0)))]
    i_dofs = DOFGenerator(i_xs, S1)

    cg3 = ElementTriple(square, (P3, C0),
                        [v_dofs, e_dofs, i_dofs])
    x = sp.Symbol("x")
    y = sp.Symbol("y")
    test_func = FuseFunction(x**2 + y**2, symbols=(x, y))

    dof_vals = np.array([0, 1, 2])
    for dof in cg3.generate():
        assert any([np.allclose(val, dof.eval(test_func).flatten()) for val in dof_vals])


def test_rt_second_order():
    tri = polygon(3)
    edge = tri.d_entities(1, get_class=True)[0]
    x = sp.Symbol("x")
    y = sp.Symbol("y")

    xs = [DOF(L2Pairing(), PolynomialKernel((1/2)*(1 + x), symbols=(x,), action=HDiv))]
    dofs = DOFGenerator(xs, S2)
    int_rt2 = ElementTriple(edge, (P1, L2), dofs)

    xs = [immerse(tri, int_rt2)]
    tri_dofs = DOFGenerator(xs, C3)

    i_xs = [DOF(L2Pairing(), VectorKernel((1, 0), action=HDiv)),
            DOF(L2Pairing(), VectorKernel((0, 1), action=HDiv))]
    i_dofs = DOFGenerator(i_xs, S1)

    vecP3 = PolynomialSpace(3, shape=2)
    rt2 = ElementTriple(tri, (vecP3, C0), [tri_dofs, i_dofs])

    phi = FuseFunction(sp.Matrix([(np.sqrt(3)/6) + (np.sqrt(3)/6)*x,
                                  1/6 + (np.sqrt(3)/6)*y]), symbols=(x, y))

    for dof in rt2.generate():
        dof.eval(phi)
    rt2.plot()
