python
import numpy as np, matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
# -------- geometry & primary constants ----------
length = 1.0
nodes = 401
dx = length/(nodes-1)
L = 5e-7 # H/m
C = 2e-10 # F/m
Z0= np.sqrt(L/C)
vel= 1/np.sqrt(L*C)
dt = 0.9*dx/vel # CFL‑limited
# -------- lossy parameters (toggled) ------------
loss_on=False
R_loss=0.5 # Ω/m
G_loss=2e-3 # S/m
# -------- dynamic state -------------------------
V = np.zeros(nodes)
I = np.zeros(nodes-1)
switch_on=True
load_mode=0
Vs=1.0
load_dict={0:np.inf,1:1e-9,2:Z0}
# -------- plotting ------------------------------
fig,ax=plt.subplots()
x=np.linspace(0,length,nodes)
top,=ax.plot(x,np.zeros_like(x),'b')
bot,=ax.plot(x,np.zeros_like(x),'r')
ax.set_ylim(-C*Vs*1.2,C*Vs*1.2)
ax.set_xlabel('position (m)')
ax.set_ylabel('charge density (C/m)')
title=ax.set_title('')
time_sim=0.0 # physical time (s)
# -------- keyboard interaction ------------------
steps_per_frame=8
def on_key(e):
global switch_on,load_mode,loss_on,steps_per_frame
if e.key=='s': switch_on=not switch_on
if e.key=='l': load_mode=(load_mode+1)%3
if e.key=='d': loss_on=not loss_on
if e.key in ['+','=']: steps_per_frame=min(256,steps_per_frame*2)
if e.key in ['-','_']: steps_per_frame=max(1,steps_per_frame//2)
if e.key=='q': plt.close(fig)
fig.canvas.mpl_connect('key_press_event',on_key)
# -------- FDTD update ---------------------------
def step():
global V,I
R=R_loss if loss_on else 0.0
G=G_loss if loss_on else 0.0
I -= dt/L*((V[1:]-V[:-1])/dx + R*I)
if not switch_on: I[0]=0.0
V[1:-1]-=dt/C*((I[1:]-I[:-1])/dx + G*V[1:-1])
if switch_on: V[0]=Vs
else: V[0]-=dt/C*((I[0]-0.0)/dx + G*V[0])
ZL=load_dict[load_mode]
Iload=0.0 if np.isinf(ZL) else V[-1]/ZL
V[-1]-=dt/C*((Iload-I[-1])/dx + G*V[-1])
# -------- animation -----------------------------
def fmt_time(t):
return f'{t*1e9:6.2f} ns' if t>=1e-10 else f'{t*1e12:6.2f} ps'
def update(_):
global time_sim
for _ in range(steps_per_frame):
step()
time_sim+=dt
rho=C*V
top.set_ydata( rho); bot.set_ydata(-rho)
mode_txt=['OPEN','SHORT','MATCH'][load_mode]
src='ON' if switch_on else 'OFF'
loss='LOSSY' if loss_on else 'LOSSLESS'
title.set_text(f'{src} | {mode_txt} | {loss} | t={fmt_time(time_sim)} | x{steps_per_frame}')
return top,bot,title
ani=FuncAnimation(fig,update,interval=30,blit=True)
plt.show()