本文整理汇总了Python中scipy.signal.argrelmax方法的典型用法代码示例。如果您正苦于以下问题:Python signal.argrelmax方法的具体用法?Python signal.argrelmax怎么用?Python signal.argrelmax使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类scipy.signal
的用法示例。
在下文中一共展示了signal.argrelmax方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: call_peaks
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import argrelmax [as 别名]
def call_peaks(sigvals, min_signal = 0, sep = 120, boundary = None, order =1):
"""Greedy algorithm for peak calling-- first call all local maxima,
then call greatest maxima as a peak, then next greatest that isn't within
'sep' distance of that peak, and so on"""
if sum(np.isnan(sigvals))>0:
if sum(np.isnan(sigvals))==len(sigvals):
return np.array([])
else:
replace = min(sigvals[~np.isnan(sigvals)])
sigvals[np.isnan(sigvals)]=replace
if boundary is None:
boundary = sep/2
random = np.random.RandomState(seed = 25)
l = len(sigvals)
peaks = signal.argrelmax(sigvals *(1+
random.uniform(0,10**-12,l)),order=order)[0]
peaks = peaks[sigvals[peaks] >= min_signal ]
peaks = peaks[ peaks >= boundary ]
peaks = peaks[ peaks < (l - boundary)]
sig = sigvals[peaks]
return reduce_peaks(peaks, sig, sep)
示例2: validate_ppg_single_waveform
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import argrelmax [as 别名]
def validate_ppg_single_waveform(single_waveform, sample_rate=PPG_SAMPLE_RATE):
period = float(len(single_waveform)) / float(sample_rate)
if period < MINIMUM_PULSE_CYCLE or period > MAXIMUM_PULSE_CYCLE:
return False
max_index = np.argmax(single_waveform)
if float(max_index) / float(len(single_waveform)) >= 0.5:
return False
if len(argrelmax(np.array(single_waveform))[0]) < 2:
return False
min_index = np.argmin(single_waveform)
if not (min_index == 0 or min_index == len(single_waveform) - 1):
return False
diff = np.diff(single_waveform[:max_index+1], n=1)
if min(diff) < 0:
return False
if abs(single_waveform[0] - single_waveform[-1]) / (single_waveform[max_index] - single_waveform[min_index]) > 0.1:
return False
return True
示例3: estimateTargetTDOAIndexesFromAngularSpectrum
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import argrelmax [as 别名]
def estimateTargetTDOAIndexesFromAngularSpectrum(angularSpectrum, microphoneSeparationInMetres, numTDOAs, numSources):
peakIndexes = argrelmax(angularSpectrum)[0]
tdoasInSeconds = getTDOAsInSeconds(microphoneSeparationInMetres, numTDOAs)
if numSources:
logging.info('numSources provided, taking first %d peaks' % numSources )
sourcePeakIndexes = peakIndexes[ argsort(angularSpectrum[peakIndexes])[-numSources:] ]
if len(sourcePeakIndexes) != numSources:
logging.info('didn''t find enough peaks in ITDFunctions.estimateTargetTDOAIndexesFromAngularSpectrum... aborting' )
os._exit(1)
else:
kMeans = KMeans(n_clusters=2, n_init=10)
kMeans.fit(angularSpectrum[peakIndexes][:, newaxis])
sourcesClusterIndex = argmax(kMeans.cluster_centers_)
sourcePeakIndexes = peakIndexes[where(kMeans.labels_ == sourcesClusterIndex)].astype('int32')
logging.info('numSources not provided, found %d sources' % len(sourcePeakIndexes) )
# return sources ordered left to right
sourcePeakIndexes = sorted(sourcePeakIndexes)
logging.info( 'Found target TDOAs: %s' % str(sourcePeakIndexes) )
return sourcePeakIndexes
示例4: estimate_actions
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import argrelmax [as 别名]
def estimate_actions(self, episode_data):
"""
Estimates hold/buy/sell signals based on local peaks filtered by time horizon and signal amplitude.
Args:
episode_data: 1D np.array of unscaled [but possibly resampled] price values in OHL[CV] format
Returns:
1D vector of signals of same length as episode_data
"""
# Find local maxima and minima indices within time horizon:
max_ind = signal.argrelmax(episode_data, order=self.time_threshold)
min_ind = signal.argrelmin(episode_data, order=self.time_threshold)
indices = np.append(max_ind, min_ind)
# Append first and last points:
indices = np.append(indices, [0, episode_data.shape[0] - 1])
indices = np.sort(indices)
indices_and_values = []
for i in indices:
indices_and_values.append([episode_data[i], i])
# Filter by value:
indices_and_values = self.filter_by_margine(indices_and_values, self.value_threshold)
#print('filtered_indices_and_values:', indices_and_values)
# Estimate advised actions (no 'close' btw):
# Assume all 'hold':
advice = np.ones(episode_data.shape[0], dtype=np.uint32) * self.action_space[0]
for num, (v, i) in enumerate(indices_and_values[:-1]):
if v < indices_and_values[num + 1][0]:
advice[i] = self.action_space[1]
else:
advice[i] = self.action_space[2]
return advice
示例5: get_landing_burn
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import argrelmax [as 别名]
def get_landing_burn(data):
max_q_landing_index = data['q'].index(max(data['q']))
post_q_data = data_between(data, start=max_q_landing_index)
minpoint = signal.argrelmax(np.array(post_q_data['acceleration']))[0][0]
return minpoint + max_q_landing_index, np.argmax(np.array(data['velocity']) < 5)
示例6: find_extrema
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import argrelmax [as 别名]
def find_extrema(signal):
signal = np.array(signal)
extrema_index = np.sort(np.unique(np.concatenate((argrelmax(signal)[0], argrelmin(signal)[0]))))
extrema = signal[extrema_index]
return zip(extrema_index.tolist(), extrema.tolist())
示例7: get_peaks
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import argrelmax [as 别名]
def get_peaks(rx):
peaks = signal.argrelmax(rx, order=10000)[0]
peak_diffs = np.diff(peaks)
if np.isfinite(peak_diffs):
print("avg peak distance:", peak_diffs.mean())
print("max peak distance:", peak_diffs.max())
print("min peak distance:", peak_diffs.min())
L = peak_diffs.min()
else:
L = None
return peaks, L
示例8: find_angle_hog
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import argrelmax [as 别名]
def find_angle_hog(image, centermass, px, py, angle_range=10):
"""Finds the angle of an image based on the method described by Sun, “Symmetry Detection Using Gradient Information.”
Pattern Recognition Letters 16, no. 9 (September 1, 1995): 987–96, and improved by N. Pinon
inputs :
- image : 2D numpy array to find symmetry axis on
- centermass: tuple of floats indicating the center of mass of the image
- px, py, dimensions of the pixels in the x and y direction
- angle_range : float or None, in deg, the angle will be search in the range [-angle_range, angle_range], if None angle angle might be returned
outputs :
- angle_found : float, angle found by the method
- conf_score : confidence score of the method (Actually a WIP, did not provide sufficient results to be used)
"""
# param that can actually be tweeked to influence method performance :
sigma = 10 # influence how far away pixels will vote for the orientation, if high far away pixels vote will count more, if low only closest pixels will participate
nb_bin = 360 # number of angle bins for the histogram, can be more or less than 360, if high, a higher precision might be achieved but there is the risk of
kmedian_size = 5
# Normalization of sigma relative to pixdim :
sigmax = sigma / px
sigmay = sigma / py
if nb_bin % 2 != 0: # necessary to have even number of bins
nb_bin = nb_bin - 1
if angle_range is None:
angle_range = 90
# Constructing mask based on center of mass that will influence the weighting of the orientation histogram
nx, ny = image.shape
xx, yy = np.mgrid[:nx, :ny]
seg_weighted_mask = np.exp(
-(((xx - centermass[0]) ** 2) / (2 * (sigmax ** 2)) + ((yy - centermass[1]) ** 2) / (2 * (sigmay ** 2))))
# Acquiring the orientation histogram :
grad_orient_histo = gradient_orientation_histogram(image, nb_bin=nb_bin, seg_weighted_mask=seg_weighted_mask)
# Bins of the histogram :
repr_hist = np.linspace(-(np.pi - 2 * np.pi / nb_bin), (np.pi - 2 * np.pi / nb_bin), nb_bin - 1)
# Smoothing of the histogram, necessary to avoid digitization effects that will favor angles 0, 45, 90, -45, -90:
grad_orient_histo_smooth = circular_filter_1d(grad_orient_histo, kmedian_size, kernel='median') # fft than square than ifft to calculate convolution
# Computing the circular autoconvolution of the histogram to obtain the axis of symmetry of the histogram :
grad_orient_histo_conv = circular_conv(grad_orient_histo_smooth, grad_orient_histo_smooth)
# Restraining angle search to the angle range :
index_restrain = int(np.ceil(np.true_divide(angle_range, 180) * nb_bin))
center = (nb_bin - 1) // 2
grad_orient_histo_conv_restrained = grad_orient_histo_conv[center - index_restrain + 1:center + index_restrain + 1]
# Finding the symmetry axis by searching for the maximum in the autoconvolution of the histogram :
index_angle_found = np.argmax(grad_orient_histo_conv_restrained) + (nb_bin // 2 - index_restrain)
angle_found = repr_hist[index_angle_found] / 2
angle_found_score = np.amax(grad_orient_histo_conv_restrained)
# Finding other maxima to compute confidence score
arg_maxs = argrelmax(grad_orient_histo_conv_restrained, order=kmedian_size, mode='wrap')[0]
# Confidence score is the ratio of the 2 first maxima :
if len(arg_maxs) > 1:
conf_score = angle_found_score / grad_orient_histo_conv_restrained[arg_maxs[1]]
else:
conf_score = angle_found_score / np.mean(grad_orient_histo_conv) # if no other maxima in the region ratio of the maximum to the mean
return angle_found, conf_score
示例9: _getDotDistance
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import argrelmax [as 别名]
def _getDotDistance(self, dots, axis):
""" calculates dot distance from dist. between all neighbouring dots
"""
# create distance matrix distM of dots
z = np.array([complex(d[0],d[1]) for d in dots])
#z = dots[:,axis] # TODO: test, ob alles auch hiermit funktionieren würde
try:
distM = abs(z[..., np.newaxis] - z)
except MemoryError:
self._raise(TooManyDotsException,self.ydPerInch)
del z
distM[distM==0] = np.max(distM)+1
neighbours = np.argmin(distM, axis=0)
#distances = distM.flat
#distances = [abs(dots[i,axis]-dots[j,axis]) for i,j in enumerate(neighbours) if dots[i,axis]!=dots[j,axis]]
distances = np.abs(dots[:,axis]-dots[neighbours,axis])
distances = distances[distances>0]
f = np.bincount(np.array(distances,dtype=np.uint16))
#print(f[:15])
#return np.argmax(f)
self._print(3,"\n%s\n"%f[:30])
maxima = np.array(argrelmax(f.argsort().argsort())[0])
#maxima = [m for m in maxima if np.argmax(f)%m==0]
MIN_DOT_DISTANCE = 0.01 # inches
minDist = int(MIN_DOT_DISTANCE*self.imgDpi)
if len(f[minDist:]) == 0:
self._raise(YDExtractingException,"Dot distances below minimum")
maximum = np.argmax(f[minDist:])+minDist
distance = maximum/2 if maximum/2.0 in maxima and float(maximum)/self.imgDpi==0.04 else maximum # because of Ricoh's marking dot
"""
maxima_vals = f[maxima]
threshold = np.percentile(f,93) #TODO schreiben TODO: oder percentile(f,...)?
maxima = maxima[maxima_vals>threshold]
maxima = [x for x in maxima if x<2 or x>len(f)-1-2 or not(f[x-2]<f[x] and f[x+2]>f[x] or f[x-2]>f[x] and f[x+2]<f[x])] #exclude hills on the way to maximum #TODO: schreiben removed
# a=f[x-2]-f[x]; b=f[x+2]-f[x]; a<0 and b>0 or a>0 and b<0 gdw a*b<0
# pitch1 =
distance = maxima[1]
"""
return distance
"""
# calculate dmin from distribution of $distances
# distances for each dot to its closest one
distances = np.min(distM, axis=0)
del distM
#div=100.0 #FIXME: depends on scaling? (hier: float2int)
div = 1
distances = np.array((distances*div).round(),dtype=np.int32)
count = np.bincount(distances)
maxima = argrelmax(count.argsort().argsort())[0]
minima = argrelmin(count.argsort().argsort())[0]
#dMin = minima[0]
MIN_DOT_DISTANCE = 4/300.0 # inches # TODO: automatic detection of dublicate dots instead
minDist = int(MIN_DOT_DISTANCE*self.imgDpi*div)
import ipdb;ipdb.set_trace()
distance = (np.argmax(count[minDist:])+minDist)/div
return distance
return maxima[1]
"""
示例10: _seg
# 需要导入模块: from scipy import signal [as 别名]
# 或者: from scipy.signal import argrelmax [as 别名]
def _seg(self, n_bkps=None, pen=None, epsilon=None):
"""Sequential peak search.
The stopping rule depends on the parameter passed to the function.
Args:
n_bkps (int): number of breakpoints to find before stopping.
penalty (float): penalty value (>0)
epsilon (float): reconstruction budget (>0)
Returns:
list: breakpoint index list
"""
# initialization
bkps = [self.n_samples]
stop = False
error = self.cost.sum_of_costs(bkps)
# peak search
# forcing order to be above one in case jump is too large (issue #16)
order = max(max(self.width, 2*self.min_size) // (2 * self.jump), 1)
peak_inds_shifted, = argrelmax(self.score,
order=order,
mode="wrap")
if peak_inds_shifted.size == 0: # no peaks if the score is constant
return bkps
gains = np.take(self.score, peak_inds_shifted)
peak_inds_arr = np.take(self.inds, peak_inds_shifted)
# sort according to score value
_, peak_inds = unzip(sorted(zip(gains, peak_inds_arr)))
peak_inds = list(peak_inds)
while not stop:
stop = True
# _, bkp = max((v, k) for k, v in enumerate(self.score, start=1)
# if not any(abs(k - b) < self.width // 2 for b in bkps[:-1]))
try:
# index with maximum score
bkp = peak_inds.pop()
except IndexError: # peak_inds is empty
break
if n_bkps is not None:
if len(bkps) - 1 < n_bkps:
stop = False
elif pen is not None:
gain = error - self.cost.sum_of_costs(sorted([bkp] + bkps))
if gain > pen:
stop = False
elif epsilon is not None:
if error > epsilon:
stop = False
if not stop:
bkps.append(bkp)
bkps.sort()
error = self.cost.sum_of_costs(bkps)
return bkps