importnumpyasnpimportmatplotlib.pyplotasplt# the TDMAdefsol(aw,ap,ae,su):n=np.size(aw)p=np.zeros(n)q=np.zeros(n)phi=np.zeros(n)p[0]=ae[0]/ap[0]q[0]=su[0]/ap[0]foriinrange(1,n):p[i]=ae[i]/(ap[i]-aw[i]*p[i-1])q[i]=(su[i]+aw[i]*q[i-1])/(ap[i]-aw[i]*p[i-1])phi[n-1]=q[n-1]foriinrange(n-1,0,-1):phi[i-1]=p[i-1]*phi[i]+q[i-1]returnphirho=1# densityL=2# lengthn=100# number of pressure nodalsnu=n-1# number of velocity nodalsdx=L/np0=10# inlet stagnation pressurep_exit=0# oulet gauge pressuremass=[]# mass flowsp=[1]# momentum residual (source of pressure Eq.)residual=[]# list of residualm=1# guessed mass flow# matrix coeff and source term coeffapu=np.zeros(nu)awu=np.zeros(nu)aeu=np.zeros(nu)suu=np.zeros(nu)app=np.zeros(n)awp=np.zeros(n)aep=np.zeros(n)sup=np.zeros(n)# under-relaxation factoralpha_u=0.8alpha_p=0.3d=np.zeros(nu)# A/ap# area of pressure node and velocity nodeAp=np.linspace(0.5,0.1,n)Au=np.linspace(0.5-0.25/n,0.1+0.25/n,nu)# initial guessed valueu=np.zeros(nu)foriinrange(nu):u[i]=m/(rho*Au[i])p=np.linspace(p0,p_exit,n)pf=np.zeros(n)# Pressure correction valuewhile(max(sp)>1e-5):sp=[]# velocity updateforiinrange(1,nu-1):awu[i]=rho*(u[i-1]+u[i])/2*Ap[i]# F_waeu[i]=0# upwind schemeapu[i]=rho*(u[i]+u[i+1])/2*Ap[i+1]# awu[i]+aeu[i]+ (F_e-F_w)apu[i]=apu[i]/alpha_u# velocity relaxationsuu[i]=Au[i]*(p[i]-p[i+1])+(1-alpha_u)*apu[i]*u[i]d[i]=Au[i]/apu[i]apu[0]=rho*(u[0]+u[1])/2*Ap[1]+rho* \
(u[0]*Au[0]/Ap[0])*Ap[0]*0.5*(Au[0]/Ap[0])**2apu[0]=apu[0]/alpha_u# velocity relaxationsuu[0]=Au[0]*(p0-p[1])+rho*(u[0]*Au[0]/Ap[0])*Ap[0]* \
(Au[0]/Ap[0])*u[0]+(1-alpha_u)*apu[0]*u[0]d[0]=Au[0]/apu[0]awu[nu-1]=rho*(u[nu-2]+u[nu-1])/2*Ap[nu-1]apu[nu-1]=rho*u[nu-1]*Au[nu-1]*Au[nu-1]/Ap[n-1]apu[nu-1]=apu[nu-1]/alpha_u# velocity relaxationsuu[nu-1]=Au[nu-1]*(p[nu-1]-p[nu])+(1-alpha_u)*apu[nu-1]*u[nu-1]d[nu-1]=Au[nu-1]/apu[nu-1]u=sol(awu,apu,aeu,suu)# pressure updateforiinrange(1,n-1):awp[i]=rho*d[i-1]*Au[i-1]aep[i]=rho*d[i]*Au[i]app[i]=awp[i]+aep[i]sup[i]=rho*u[i-1]*Au[i-1]-rho*u[i]*Au[i]sp.append(abs(sup[i]))# do not update boundary pressure# so set app to none-zero number and set sup to zeroapp[0]=1sup[0]=0app[n-1]=1sup[n-1]=0pf=sol(awp,app,aep,sup)# under-relaxation of pressureprev=pp=p+pfp[0]=p0-0.5*rho*u[0]*u[0]*(Au[0]/Ap[0])**2p=(1-alpha_p)*prev+alpha_p*pforiinrange(nu):u[i]=u[i]+d[i]*(pf[i]-pf[i+1])# calculate mass flowmass.append(rho*Au[0]*u[0])residual.append(max(sp))plt.figure(1)plt.plot(mass)plt.title("mass flow")plt.figure(2)plt.yscale('log')plt.plot(residual)plt.title("max residual")print("mass flow:",mass[-1])print("momentum residual:",max(sp))