Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Valley detection, based on peak detection macro by Peter Davidowicz, adapted by jywarren (
/* Sample data:
$W.spectrum_data = {"lines":[
Now, setup a Spectral Workbench macro (although we'll keep it commented out until we're ready to deploy it):
setup: function() {
// code to run on startup
compare = function(dist,i,pixels) {
if (dist <= 1) return true
else return (compare(dist-1,i,pixels)) && pixels[i+dist]['average'] >= pixels[i]['average'] && pixels[i-dist]['average'] > pixels[i]['average']
detect_peaks = function(search_dist) {
var peaks = []
var peak_wavelengths = []
var pixels = $W.spectrum.lines
for (var i = search_dist; i < pixels.length-search_dist+1; i++) { //start a few pixels because we need to compare to neighboring pixels
if (pixels[i]['average'] < pixels[i-1]['average']) {
if (compare(search_dist,i,pixels)) { //This skips tiny valleys, more checks (increasing search_dist) skips larger valleys
// Pixel is Peak Pixel, add it to peak pixel list
peaks.push(pixels[i]) // here, adding the entire pixel object, including separate rgb and wavelength values
peaks[peaks.length-1]['index'] = i // save the pixel index too
peak_wavelengths.push(parseFloat(pixels[i]['wavelength'].toFixed(2))) // here, adding just the rounded wavelength
$W.plot.highlight(0,i) // highlight the peak on the graph
return peaks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.