peak identification with array expressions (R/Python/Matlab/...)

Status
Not open for further replies.
I have a signal in which I want to identify peaks, in R or Python (using numpy or scipy), preferentially using array expressions instead of loops.
I have a pair of thresholds that define the levels a peak has to exceed in order to be a peak, so I can easily obtain all samples that are part of a peak with an expression like

Code:
peaksamples = sig[ (sig > Hthres) | (sig < Lthres) ]

However, I'd like to identify to first and last samples of each peak ... and I don't really see how to achieve that easily when there is more than 1 peak in my signal.
Something like

Code:
peakStarts = sig[ ((sig > Hthres) & (Shift1Left(sig) <= Hthres)) | ((sig < Lthres) & (Shift1Right(sig) >= Lthres)) ]
peakStops = sig[ ((sig <= Hthres) & (Shift1Left(sig) > Hthres)) | ((sig >= Lthres) & (Shift1Right(sig) < Lthres)) ]

should do the trick, but I haven't yet found primitives to do the shifting.

Is there an efficient call or set of calls that allows to do this without resorting to looping over my signal? Is there a signal length/size above (or under...) which it is more efficient to write a bit of C-code containing the necessary loops?

And while I'm at it, how about more elaborate peak identification, where one tries to find the 'real' start and end of a peak found by the threshold crossing, for instance the preceding or subsequent zero-crossing?

Thanks in advance,
René
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
if you have a signal not guaranteed to have a high peak followed by a low peak isn't your above code going to incorrectly deem it to all be one 'peak' and mask all the medium values?

If your data is guaranteed to not do this the approach you describe (take the post filter output then find the sign changes) will work but fundamentally that what you'd have to do o the raw signal. maintain state as you loop through an note when the transitions occur.

