import sympy as sp, random, re
from sympy.parsing.sympy_parser import parse_expr
import mpmath as mp
mp.mp.dps = 60
x, n = sp.symbols('x n')
s2 = sp.sqrt(2)
NMAX = 40

# name: (alpha, beta, {k: coeff}, offset, r, [P_0..P_r strings])
SEQS = {
 'A116408': (1, 2, {2:1,3:-1,4:1}, 4, [
   "2*(n+4)*(n-23)", "2*(n**2+64*n+79)", "(-59*n**2+232*n+740)", "(64*n**2-585*n+1019)", "3*(n-3)*(41*n-124)"]),
 'A116385': (0, 2, {2:1,3:2,4:1}, 4, [
   "(n+4)", "-2", "(-7*n-8)", "6", "12*(n-2)"]),
 'A119975': (1, 2*s2, {0:1,1:1/s2}, 3, [
   "(n+1)", "(n-4)", "(9-13*n)", "21*(2-n)"]),
 'A098664': (0, 4, {0:1,1:sp.Rational(1,2)}, 3, [
   "(n+1)", "8*(n-1)", "-16*n", "128*(2-n)"]),
 'A098520': (1, 4, {1:sp.Rational(1,2)}, 3, [
   "(n-1)*(n+1)", "-n*(2*n-1)", "-15*n*(n-1)"]),
}
# r = order = len(P)-1
def Pexpr(s): return sp.expand(parse_expr(s, local_dict={'n': n}))

def read_seq(sid):
    fn = f"/home/user/oeisdata/seq/{sid[:4]}/{sid}.seq"
    terms, off = [], None
    for line in open(fn):
        if line.startswith(('%S','%T','%U')):
            terms += [int(t) for t in line.split(None,2)[2].strip().split(',') if t.strip()]
        elif line.startswith('%O'):
            off = int(line.split()[2].split(',')[0])
    return terms, off

# ---- exact series ----
def bessel_I_series(k, beta, N):
    # coefficients of x^p in I_k(beta x), p<N
    c = {}
    for m in range(0, N):
        p = 2*m + k
        if p >= N: break
        c[p] = sp.nsimplify(sp.expand((beta/2)**p)) / (sp.factorial(m)*sp.factorial(m+k))
    return c
def egf_coeffs(alpha, beta, comb, N):
    f = {}
    for k, ck in comb.items():
        for p, v in bessel_I_series(k, beta, N).items():
            f[p] = f.get(p, 0) + ck*v
    out = []
    for m in range(N):
        t = sum(f.get(p,0)*sp.Integer(alpha)**(m-p)/sp.factorial(m-p) for p in range(0, m+1))
        out.append(sp.nsimplify(sp.radsimp(sp.expand(t*sp.factorial(m)))))
    return out

# ---- module arithmetic: element = (R0,R1) meaning e^{alpha x}(R0 I0(beta x)+R1 I1(beta x)) ----
def Ik_pair(k, beta):
    a, b = (sp.Integer(1), sp.Integer(0)), (sp.Integer(0), sp.Integer(1))
    if k == 0: return a
    if k == 1: return b
    prev, cur = a, b
    for j in range(1, k):   # I_{j+1} = I_{j-1} - (2j/(beta x)) I_j
        nxt = tuple(sp.cancel(sp.radsimp(p - 2*j/(beta*x)*c)) for p, c in zip(prev, cur))
        prev, cur = cur, nxt
    return cur
def simp(e): return sp.cancel(sp.radsimp(sp.expand(e)), extension=s2) if e != 0 else sp.Integer(0)
def D(el, alpha, beta):
    R0, R1 = el
    return (simp(alpha*R0 + sp.diff(R0,x) + beta*R1),
            simp(alpha*R1 + sp.diff(R1,x) + beta*R0 - R1/x))
def theta(el, alpha, beta):
    d = D(el, alpha, beta); return (simp(x*d[0]), simp(x*d[1]))
def add(a,b): return (simp(a[0]+b[0]), simp(a[1]+b[1]))
def scal(c,a): return (simp(c*a[0]), simp(c*a[1]))

def apply_poly_theta(Pn, shift, el, alpha, beta):
    """apply P(theta+shift) to el; Pn is polynomial in n"""
    P = sp.Poly(sp.expand(Pn.subs(n, n+shift)), n)   # polynomial in theta
    res = (sp.Integer(0), sp.Integer(0))
    cur = el
    coeffs = P.all_coeffs()[::-1]
    for kk, c in enumerate(coeffs):
        res = add(res, scal(c, cur))
        if kk < len(coeffs)-1: cur = theta(cur, alpha, beta)
    return res

def closed_E(alpha, beta, comb, Ps):
    r = len(Ps)-1
    F = [sp.Integer(0), sp.Integer(0)]
    for k, ck in comb.items():
        p = Ik_pair(k, beta); F = [F[0]+ck*p[0], F[1]+ck*p[1]]
    F = (simp(F[0]), simp(F[1]))
    ders = [F]
    for i in range(r): ders.append(D(ders[-1], alpha, beta))
    E = (sp.Integer(0), sp.Integer(0))
    for j, Pj in enumerate(Ps):
        E = add(E, apply_poly_theta(Pj, r, ders[r-j], alpha, beta))
    return E, F

