当前位置: 首页>>代码示例>>Python>>正文


Python signal.argrelextrema函数代码示例

本文整理汇总了Python中scipy.signal.argrelextrema函数的典型用法代码示例。如果您正苦于以下问题:Python argrelextrema函数的具体用法?Python argrelextrema怎么用?Python argrelextrema使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了argrelextrema函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: findBump

def findBump(twoder):
	mins = argrelextrema(twoder[20:70], np.less, order = 5)[0]
	maxes = argrelextrema(twoder[10:65], np.greater, order = 5)[0]
	
	max2der = max(abs(twoder))
	realmins = []
	realmaxes = []
	thresh = 0.00
	for i in range(len(mins)):
		ind = mins[i] + 20
		if twoder[min(len(twoder)-1,ind+6)] - twoder[ind] > thresh*max2der and twoder[ind-6] - twoder[ind] > thresh*max2der:
			realmins.append(ind)
	if twoder[-1] < 0 and twoder[-3] < 0:
		realmins.append(len(twoder)-1)
	for i in range(len(maxes)):
		ind = maxes[i] + 10
		if twoder[ind] - twoder[min(len(twoder)-1,ind+6)] > thresh*max2der and twoder[ind] - twoder[ind-6] > thresh*max2der:
			realmaxes.append(ind)
	
	if len(realmaxes) <= 1:
		return -1
	startLoc = -1
	for i in range(len(realmins)):
		if realmins[-i-1] < realmaxes[1]:
			startLoc = (realmins[-i-1] + realmaxes[1])/2
			break
	midLoc = -1
	for i in range(len(realmins)):
		if realmins[i] > realmaxes[1]:
			midLoc = (realmins[i] + realmaxes[1])/2
			break
	return [startLoc, midLoc]
开发者ID:arajagopalchromacode,项目名称:tp2_release_20160705,代码行数:32,代码来源:release_ccode_analyze_20160701.py

示例2: localMinMax

    def localMinMax(self, y, box_pts=None):

        #  detect local minima and maxima using the smoothed curve

        self.resetLocalMinMax()

        leny = len(y)
        # smooth the signal
        # print box_pts,len(y)
        if box_pts is None:             # detail segmentation box
            n = int(leny/10)
            box_pts = 3 if n<3 else n
        if leny>52 and box_pts>=leny:   # segment > 0.3s but box is too large
            n = int(leny/5)
            box_pts = n
        if box_pts < leny:
            self.ySmooth = uf.smooth(y, box_pts)
        half_box_pts = np.ceil(box_pts/2.0)

        if len(self.ySmooth):
            # for local maxima
            self.maximaInd = argrelextrema(self.ySmooth, np.greater)
            # remove the boundary effect of convolve
            self.maximaInd = [mi for mi in self.maximaInd[0] if (mi>half_box_pts and mi<leny-half_box_pts)]

            # for local minima
            self.minimaInd = argrelextrema(self.ySmooth, np.less)
            # remove the boundary effect of convolve
            self.minimaInd = [mi for mi in self.minimaInd[0] if (mi>half_box_pts and mi<leny-half_box_pts)]

        return box_pts
开发者ID:MTG,项目名称:smc-2016,代码行数:31,代码来源:noteClass.py

示例3: extract

    def extract(self, spikes, sample_rate):
        channels_data = spikes
        number_of_channels = len(channels_data)
        number_of_points_in_channel = len(channels_data[0])
        lower_boundary = 0
        upper_boundary = int(number_of_points_in_channel / 2) - 1

        lmda = int(upper_boundary * 1.5)
        dt = 1.0 / sample_rate
        step_tau = int((upper_boundary - lower_boundary) / 50)  ## was constant 1000 ## ensure that integer
        number_of_iterations = len(np.r_[lower_boundary:upper_boundary:step_tau])  ##(upper_boundary-lower_boundary)/step_tau

        # TODO: From the auditory nerve activity compute the autocorrelation of each nerve activity
        iteration = np.zeros(number_of_iterations)
        for i in range(number_of_iterations):
            for j in range(number_of_channels):
                # TODO: Sum these autocorrelation across nerves to construct the summary autocorrelation
                iteration[i] += self.integration(lower_boundary, upper_boundary, sample_rate, dt, channels_data, j, i * step_tau, lmda)
        iteration = iteration / iteration[0]  ##normalization

        # TODO: Extract the argument of the first non-zero peak in the autocorrelation
        peak_tau = step_tau * argrelextrema(iteration, np.greater)[0][iteration[argrelextrema(iteration, np.greater)[0]].argmax()]

        # TODO: Pitch matching maybe?

        # TODO: Return pitch estimate
        return 1.0 / (peak_tau * dt)
