下面是一份单文件、极简可交互的 Python 脚本,采用 FDTD 方法实时仿真传输线上的“电子密度”ρ=C·V。界面上有开/关按钮、三种负载单选、损耗开关和速度滑条,仿真过程中会显示物理时间,并在上下两个子图分别画正负ρ。
python
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Button, RadioButtons, CheckButtons, Slider
# —— 参数 ——
N = 200 # 空间离散点数
length = 1.0 # 线长 (m)
L, C = 1e-6, 1e-6 # 分布电感、电容
dx = length/N
c0 = 1/np.sqrt(L*C)
dt = dx/c0*0.5 # 满足 CFL
V0 = 1.0 # 电压源幅值
Z0 = np.sqrt(L/C)
R_loss, G_loss = 1e-2, 1e-2 # 损耗参数
# —— 状态 ——
switch_on = False
term = 'open' # 'open','short','match'
use_loss = False
speed = 1.0
# —— 域 ——
V = np.zeros(N)
I = np.zeros(N)
# —— 画布和控件 ——
plt.ion()
fig = plt.figure(figsize=(8,6))
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212, sharex=ax1)
x = np.linspace(0, length, N)
line_up, = ax1.plot(x, C*V, color='C0')
line_down, = ax2.plot(x, -C*V, color='C1')
for ax in (ax1,ax2):
ax.set_ylim(-V0*1.2, V0*1.2)
ax1.set_title("电子密度 ρ=C·V (上)")
ax2.set_title("电子密度 ρ=C·V (下)")
ax2.set_xlabel("位置 x (m)")
time_text = fig.text(0.5, 0.94, "", ha='center')
# 按钮、单选、勾选、滑条
ax_sw = plt.axes([0.02,0.8,0.1,0.06])
bx = Button(ax_sw, 'Switch\nOFF')
def on_switch(event):
global switch_on
switch_on = not switch_on
bx.label.set_text('Switch\nON' if switch_on else 'Switch\nOFF')
bx.on_clicked(on_switch)
ax_rb = plt.axes([0.15,0.7,0.15,0.15], facecolor='lightgoldenrodyellow')
rb = RadioButtons(ax_rb, ('open','short','match'))
def on_term(label):
global term
term = label
rb.on_clicked(on_term)
ax_ck = plt.axes([0.35,0.85,0.1,0.1], facecolor='lightgoldenrodyellow')
ck = CheckButtons(ax_ck, ['Loss'], [use_loss])
def on_loss(label):
global use_loss
use_loss = not use_loss
ck.on_clicked(on_loss)
ax_sl = plt.axes([0.55,0.85,0.3,0.03], facecolor='lightgoldenrodyellow')
sl = Slider(ax_sl, 'Speed', 0.1, 5.0, valinit=speed)
def on_speed(val):
global speed
speed = val
sl.on_changed(on_speed)
plt.tight_layout(rect=[0,0,1,0.92])
# —— 主循环 ——
nsteps = 5000
for n in range(nsteps):
# 电流更新
I[:-1] += -(dt/L/dx)*(V[1:]-V[:-1])
if use_loss:
I[:-1] += -R_loss/L*dt*I[:-1]
if term=='open':
I[-1] = 0
# 电压更新
V[1:] += -(dt/C/dx)*(I[1:]-I[:-1])
if use_loss:
V[1:] += -G_loss/C*dt*V[1:]
V[0] = V0 if switch_on else 0
if term=='short':
V[-1] = 0
elif term=='match':
V[-1] = Z0*I[-1]
# 绘图更新
rho = C*V
line_up.set_ydata( rho)
line_down.set_ydata(-rho)
time_text.set_text(f"模拟时间: {n*dt:.4f} s")
plt.pause(0.01/speed)
plt.ioff()
plt.show()