gpt4 book ai didi

python - 使用 Python lfilter 过滤信号

转载 作者:太空狗 更新时间:2023-10-30 00:50:26 28 4
gpt4 key购买 nike

我是 Python 的新手,在过滤信号时完全卡住了。这是代码:

import numpy as np
import matplotlib.pyplot as plt
from scipy import signal

fs=105e6
fin=70.1e6

N=np.arange(0,21e3,1)

# Create a input sin signal of 70.1 MHz sampled at 105 MHz
x_in=np.sin(2*np.pi*(fin/fs)*N)

# Define the "b" and "a" polynomials to create a CIC filter (R=8,M=2,N=6)
b=np.zeros(97)
b[[0,16,32,48,64,80,96]]=[1,-6,15,-20,15,-6,1]
a=np.zeros(7)
a[[0,1,2,3,4,5,6]]=[1,-6,15,-20,15,-6,1]

w,h=signal.freqz(b,a)
plt.plot(w/max(w),20*np.log10(abs(h)/np.nanmax(h)))
plt.title('CIC Filter Response')

output_nco_cic=signal.lfilter(b,a,x_in)

plt.figure()
plt.plot(x_in)
plt.title('Input Signal')
plt.figure()
plt.plot(output_nco_cic)
plt.title('Filtered Signal')

情节:

Input, filter and output signals

如您所见,虽然滤波器传递函数正确,但输出却不正确。而且我不明白为什么我的代码不起作用。我在 Matlab 中编写了相同的代码,输出看起来不错。

感谢您的帮助!

最佳答案

我不觉得这不适用于 Python 令人困惑,但我确实觉得它适用于 Matlab 令人困惑。

CIC 过滤器不适用于 float 。

更新:

有趣的是,至少在我拥有的 scipy 版本中,lfilter 不适用于整数数组——我得到一个 NotImplemented 错误。这是 CIC 过滤器的一个 numpy 版本,它的速度大约是我机器上纯 Python 实现的两倍:

# Implements an in-memory CIC decimator using numpy.

from math import log
from numpy import int32, int64, array

def cic_decimator(source, decimation_factor=32, order=5, ibits=1, obits=16):

# Calculate the total number of bits used internally, and the output
# shift and mask required.
numbits = order * int(round(log(decimation_factor) / log(2))) + ibits
outshift = numbits - obits
outmask = (1 << obits) - 1

# If we need more than 64 bits, we can't do it...
assert numbits <= 64

# Create a numpy array with the source
result = array(source, int64 if numbits > 32 else int32)

# Do the integration stages
for i in range(order):
result.cumsum(out=result)

# Decimate
result = array(result[decimation_factor - 1 : : decimation_factor])

# Do the comb stages. Iterate backwards through the array,
# because we use each value before we replace it.
for i in range(order):
result[len(result) - 1 : 0 : -1] -= result[len(result) - 2 : : -1]

# Normalize the output
result >>= outshift
result &= outmask
return result

关于python - 使用 Python lfilter 过滤信号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21879676/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com