开发者ID:flschaefer,项目名称:aacimp15-pitch-perception,代码行数:27,代码来源:temporal_pitch_extractor.py

示例4: most_like_imf

def most_like_imf(data, imf, imf_index1, imf_index2): 


    residual_short_sample_width, residual_short_std, short_distance = most_like_gaussian(data,imf,imf_index1)
    print "short sample width %s"%residual_short_sample_width
    print "short std %s"%residual_short_std
    residual_long_sample_width, residual_long_std, long_distance = most_like_gaussian(data,imf,imf_index2)
    i = 1
    while residual_short_sample_width == residual_long_sample_width:# and residual_short_factor == residual_long_factor:
        residual_long_sample_width, residual_long_std, _ = most_like_gaussian(data,imf,imf_index2,i)
        print "long sample width %s"%residual_long_sample_width
        print "long std %s"%residual_long_std
        i += 1
    

    print "long sample width %s"%residual_long_sample_width
    print "long std %s"%residual_long_std

    confidence = 0
    if (short_distance/np.mean(data[-20:]))<0.01 and (long_distance/np.mean(data[-20:]))<0.01:
        confidence = 1
    long_period = gaussian_smooth(data, residual_long_sample_width, residual_long_std)
    short_period = gaussian_smooth(data, residual_short_sample_width, residual_short_std)
 
    diff = [short_period[i]-long_period[i] for i in range(len(long_period))]
    #diff = gaussian_smooth(diff, 21, 4)
    
    data = np.array(diff)
    max_index = list(argrelextrema(data,np.greater)[0])
    min_index = list(argrelextrema(data,np.less)[0])

    return max_index, min_index, residual_long_sample_width, residual_short_sample_width, diff, confidence
开发者ID:fndjjx,项目名称:emd,代码行数:32,代码来源:calc_gaussian_imf.py

示例5: calc_para

def calc_para(list1,list2):
    

    list1_max_index = list(argrelextrema(np.array(list1),np.greater)[0])
    list1_min_index = list(argrelextrema(np.array(list1),np.less)[0])

    list2_max_index = list(argrelextrema(np.array(list2),np.greater)[0])
    list2_min_index = list(argrelextrema(np.array(list2),np.less)[0])

    error=10000

#######
#    if list1_max_index!=[] and list2_max_index!=[]:
#        error = abs(abs(list1[0]-list2[0])/list2[0])+abs(abs(list1[-1]-list2[-1])/list2[-1])+abs(abs(list1[list1_max_index[0]]-list2[list2_max_index[0]])/list2[list2_max_index[0]])+abs(1-list1_max_index[0]/list2_max_index[0])+abs(1-(len(list1)-list1_max_index[0])/(len(list2)-list2_max_index[0]))
#    if list1_min_index!=[] and list2_min_index!=[]:
#        error = abs(abs(list1[0]-list2[0])/list2[0])+abs(abs(list1[-1]-list2[-1])/list2[-1])+abs(abs(list1[list1_min_index[0]]-list2[list2_min_index[0]])/list2[list2_min_index[0]])+abs(1-list1_min_index[0]/list2_min_index[0])+abs(1-(len(list1)-list1_min_index[0])/(len(list2)-list2_min_index[0]))
        #error = abs(list1[0]-list2[0])+abs(list1[-1]-list2[-1])+abs(list1[list1_min_index[0]]-list2[list2_min_index[0]])
#######
    if list1_max_index!=[] and list2_max_index!=[]:
