"""Independent educational arithmetic, not execution of KiCad/Qucs or a field solver.
Qucs technical note eqs 11.4, 11.6, 11.15-18; t=0.
Centered stripline: Cohn elliptic relation documented by KiCad/Polar.
Dimensions in mm; ideal perfect conductors, no mask/dispersion/loss/vias.
"""
from math import pi,log,exp,sqrt,cosh,tanh
from pathlib import Path
import csv,json
ETA=376.730313668
ER=3.66
H=0.20 # microstrip height; also stripline half plane separation
B=2*H

def micro(w):
 u=w/H
 a=1+log((u**4+(u/52)**2)/(u**4+0.432))/49+log(1+(u/18.1)**3)/18.7
 b=0.564*((ER-0.9)/(ER+3))**0.053
 eff=(ER+1)/2+(ER-1)/2*(1+10/u)**(-a*b)
 fu=6+(2*pi-6)*exp(-(30.666/u)**0.7528)
 z=ETA/(2*pi)*log(fu/u+sqrt(1+(2/u)**2))/sqrt(eff)
 return z,eff

def K(k):
 # Complete elliptic integral, argument is modulus k, not parameter m=k^2.
 a,b=1.,sqrt(1-k*k)
 for _ in range(100):
  a,b=(a+b)/2,sqrt(a*b)
  if abs(a-b)<1e-15:break
 return pi/(2*a)

def strip(w):
 x=pi*w/(2*B)
 return ETA/(4*sqrt(ER))*K(1/cosh(x))/K(tanh(x)),ER

def width(fn,target=50):
 lo,hi=.01,2.
 for _ in range(100):
  m=(lo+hi)/2
  if fn(m)[0]>target:lo=m
  else:hi=m
 return (lo+hi)/2

if __name__=='__main__':
 p=Path(__file__).parent
 rows=[]
 for label,fn in [('microstrip',micro),('symmetric_stripline',strip)]:
  for case,w in [('same_width',.30),('synthesized_50ohm',width(fn))]:
   z,e=fn(w)
   rows.append({'structure':label,'case':case,'width_mm':round(w,6),'material_er':ER,'microstrip_h_mm':H if label=='microstrip' else '', 'stripline_plane_separation_mm':B if label!='microstrip' else '', 'metal_thickness_mm':0,'z0_ohm':round(z,6),'effective_er':round(e,6),'delay_ps_per_mm':round(sqrt(e)/299792458*1e9,6)})
 with (p/'calculated-results.csv').open('w',newline='') as f:
  wr=csv.DictWriter(f,fieldnames=rows[0]);wr.writeheader();wr.writerows(rows)
 assert abs(K(0)-pi/2)<1e-12
 assert micro(.2)[0]>micro(.4)[0] and strip(.2)[0]>strip(.4)[0]
 assert all(abs(fn(width(fn))[0]-50)<1e-9 for fn in [micro,strip])
 print(json.dumps({'checks':'passed','results':rows},indent=2))