def direct_E_value(alpha, beta, comb, Ps, pt):
    """E built directly from sympy besseli, unsimplified, evaluated at pt with mpmath"""
    r = len(Ps)-1
    Fx = sum(ck*sp.exp(alpha*x)*sp.besseli(k, beta*x) for k, ck in comb.items())
    def th(f): return x*sp.diff(f, x)
    E = 0
    for j, Pj in enumerate(Ps):
        P = sp.Poly(sp.expand(Pj.subs(n, n+r)), n).all_coeffs()[::-1]
        cur = sp.diff(Fx, x, r-j)
        for kk, c in enumerate(P):
            E += c*cur
            if kk < len(P)-1: cur = th(cur)
    return sp.N(E.subs(x, pt), 60)

def laurent_series_mul(R, ser, N):
    """series of rational R times power series dict ser, up to x^N, as dict (may have negative powers)"""
    Rs = sp.series(R, x, 0, N+1).removeO() if R != 0 else 0
    Rs = sp.expand(Rs)
    out = {}
    for term in sp.Add.make_args(Rs):
        if term == 0: continue
        c, p = term.as_coeff_exponent(x)
        for q, v in ser.items():
            out[p+q] = out.get(p+q, 0) + c*v
    return out

def main():
    random.seed(12345)
    for sid, (alpha, beta, comb, off, Pstr) in SEQS.items():
        print("="*78); print(sid, "alpha=",alpha,"beta=",beta,"comb=",comb)
        Ps = [Pexpr(s) for s in Pstr]; r = len(Ps)-1
        terms, offset = read_seq(sid)
        print("OEIS offset", offset, "num terms", len(terms), "recurrence order r =", r)
        # (a)
        a = egf_coeffs(alpha, beta, comb, NMAX+r+5)
        ok = all(a[offset+i] == terms[i] for i in range(len(terms))) and all(a[i]==0 for i in range(offset))
        # a[0..offset-1] should be 0 only when offset>0 is a zero-prefix in data; check data itself
        ok = all(a[i] == terms[i-offset+0] for i in range(offset, offset+len(terms))) if False else all(a[i]==terms[i] for i in range(len(terms)))
        print("(a) computed a(n) match all", len(terms), "OEIS terms (index n=0..):", ok)
        if not ok:
            print("MISMATCH, stop"); print(a[:len(terms)]); print(terms); continue
        # closed form
        E, F = closed_E(alpha, beta, comb, Ps)
        print("F = e^{%s x}(%s * I0 + %s * I1)" % (alpha, sp.factor(F[0]), sp.factor(F[1])))
        print("E = e^{%s x}(R0*I0(%s x) + R1*I1(%s x))" % (alpha, beta, beta))
        print("R0 =", sp.factor(E[0], extension=s2)); print("R1 =", sp.factor(E[1], extension=s2))
        zero = (E[0] == 0 and E[1] == 0)
        print("E == 0 identically (R0==R1==0):", zero)
        # (b)
        fails = []
        for N in range(r, NMAX):
            res = sum(Ps[j].subs(n, N)*a[N-j] for j in range(r+1))
            if sp.simplify(res) != 0: fails.append((N, sp.simplify(res)))
        print("(b) failing n in [%d,%d):" % (r, NMAX), [f[0] for f in fails])
        if not zero:
            # predicted: coefficient m!*[x^m] of e^{alpha x}(R0 I0 + R1 I1), n=m+r
            I0s = bessel_I_series(0, beta, NMAX+8); I1s = bessel_I_series(1, beta, NMAX+8)
            ex = {p: sp.Integer(alpha)**p/sp.factorial(p) for p in range(NMAX+8)}
            def pm(A,B):
                o = {}
                for p,v in A.items():
                    for q,w in B.items():
                        if p+q < NMAX+8: o[p+q] = o.get(p+q,0)+v*w
                return o
            t0 = pm(laurent_series_mul(E[0], I0s, NMAX+6), ex)
            t1 = pm(laurent_series_mul(E[1], I1s, NMAX+6), ex)
            pred = []
            for m in range(-5, NMAX-r):
                c = sp.nsimplify(sp.radsimp(sp.expand(t0.get(m,0)+t1.get(m,0))))
                if m < 0:
                    if c != 0: print("   nonzero negative-power coeff at x^%d: %s" % (m, c))
                    continue
                if c != 0: pred.append((m+r, sp.nsimplify(sp.expand(c*sp.factorial(m)))))
            print("    E predicts failure set (n=m+r):", [p[0] for p in pred])
            match = ([p[0] for p in pred] == [f[0] for f in fails]) and all(sp.simplify(p[1]-f[1])==0 for p,f in zip(pred,fails))
            print("    predicted residual values equal observed residuals:", match)
            print("    observed residuals (n: value):", [(f[0], f[1]) for f in fails[:8]], "...")
        else:
            print("    E predicts no failures; observed none:", len(fails)==0)
        # (c)
        resid = []
        for _ in range(5):
            pt = mp.mpf(random.uniform(0.001, 0.5))
            pt = sp.Float(str(pt), 60)
            dv = direct_E_value(alpha, beta, comb, Ps, pt)
            cf = sp.N(sp.exp(alpha*pt)*(E[0].subs(x,pt)*sp.besseli(0,beta*pt) + E[1].subs(x,pt)*sp.besseli(1,beta*pt)), 60)
            resid.append(abs(dv-cf))
        print("(c) max |E_direct - E_closed| over 5 pts (60 digits):", sp.N(max(resid), 5))
main()
