"""Reproducible transport examples. Python 3 with NumPy and Pillow; outputs are model data."""
from pathlib import Path
import json,math
import numpy as np
from PIL import Image,ImageDraw,ImageFont
ROOT=Path(__file__).resolve().parent
FIG=ROOT/'figures';FIG.mkdir(exist_ok=True)
e=1.602176634e-19;h=6.62607015e-34;hb=h/(2*np.pi);kb=1.380649e-23;me=9.1093837139e-31
checks=[]
def ck(name,condition):
 if not condition:raise AssertionError(name)
 checks.append(name)
def two(B,r=1,ue=1,uh=.5):
 d=ue/(1+(ue*B)**2)+r*uh/(1+(uh*B)**2)
 q=B*(ue**2/(1+(ue*B)**2)-r*uh**2/(1+(uh*B)**2))
 return d/(d*d+q*q)*(ue+r*uh),-q/(d*d+q*q)
n=8.5e28;rho=1.7e-8;tau=me/(n*e*e*rho);kf=(3*np.pi**2*n)**(1/3);ef=hb**2*kf*kf/(2*me);vf=hb*kf/me
copper=dict(tau_s=tau,kF_m_1=kf,EF_eV=ef/e,vF_m_s=vf,l_nm=vf*tau*1e9,Cel_J_m3K=np.pi**2*n*kb*300/(2*ef/kb),kappa_W_mK=np.pi**2*kb**2/(3*e**2)*300/rho)
ng=1e16;vg=1e6;kg=np.sqrt(np.pi*ng);eg=hb*vg*kg;mc=eg/vg**2
graphene=dict(n_m2=ng,kF_m_1=kg,EF_meV=eg/e*1000,mc_me=mc/me,tau_ps=mc/e*1e12,l_nm=vg*mc/e*1e9,F_T=hb*np.pi*kg*kg/(2*np.pi*e),zero_level_only_B_T=ng*h/(2*e))
for b in np.linspace(0,10,21):
 a,_=two(b,0);ck('single_band_'+str(b),abs(a-1)<2e-14)
 a,_=two(b,1);ck('compensation_'+str(b),abs(a-(1+.5*b*b))<2e-12)
ck('B5_correct_13point5',abs(two(5,1)[0]-13.5)<1e-12)
Bs=np.linspace(0,10,201)
np.savetxt(ROOT/'transport_two_band.csv',np.c_[Bs,*[two(Bs,r)[0] for r in [0,.8,1]]],delimiter=',',header='B_T,rho_norm_p0,rho_norm_p0p8n,rho_norm_pn',comments='')
def lk(T,B,m):
 x=2*np.pi**2*kb*T*m/(e*hb*B)
 return np.where(x<1e-9,1,x/np.sinh(x))
def noise(aspect,N=10000):
 q=(np.arange(N)+.5)*np.pi/aspect
 t=1/np.cosh(np.minimum(q,350))**2
 return float(4*e*e/h*t.sum()),float((t*(1-t)).sum()/t.sum())
g,fn=noise(10);ck('graphene_Fano',abs(fn-1/3)<1e-5)
def moments(T,r,mu=.2):
 energies=np.linspace(1e-9,max(mu+30*kb*T/e,.8),50001)
 eps=energies*e;M=mu*e;x=(eps-M)/(kb*T)
 fprime=1/(4*kb*T*np.cosh(np.minimum(np.abs(x)/2,350))**2)
 sig=energies**(r+1)
 L=[np.trapezoid(sig*(eps-M)**a*fprime,eps) for a in range(3)]
 return -L[1]/(e*T*L[0])
S={str(r):moments(100,r)*1e6 for r in [-1,0,1]}
ck('Mott_constant_tau_100K',abs(S['0']+12.215)<.02)
figs=[]
fontfile=Path('C:/Windows/Fonts/arial.ttf')
def font(n):return ImageFont.truetype(str(fontfile),n)
colors=['#1c5a91','#b64d32','#27815e','#765595']
def panel(im,box,title,xlabel,ylabel,xlim,ylim):
 d=ImageDraw.Draw(im);x,y,w,hh=box;L=x+100;R=x+w-30;U=y+55;D=y+hh-150
 d.text((x+30,y+8),title,font=font(25),fill='black')
 d.text((L,U-24),ylabel,font=font(20),fill='#222222')
 for a in np.linspace(0,1,5):
  xx=L+a*(R-L);yy=D-a*(D-U)
  d.line((xx,U,xx,D),fill='#e1e4e8',width=1);d.line((L,yy,R,yy),fill='#e1e4e8',width=1)
  d.text((xx-18,D+10),f'{xlim[0]+a*(xlim[1]-xlim[0]):g}',font=font(18),fill='#333333')
  value=f'{ylim[0]+a*(ylim[1]-ylim[0]):.3g}';d.text((L-15,yy),value,font=font(18),fill='#333333',anchor='rm')
 d.line((L,U,L,D,R,D),fill='black',width=2)
 d.text(((L+R)/2,D+48),xlabel,font=font(21),fill='black',anchor='mm')
 def curve(xx,yy,color,label='',row=0):
  pts=[(L+(float(a)-xlim[0])/(xlim[1]-xlim[0])*(R-L),D-(float(b)-ylim[0])/(ylim[1]-ylim[0])*(D-U)) for a,b in zip(xx,yy)]
  d.line(pts,fill=color,width=3)
  if label:d.text((L+12,D+70+24*row),label,font=font(20),fill=color)
 return curve
