'absorption_detection' by warren


Report abuse

Created on July 31, 2013 12:15 | Updated over 6 years ago

Link: https://gist.github.com/jywarren/6121454

Valley detection, based on peak detection macro by Peter Davidowicz, adapted by jywarren (https://gist.github.com/jywarren/6020668)

/* Sample data:

$W.spectrum_data = {"lines":[
  {"wavelength":842.3466875,"b":21,"g":13,"r":30,"average":21},
  {"wavelength":841.455655089628,"b":13,"g":5,"r":22,"average":13},
  {"wavelength":840.564622679257,"b":0,"g":0,"r":27,"average":9},
  ]
}

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
        } 
      }
    }
    alert(peak_wavelengths.join(','))
    return peaks
  }
  detect_peaks(5)

}