将来自 MATLAB 的 SNR 计算转换为 python 的语法

translated the SNR calculation from MATLAB into the syntax of python

这是我想翻译成 Python 的 MATLAB 代码。

function [SNR] = bvpsnr(BVP, FS, HR, PlotTF)
HR_F=HR/60;
NyquistF = FS/2;
FResBPM = 0.5; %resolution (bpm) of bins in power spectrum used to determine PR and SNR
N = (60*2*NyquistF)/FResBPM; %number of bins in power spectrum

%% Construct Periodogram
[Pxx,F] = periodogram(BVP,hamming(length(BVP)),N,FS);
GTMask1 = (F >= HR_F-0.1)&(F <= HR_F+0.1);
GTMask2 = (F >= HR_F*2-0.2)&(F <= HR_F*2+0.2);
SPower = sum(Pxx(GTMask1|GTMask2));
FMask2 = (F >= 0.5)&(F <= 4);
AllPower = sum(Pxx(FMask2));
SNR = pow2db(SPower/(AllPower-SPower));

这里我试着翻译成python

def pow2db(x):
    return 10 * log10(x)

def SNR(bvp, fps, hr):

    HR_F = hr/60
    Nyquist = fps/2
    FResBPM = 0.5
    N = (60*2*Nyquist)/FResBPM
    print(N)

    f_set, Pxx_den = welch(bvp, fps, window='hann', nperseg=32)
    GTMask1 = f_set >= HR_F-0.1 and f_set <= HR_F+0.1
    GTMask2 = f_set >= HR_F*2-0.2 and f_set <= HR_F*2+0.2
    SPower = sum(Pxx_den[GTMask1:GTMask2])
    FMask2 = f_set >= 0.5 and f_set <=3
    AllPower = sum(Pxx_den[FMask2])
    SNR = pow2db(SPower/(AllPower-SPower))

当我 运行 将以下代码与我的数据一起使用时,出现错误:

GTMask1 = f_set >= HR_F-0.1 and f_set <= HR_F+0.1 ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

要比较 numpy 数组 element-wise,请使用 & 运算符(逻辑与 ):

GTMask1 = (f_set >= HR_F-0.1) & (f_set <= HR_F+0.1)
GTMask2 = (f_set >= HR_F*2-0.2) & (f_set <= HR_F*2+0.2)

对于逻辑或使用|:

SPower = sum(Pxx_den[GTMask1|GTMask2])