简体   繁体   English

将方波函数应用于 numpy 数组

[英]Apply square wave function to numpy array

I can quickly apply a cos function as follows to a float32 numpy array:我可以快速将 cos 函数应用到 f​​loat32 numpy 数组,如下所示:

 cos_f = np.vectorize(lambda x: math.cos(2 * math.pi * x))
 signal = square_f(integral)

However if I try this:但是,如果我尝试这样做:

 square_f = np.vectorize(lambda x: sig.square(2 * math.pi * x))
 signal = square_f(integral)

it takes 15 seconds for 60,000 samples. 60,000 个样本需要 15 秒。 integral has a length of 1024 and is used as a buffer. integral的长度为 1024,用作缓冲区。

How should I be applying the square wave to my signal?我应该如何将方波应用于我的信号?

I am not sure you need the np.vectorize here at all:我不确定你在这里是否需要np.vectorize

import numpy as np
from scipy import signal as sig

integral = np.linspace(0, 10, 1024)
signal1 = np.cos(2*np.pi * integral)
signal2 = sig.square(2*np.pi * integral)

You can of course also create a function and than call it with an array as input:您当然也可以创建一个函数,然后使用数组作为输入调用它:

def cos2pi(x):
    return np.cos(2*np.pi * x)

signal1 = cos2pi(integral)

And one could go even further and call the function just once for all samples simultaneously.并且可以更进一步,对所有样本同时调用该函数一次。

samples = np.random.random((60000, 1024))
signal1 = cos2pi(samples)

sig.square(2*np.pi * x) is three times slower than np.cos(2*np.pi * x) , however, this is not a bottleneck here. sig.square(2*np.pi * x)np.cos(2*np.pi * x)np.cos(2*np.pi * x) ,但是,这不是这里的瓶颈。 This nice np.vectorize - based decoration actually costs 120x slowdown!这个不错的基于np.vectorize的装饰实际上会降低 120 np.vectorize速度! The reason why this happens is that square_f applies scipy.signal.square on items being iterated which is a bunch of aritmetics designed to work with arrays instead (unlike math.cos ).之所以出现这种情况的原因是, square_f适用scipy.signal.square正在迭代上的项目是一堆设计工作与数组来代替(不像aritmetics的math.cos )。 This is an example of arithmetics done inside scipy.signal.square :这是在scipy.signal.square完成的算术scipy.signal.square

def example(x, w=0.5):
    return (1 - (w > 1) | (w < 0)) & (np.mod(x, 2 * pi) < w * 2 * np.pi)

Assuming arr is a large array, this is obviously more efficient to call example(arr) instead of假设arr是一个大数组,这显然更有效地调用example(arr)而不是

ex = np.vectorize(lambda x: example(x))
ex(arr)

The timings show that as well:时间安排也表明:

arr = np.linspace(0,1,1000000)
%timeit ex(arr)
%timeit example(arr)
8.13 s ± 208 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
18.5 ms ± 1.14 ms per loop (mean ± std. dev. of 7 runs, 100 loops each)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM