«simple peak detection algorithm» by LFSaw

on 13 Aug'13 16:16 in toolsignal analysispeak detection

after http://www.tcs-trddc.com/trddc_website/pdf/SRL/Palshikar_SAPDTS_2009.pdf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
q = q ? ();

(
q.s1 = {|q, left, item, right, rContextSize|
	//[left, item, right].postln;
	((maxItem(item - left) ? 0) + (maxItem(item - right) ? 0)) * 0.5
};

q.peak1 = {|q, signal, windowSize = 4|
	var mean, sDev, aAbs, peaksSize;
	var rWindowSize = windowSize.reciprocal;
	var h = 3; // 1<= h <= 3
	var idxs = List[];
	var a = signal.collect{|val, i|
		// compute peak function value for each of the N points in T
		q.s1(
			signal.copyRange(i-windowSize, i-1), 
			val, 
			signal.copyRange(i+1, i + windowSize), 
			val
		);
	};
	// Compute the mean m and standard deviation s of all positive values in array a;
	aAbs = a.abs;
	mean = aAbs.mean;
	sDev = aAbs.stdDev;

//	mean.postln;
//	sDev.postln;
	

	a.do{|val, i| // collect all indices that are concidered big 
		if ((a[i]>0) && ((a[i]-mean) > (h*sDev))) {
			idxs.add(i);
		}
	};
	peaksSize = idxs.size.postln;

	// retain only one peak of any set of peaks within windowSize of each other
	idxs.inject([0], {|last, now, i|
		((now - last.last) <= windowSize).if({
			(signal[now] > signal[last.last]).if({
				last.pop;
				last ++ now;
			}, {
				last;
			})
		}, {
			last ++ now;	
		})
	})
}
)

// apply peak1 to any "signal", i.e. a 1-dimensional sequence of numbers, play around with the windowSize param (and possibly h, see above).
q.res = q.peak1(q.wireWset.amps, 4);q.res
raw 1398 chars (focus & ctrl+a+c to copy)
reception
comments