# Independent check used in the validation (coplanar strips): 2D quasi-static moment method for flat strips on a board in air.
# Requires Python 3 with NumPy and SciPy. Result: effective permittivity of the coplanar strips.
import numpy as np
from scipy import integrate
def eps_eq(k,er,d):
    t=np.tanh(k*d); return er*(1+er*t)/(er+t)
def cps_eeff_2d(W,S,h,er,N=60):
    # strips at z=0 on top of a slab (thickness h, er) in air; quasi-static 2D MoM with flat-strip pulses
    def edges(x0):
        t=np.linspace(0,np.pi,N+1); return x0-W/2+W*(1-np.cos(t))/2
    e1=edges(-(S+W)/2); e2=edges((S+W)/2)
    E=[(e1[i],e1[i+1]) for i in range(N)]+[(e2[i],e2[i+1]) for i in range(N)]
    xc=np.array([(a+b)/2 for a,b in E]); n=len(E)
    def Ilog(x,a,b,c2=0.0):   # int_a^b ln sqrt((x-x')^2+c2) dx'
        def F(u):
            if c2==0: return u*np.log(abs(u)+1e-300)-u
            c=np.sqrt(c2); return 0.5*u*np.log(u*u+c2)-u+c*np.arctan(u/c)
        return F(x-a)-F(x-b)
    def matrix(er):
        ginf=2/(1+er); M=np.zeros((n,n))
        if er>1:
            r=lambda k: 2/(1+eps_eq(k,er,h))-ginf-(1-ginf)*np.exp(-2*k*h)
            D=np.linspace(0,3*(S+2*W),400); sm=[]
            for Dl in D:
                val=integrate.quad(lambda k: r(k)*np.cos(k*Dl)/k, 0, 60/h, limit=400)[0]; sm.append(val)
            sm=np.array(sm)
        for i in range(n):
            for j in range(n):
                a,b=E[j]
                v=-ginf*Ilog(xc[i],a,b)
                if er>1:
                    v+=-(1-ginf)*Ilog(xc[i],a,b,4*h*h)
                    xs=np.linspace(a,b,5); v+=np.trapezoid(np.interp(np.abs(xc[i]-xs),D,sm),xs)
                M[i,j]=v
        return M
    def cap(er):
        M=matrix(er)
        A=np.zeros((n+1,n+1)); A[:n,:n]=M; A[:n,n]=-1; A[n,:n]=1   # unknown constant potential offset, neutrality
        rhs=np.zeros(n+1); rhs[:N]=-0.5; rhs[N:n]=0.5
        q=np.linalg.solve(A,rhs)[:n]; return np.sum(q[N:])     # charge on strip 2 for unit voltage (scaled)
    return cap(er)/cap(1.0)
for (W,S,h,er) in [(0.5,1.0,1.6,4.4),(0.5,2.0,0.635,10.2),(0.5,2.0,30,10.2),(0.5,2.0,0.635,4.4)]:
    print(W,S,h,er,'2D quasi-static eeff %.3f'%cps_eeff_2d(W,S,h,er))
