"""Exact check of a conjectured recurrence sum_j P_j(n) a(n-j) = 0 for a sequence
with explicit o.g.f. A(x).  E(x) := sum_n [sum_j P_j(n) a(n-j)] x^n
          = sum_j x^j * P_j(theta + j) A,   theta = x d/dx.
If E simplifies to a polynomial of degree d, the recurrence holds exactly for n > d
(and the failing indices are those n <= d with nonzero coefficient, n >= order)."""
from sympy import symbols, diff, simplify, radsimp, together, Poly, series, expand, factor
x, n = symbols('x n')

def theta_apply(P, A):
    """Apply polynomial P(theta) to A, theta = x d/dx."""
    p = Poly(P, n)
    res, T = 0, A
    for k in range(p.degree() + 1):
        res += p.coeff_monomial(n**k) * T
        T = x*diff(T, x)
    return res

def E_of(A, Ps):
    E = 0
    for j, P in enumerate(Ps):
        E += x**j * theta_apply(expand(P.subs(n, n + j)), A)
    return E

def check(name, A, Ps, N=40):
    E = simplify(radsimp(together(E_of(A, Ps))))
    s = series(A, x, 0, N).removeO()
    a = [s.coeff(x, k) for k in range(N)]
    r = len(Ps) - 1
    vals = {k: sum(Ps[j].subs(n, k)*a[k-j] for j in range(len(Ps))) for k in range(r, N)}
    bad = [k for k, v in vals.items() if v != 0]
    print(name, "E(x) =", factor(E), "| is polynomial:", E.is_polynomial(x), "| terms", a[:8], "| fails at", bad)
    return E, bad

if __name__ == "__main__":
    from sympy import sqrt
    s4 = sqrt(1 - 4*x); C = (1 - s4)/(2*x)
    # A182959 regression
    check("A182959", 2*(1 + x)**2/(1 - 2*x + sqrt(1 - 8*x)), [n + 1, -7*n + 3, 4*(-2*n + 5)])
    # A071264: (n+6)(8587n^2+62958n+61667) a(n) + (8587n^3-377960n^2-2268967n-1091596) a(n-1) - 2(2n-1)(42935n^2-14497n-123334) a(n-2) = 0
    check("A071264", (1 + x*C**4)*C**3,
          [(n + 6)*(8587*n**2 + 62958*n + 61667),
           8587*n**3 - 377960*n**2 - 2268967*n - 1091596,
           -2*(2*n - 1)*(42935*n**2 - 14497*n - 123334)])
