"""Reproducible teaching calculations, NumPy only; all energies in cutoff units unless stated."""
from pathlib import Path
import numpy as np, json
out=Path(__file__).parent
def bisect(f,a,b,tol=1e-12):
    fa=f(a)
    assert fa*f(b)<=0
    for _ in range(100):
        c=(a+b)/2; fc=f(c)
        if b-a<tol:return c
        if fc*fa>0:a,fa=c,fc
        else:b=c
    return c
def bcs(lam=.3,N=12001):
    x=np.linspace(0,1,N)
    def kernel(d,T):
        E=np.sqrt(x*x+d*d)
        if T==0:return np.trapezoid(1/E,x)
        y=np.empty_like(E);nz=E>1e-14
        y[nz]=np.tanh(E[nz]/(2*T))/E[nz];y[~nz]=1/(2*T)
        return np.trapezoid(y,x)
    tc=bisect(lambda T:lam*kernel(0,T)-1,.001,1)
    d0=1/np.sinh(1/lam)
    rows=[]
    for q in [0,.2,.5,.8,.9,.95,.99,1,1.1]:
        T=q*tc
        d=d0 if T==0 else (0 if q>=1 else bisect(lambda d:lam*kernel(d,T)-1,0,d0*1.01))
        rows.append([q,d,d/d0])
    return {'lambda':lam,'Tc_over_cutoff':tc,'Delta0_over_cutoff':d0,'ratio_2Delta0_Tc':2*d0/tc,'table':rows}
def lattice(N=300,U=3,n=.8,T=.05):
    k=(np.arange(N)+.5)*2*np.pi/N-np.pi
    ep=-2*(np.cos(k)[:,None]+np.cos(k)[None,:])
    def gap(mu):
        xi=ep-mu
        def f(d):
            E=np.sqrt(xi*xi+d*d)
            return U*np.mean(np.tanh(E/(2*T))/(2*E))-1
        return bisect(f,1e-10,U) if f(1e-10)>0 else 0.
    def density(mu):
        d=gap(mu);xi=ep-mu;E=np.sqrt(xi*xi+d*d)
        return np.mean(1-xi/E*np.tanh(E/(2*T)))
    mu=bisect(lambda m:density(m)-n,-5,5);d=gap(mu)
    # mu here is Hartree-shifted effective chemical potential.
    return {'N':N,'U':U,'n':n,'T':T,'mu_effective':mu,'mu_bare':mu-U*n/2,'Delta':d,'density':density(mu)}
def kitaev(N,mu,t=1,delta=.6):
    h=-mu*np.eye(N)-t*(np.diag(np.ones(N-1),1)+np.diag(np.ones(N-1),-1))
    D=delta*(np.diag(np.ones(N-1),1)-np.diag(np.ones(N-1),-1))
    H=np.block([[h,D],[-D,-h]])
    assert np.max(abs(H-H.T))<1e-13
    E,V=np.linalg.eigh(H)
    assert np.max(abs(E+E[::-1]))<1e-12
    ix=np.argsort(abs(E))[:2];P=np.sum(abs(V[:N,ix])**2+abs(V[N:,ix])**2,axis=1)/2
    return {'N':N,'mu':mu,'t':t,'delta':delta,'smallest_abs_E':float(np.min(abs(E))),'edge_pair_weight_first5_last5':float(P[:5].sum()+P[-5:].sum())}
R={'BCS':bcs(),'lattice':[lattice(n) for n in [100,200,300]],'Kitaev':[kitaev(N,mu) for mu in [0.5,3.] for N in [20,40,80]]}
e=1.602176634e-19;h=6.62607015e-34;hb=h/(2*np.pi);kb=1.380649e-23;mu0=1.25663706212e-6;m=9.1093837139e-31;phi=h/(2*e)
lam=150e-9;xi=10e-9
R['SI_examples']={'flux_quantum_Wb':phi,'london_n5e28_nm':1e9*np.sqrt(m/(mu0*5e28*e*e)), 'Bc2_T':phi/(2*np.pi*xi**2),'Bc_T':phi/(2*np.sqrt(2)*np.pi*lam*xi),'Bc1_T_large_kappa':phi/(4*np.pi*lam**2)*(np.log(lam/xi)+.5),'depairing_A_m2':(2/3)**1.5*phi/(2*np.sqrt(2)*np.pi*lam*xi)/(mu0*lam),'Josephson_10uV_GHz':2*e*1e-5/h/1e9,'LittleParks_R500nm_period_mT':1e3*phi/(np.pi*(500e-9)**2)}
(out/'sc_results.json').write_text(json.dumps(R,indent=2),encoding='utf8')
print(json.dumps(R,indent=2))
