def alternate_pivots(s, peaks, troughs):
''' Given a timeseries s and 2 lists of turning points, defined by their indices in s,
this routine will return new sets of alternating peaks and troughs (new_peaks,
new_troughs). With the exception of the first and last elements, every trough
will correspond to a global minimum in the time interval defined by the pair of peaks
surrounding it, and vice versa – every peak is a global maximum in the time interval
defined by the troughs surrounding it.
calling: new_peaks, new_troughs = alternate_pivots(s, peaks, troughs)
'''
if peaks == [] or troughs == []:
print ('*** Error : lists may not be empty')
quit
idxs = sorted(peaks + troughs)
vals = [s[i] for i in idxs]
pts = [1 if idxs[i] in peaks else 0 for i in range(len(idxs))]
current_val = vals[0]
current_idx = idxs[0]
new_idxs = []
new_peaks = []
new_troughs = []
for i in range(1,len(idxs)):
#print i, current_idx, idxs[i]
if pts[i] != pts[i - 1]:
if pts[i-1] == 0:
new_troughs.append(current_idx)
else:
new_peaks.append(current_idx)
new_idxs.append(current_idx)
current_val = vals[i]
current_idx = idxs[i]
elif pts[i] == pts[i - 1] & pts[i] == 0: # another trough
if vals[i] < current_val:
current_val = vals[i]
current_idx = idxs[i]
elif pts[i] == pts[i - 1] & pts[i] == 1: # another peak
if vals[i] > current_val:
current_val = vals[i]
current_idx = idxs[i]
if i == len(idxs) - 1:
#print 'last one', current_idx
if pts[i] == 0:
new_troughs.append(current_idx)
else:
new_peaks.append(current_idx)
new_idxs.append(current_idx)
return new_peaks, new_troughs