本文整理汇总了Python中scipy.signal.argrelmax函数的典型用法代码示例。如果您正苦于以下问题:Python argrelmax函数的具体用法?Python argrelmax怎么用?Python argrelmax使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了argrelmax函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: timebetweenpeaks
def timebetweenpeaks(dataMatrix, Sensor,Min = False,order=10):
timedifference = []
if Min==False:
for Sensors in Sensor:
peaks = (argrelmax(dataMatrix[:,Sensors],order=order))
distance = []
for p in range(0,len(peaks[0])-1):
distance.append((peaks[0][p+1]-peaks[0][p]))
number=0
for d in distance:
number +=d
timedifference.append((number/len(distance)))
else:
for Sensors in Sensor:
peaks = (argrelmax(dataMatrix[:,Sensors],order=order))
distance = []
for p in range(0,len(peaks[0])-1):
distance.append((peaks[0][p+1]-peaks[0][p]))
number=0
for d in distance:
number +=d
timedifference.append((number/len(distance)))
return timedifference
示例2: detect_jumps
def detect_jumps(self):
wle = int(self.regressor_t/self.pitch_t_hop)
isel = self.mag > np.max(self.mag)*self.mag_threshold
tsel = self.t[isel]
fsel = self.f0[isel]
self.isel = isel
#pl.plot(np.flatnonzero(isel),20*np.log10(m[isel]))
le = linreg2_err(tsel, fsel, wleft=wle, wright=wle, use_l=True)
#ax[0].plot(tsel,fsel)
#ax[1].plot(tsel,le)
imax = argrelmax(le)[0]
lemax = le[imax]
idx = imax[lemax > self.t_threshold]
ijup = idx
#ax[0].plot(tsel[idx],fsel[idx],'o')
#ax[1].plot(tsel[idx],le[idx],'o')
imin = argrelmax(-le)[0]
lemin = le[imin]
idx = imin[lemin < -self.t_threshold]
ijdn = idx
#ax[0].plot(tsel[idx],fsel[idx],'o')
#ax[1].plot(tsel[idx],le[idx],'o')
self.down_jump_indices = np.asarray(ijdn)
self.up_jump_indices = np.asarray(ijup)
self.down_jump_times = tsel[ijdn]
self.up_jump_times = tsel[ijup]
示例3: on_change2
def on_change2(pt):
#maxi=sp.argrelmax(normList)[0]
#pt=maxi[pt]
fig=plt.figure(figsize=(20,10))
gs = gridspec.GridSpec(2, 2)
ax1 = plt.subplot(gs[:, 0])
ax2 = plt.subplot(gs[0,1])
ax3 = plt.subplot(gs[1,1])
#ax=plt.subplot(1,2,1)
ax1.plot(f,normList)
ax1.plot(f[pt],normList[pt],'ko')
#ax1.text(f[pt],normList[pt],str(f[pt])+ 'Hz')
string='f={:.3f} Hz\nMode={:.0f}'.format(f[pt],pt)
ax1.text(0.05, 0.95, string, transform=ax1.transAxes, fontsize=14,
verticalalignment='top')
ax1.set_xscale('log')
ax1.set_yscale('log')
#ax=plt.subplot(1,2,2)
idxMode=myDMD_Uy.getIdxforFrq(f[pt])
mode=myDMD_Uy.getMode(idxMode)
ax2.imshow(np.real(mode),vmin=vmin,vmax=vmax,interpolation='nearest')
uy=np.array(np.real(mode)[iRow,:])
uy_imag=np.array(np.imag(mode)[iRow,:])
ax3.plot(uy)
ax3.plot(uy_imag,'r')
maxi=sp.argrelmax(uy)[0]
mini=sp.argrelmin(uy)[0]
exti=np.sort(np.r_[maxi,mini])
maxi_imag=sp.argrelmax(uy_imag)[0]
mini_imag=sp.argrelmin(uy_imag)[0]
exti_imag=np.sort(np.r_[maxi_imag,mini_imag])
print np.diff(exti)
ax3.scatter(maxi,uy[maxi],marker=2)
ax3.scatter(mini,uy[mini],marker=3)
ax3.scatter(maxi_imag,uy_imag[maxi_imag],marker=2)
ax3.scatter(mini_imag,uy_imag[mini_imag],marker=3)
ax3.set_xlim([0,np.real(mode).shape[1]])
gamma=0
print 'n=',L/(np.diff(maxi)*dx)+gamma
print 'n=',L/(np.diff(mini)*dx)+gamma
print 'n=',L/(np.diff(exti)*dx*2.0)+gamma
print 'n=',L/(np.diff(maxi_imag)*dx)+gamma
print 'n=',L/(np.diff(mini_imag)*dx)+gamma
print 'n=',L/(np.diff(exti_imag)*dx*2.0)+gamma
示例4: getWinSize
def getWinSize(im, padFactor=4):
h, w = im.shape
im = np.pad(im, ((0, h * (padFactor - 1)), (0, w * (padFactor - 1))), mode='constant')
spec = abs(np.fft.fft2(im))
horizIs = sig.argrelmax(spec[0, :])[0]
vertIs = sig.argrelmax(spec[:, 0])[0]
maxHorizI = max(horizIs, key=lambda i: spec[0, i])
maxVertI = max(vertIs, key=lambda i: spec[i, 0])
return round(float(im.shape[1]) / maxHorizI), round(float(im.shape[0]) / maxVertI)
示例5: locxymax
def locxymax(nda, order=1, mode='clip') :
"""For 2-d or 3-d numpy array finds mask of local maxima in x and y axes (diagonals are ignored)
using scipy.signal.argrelmax and return their product.
@param nda - input ndarray
@param order - range to search for local maxima along each dimension
@param mode - parameter of scipy.signal.argrelmax of how to treat the boarder
"""
shape = nda.shape
size = nda.size
ndim = len(shape)
if ndim< 2 or ndim>3 :
msg = 'ERROR: locxymax nda shape %s should be 2-d or 3-d' % (shape)
sys.exit(msg)
ext_cols = argrelmax(nda, -1, order, mode)
ext_rows = argrelmax(nda, -2, order, mode)
indc = np.array(ext_cols, dtype=np.uint16)
indr = np.array(ext_rows, dtype=np.uint16)
msk_ext_cols = np.zeros(shape, dtype=np.uint16)
msk_ext_rows = np.zeros(shape, dtype=np.uint16)
if ndim == 2 :
icr = indc[0,:]
icc = indc[1,:]
irr = indr[0,:]
irc = indr[1,:]
msk_ext_cols[icr,icc] = 1
msk_ext_rows[irr,irc] = 1
elif ndim == 3 :
ics = indc[0,:]
icr = indc[1,:]
icc = indc[2,:]
irs = indr[0,:]
irr = indr[1,:]
irc = indr[2,:]
msk_ext_cols[ics,icr,icc] = 1
msk_ext_rows[irs,irr,irc] = 1
#print 'nda.size:', nda.size
#print 'indc.shape:', indc.shape
#print 'indr.shape:', indr.shape
return msk_ext_rows * msk_ext_cols
示例6: extr
def extr(x):
"""Extract the indices of the extrema and zero crossings.
:param x: input signal
:type x: array-like
:return: indices of minima, maxima and zero crossings.
:rtype: tuple
"""
m = x.shape[0]
x1 = x[:m - 1]
x2 = x[1:m]
indzer = find(x1 * x2 < 0)
if np.any(x == 0):
iz = find(x == 0)
indz = []
if np.any(np.diff(iz) == 1):
zer = x == 0
dz = np.diff([0, zer, 0])
debz = find(dz == 1)
finz = find(dz == -1) - 1
indz = np.round((debz + finz) / 2)
else:
indz = iz
indzer = np.sort(np.hstack([indzer, indz]))
indmax = argrelmax(x)[0]
indmin = argrelmin(x)[0]
return indmin, indmax, indzer
示例7: get_envelops
def get_envelops(x, t=None):
""" Find the upper and lower envelopes of the array `x`.
"""
if t is None:
t = np.arange(x.shape[0])
maxima = argrelmax(x)[0]
minima = argrelmin(x)[0]
# consider the start and end to be extrema
ext_maxima = np.zeros((maxima.shape[0] + 2,), dtype=int)
ext_maxima[1:-1] = maxima
ext_maxima[0] = 0
ext_maxima[-1] = t.shape[0] - 1
ext_minima = np.zeros((minima.shape[0] + 2,), dtype=int)
ext_minima[1:-1] = minima
ext_minima[0] = 0
ext_minima[-1] = t.shape[0] - 1
tck = interpolate.splrep(t[ext_maxima], x[ext_maxima])
upper = interpolate.splev(t, tck)
tck = interpolate.splrep(t[ext_minima], x[ext_minima])
lower = interpolate.splev(t, tck)
return upper, lower
示例8: decode
def decode(file_name):
border.rotate(file_name)
image = Image.open("temp.png")
q = border.find("temp.png")
ind = sp.argmin(sp.sum(q, 1), 0)
up_left = q[ind, 0] + 2
up_top = q[ind, 1] + 2
d_right = q[ind+1, 0] - 3
d_bottom = q[ind-1, 1] - 3
box = (up_left, up_top, d_right, d_bottom)
region = image.crop(box)
h_sum = sp.sum(region, 0)
m = argrelmax(sp.correlate(h_sum, h_sum, 'same'))
s = sp.average(sp.diff(m))
m = int(round(d_right - up_left)/s)
if m % 3 != 0:
m += 3 - m % 3
n = int(round(d_bottom - up_top)/s)
if n % 4 != 0:
n += 4 - n % 4
s = int(round(s))+1
region = region.resize((s*m, s*n), PIL.Image.ANTIALIAS)
region.save("0.png")
pix = region.load()
matrix = mix.off(rec.matrix(pix, s, m, n))
str2 = hamming.decode(array_to_str(matrix))
return hamming.bin_to_str(str2)
示例9: elliptical_orbit_to_events
def elliptical_orbit_to_events(t, w):
"""
Convert an orbit to MIDI events using Cartesian coordinates and rules.
Parameters
----------
t : array_like
w : array_like
midi_pool : array_like
"""
loop = gd.classify_orbit(w)
# apocenters
x,y,z = w.T[:3]
r = np.sqrt(x**2 + y**2 + z**2)
apo = np.array([argrelmax(rr)[0] for rr in r])
# get periods
periods = []
for i in range(w.shape[1]):
if np.any(loop[i] == 1):
w2 = gd.align_circulation_with_z(w[:,i], loop[i])
R = np.sqrt(w2[:,0]**2 + w2[:,1]**2)
phi = np.arctan2(w2[:,1], w2[:,0]) % (2*np.pi)
z = w2[:,2]
# loop
T1 = gd.peak_to_peak_period(t, R)
T2 = gd.peak_to_peak_period(t, phi)
T3 = gd.peak_to_peak_period(t, z)
else:
# box
T1 = gd.peak_to_peak_period(t, w[:,i,0])
T2 = gd.peak_to_peak_period(t, w[:,i,1])
T3 = gd.peak_to_peak_period(t, w[:,i,2])
periods.append([T1,T2,T3])
freqs = (2*np.pi / np.array(periods)) * 10000.
delays = []
notes = []
for j in range(w.shape[0]):
_no = []
for i in range(w.shape[1]):
if j in apo[i]:
_no.append(freqs[i].tolist())
if len(_no) > 0:
delays.append(t[j])
notes.append(np.unique(_no).tolist())
delays = np.array(delays)
notes = np.array(notes)
return delays, notes
示例10: find_current_peak_position
def find_current_peak_position(self, data):
"""
Finds the current average peak position.
Parameters
----------
data : numpy.ndarray
A phase-corrected datacube.
Returns
-------
peak_position : int
The argument of the highest local maximum.
"""
self.info('Finding current peak position.')
data = data.sum(axis=2)
data = data.sum(axis=1)
data = np.where(data < 0.75 * data.max(), 0, data)
peaks = signal.argrelmax(data, axis=0, order=5)[0]
self.info('Encountered {:d} peaks: '.format(len(peaks)))
peaks_values = data[peaks]
max_peaks_arg = np.argmax(peaks_values)
peak = peaks[max_peaks_arg]
return peak
示例11: apocenter
def apocenter(self, type=np.mean):
"""
Estimate the apocenter(s) of the orbit. By default, this returns
the mean apocenter. To get, e.g., the minimum apocenter,
pass in ``type=np.min``. To get all apocenters, pass in
``type=None``.
Parameters
----------
type : func (optional)
By default, this returns the mean apocenter. To return all
apocenters, pass in ``None``. To get, e.g., the minimum
or maximum apocenter, pass in ``np.min`` or ``np.max``.
Returns
-------
apo : float, :class:`~numpy.ndarray`
Either a single number or an array of apocenters.
"""
r = self.r
max_ix = argrelmax(r, mode='wrap')[0]
max_ix = max_ix[(max_ix != 0) & (max_ix != (len(r)-1))]
if type is not None:
return type(r[max_ix])
else:
return r[max_ix]
示例12: par_find_peaks_by_chan
def par_find_peaks_by_chan(info):
"""
Parameters
----------
p_spect_array: numpy.ndarray
An array with dimensions frequencies x channels
frequencies: numpy.ndarray
An array of the frequencies used
std_thresh: float
Threshold in number of standard deviations above the corrected power spectra to be counted as a peak
Returns
-------
peaks_all_chans: numpy.ndarray with type bool
An array of booleans the same shape as p_spect_array, specifying if there is a peak at a given frequency
and electrode
"""
p_spect_array = info[0]
frequencies = info[1]
std_thresh = info[2]
peaks_all_chans = np.zeros(p_spect_array.shape).astype(bool)
for i, chan_data in enumerate(p_spect_array.T):
x = sm.tools.tools.add_constant(np.log10(frequencies))
model_res = sm.RLM(chan_data, x).fit()
peak_inds = argrelmax(model_res.resid)
peaks = np.zeros(x.shape[0], dtype=bool)
peaks[peak_inds] = True
above_thresh = model_res.resid > (np.std(model_res.resid) * std_thresh)
peaks_all_chans[:,i] = peaks & above_thresh
return peaks_all_chans
示例13: find_peaks
def find_peaks(x, threshold=None, order=1):
"""Finds local maxima of a function.
Args:
x: A data vector.
threshold: Local maxima under this value will be discarded.
If threshold is None, the function will return only the global
maximum.
Defaut value os None.
order: Number of samples before and after a data point that have
to be smaller than the data point to be considered a local maximum.
If 'threshold' is None, this argument has no effect.
Default: 1.
Returns:
out: A list of local maxima, numpy array type.
"""
if threshold is not None:
event_peaks = signal.argrelmax(x, order=int(order))[0]
if event_peaks.size > 0:
return event_peaks[x[event_peaks] > threshold]
return event_peaks
else:
if x.size > 0:
return np.array([np.argmax(x)])
return np.array([])
示例14: _get_psp_list
def _get_psp_list(bins, neuron_model, di_param, timestep, simtime):
'''
Return the list of effective weights from a list of NEST connection
weights.
'''
nest.ResetKernel()
nest.SetKernelStatus({"resolution":timestep})
# create neuron and recorder
neuron = nest.Create(neuron_model, params=di_param)
vm = nest.Create("voltmeter", params={"interval": timestep})
nest.Connect(vm, neuron)
# send the spikes
times = [ timestep+n*simtime for n in range(len(bins)) ]
sg = nest.Create("spike_generator", params={'spike_times':times,
'spike_weights':bins})
nest.Connect(sg, neuron)
nest.Simulate((len(bins)+1)*simtime)
# get the max and its time
dvm = nest.GetStatus(vm)[0]
da_voltage = dvm["events"]["V_m"]
da_times = dvm["events"]["times"]
da_max_psp = da_voltage[ argrelmax(da_voltage) ]
da_min_psp = da_voltage[ argrelmin(da_voltage) ]
da_max_psp -= da_min_psp
if len(bins) != len(da_max_psp):
raise InvalidArgument("simtime too short: all PSP maxima are not in \
range")
else:
plt.plot(da_times, da_voltage)
plt.show()
return da_max_psp
示例15: get_peaks
def get_peaks(freq, spectrum, threshold, outdir, metadata):
"""
This gets the frequency of the peaks of a signal.
"""
# Smooth the data by using repeated mean smoothing.
radius = 2
for i in range(3):
smooth_spec, _ = mean_smooth(spectrum, radius)
freq = freq[radius:-radius+1]
spectrum = spectrum[radius:-radius+1]
# Get the peaks from the smoothed spectum.
prad = 4
peak_index = sig.argrelmax(smooth_spec, order=prad)[0]
# Remove "peaks" that are only noise fluctuations.
peaks = []
for i in peak_index:
lower = max(i - prad, 0)
upper = min(i + prad + 1, len(smooth_spec))
segment = smooth_spec[lower:upper] - smooth_spec[i]
if abs(np.min(segment)) > threshold:
peaks.append(i)
# Frequencies and the spectra.
freq_peaks = np.array([freq[i] for i in peaks])
spec_peaks = np.array([spectrum[i] for i in peaks])
# Create a plot.
plt.plot(freq, spectrum, 'k')
plt.plot(freq, smooth_spec, 'r')
plt.plot(freq_peaks, spec_peaks, 'bo')
plot_tools(metadata, outdir, 'peak_find')
return freq_peaks