#        list1 = [i/abs(list1[list1_max_index[0]]-list1[0]) for i in list1]
#        list2 = [i/abs(list2[list2_max_index[0]]-list2[0]) for i in list2]
    #    error = abs((list2[0]/list1[0])-1)+abs((list2_max_index[0]/list1_max_index[0])-1)+abs((len(list2)-list2_max_index[0])/(len(list1)-list1_max_index[0])-1)
        #error = abs((list2[0]-list1[0])/list2[0])+abs((list2_max_index[0]-list1_max_index[0])/list2_max_index[0])+abs(((len(list2)-list2_max_index[0])-(len(list1)-list1_max_index[0]))/(len(list2)-list2_max_index[0]))+abs((list1[list1_max_index[0]]-list2[list2_max_index[0]])/list1[list1_max_index[0]])+abs((list2[-1]-list1[-1])/list2[-1])
        error = abs((list2[0]-list1[0])/min(list2[0],list1[0]))+abs((list2_max_index[0]-list1_max_index[0])/min(list2_max_index[0],list1_max_index[0]))+abs(((len(list2)-list2_max_index[0])-(len(list1)-list1_max_index[0]))/min((len(list2)-list2_max_index[0]),(len(list1)-list1_max_index[0])))+abs((list1[list1_max_index[0]]-list2[list2_max_index[0]])/min(list1[list1_max_index[0]],list2[list2_max_index[0]]))+abs((list2[-1]-list1[-1])/min(list1[-1],list2[-1]))+abs((len(list1)-len(list2))/min(len(list1),len(list2)))
    if list1_min_index!=[] and list2_min_index!=[]:
#        list1 = [i/abs(list1[list1_min_index[0]]-list1[0]) for i in list1]
#        list2 = [i/abs(list2[list2_min_index[0]]-list2[0]) for i in list2]
    #    error = abs((list2[0]/list1[0])-1)+abs((list2_min_index[0]/list1_min_index[0])-1)+abs((len(list2)-list2_min_index[0])/(len(list1)-list1_min_index[0])-1)
        #error = abs((list2[0]-list1[0])/list2[0])+abs((list2_min_index[0]-list1_min_index[0])/list2_min_index[0])+abs(((len(list2)-list2_min_index[0])-(len(list1)-list1_min_index[0]))/(len(list2)-list2_min_index[0]))+abs((list1[list1_min_index[0]]-list2[list2_min_index[0]])/list1[list1_min_index[0]])+abs((list2[-1]-list1[-1])/list2[-1])
        error = abs((list2[0]-list1[0])/min(list2[0],list1[0]))+abs((list2_min_index[0]-list1_min_index[0])/min(list2_min_index[0],list1_min_index[0]))+abs(((len(list2)-list2_min_index[0])-(len(list1)-list1_min_index[0]))/min((len(list2)-list2_min_index[0]),(len(list1)-list1_min_index[0])))+abs((list1[list1_min_index[0]]-list2[list2_min_index[0]])/min(list1[list1_min_index[0]],list2[list2_min_index[0]]))+abs((list2[-1]-list1[-1])/min(list1[-1],list2[-1]))+abs((len(list1)-len(list2))/min(len(list1),len(list2)))
    return error
开发者ID:fndjjx,项目名称:emd,代码行数:31,代码来源:calc_match.py

示例6: simplify3

def simplify3(nk):
	result=[]
	nk=np.array(nk)
	xk = nk/float(np.sum(nk))
	#print nk
	
	#X_plot = np.linspace(0, len(nk), 1000)[:, np.newaxis]
	sdiv=1000
	X_plot = np.linspace(0, len(xk), sdiv)[:, np.newaxis]
	custm = stats.rv_discrete(name='custm',a=0,b=7, values=(range(len(xk)), xk))
	yk= custm.rvs(size=100000)
	#yk.flatten()
	#fig, ax = plt.subplots(1, 1)
	#ax.hist(yk, normed=True, histtype='stepfilled', alpha=0.2)
	# gaussian KDE
	X=yk.reshape(-1, 1)
	kde = KernelDensity(kernel='gaussian', bandwidth=0.6).fit(X)
	log_dens = kde.score_samples(X_plot)
	mi, ma = argrelextrema(log_dens, np.less)[0], argrelextrema(log_dens, np.greater)[0]
	mi=np.rint(mi*float(len(xk))/float(sdiv))
	ma=np.rint(ma*float(len(xk))/float(sdiv))
	start=0	
	#print mi
	for i in mi:
		i=int(i)
		if start!=i:
			val=np.average(nk[start:i])
			for j in xrange(start,i):
				result.append(val)
		start=i	
	val=np.average(nk[start:])
	for j in xrange(start,len(nk)):
			result.append(val)
	return np.array(result)