Writing that as a generator (and augmenting the resulting output with out of band indications of the start/end of the peak sounds more sensible, but I don't know python so can't say if that's idiomatic or not.
 
ShuggyCoUk":36cehj9r said:
if you have a signal not guaranteed to have a high peak followed by a low peak isn't your above code going to incorrectly deem it to all be one 'peak' and mask all the medium values?

What exactly do you mean by this? My signal is a steering angle measured through a sensor coupled to a steering wheel or the handlebars of a bike. So there's a lot of small oscillations around 0º (straight ahead), and peaks - voluntary turns.

[...]maintain state as you loop through an note when the transitions occur.

And that's what I've always done, but since I'm now trying to do all processing and analysis in R or python, I'd prefer to avoid writing loops...

I'm not sure what you mean with a generator in this context?

PS: R is the one from www.r-project.org :eyebrow:
 
RJVB":xgpne4md said:
ShuggyCoUk":xgpne4md said:
if you have a signal not guaranteed to have a high peak followed by a low peak isn't your above code going to incorrectly deem it to all be one 'peak' and mask all the medium values?

What exactly do you mean by this? My signal is a steering angle measured through a sensor coupled to a steering wheel or the handlebars of a bike. So there's a lot of small oscillations around 0º (straight ahead), and peaks - voluntary turns - but each high (low) peak isn't necessarily followed by another (low or high) peak.

[...]maintain state as you loop through an note when the transitions occur.

And that's what I've always done, but since I'm now trying to do all processing and analysis in R or python, I'd prefer to avoid writing loops...

I'm not sure what you mean with a generator in this context?

PS: R is the one from http://www.r-project.org :eyebrow:
 

ShuggyCoUk

Ars Legatus Legionis
10,387
Subscriptor++
RJVB":1p9e7p6y said:
What exactly do you mean by this? My signal is a steering angle measured through a sensor coupled to a steering wheel or the handlebars of a bike. So there's a lot of small oscillations around 0º (straight ahead), and peaks - voluntary turns.
Ah right, so you signal is [0,n] rather than [-n,+n] that avoids that issue then, I was interpreting it as you having thresholds for positive and negative peaks.

I'm not sure what you mean with a generator in this context?
section 9.10
If you are, in effect, expressing a state machine, they work very nicely.

As to R, I've no experience with it sorry.
 
ShuggyCoUk":2hkfwjh2 said:
Ah right, so you signal is [0,n] rather than [-n,+n] that avoids that issue then, I was interpreting it as you having thresholds for positive and negative peaks.

Actually, the signal could very well resemble a sinusoid, i.e. covering a range [-maxSteeringAngle, maxSteeringAngle] ... but I calculate my thresholds with something like

Code:
Hthres = mean(signal) + k * std.dev(signal)
Lthres = mean(signal) - k * std.dev(signal)

That's the programmatic equivalent of the window-discriminators I worked with long ago, so I think your worry about negative peaks is moot :)

I'll have a look at the link, thanks. Indeed, if I have a vector POI that indicates for each sample whether it responds to my selection criteria, the following is relatively efficient in that it avoids looping over data that doesn't exceed the thresholds:

Code:
def idx(a):
    return a.nonzero()[0]

for i in idx(POI):
    if( signal[i] > Hthres and signal[i-1] <= hThres ):
        print 'High peak onset at t=%g' %(time[i])
## etc

or...

Code:
idxPOI = idx(POI)

for i in idxPOI[idx(append(0,diff(idxPOI)) > 1)]:
    print 'threshold crossing: signal[t=%g]=%g' %(time[i], signal[i])
 
Small correction on that last bit (which only printed peak onsets):

Code:
> time[0], time[time.size-1]

(0.0, 19.960000000000001)

> signal=numpy.sin(time)

> elems=(signal > 0.75) | (signal < -0.75)

> crossings = sort(append( idx(elems)[idx(append(2,diff(idx(elems)))>1)], idx(elems)[idx(append(0,diff(idx(elems)))>1)-1] ))
 
> crossings

array([ 22,  57, 100, 135, 179, 214, 257, 292, 336, 371, 414, 450, 493])

> for i in crossings:
   .....:       print 'crossing; signal[t=%g]=%g flanked by %g and %g' %(time[i], signal[i], signal[i-1], signal[i+1])
   .....: 
crossing; signal[t=0.88]=0.770739 flanked by 0.744643 and 0.795602
crossing; signal[t=2.28]=0.758881 flanked by 0.784316 and 0.732231
crossing; signal[t=4]=-0.756802 flanked by -0.730058 and -0.782336
crossing; signal[t=5.4]=-0.772764 flanked by -0.797527 and -0.746765
crossing; signal[t=7.16]=0.768705 flanked by 0.742513 and 0.793668
crossing; signal[t=8.56]=0.760951 flanked by 0.786288 and 0.734397
crossing; signal[t=10.28]=-0.754717 flanked by -0.727878 and -0.780348
crossing; signal[t=11.68]=-0.774782 flanked by -0.799445 and -0.74888
crossing; signal[t=13.44]=0.766664 flanked by 0.740376 and 0.791726
crossing; signal[t=14.84]=0.763014 flanked by 0.788252 and 0.736555
crossing; signal[t=16.56]=-0.752623 flanked by -0.72569 and -0.778352
crossing; signal[t=18]=-0.750987 flanked by -0.776792 and -0.723981
crossing; signal[t=19.72]=0.764615 flanked by 0.738231 and 0.789776
 
Small correction on that last bit (which only printed peak onsets):

Code:
> time[0], time[time.size-1]

(0.0, 19.960000000000001)

> signal=numpy.sin(time)

> elems=(signal > 0.75) | (signal < -0.75)
# the element indices of the selected signal values:
> idxelems = idx(elems)

# ON crossings are detected when there's a gap in the sequence of selected values, i.e. a >1 jump in subsequent element indices. The first selected element also qualifies, of course!
> gaps = append(2,diff(idxelems))
> ONcrossings = idxelems[idx(gaps>1)]
# OFF crossings are the last elements of each range of selected values; so we exclude the 1st...
> gaps[0] = 0
> OFFcrossings = idxelems[idx(gaps>1)-1]
# combine into a sorted list:
> crossings = sort(append(ONcrossings, OFFcrossings ))
 
> crossings

array([ 22,  57, 100, 135, 179, 214, 257, 292, 336, 371, 414, 450, 493])

> for i in crossings:
   .....:       print 'crossing; signal[t=%g]=%g flanked by %g and %g' %(time[i], signal[i], signal[i-1], signal[i+1])
   .....: 
crossing; signal[t=0.88]=0.770739 flanked by 0.744643 and 0.795602
crossing; signal[t=2.28]=0.758881 flanked by 0.784316 and 0.732231
crossing; signal[t=4]=-0.756802 flanked by -0.730058 and -0.782336
crossing; signal[t=5.4]=-0.772764 flanked by -0.797527 and -0.746765
crossing; signal[t=7.16]=0.768705 flanked by 0.742513 and 0.793668
crossing; signal[t=8.56]=0.760951 flanked by 0.786288 and 0.734397
crossing; signal[t=10.28]=-0.754717 flanked by -0.727878 and -0.780348
crossing; signal[t=11.68]=-0.774782 flanked by -0.799445 and -0.74888
crossing; signal[t=13.44]=0.766664 flanked by 0.740376 and 0.791726
crossing; signal[t=14.84]=0.763014 flanked by 0.788252 and 0.736555
crossing; signal[t=16.56]=-0.752623 flanked by -0.72569 and -0.778352
crossing; signal[t=18]=-0.750987 flanked by -0.776792 and -0.723981
crossing; signal[t=19.72]=0.764615 flanked by 0.738231 and 0.789776

or packed into a function:

Code:
def Find_Selection_OnOffSets(elems, signal=None, low=None, high=None):
	# the element indices of the selected signal values:
	idxelems = idx(elems)
#
	# ON crossings are detected when there's a gap in the sequence of selected values, i.e. a >1 jump in subsequent element indices. The first selected element also qualifies, of course!
	gaps = append(0,diff(idxelems))
	ONcrossings = idxelems[idx(gaps>1)]
	OFFcrossings = idxelems[idx(gaps>1)-1]
	# combine into a sorted list:
	if( idxelems[0] != 0 ):
		crossings = append( [ONcrossings, OFFcrossings], idxelems[0] )
	else:
		crossings = append( ONcrossings, OFFcrossings )
	if( idxelems[idxelems.size-1] != elems.size-1 ):
		crossings = append( crossings, idxelems[idxelems.size-1] )
	crossings = sort(crossings)
#
	if( signal != None ):
		if( (crossings.size > 0) and (low != None) and (high != None) ):
			print >>sys.stderr, '%d Crossings of thresholds %g and/or %g:' %(crossings.size, low, high)
		for i in crossings:
			if( i == 0 ):
				print >>sys.stderr, '\tsignal[%d]=%g followed by %g' %(i, signal[i], signal[i+1])
			elif( i == signal.size-1 ):
				print >>sys.stderr, '\tsignal[%d]=%g preceded by %g' %(i, signal[i], signal[i-1])
			else:
				print >>sys.stderr, '\tsignal[%d]=%g flanked by %g and %g' %(i, signal[i], signal[i-1], signal[i+1])
#
	return crossings


In [68]: Find_Selection_OnOffSets( elems, signal, -0.75, 0.75 )
13 Crossings of thresholds -0.75 and/or 0.75:
	signal[22]=0.770739 flanked by 0.744643 and 0.795602
	signal[57]=0.758881 flanked by 0.784316 and 0.732231
	signal[100]=-0.756802 flanked by -0.730058 and -0.782336
	signal[135]=-0.772764 flanked by -0.797527 and -0.746765
	signal[179]=0.768705 flanked by 0.742513 and 0.793668
	signal[214]=0.760951 flanked by 0.786288 and 0.734397
	signal[257]=-0.754717 flanked by -0.727878 and -0.780348
	signal[292]=-0.774782 flanked by -0.799445 and -0.74888
	signal[336]=0.766664 flanked by 0.740376 and 0.791726
	signal[371]=0.763014 flanked by 0.788252 and 0.736555
	signal[414]=-0.752623 flanked by -0.72569 and -0.778352
	signal[450]=-0.750987 flanked by -0.776792 and -0.723981
	signal[493]=0.764615 flanked by 0.738231 and 0.789776
 
Status
Not open for further replies.