"""Exact rational iterates, local singular expansions, and reduced degrees on a line.

Python 3 and SymPy. The finite-field samples test degree sequences; their use is
independent of the geometric argument for asymptotic entropy.
"""
import sympy as sp


def reduced_degrees(map_name, depth, prime, line):
    t = sp.symbols("t")
    X, Y, Z = [sp.Poly(a*t+b,t,modulus=prime) for a,b in line]
    degrees = [1]
    for _ in range(depth):
        if map_name == "lyness":
            nxt = (X*Y, Z*(2*Z+Y), X*Z)
        else:
            nxt = (Y**3, (Y-X)*Y**2+Z**3, Z*Y**2)
        gcd = sp.gcd(sp.gcd(nxt[0],nxt[1]),nxt[2])
        X,Y,Z = (sp.exquo(v,gcd) for v in nxt)
        degrees.append(max(v.degree() for v in (X,Y,Z)))
    return degrees


def singular_series(previous, discrete_painleve, broken=False):
    e = sp.symbols("e")
    left, right = previous, e
    for n in range(4):
        if discrete_painleve:
            strength = n+2+int(broken and n==3)
            new = -right-left+strength/right
        else:
            new = right-left+1/right**2
        # Retain extra Laurent coefficients before taking inverses near a zero.
        left,right = right,sp.series(new,e,0,10-n).removeO()
    return sp.series(right,e,0,1)


if __name__ == "__main__":
    x,y,a = sp.symbols("x y a")
    invariant = (x+1)*(y+1)*(x+y+a)/(x*y)
    advance = (y,(a+y)/x)
    assert sp.cancel(invariant.subs({x:advance[0],y:advance[1]},simultaneous=True)-invariant)==0
    jac = sp.Matrix(advance).jacobian([x,y]).det()
    assert sp.cancel(jac/(advance[0]*advance[1])-1/(x*y))==0
    m,n = x,y
    for _ in range(5):
        m,n = n, sp.cancel((1+n)/m)
    assert (m,n) == (x,y)
    for initial in (sp.Rational(3,2),sp.Rational(-1,2)):
        print("previous, dPI, broken dPI, HV:",initial,
              singular_series(initial,True),singular_series(initial,True,True),
              singular_series(initial,False))
    for name,depth in (("lyness",12),("hv",5)):
        row = reduced_degrees(name,depth,1009,[(3,8),(7,17),(11,37)])
        assert row == reduced_degrees(name,depth,10007,[(2,13),(13,7),(5,19)])
        print(name, row)
