"""Boundary collocation on a circle and a saddle-scaled triangular jump."""
from math import atan,pi,sqrt
import numpy as np


def circle(K, matrix):
    dim=2 if matrix else 1
    eye=np.eye(dim)
    A=np.array([[0,.4],[0,0]]) if matrix else np.array([[.4]])
    B=np.array([[0,0],[.3,0]]) if matrix else np.array([[.3]])
    def exact(z):
        minus=eye+B/(3*z-1)
        plus=eye+A*z/(3-z)
        return minus,plus,np.linalg.solve(minus,plus)
    n=4*K+8
    zs=np.exp(2j*pi*np.arange(n)/n)
    design=[]
    rhs=[]
    for z in zs:
        _,_,J=exact(z)
        # Each unknown is a row of a Laurent coefficient (one output row at a time).
        design.append(np.hstack([z**j*eye for j in range(K+1)]+
                                [-z**(-j)*J.T for j in range(1,K+1)]))
        rhs.append(J.T)
    coefs=np.linalg.lstsq(np.vstack(design),np.vstack(rhs),rcond=None)[0]
    mats=[a.T for a in np.split(coefs,2*K+1)]
    def approx(z):
        plus=sum(mats[j]*z**j for j in range(K+1))
        minus=eye+sum(mats[K+j]*z**(-j) for j in range(1,K+1))
        return minus,plus
    errors=[]
    for z in zs*np.exp(1j*pi/n):
        minus,plus=approx(z)
        errors.append(np.linalg.norm(plus-minus@exact(z)[2],ord=np.inf))
    print("K, dimension, withheld jump error, first coefficient error:",K,dim,
          max(errors),np.linalg.norm(mats[K+1]-B/3,ord=np.inf))


def hyperbolic_phase(t):
    theta=atan(t)/2
    scale=np.exp(1j*theta)/(1+t*t)**.25
    exact=sqrt(pi)/np.sqrt(1-1j*t)
    for intervals in (64,128,256,512,1024):
        x=np.linspace(-7,7,intervals+1)
        mid_weights=np.ones(len(x))
        mid_weights[[0,-1]]=.5
        def integrate(z,dz):
            return dz*(mid_weights@np.exp(-(1-1j*t)*z*z))
        h=14/intervals
        print("Intervals and relative quadrature errors:",intervals,
              abs(integrate(x,h)/exact-1),abs(integrate(scale*x,scale*h)/exact-1))


def winding_control(nodes=32):
    """A unit-determinant jump diag(z,1/z) has an unresolved Fourier mode."""
    z = np.exp(2j * pi * np.arange(nodes) / nodes)
    order = 5
    interior = z[:, None] ** np.arange(order + 1)
    exterior = z[:, None] ** (-np.arange(1, order + 1))
    # Second diagonal entry: z*M_plus - (M_minus-1) = 1.
    modes = np.column_stack((z[:, None] * interior, -exterior))
    rhs = np.ones(nodes)
    coefs = np.linalg.lstsq(modes, rhs, rcond=None)[0]
    rms = np.linalg.norm(modes @ coefs - rhs) / sqrt(nodes)
    assert abs(rms - 1) < 1e-13
    print("Diagonal winding jump, best second-entry RMS defect:", rms)


def finite_probe():
    """Evaluate the Cauchy integral before and after a contour crosses its pole."""
    probe = 0.5 + 0.25j
    for time in (0.5, 4.0):
        exponent = 1 - 1j * time
        ray = 1 / np.sqrt(exponent)
        enclosed = np.angle(ray) > np.angle(probe)
        residue = np.exp(-exponent * probe**2) if enclosed else 0
        for intervals in (1024, 2048):
            nodes = np.linspace(-10, 10, intervals + 1)
            def cauchy(direction):
                points = direction * nodes
                values = direction * np.exp(-exponent * points**2) / (points - probe)
                total = values[1:-1].sum() + (values[0] + values[-1]) / 2
                return 20 * total / (intervals * 2j * pi)
            original, rotated = cauchy(1), cauchy(ray)
            assert abs(original - rotated - residue) < 5e-13
        print("Time, original, rotated and crossed-pole correction:",
              time, original, rotated, residue)


if __name__=="__main__":
    for dimension_two in (False,True):
        for order in (3,6,12):
            circle(order,dimension_two)
    hyperbolic_phase(100)
    winding_control()
    finite_probe()