im=Image.new('RGB',(1600,1120),'white')
x=np.linspace(0,5,401);c=panel(im,(0,0,800,550),'T1  Drude optical response','omega tau','sigma / sigma_DC',(0,5),(0,1));c(x,1/(1+x*x),colors[0],'real');c(x,x/(1+x*x),colors[1],'imaginary',1)
tt=np.linspace(0,3,501);c=panel(im,(800,0,800,550),'T4  Bloch oscillation','time (ps)','x(t)-x(0) (nm)',(0,3),(-50,0))
for j,E in enumerate([4e5,8e5]):c(tt,(.020*e/(2*e*E))*(np.cos(e*E*1e-8*tt*1e-12/hb)-1)*1e9,colors[j],f'E = {E/1e5:g} kV/cm',j)
ns=np.linspace(.05,4,401);c=panel(im,(0,550,800,550),'T3  Dirac orbit mass','density (10^12 cm^-2)','cyclotron mass / m_e',(0,4),(0,.045));c(ns,hb*np.sqrt(np.pi*ns*1e16)/vg/me,colors[0],'v_F = 10^6 m/s')
temp=np.linspace(1,300,70);c=panel(im,(800,550,800,550),'T7  Thermopower and scattering','temperature (K)','Seebeck (microV/K)',(0,300),(-80,0))
for j,r in enumerate([-1,0,1]):c(temp,[moments(T,r)*1e6 for T in temp],colors[j],f'tau proportional to E^{r}',j)
im.save(FIG/'transport_foundations.png')
im=Image.new('RGB',(1600,1120),'white')
c=panel(im,(0,0,800,550),'T9  Compensation enhances MR','B (T)','rho_xx(B) / rho_xx(0)',(0,10),(0,55))
for j,r in enumerate([0,.8,1]):c(Bs,two(Bs,r)[0],colors[j],f'p/n = {r:g}',j)
c=panel(im,(800,0,800,550),'T12  Angular orbit test','field angle (degrees)','F(theta) / F(0)',(0,80),(0,6))
ang=np.linspace(0,80,301);rad=np.deg2rad(ang);c(ang,1/np.cos(rad),colors[0],'2D sheet');c(ang,1/np.sqrt(np.cos(rad)**2+np.sin(rad)**2/9),colors[1],'ellipsoid c/a=3',1)
c=panel(im,(0,550,800,550),'T11  Thermal damping of oscillations','temperature (K)','R_T',(0,30),(0,1));tt=np.linspace(.01,30,301)
for j,B in enumerate([1,2,5]):c(tt,lk(tt,B,mc),colors[j],f'B={B} T, m*=0.02052 m_e',j)
c=panel(im,(800,550,800,550),'T16  Contact asymmetry','energy detuning (meV)','transmission',(0,60),(0,1));de=np.linspace(0,60,401)
for j,(gl,gr) in enumerate([(10,10),(5,15)]):c(de,gl*gr/(de**2+(gl+gr)**2/4),colors[j],f'Gamma_L={gl}, Gamma_R={gr} meV',j)
im.save(FIG/'transport_measurements.png')
results=dict(copper=copper,graphene=graphene,two_band=dict(B2=two(2,1)[0],B5=two(5,1)[0]),thermopower_at_100K_uV_K=S,neutral_graphene=dict(G_uS=g*1e6,Fano=fn),checks=checks,provenance='All values and figures are calculations of specified instructional models; no measured datasets.')
(ROOT/'transport_results.json').write_text(json.dumps(results,indent=2),encoding='utf8')
print(json.dumps({'checks_passed':len(checks),'B5':results['two_band']['B5'],'figures':2}))
