LLRFLibsPy库中ss_discrete函数解读

source code:Github

这段代码定义了一个名为 ss_discrete 的函数,该函数用于将连续状态空间模型转换为离散状态空间模型,并比较它们的频率响应。以下是对这段代码的详细解读:

函数定义

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
def ss_discrete(Ac, Bc, Cc, Dc, Ts, method = 'zoh', alpha = 0.3, plot = False, plot_pno = 1000, spec_data = False):
'''
Derive the discrete state-space equation from a continous one and compare
their frequency responses.

Parameters:
Ac, Bc, Cc, Dc: numpy matrix (complex), continous state-space model
Ts: float, sampling time, s
method: string, ``gbt``, ``bilinear``, ``euler``, ``backward_diff``, ``zoh``,
``foh`` or ``impulse`` (see document of signal.cont2discrete)
alpha: float, 0 to 1 (see document of signal.cont2discrete)
plot: boolean, enable the plot of frequency responses
plot_pno: int, number of point in the plot
spec_data: boolean, return spectra data or not

Returns:
status: boolean, success (True) or fail (False)
Ad, Bd, Cd, Dd: numpy matrix (complex), discrete state-space model
'''

函数接受以下参数:

  • Ac, Bc, Cc, Dc:连续状态空间模型的矩阵。
  • Ts:采样时间,单位为秒。
  • method:离散化方法,可以是 'gbt', 'bilinear', 'euler', 'backward_diff', 'zoh', 'foh''impulse'(详细信息见 scipy.signal.cont2discrete 文档)。
  • alpha:在 01 之间的浮点数,某些离散化方法(如 'gbt')使用的参数。
  • plot:布尔值,是否绘制频率响应图。
  • plot_pno:绘图时的点数。
  • spec_data:布尔值,是否返回频谱数据。

返回值包括一个布尔值 status(表示成功与否),离散状态空间模型的四个矩阵 Ad, Bd, Cd, Dd,以及可选的频谱数据 spec

参数检查

1
2
3
4
5
# check the input
if (Ts <= 0):
return (False,) + (None,)*5

plot_pno = 1000 if (plot_pno <= 0) else plot_pno

检查采样时间 Ts 是否大于 0。如果不满足条件,函数返回 False 和五个 None。设置绘图点数 plot_pno 为至少 1000 点。

离散化

1
2
# discretize it
Ad, Bd, Cd, Dd, _ = signal.cont2discrete((Ac, Bc, Cc, Dc), Ts, method = method, alpha = alpha)

使用 scipy.signal.cont2discrete 函数将连续状态空间模型转换为离散状态空间模型。

计算频率响应

1
2
3
4
5
6
7
8
9
# calculate the responses of both continous and discrete versions
if plot or spec_data:
sc, fc, Ac_dB, Pc_deg, _ = ss_freqresp(Ac, Bc, Cc, Dc, plot_pno = plot_pno, plot_maxf = 1.0 / Ts)
sd, fd, Ad_dB, Pd_deg, _ = ss_freqresp(Ad, Bd, Cd, Dd, plot_pno = plot_pno, Ts = Ts)

spec = {'fc': fc, 'Ac_dB': Ac_dB, 'Pc_deg': Pc_deg,
'fd': fd, 'Ad_dB': Ad_dB, 'Pd_deg': Pd_deg}
else:
spec = None

如果 plotspec_dataTrue,则使用 ss_freqresp 函数计算连续和离散状态空间模型的频率响应,并存储频谱数据到 spec 字典中。

绘制频率响应图

1
2
3
4
5
6
# plot the responses
if plot:
# make the plot
if sc and sd:
from rf_plot import plot_ss_discrete
plot_ss_discrete(fc, Ac_dB, Pc_deg, fd, Ad_dB, Pd_deg, Ts)

如果 plotTrue,并且 scsd 都为 True,则使用 plot_ss_discrete 函数绘制频率响应图。

返回结果

1
2
# return the results
return True, Ad, Bd, Cd, Dd, spec

返回成功状态 True,离散状态空间模型的四个矩阵 Ad, Bd, Cd, Dd,以及频谱数据 spec(如果 spec_dataTrue)。

总结

ss_discrete 函数的作用是将给定的连续状态空间模型转换为离散状态空间模型,并根据需要比较它们的频率响应。函数首先检查输入参数的有效性,然后进行离散化处理,并根据需要计算和绘制频率响应图。最后返回离散状态空间模型和频谱数据。

示例

source code:Github

Detuning-By-Mech.png