"""Reproducible teaching calculations; eV and nm unless stated otherwise."""
from pathlib import Path
import numpy as np, json
OUT=Path(__file__).parent
kB=8.617333262e-5
def afm(U,N=400,T=0.,seed=.2,mix=.5):
    k=2*np.pi*(np.arange(N)+.5)/N-np.pi
    eps=-2*(np.cos(k[:,None])+np.cos(k[None,:]))
    m=seed; trace=[]
    for it in range(20000):
        E=np.sqrt(eps**2+(U*m)**2)
        fac=1 if T==0 else np.tanh(E/(2*T))
        new=.5*np.mean(U*m/E*fac)
        residual=abs(new-m)
        if it<12: trace.append([it,float(m),float(residual)])
        if residual<1e-12: break
        m=(1-mix)*m+mix*new
    energy=U/4+U*m*m-np.mean(E)
    pm=U/4-np.mean(abs(eps))
    return dict(U=U,N=N,T=T,m=float(m),gap=float(2*U*m),energy=float(energy),pm_energy=float(pm),difference=float(energy-pm),iterations=it+1,residual=float(residual),trace=trace)
res={'hubbard':[afm(U) for U in [1,2,4,8]],'mesh':[afm(4,N) for N in [100,200,400]],'seeds':[afm(4,200,seed=s) for s in [.01,.2,.49]]}
a=.5653; N0=4/a**3; p=.35; mass=.5; h2over2m=.0380998212
kf=(3*np.pi**2*p)**(1/3); ef=h2over2m*kf*kf/mass
dos=mass*kf/(2*np.pi**2*h2over2m); Jpd=-1.2/N0; x=.05; S=2.5; AF=1.2
tc=x*N0*S*(S+1)*Jpd**2*AF*dos/(12*kB)
res['zener']=dict(N0=N0,p=p,mass=mass,kf=kf,ef=ef,dos=dos,Jpd=Jpd,AF=AF,Tc=tc,Tc_p8=2*tc)
# BHZ four-band simplification: no BIA/SIA, anisotropy or disorder.
kr=np.linspace(0,.12,24001); A=.3; B=-38.5; D=-31.5; M=-.005; C=-.00297
def bhz(s):
    ge=.035*s*(.5*.52-.98*.48/3); gh=.035*s*(-.98)
    g0=(ge+gh)/2; gz=(ge-gh)/2
    es=[]
    for spin in [-1,1]:
        E0=C-D*kr**2+spin*g0
        E=np.sqrt(A*A*kr**2+(M-B*kr**2+spin*gz)**2)
        es.extend([E0-E,E0+E])
    ordered=np.sort(np.array(es),axis=0)
    return dict(Sz=s,GE=ge,GH=gh,masses=[M+gz,M-gz],indirect_gap=float(ordered[2].min()-ordered[1].max()),direct_gap=float(np.min(ordered[2]-ordered[1])),kcut=.12)
res['bhz']=[bhz(s) for s in [0,.2,.3,.5,1.,2.5]]
def mf(t):
    if t>=1:return 0.
    lo,hi=1e-12,1.
    for _ in range(70):
        mid=(lo+hi)/2
        if np.tanh(mid/t)-mid>0:lo=mid
        else:hi=mid
    return (lo+hi)/2
res['weiss']=[dict(t=t,m=mf(t)) for t in [.2,.5,.8,.9,.99,1.,1.1]]
mu0=4*np.pi*1e-7; muB=9.2740100783e-24; kbSI=1.380649e-23; e=1.602176634e-19
n=8.5e28; efSI=7.04936*e
res['pauli']=dict(chi=mu0*muB**2*3*n/(2*efSI),chi_landau=-mu0*muB**2*n/(2*efSI))
res['curie']=dict(Fe3_p=np.sqrt(35),Ce3_p=(6/7)*np.sqrt(35/4),Fe3_Cmolar=mu0*6.02214076e23*muB**2*35/(3*kbSI))
OUT.joinpath('magnet_results.json').write_text(json.dumps(res,indent=2),encoding='utf-8')
print(json.dumps({k:v for k,v in res.items() if k not in ['hubbard','mesh','seeds']},indent=2))
print('Hubbard:',[(r['U'],r['m'],r['gap'],r['energy'],r['difference']) for r in res['hubbard']])