开发者ID:leaguilar,项目名称:playground,代码行数:34,代码来源:test4.py

示例7: get_extrema

  def get_extrema(self, limits=(0.0, float('inf')), order=5):
    """Computes masks (i.e. arrays of indices) of the extrema of the force.

    Parameters
    ----------
    order: integer, optional
      Number of neighboring points used to define an extremum; 
      default: 5.

    Returns
    -------
    minima: 1D array of integers
      Index of all minima.
    maxima: 1D array of integers
      Index of all maxima.
    """
    minima = signal.argrelextrema(self.values, numpy.less_equal, 
                                  order=order)[0][:-1]
    maxima = signal.argrelextrema(self.values, numpy.greater_equal, 
                                  order=order)[0][:-1]
    mask = numpy.where(numpy.logical_and(self.times >= limits[0],
                                         self.times <= limits[1]))[0]
    minima = numpy.intersect1d(minima, mask, assume_unique=True)
    maxima = numpy.intersect1d(maxima, mask, assume_unique=True)
    # remove indices that are too close
    minima = minima[numpy.append(True, minima[1:]-minima[:-1] > order)]
    maxima = maxima[numpy.append(True, maxima[1:]-maxima[:-1] > order)]
    return minima, maxima
开发者ID:Haider-BA,项目名称:snake,代码行数:28,代码来源:force.py

示例8: peaksValleys

def peaksValleys(data, attrib):

	for i in range(0,len(attrib)-2):

		k = [[], []] # k[0] picos e k[1] vales

		[k[0].append(data[j]) for j in argrelextrema(data, np.greater)[0]]
		[k[1].append(data[j]) for j in argrelextrema(data, np.less)[0]]

		#print (k[0])
		#print (k[1])

		aux = max(k[0])
		aux2 = min(k[1])
		for i in range(len(k[0])):
			try:
				if aux/k[0][i] < 0.7:
					k[0].pop(i)
			except:
				break


		for i in range(len(k[1])):
			try:
				if aux2/k[1][i] < 0.1:
					k[1].pop(i)
			except:
				break
		#print (k[0])
		#print (k[1])

	return k[0], k[1]
开发者ID:dutrasr,项目名称:Biometrics-of-Human-Gait-Using-Kinect,代码行数:32,代码来源:dataAnalysis.py

示例9: tribocycle_finder

def tribocycle_finder(y_disp):
    """
    finds tribo-cycles using the y displacement curve
    :param y_disp:
    :return:
    """

    y_disp = moving_average(y_disp)
    maxima = argrelextrema(y_disp, np.greater, order=1000)
    minima = argrelextrema(y_disp, np.less, order=500)

    if maxima[0].size > minima[0].size:
        cycle_ends = maxima
        cycle_mid = minima
    elif minima[0].size > maxima[0].size:
        cycle_ends = minima
        cycle_mid = maxima
    else:
        print 'Error in tribocycle finder, y displacement waveform incorrect'
        plt.plot(y_disp)
        plt.show()
        cycle_ends = np.nan
        cycle_mid = np.nan

    return cycle_ends, cycle_mid
开发者ID:mlsamsom,项目名称:PyFrictionTools,代码行数:25,代码来源:utilities.py

示例10: find_order_edge_peaks

