Skip to content

Instantly share code, notes, and snippets.

@gakhov
Created August 7, 2015 16:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gakhov/989eb06b59b26f805f61 to your computer and use it in GitHub Desktop.
Save gakhov/989eb06b59b26f805f61 to your computer and use it in GitHub Desktop.
Using a window smoothing and local extrema find intervals where curve is growing or lowering.
from scipy.signal import argrelextrema
def get_intervals(local_min, local_max, total):
"""Calculate growing and lowering intervals based on
local max and min. From the definition, growing intervals
start from local minimum, and lowering intervals start from
local maximum.
"""
growing = []
lowering = []
extremums = np.append(local_min, local_max)
extremums = np.sort(extremums)
index = None
for i in extremums:
if index is None:
index = i
continue
interval = (index, i)
index = i
if i in local_min:
growing.append(interval)
elif i in local_max:
lowering.append(interval)
return lowering, lowering
def smooth(x, window_len=11, window='hanning'):
"""see http://wiki.scipy.org/Cookbook/SignalSmooth
"""
if x.ndim != 1:
raise ValueError, "smooth only accepts 1 dimension arrays."
if x.size < window_len:
raise ValueError, "Input vector needs to be bigger than window size."
if window_len<3:
return x
if not window in ['flat', 'hanning', 'hamming', 'bartlett', 'blackman']:
raise ValueError, "Window is on of 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'"
s = np.r_[x[window_len-1:0:-1], x , x[-1:-window_len:-1]]
if window == 'flat':
# moving average
w = np.ones(window_len,'d')
else:
w = eval('np.' + window + '(window_len)')
y = np.convolve(w / w.sum(), s, mode='valid')
return y[(window_len/2-1):-(window_len/2)]
# Construct smoothed version of the curve.
smoothed_curve = smooth(
smoothed_curve,
int(len(smoothed_curve) / 25.0),
'hamming')
# Visualize curve and its smoothed version.
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(curve, 'r--', lw=1, label="curve")
ax.plot(smoothed_curve, 'b-', lw=1, label="smoothed curve")
ax.legend(loc='best')
# Find indices of local extrema for the smoothed curve.
local_max, = argrelextrema(smoothed_curve, np.greater, order=15)
local_min, = argrelextrema(smoothed_curve, np.less, order=15)
# Vizualize local extrema points on the smoothed curve.
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(smoothed_curve, 'b-', label='smoothed curve')
ax.plot(local_min, smoothed_curve[local_min], 'ro', markersize = 5, label='min')
ax.plot(local_max, smoothed_curve[local_max], 'go', markersize = 5, label='max')
ax.legend(loc='best')
# Find intervals of growing and lowering.
growing, lowering = get_intervals(local_min, local_max, len(smoothed_curve))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment