Python/Numpy中数组元素移位的优化

2024-04-26 17:50:21 发布

您现在位置:Python中文网/ 问答频道 /正文

问题:

在对我编写的数据分析代码进行行分析之后,我发现大约70%的运行时间集中在对两个不同数组操作例程的调用上。我最终希望以实时方式分析数据,所以这里的任何优化都会有很大帮助。

Matrix Forms

这两个函数获取左边的矩阵并将其转换为右边的形式(反之亦然)。

我感兴趣的矩阵目前存储为N乘n2d numpy数组(其中N是偶数)。

代码:

为此,我编写了以下代码:

# Shifts elements of a vector to the left by the given amount.
def Vec_shift_L(vec, shift=0):
    s = vec.size
    out = np.zeros(s, dtype=complex)
    out[:s-shift] = vec[shift:]
    out[s-shift:] = vec[:shift]
    return out

# Shifts elements of a vector to the right by the given amount.
def Vec_shift_R(vec,shift=0):
    s=vec.size
    out=np.zeros(s, dtype=complex)
    out[:shift] = vec[s-shift:]
    out[shift:] = vec[:s-shift]
    return out

# Shifts a matrix from the left form (above) to the right form.
def OP_Shift(Trace):
    s = Trace.shape
    Out = np.zeros(s, dtype=complex)

    for i in np.arange(s[0]):
        Out[i,:] = Vec_shift_L(Trace[i,:], (i+s[0]/2) % s[0])

    for i in np.arange(s[0]):
        Out[i,:] = np.flipud(Out[i,:])

    return Out

# Shifts a matrix from the right form (above) to the left form.
def iOP_Shift(Trace):
    s = Trace.shape
    Out = np.zeros(s, dtype=complex)
    for i in np.arange(s[0]):
        Out[i,:] = np.flipud(Trace[i,:])

    for i in np.arange(s[0]):
        Out[i,:] = Vec_shift_R(Out[i,:], (i+s[0]/2) % s[0])

    return Out

在最初编写本文时,我并没有意识到numpy的roll函数,所以我编写了vec_shift函数来代替它。在我目前的系统上,他们似乎比使用roll的性能提高了30%左右。

有没有办法进一步提高这段代码的性能?


Tags: theto代码shiftdefnpzerostrace
1条回答
网友
1楼 · 发布于 2024-04-26 17:50:21

^{}帮你解决一个矢量化的解决方案!在

# Store shape of input array
s = Trace.shape

# Store arrays corresponding to row and column indices
I = np.arange(s[0])
J = np.arange(s[1]-1,-1,-1)

# Store all iterating values in "(i+s[0]/2) % s[0]" as an array
shifts = (I + s[0]/2)%s[0]

# Calculate all 2D linear indices corresponding to 2D transformed array
linear_idx = (((shifts[:,None] + J)%s[1]) + I[:,None]*s[1])

# Finally index into input array with indices for final output
out = np.take(Trace,linear_idx)

相关问题 更多 >