def find_order_edge_peaks(reduced):
    
    from scipy.signal import argrelextrema

    # make top and bottom edge images
    rolled = np.roll(reduced.flat, 5, axis=0)
    reduced.topEdgesImg = rolled - reduced.flat
    reduced.botEdgesImg = reduced.flat - rolled
    
    
    # take a vertical cut of edges
    reduced.topEdgesProfile = np.median(reduced.topEdgesImg[:, 40:50], axis=1)
    reduced.botEdgesProfile = np.median(reduced.botEdgesImg[:, 40:50], axis=1)

    # find the highest peaks in crosscut, search +/- 15 pixels to narrow down list
    top_extrema = argrelextrema(reduced.topEdgesProfile, np.greater, order=35)[0]
    bot_extrema = argrelextrema(reduced.botEdgesProfile, np.greater, order=35)[0]

    # find crosscut values at those extrema
    top_intensities = reduced.topEdgesProfile[top_extrema]
    bot_intensities = reduced.botEdgesProfile[bot_extrema]

    reduced.topEdgePeaks = zip(top_extrema, top_intensities)
    reduced.botEdgePeaks = zip(bot_extrema, bot_intensities)
    
    return
开发者ID:hdtee,项目名称:nirspec_drp,代码行数:26,代码来源:reduce_frame.py

示例11: plotPlots

def plotPlots(linearray, sampletitle, roi):
	plt.figure(figsize=(14, 14))
	gs1 = matplotlib.gridspec.GridSpec(8, 8)
	gs1.update(wspace=0.25,  hspace=0.3)
	from scipy.signal import argrelextrema

	for i, li in enumerate(linearray):  # [0, :]):

		axarr = plt.subplot(gs1[i])

		lin = linearray[:, i]

		axarr.plot(lin)

		try:
			ma = np.mean(lin[argrelextrema(lin, np.greater)[0]])
			mi = np.mean(lin[argrelextrema(lin, np.less)[0]])
			axarr.plot([0,len(lin)],[ma,ma])
			axarr.plot([0,len(lin)],[mi,mi])
			axarr.set_title('{:.2%}'.format((ma-mi)/ma))
		except IndexError:
			print "Index error."

		axarr.set_ylim(0.6,1)
		# set_title('%.4f, %.4f' % (float(a[i]), float(b[i])))
		axarr.xaxis.set_major_formatter(plt.NullFormatter())
		axarr.yaxis.set_major_formatter(plt.NullFormatter())

	print data.directory, sampletitle, str(roi)
	# plt.savefig('{}/{}_{}_lines.pdf'.format(data.directory, sampletitle, str(roi)))
	plt.savefig(data.directory + '/%s_%s_lines.pdf' % (sampletitle, str(roi)))
开发者ID:acjak,项目名称:dfxm,代码行数:31,代码来源:resolution_direct_line.py

示例12: find_strong_lines

def find_strong_lines(x, xo, gggf, gggf_infm, cfile, logfile):
    # We need to find strong lines in spectrum and ingnore all small changes in flux.
    # Here - code checks the change in signal around inflection points and compares it
    # to noise multiplied by rejection parameter

    max_ind = argrelextrema(gggf, np.greater)
    min_ind = argrelextrema(gggf, np.less)

    max_tab = np.array([x[max_ind], gggf[max_ind]])
    min_tab = np.array([x[min_ind], gggf[min_ind]])

    thold = get_thold(gggf, cfile.getfloat('Lines', 'r_lvl'))
    str_lines = []

    if not (max_tab.size != 0 and min_tab.size != 0 and thold == 0.0):
        for item in gggf_infm:
            indx = np.abs(max_tab[0, :] - item).argmin()
            indm = np.abs(min_tab[0, :] - item).argmin()

            if ((np.abs(max_tab[1, indx]) > thold) and
                    (np.abs(min_tab[1, indm]) > thold)):
                str_lines.append(item)

    str_lines = evaluate_lines(xo, str_lines,
                               cfile.getfloat('Lines', 'det_level'),
                               gggf_infm, logfile)
    return str_lines
开发者ID:madamow,项目名称:pyEW,代码行数:27,代码来源:Prepare_spectrum.py

示例13: accumulateFrame

