我从位移传感器捕获了一个数据,一次迭代的增量值看起来像这样。0、1、2、4、7、9、14日,24日,14日,10日,9日,7日,3 2 1 0,0,0,0,1,3,5,7,9,-14年,-24年,-14年,9、8、6、4、3、1,0,0,0。(其他迭代也有相同的模式)
我对曲线的最大值和最小值点很感兴趣。我从一个初始位置开始,然后回到这个位置进行循环(我已经取了这些值的部分和来获得总位移或直线)。部分和是这样的[0,1,3,7,14,23,37,61,75,85,94,101,104,106,107,107,107,107,107,106,103,98,91,82,68,44,30,21,13,7,3,0,-1,-1,-1,-1]。我对107和-1(下一个曲线最小值)感兴趣
但我不知道代码说n不。曲线(迭代)。你能帮我一下吗?
您可以使用这个函数来获取绝对极值:
def extrema(value, deltas):
max_value = min_value = value
for delta in deltas:
value += delta
if value < min_value:
min_value = value
elif value > max_value:
max_value = value
return min_value, max_value
这里我调整了函数以产生局部极值:
def extrema(value, deltas):
values = [value]
for delta in deltas:
value += delta
values.append(value)
average = sum(values)/len(values)
threshold = (max(values) - min(values))/6
min_threshold = average - threshold
max_threshold = average + threshold
min_value = max_value = None
for value in values:
if value < min_threshold:
if min_value is None or value < min_value:
min_value = value
elif value > max_threshold:
if max_value is None or value > max_value:
max_value = value
elif min_value is not None and max_value is not None:
yield min_value, max_value
max_value = min_value = None
您可以从这里对函数进行微调。例如,该函数可以跳过第一个值直到min_threshold < value < max_threshold
以找到循环的开始,并且在结束时,如果它没有以完整的循环结束,它可以产生最后一个极值。
最后,这里有一个函数,可以像您的示例数据一样处理点元组。
class Point(object):
__slots__ = ('x', 'y')
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __repr__(self):
return str((self.x, self.y))
def __iadd__(self, other):
self.x += other.x
self.y += other.y
return self
def __isub__(self, other):
self.x -= other.x
self.y -= other.y
return self
def __idiv__(self, number):
self.x /= number
self.y /= number
return self
def abs(self):
return abs(self.x) + abs(self.y)
def copy(self):
return Point(self.x, self.y)
def extrema(moves, jitter=0.1, threshold=1000, sample=16):
point = Point()
minpoint = Point()
maxpoint = Point()
average = Point()
average /= 1.0
turned = False
for move in moves:
point += move
x = point.x
if x < minpoint.x:
minpoint.x = x
elif x > maxpoint.x:
maxpoint.x = x
y = point.y
if y < minpoint.y:
minpoint.y = y
elif y > maxpoint.y:
maxpoint.y = y
delta = move.copy()
delta -= average
delta /= sample
average += delta
if average.abs() < jitter:
if point.abs() > threshold:
turned = True
elif turned:
yield minpoint, maxpoint
point = Point() # reset (calibrate)
minpoint = Point()
maxpoint = Point()
turned = False
# read data from file
moves = [Point(*map(int, move.split(',')))
for move in open('data.txt').read().split(';') if move]
# generate extrema
print list(extrema(moves))