我的代码应该在生成的NumPy数组中找出极值,并将它们极小的写在新数组中(最小值,最大值,最小值,最大值等)。该代码有效,但是速度太慢。所以我需要没有周期地做。我用numpy.logical_and删除了一个,但是剩下的两个是大的。也许np.where可以用,但是我不知道如何在这里使用它们。
import numpy as np
from scipy.signal import argrelextrema
import matplotlib.pyplot as plt
import timeit
if __name__ == '__main__':
N = 1000000 # Length of an array
T = 4 # Diff between indexes of an array
D = 4 # Diff between values of an array
x = np.random.uniform(low=-1, high=1, size=N)
x[0] = 1 # Starting value
x = np.cumsum(x) # Using cumsum for faster generating
index = [] # Array for indexes of local extremums
mins = argrelextrema(x, np.less)[0] # Array of min local extremums
maxs = argrelextrema(x, np.greater)[0] # Array of max local extremums
# print('AutoGenerated NumPy massive prepared using np.cumsum() \n', x)
index.append(mins[0]) # Zero will be min
min_elem = mins[0]
assert index[0] in mins
for max_elem in maxs:
# Checking the diff in values and in indexes, write if if suites
if x[max_elem] - x[min_elem] >= D and max_elem - min_elem >= T:
# Check if there's more suitable local minimum
min_elem = np.argmin(x[min_elem:max_elem]) + min_elem
index[-1] = min_elem
index.append(max_elem)
assert index[-1] in maxs
assert max_elem - min_elem >= T
assert x[max_elem] - x[min_elem] >= D
assert np.all(np.logical_and(x[min_elem+1:max_elem] >= x[min_elem],
x[min_elem+1:max_elem] <= x[max_elem]))
for min_elem in mins:
# Checking the diff in values and in indexes, write if if suites
if x[max_elem] - x[min_elem] >= D and min_elem - max_elem >= T:
# Check if there's more suitable local maximum
max_elem = np.argmax(x[max_elem:min_elem]) + max_elem
index[-1] = max_elem
index.append(min_elem)
assert index[-1] in mins
assert min_elem - max_elem >= T
assert x[max_elem] - x[min_elem] >= D
break
编辑:
[Remove在测试代码之前所有不需要的“打印”语句,因为Console Output速度慢,会给您不正确的时间。
[[已添加错误消息到assert statements,例如assert x >= 0, 'x is less than zero'
试图消除 x in y
语句,因为语言/编译器必须检查y
中的每个元素以查看是否存在x
。 References
祝你好运。>>