def accumulateFrame(symbols, order, mindate, maxdate):
    connection = sqlite3.connect('../data/historical.sl')
    c = connection.cursor()
    df = pd.DataFrame(columns=['ts','min','max']).set_index('ts')
    for symbol in symbols:
        query = "SELECT ts,close,high,low FROM eod WHERE symbol = '" + symbol + "' AND ts BETWEEN " + str(mindate) + " AND " + str(maxdate) + " ORDER BY ts;"
        c.execute(query)
        data = c.fetchall()
        dates = array([datetime.datetime.fromordinal(q[0]) for q in data])
        closes = array([q[1] for q in data])
        highs = array([q[2] for q in data])
        lows = array([q[3] for q in data])
        # compute extrema
        if len(lows) > 0:
            cmin = argrelextrema(data=lows, comparator=np.less, order=order)
            # create frame for minima indexed by date
            if(len(cmin[0]) > 0):
                mins = np.vstack((dates[cmin], np.negative(np.ones(cmin[0].size)), np.zeros(cmin[0].size))).transpose()
                df1 = pd.DataFrame(mins, columns=['ts','min','max']).set_index('ts')
                df = df.add(df1, fill_value=0)
        if len(highs) > 0:
            cmax = argrelextrema(data=highs, comparator=np.greater, order=order)
            # create frame for maxima indexed by date
            if(len(cmax[0]) > 0):
                maxes = np.vstack((dates[cmax], np.zeros(cmax[0].size), np.ones(cmax[0].size))).transpose()
                df2 = pd.DataFrame(maxes, columns=['ts','min','max']).set_index('ts')
                df = df.add(df2, fill_value=0)
    return df
开发者ID:Yasboti,项目名称:Stocker,代码行数:28,代码来源:extrema.py

示例14: get_local_Extrema

def get_local_Extrema(time,data):
    ''' # Function to get the local extrema for a response
    #
    # Inputs:
    #   time = time array corresponding to the data
    #   data = the response data array (only pass a single dimension/state at at time)
    #
    # Output:
    #   localMaxes = the amplitude of the local maxes
    #   localMax_Times = the times of the local maxes
    #
    # Created: 03/28/14
    #   - Joshua Vaughan
    #   - [email protected]
    #   - http://www.ucs.louisiana.edu/~jev9637
    ######################################################################################
    '''
    from scipy import signal
    
    # Get local maximums
    localMax_indexes = signal.argrelextrema(data, np.greater)
    localMaxes = data[localMax_indexes]
    localMax_Times = time[localMax_indexes]

    # Get local minimums
    localMin_indexes = signal.argrelextrema(data, np.less)
    localMins = data[localMin_indexes]
    localMin_Times = time[localMin_indexes]
    
    return localMaxes, localMax_Times, localMins, localMin_Times
开发者ID:DocVaughan,项目名称:CRAWLAB-Code-Snippets,代码行数:30,代码来源:systemID_functions.py

示例15: check

    def check(self, data, date):
        dataarr = np.asarray(data)
        extmax = argrelextrema(dataarr, np.greater)
        extmin = argrelextrema(dataarr, np.less)

        newdata = [[],[]]
        retpattern = []
        for i,d in enumerate(data):
            if i in extmax[0] or i in extmin[0]:
                newdata[0].append(date[i])
                newdata[1].append(d)

        for idx, val in enumerate(newdata[0]):
            if idx + 6 > len(newdata[0]):
                break
            itemx = newdata[0][idx: idx+6]
            itemy = newdata[1][idx: idx+6]
            for p in self.pattern:
                try:
                    ret = p.pattern(itemy)
                    if ret:
                        print p.name 
                        print itemx, itemy
                        #pylab.scatter(itemx, itemy)
                        retpattern.append({'name': p.name, "iyd": itemy, \
                                                                "ixd": itemx})
                except:
                    print "error in %s" % p.name

        return retpattern
开发者ID:LumbaJack,项目名称:Plan-Visualizer,代码行数:30,代码来源:pattersdb.py


注:本文中的scipy.signal.argrelextrema函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。