python 中的矩形脉冲序列

rectangular pulse train in python

我正在尝试在 python 中实现矩形脉冲序列。

我搜索了scipy,没有实现的信号。 http://docs.scipy.org/doc/scipy/reference/signal.html

在matlab中有一个名为pulstran的信号: http://es.mathworks.com/help/signal/ref/pulstran.html

matlab 中的代码示例如下:

T=10; %Period
D=5; %Duration
N=10; %Number of pulses

x=linspace(0,T*N,10000);
d=[0:T:T*N];
y=pulstran(x,d,'rectpuls',D);
plot(x,y);
ylim([-1,2]);

我如何在 python?

中实现这个信号

谢谢。

如果您只是在寻找周期性脉冲序列,就像您给出的示例一样 - 这是一个脉冲序列,开启 5 个周期然后关闭五个周期:

N = 100 # sample count
P = 10  # period
D = 5   # width of pulse
sig = np.arange(N) % P < D

给予

plot(sig)

您可以在此处将 np.arange(N) 替换为您的 linspace。请注意,这与您的代码不等价,因为脉冲未居中。


这是一个完全可配置的脉冲序列:

def rect(T):
    """create a centered rectangular pulse of width $T"""
    return lambda t: (-T/2 <= t) & (t < T/2)

def pulse_train(t, at, shape):
    """create a train of pulses over $t at times $at and shape $shape"""
    return np.sum(shape(t - at[:,np.newaxis]), axis=0)

sig = pulse_train(
    t=np.arange(100),              # time domain
    at=np.array([0, 10, 40, 80]),  # times of pulses
    shape=rect(10)                 # shape of pulse
)

给予:


我认为这是 matlab 的 pulsetran 函数比 python 中的单行实现更令人困惑的情况之一,这可能是 scipy 没有的原因提供。

您可以使用 scipy.signal 中的 square 函数:

来自 here 的逐字记录:

from scipy import signal
import matplotlib.pyplot as plt
t = np.linspace(0, 1, 500, endpoint=False)
plt.plot(t, signal.square(2 * np.pi * 5 * t))
plt.ylim(-2, 2)

因此,对于您的示例,请执行以下操作:

T=10
D=5
N=10
shift = 1/4   # number of cycles to shift (1/4 cycle in your example)
x = np.linspace(0, T*N, 10000, endpoint=False)
y=signal.square(2 * np.pi * (1/T) * x + 2*shift*np.pi)
plt.plot(x,y)
plt.ylim(-2, 2)
plt.xlim(0, T*N)

所有答案都很好,但我发现他们在使用 scipy.integrate 时遇到了一些问题,所以我创建了 3 种类型,特别牢记 scipy.integrate:

  • 统一的脉冲宽度和统一的时间周期(每个参数必须是一个数字)。

def uniform_pulse_function(self, t, start, stop, pulsewidth, period, amplitude):
        func = amplitude * np.where((t > start and t < stop and (t % period <(pulsewidth))),
                                    1, 0)

  • 脉冲宽度相同但振幅不同(每个参数必须是单个数字,振幅除外,振幅应该是长度与开始和停止内可容纳的脉冲数相同长度的元组):

func = (amplitude[int(t//period)])*np.where((t>start and t<stop and (t%period<(pulsewidth))), 1, 0)
        return func

  • 不均匀的脉冲宽度和不均匀的幅度但周期应保持不变(幅度和脉冲宽度应为长度与开始和停止内可容纳的脉冲数相同的元组,而周期应为单个数字) :

def custom_pulse_function(self, t, start, stop, pulsewidth, period, amplitude):
        func = (amplitude[int(t//period)]) * np.where((t > start and t < stop and (t % period < (pulsewidth[int(t//period)]))), 1, 0)
        return func