def peaks(spectra,frequency,number=3,thresh=0.01):
""" Return the peaks from the Fourier transform
Variables:
number: integer. number of peaks to print.
thresh: float. Threshhold intensity for printing.
Returns: Energy (eV), Intensity (depends on type of spectra)
"""
from scipy.signal import argrelextrema as pks
# find all peak indices [idx], and remove those below thresh [jdx]
idx = pks(np.abs(spectra),np.greater,order=3)
jdx = np.where((np.abs(spectra[idx]) >= thresh))
kdx = idx[0][jdx[0]] # indices of peaks matching criteria
if number > len(kdx):
number = len(kdx)
print("First "+str(number)+" peaks (eV) found: ")
for i in xrange(number):
print("{0:.4f}".format(frequency[kdx][i]*27.2114),
"{0:.4f}".format(spectra[kdx][i]))
python类argrelextrema()的实例源码
def get_local_maxima(x, y):
"""
This function ...
:param x:
:param y:
:return:
"""
m = argrelextrema(y, np.greater)[0].tolist()
# Find the index of the absolute maximum (should also be included, is not for example when it is at the edge)
index = np.argmax(y)
if index not in m: m.append(index)
x_maxima = [x[i] for i in m]
y_maxima = [y[i] for i in m]
return x_maxima, y_maxima
# -----------------------------------------------------------------
def get_local_minima(x, y):
"""
This function ...
:param x:
:param y:
:return:
"""
m = argrelextrema(y, np.less)[0].tolist()
# Find the indx of the absolute minimum (should also be included, is not for example when it is at the edge)
index = np.argmin(y)
if index not in m: m.append(index)
x_minima = [x[i] for i in m]
y_minima = [y[i] for i in m]
return x_minima, y_minima
# -----------------------------------------------------------------
def get_local_maxima(x, y):
"""
This function ...
:param x:
:param y:
:return:
"""
m = argrelextrema(y, np.greater)[0].tolist()
# Find the index of the absolute maximum (should also be included, is not for example when it is at the edge)
index = np.argmax(y)
if index not in m: m.append(index)
x_maxima = [x[i] for i in m]
y_maxima = [y[i] for i in m]
return x_maxima, y_maxima
# -----------------------------------------------------------------
def get_local_minima(x, y):
"""
This function ...
:param x:
:param y:
:return:
"""
m = argrelextrema(y, np.less)[0].tolist()
# Find the indx of the absolute minimum (should also be included, is not for example when it is at the edge)
index = np.argmin(y)
if index not in m: m.append(index)
x_minima = [x[i] for i in m]
y_minima = [y[i] for i in m]
return x_minima, y_minima
# -----------------------------------------------------------------
def detect_peaks(hist, count=2):
hist_copy = hist
peaks = len(argrelextrema(hist_copy, np.greater, mode="wrap")[0])
sigma = log1p(peaks)
print(peaks, sigma)
while (peaks > count):
new_hist = gaussian_filter(hist_copy, sigma=sigma)
peaks = len(argrelextrema(new_hist, np.greater, mode="wrap")[0])
if peaks < count:
peaks = count + 1
sigma = sigma * 0.5
continue
hist_copy = new_hist
sigma = log1p(peaks)
print(peaks, sigma)
return argrelextrema(hist_copy, np.greater, mode="wrap")[0]
def plot_kde(data):
bw = 1.06 * st.stdev(data) / (len(data) ** .2)
kde = KernelDensity(kernel='gaussian', bandwidth=bw).fit(
np.array(data).reshape(-1, 1))
s = np.linspace(0, 1)
e = kde.score_samples(s.reshape(-1, 1))
plt.plot(s, e)
mi, ma = argrelextrema(e, np.less)[0], argrelextrema(e, np.greater)[0]
logger.info("Minima: %s" % s[mi])
logger.info("Maxima: %s" % s[ma])
plt.plot(s[:mi[0] + 1], e[:mi[0] + 1], 'r',
s[mi[0]:mi[1] + 1], e[mi[0]:mi[1] + 1], 'g',
s[mi[1]:], e[mi[1]:], 'b',
s[ma], e[ma], 'go',
s[mi], e[mi], 'ro')
plt.xlabel('Probability')
def find_hist_peaks(img, drop_first_max=False):
'''Finds the first two interior peaks in the histogram; usually a good binary
threshold lies halfway between these two peaks.'''
import scipy.signal as sig
array = sitk.GetArrayFromImage(img)
hist = np.histogram(array, 16)
hist_counts = np.array(hist[0])
hist_centers = np.array(hist[1])
peaks = sig.argrelextrema(hist_counts, np.greater)[0]
if hist_counts[peaks[0]] < (0.01 * (hist_counts[peaks].mean())): # Don't allow a "noise" peak at the beginning.
peaks = peaks[1:]
if len(peaks) < 2: # Only one peak is found if the other peak is really at the edge.
peaks = np.array([0, peaks[0]])
elif hist_counts[0] > hist_counts[peaks[0]]:
if not drop_first_max:
peaks = np.array([0, peaks[0]])
elif drop_first_max:
peaks = np.array([peaks[1], peaks[2]])
i_L = hist_centers[peaks[0]]
i_FM = hist_centers[peaks[1]]
return i_L, i_FM
def spikes(data, start_sample, threshs, pad_len, order):
for col_i in range(data.shape[1]):
column = data[:, col_i]
rel_extremes, = argrelextrema(
column,
lambda x, y: thres_extrema(x, y, threshs[col_i]),
order=order)
mask = (rel_extremes >= pad_len) & (
rel_extremes < data.shape[0] - pad_len)
extreme_samples = rel_extremes[mask] + start_sample - pad_len
yield from [(col_i, sample) for sample in extreme_samples]
def test_thres_extrema():
rs, = argrelextrema(data1[:, 0], lambda x, y: thres_extrema(x, y, 0.1))
assert len(rs) == 1
assert rs == 1
def _significant_periods(periods, pgram):
# Order ascending
periods = periods[::-1]
pgram = pgram[::-1]
# Scale and extract significant
pgram = (pgram - pgram.min()) / pgram.ptp()
significant = argrelextrema(pgram, np.greater, order=5)
return periods[significant], pgram[significant]
def _significant_acf(corr, has_confint):
if has_confint:
corr, confint = corr
periods = argrelextrema(np.abs(corr), np.greater, order=3)[0]
corr = corr[periods]
if has_confint:
confint = confint[periods]
result = np.column_stack((periods, corr))
if has_confint:
result = (result, np.column_stack((periods, confint)))
return result
def find_max_min(prices):
prices_ = prices.copy()
prices_.index = linspace(1., len(prices_), len(prices_))
#kr = KernelReg([prices_.values], [prices_.index.values], var_type='c', bw=[1.8, 1])
kr = KernelReg([prices_.values], [prices_.index.values], var_type='c', bw=[2]) # ????????????? ?
# Either a user-specified bandwidth or the method for bandwidth selection.
# If a string, valid values are ‘cv_ls’ (least-squares cross-validation) and ‘aic’ (AIC Hurvich bandwidth estimation).
# Default is ‘cv_ls’.
f = kr.fit([prices_.index.values])
smooth_prices = pd.Series(data=f[0], index=prices.index)
local_max = argrelextrema(smooth_prices.values, np.greater)[0]
local_min = argrelextrema(smooth_prices.values, np.less)[0]
price_local_max_dt = []
for i in local_max:
if (i > 1) and (i < len(prices) - 1):
price_local_max_dt.append(prices.iloc[i - 2:i + 2].argmax())
price_local_min_dt = []
for i in local_min:
if (i > 1) and (i < len(prices) - 1):
price_local_min_dt.append(prices.iloc[i - 2:i + 2].argmin())
prices.name = 'price'
maxima = pd.DataFrame(prices.loc[price_local_max_dt])
minima = pd.DataFrame(prices.loc[price_local_min_dt])
max_min = pd.concat([maxima, minima]).sort_index()
max_min.index.name = 'date'
max_min = max_min.reset_index()
max_min = max_min[~max_min.date.duplicated()]
p = prices.reset_index()
max_min['day_num'] = p[p['index'].isin(max_min.date)].index.values
max_min = max_min.set_index('day_num').price
return max_min
def find_pred_onsets(scores, window):
if window.shape[0] > 0:
onset_function = np.convolve(scores, window, mode='same')
else:
onset_function = scores
# see page 592 of "Universal onset detection with bidirectional long short-term memory neural networks"
maxima = argrelextrema(onset_function, np.greater_equal, order=1)[0]
return set(list(maxima))
def find_pred_onsets(scores, window):
if window.shape[0] > 0:
onset_function = np.convolve(scores, window, mode='same')
else:
onset_function = scores
# see page 592 of "Universal onset detection with bidirectional long short-term memory neural networks"
maxima = argrelextrema(onset_function, np.greater_equal, order=1)[0]
return set(list(maxima))
def idxsOfRelativeExtrema(x, maxima=True, allowEq=False, axis=0):
"""
>>> idxsOfRelativeExtrema([2,1,5])
array([0, 2])
>>> idxsOfRelativeExtrema([2,1])
array([0])
>>> idxsOfRelativeExtrema([1,2])
array([1])
>>> idxsOfRelativeExtrema([2,1,5], maxima=False)
array([1])
>>> idxsOfRelativeExtrema([1,1,1], allowEq=False)
array([], dtype=int64)
>>> idxsOfRelativeExtrema([0,1,1,1,0], allowEq=False)
array([], dtype=int64)
>>> idxsOfRelativeExtrema([1,1,1], allowEq=True)
array([0, 1, 2])
"""
if len(x) == 0:
return np.empty(1) # []
if len(x) == 1:
return np.zeros(1) # [0]
x = np.asarray(x)
pad = -np.inf if maxima else np.inf
if maxima:
if allowEq:
func = np.greater_equal
else:
func = np.greater
else:
if allowEq:
func = np.less_equal
else:
func = np.less
if len(x.shape) == 1:
x = np.r_[x, pad] # combine with wrap to check endpoints
return signal.argrelextrema(x, func, mode='wrap')[0]
elif axis == 0:
pad = np.zeros((1, x.shape[1])) + pad
x = np.vstack((x, pad))
return signal.argrelextrema(x, func, mode='wrap', axis=axis)
elif axis == 1:
pad = np.zeros((x.shape[0], 1)) + pad
x = np.hstack((x, pad))
return signal.argrelextrema(x, func, mode='wrap', axis=axis)
else:
raise NotImplementedError("only supports axis={0, 1}!")