{
   "name" : "simple peak detection algorithm",
   "author" : "LFSaw",
   "description" : "after http://www.tcs-trddc.com/trddc_website/pdf/SRL/Palshikar_SAPDTS_2009.pdf",
   "ancestor_list" : [],
   "labels" : [
      "tool",
      "signal analysis",
      "peak detection"
   ],
   "code" : "q = q ? ();\r\n\r\n(\r\nq.s1 = {|q, left, item, right, rContextSize|\r\n\t//[left, item, right].postln;\r\n\t((maxItem(item - left) ? 0) + (maxItem(item - right) ? 0)) * 0.5\r\n};\r\n\r\nq.peak1 = {|q, signal, windowSize = 4|\r\n\tvar mean, sDev, aAbs, peaksSize;\r\n\tvar rWindowSize = windowSize.reciprocal;\r\n\tvar h = 3; // 1<= h <= 3\r\n\tvar idxs = List[];\r\n\tvar a = signal.collect{|val, i|\r\n\t\t// compute peak function value for each of the N points in T\r\n\t\tq.s1(\r\n\t\t\tsignal.copyRange(i-windowSize, i-1), \r\n\t\t\tval, \r\n\t\t\tsignal.copyRange(i+1, i + windowSize), \r\n\t\t\tval\r\n\t\t);\r\n\t};\r\n\t// Compute the mean m and standard deviation s of all positive values in array a;\r\n\taAbs = a.abs;\r\n\tmean = aAbs.mean;\r\n\tsDev = aAbs.stdDev;\r\n\r\n//\tmean.postln;\r\n//\tsDev.postln;\r\n\t\r\n\r\n\ta.do{|val, i| // collect all indices that are concidered big \r\n\t\tif ((a[i]>0) && ((a[i]-mean) > (h*sDev))) {\r\n\t\t\tidxs.add(i);\r\n\t\t}\r\n\t};\r\n\tpeaksSize = idxs.size.postln;\r\n\r\n\t// retain only one peak of any set of peaks within windowSize of each other\r\n\tidxs.inject([0], {|last, now, i|\r\n\t\t((now - last.last) <= windowSize).if({\r\n\t\t\t(signal[now] > signal[last.last]).if({\r\n\t\t\t\tlast.pop;\r\n\t\t\t\tlast ++ now;\r\n\t\t\t}, {\r\n\t\t\t\tlast;\r\n\t\t\t})\r\n\t\t}, {\r\n\t\t\tlast ++ now;\t\r\n\t\t})\r\n\t})\r\n}\r\n)\r\n\r\n// apply peak1 to any \"signal\", i.e. a 1-dimensional sequence of numbers, play around with the windowSize param (and possibly h, see above).\r\nq.res = q.peak1(q.wireWset.amps, 4);q.res",
   "is_private" : null,
   "id" : "1-4Ud"
}
