Home  · Classes  · Annotated Classes  · Modules  · Members  · Namespaces  · Related Pages

SignalToNoiseEstimatorMedian.h

Go to the documentation of this file.
00001 // --------------------------------------------------------------------------
00002 //                   OpenMS -- Open-Source Mass Spectrometry
00003 // --------------------------------------------------------------------------
00004 // Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
00005 // ETH Zurich, and Freie Universitaet Berlin 2002-2012.
00006 //
00007 // This software is released under a three-clause BSD license:
00008 //  * Redistributions of source code must retain the above copyright
00009 //    notice, this list of conditions and the following disclaimer.
00010 //  * Redistributions in binary form must reproduce the above copyright
00011 //    notice, this list of conditions and the following disclaimer in the
00012 //    documentation and/or other materials provided with the distribution.
00013 //  * Neither the name of any author or any participating institution
00014 //    may be used to endorse or promote products derived from this software
00015 //    without specific prior written permission.
00016 // For a full list of authors, refer to the file AUTHORS.
00017 // --------------------------------------------------------------------------
00018 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
00019 // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
00020 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
00021 // ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING
00022 // INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
00023 // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
00024 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
00025 // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
00026 // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
00027 // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
00028 // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
00029 //
00030 // --------------------------------------------------------------------------
00031 // $Maintainer: Chris Bielow $
00032 // $Authors: $
00033 // --------------------------------------------------------------------------
00034 //
00035 
00036 #ifndef OPENMS_FILTERING_NOISEESTIMATION_SIGNALTONOISEESTIMATORMEDIAN_H
00037 #define OPENMS_FILTERING_NOISEESTIMATION_SIGNALTONOISEESTIMATORMEDIAN_H
00038 
00039 
00040 #include <OpenMS/FILTERING/NOISEESTIMATION/SignalToNoiseEstimator.h>
00041 #include <OpenMS/CONCEPT/LogStream.h>
00042 #include <OpenMS/CONCEPT/Exception.h>
00043 #include <vector>
00044 
00045 namespace OpenMS
00046 {
00070   template <typename Container = MSSpectrum<> >
00071   class SignalToNoiseEstimatorMedian :
00072     public SignalToNoiseEstimator<Container>
00073   {
00074 
00075 public:
00076 
00078     enum IntensityThresholdCalculation {MANUAL = -1, AUTOMAXBYSTDEV = 0, AUTOMAXBYPERCENT = 1};
00079 
00080     using SignalToNoiseEstimator<Container>::stn_estimates_;
00081     using SignalToNoiseEstimator<Container>::first_;
00082     using SignalToNoiseEstimator<Container>::last_;
00083     using SignalToNoiseEstimator<Container>::is_result_valid_;
00084     using SignalToNoiseEstimator<Container>::defaults_;
00085     using SignalToNoiseEstimator<Container>::param_;
00086 
00087     typedef typename SignalToNoiseEstimator<Container>::PeakIterator PeakIterator;
00088     typedef typename SignalToNoiseEstimator<Container>::PeakType PeakType;
00089 
00090     typedef typename SignalToNoiseEstimator<Container>::GaussianEstimate GaussianEstimate;
00091 
00093     inline SignalToNoiseEstimatorMedian()
00094     {
00095       //set the name for DefaultParamHandler error messages
00096       this->setName("SignalToNoiseEstimatorMedian");
00097 
00098       defaults_.setValue("max_intensity", -1, "maximal intensity considered for histogram construction. By default, it will be calculated automatically (see auto_mode)." \
00099                                               " Only provide this parameter if you know what you are doing (and change 'auto_mode' to '-1')!" \
00100                                               " All intensities EQUAL/ABOVE 'max_intensity' will be added to the LAST histogram bin." \
00101                                               " If you choose 'max_intensity' too small, the noise estimate might be too small as well. " \
00102                                               " If chosen too big, the bins become quite large (which you could counter by increasing 'bin_count', which increases runtime)." \
00103                                               " In general, the Median-S/N estimator is more robust to a manual max_intensity than the MeanIterative-S/N.", StringList::create("advanced"));
00104       defaults_.setMinInt("max_intensity", -1);
00105 
00106       defaults_.setValue("auto_max_stdev_factor", 3.0, "parameter for 'max_intensity' estimation (if 'auto_mode' == 0): mean + 'auto_max_stdev_factor' * stdev", StringList::create("advanced"));
00107       defaults_.setMinFloat("auto_max_stdev_factor", 0.0);
00108       defaults_.setMaxFloat("auto_max_stdev_factor", 999.0);
00109 
00110       defaults_.setValue("auto_max_percentile", 95, "parameter for 'max_intensity' estimation (if 'auto_mode' == 1): auto_max_percentile th percentile", StringList::create("advanced"));
00111       defaults_.setMinInt("auto_max_percentile", 0);
00112       defaults_.setMaxInt("auto_max_percentile", 100);
00113 
00114       defaults_.setValue("auto_mode", 0, "method to use to determine maximal intensity: -1 --> use 'max_intensity'; 0 --> 'auto_max_stdev_factor' method (default); 1 --> 'auto_max_percentile' method", StringList::create("advanced"));
00115       defaults_.setMinInt("auto_mode", -1);
00116       defaults_.setMaxInt("auto_mode", 1);
00117 
00118       defaults_.setValue("win_len", 200.0, "window length in Thomson");
00119       defaults_.setMinFloat("win_len", 1.0);
00120 
00121       defaults_.setValue("bin_count", 30, "number of bins for intensity values");
00122       defaults_.setMinInt("bin_count", 3);
00123 
00124       defaults_.setValue("min_required_elements", 10, "minimum number of elements required in a window (otherwise it is considered sparse)");
00125       defaults_.setMinInt("min_required_elements", 1);
00126 
00127       defaults_.setValue("noise_for_empty_window", std::pow(10.0, 20), "noise value used for sparse windows", StringList::create("advanced"));
00128 
00129 
00130       SignalToNoiseEstimator<Container>::defaultsToParam_();
00131     }
00132 
00134     inline SignalToNoiseEstimatorMedian(const SignalToNoiseEstimatorMedian & source) :
00135       SignalToNoiseEstimator<Container>(source)
00136     {
00137       updateMembers_();
00138     }
00139 
00143 
00144     inline SignalToNoiseEstimatorMedian & operator=(const SignalToNoiseEstimatorMedian & source)
00145     {
00146       if (&source == this) return *this;
00147 
00148       SignalToNoiseEstimator<Container>::operator=(source);
00149       updateMembers_();
00150       return *this;
00151     }
00152 
00154 
00155 
00157     virtual ~SignalToNoiseEstimatorMedian()
00158     {}
00159 
00160 
00161 protected:
00162 
00163 
00169     void computeSTN_(const PeakIterator & scan_first_, const PeakIterator & scan_last_)
00170     {
00171       // reset counter for sparse windows
00172       double sparse_window_percent = 0;
00173       // reset counter for histogram overflow
00174       double histogram_oob_percent = 0;
00175 
00176       // reset the results
00177       stn_estimates_.clear();
00178 
00179       // maximal range of histogram needs to be calculated first
00180       if (auto_mode_ == AUTOMAXBYSTDEV)
00181       {
00182         // use MEAN+auto_max_intensity_*STDEV as threshold
00183         GaussianEstimate gauss_global = SignalToNoiseEstimator<Container>::estimate_(scan_first_, scan_last_);
00184         max_intensity_ = gauss_global.mean + std::sqrt(gauss_global.variance) * auto_max_stdev_Factor_;
00185       }
00186       else if (auto_mode_ == AUTOMAXBYPERCENT)
00187       {
00188         // get value at "auto_max_percentile_"th percentile
00189         // we use a histogram approach here as well.
00190         if ((auto_max_percentile_ < 0) || (auto_max_percentile_ > 100))
00191         {
00192           String s = auto_max_percentile_;
00193           throw Exception::InvalidValue(__FILE__,
00194                                         __LINE__,
00195                                         __PRETTY_FUNCTION__,
00196                                         "auto_mode is on AUTOMAXBYPERCENT! auto_max_percentile is not in [0,100]. Use setAutoMaxPercentile(<value>) to change it!",
00197                                         s);
00198         }
00199 
00200         std::vector<int> histogram_auto(100, 0);
00201 
00202         // find maximum of current scan
00203         int size = 0;
00204         typename PeakType::IntensityType maxInt = 0;
00205         PeakIterator run = scan_first_;
00206         while (run != scan_last_)
00207         {
00208           maxInt = std::max(maxInt, (*run).getIntensity());
00209           ++size;
00210           ++run;
00211         }
00212 
00213         double bin_size = maxInt / 100;
00214 
00215         // fill histogram
00216         run = scan_first_;
00217         while (run != scan_last_)
00218         {
00219           ++histogram_auto[(int) (((*run).getIntensity() - 1) / bin_size)];
00220           ++run;
00221         }
00222 
00223         // add up element counts in histogram until ?th percentile is reached
00224         int elements_below_percentile = (int) (auto_max_percentile_ * size / 100);
00225         int elements_seen = 0;
00226         int i = -1;
00227         run = scan_first_;
00228 
00229         while (run != scan_last_ && elements_seen < elements_below_percentile)
00230         {
00231           ++i;
00232           elements_seen += histogram_auto[i];
00233           ++run;
00234         }
00235 
00236         max_intensity_ = (((double)i) + 0.5) * bin_size;
00237       }
00238       else //if (auto_mode_ == MANUAL)
00239       {
00240         if (max_intensity_ <= 0)
00241         {
00242           String s = max_intensity_;
00243           throw Exception::InvalidValue(__FILE__,
00244                                         __LINE__,
00245                                         __PRETTY_FUNCTION__,
00246                                         "auto_mode is on MANUAL! max_intensity is <=0. Needs to be positive! Use setMaxIntensity(<value>) or enable auto_mode!",
00247                                         s);
00248         }
00249       }
00250 
00251       if (max_intensity_ < 0)
00252       {
00253         std::cerr << "TODO SignalToNoiseEstimatorMedian: the max_intensity_ value should be positive! " << max_intensity_ << std::endl;
00254         return;
00255       }
00256 
00257       PeakIterator window_pos_center  = scan_first_;
00258       PeakIterator window_pos_borderleft = scan_first_;
00259       PeakIterator window_pos_borderright = scan_first_;
00260 
00261       double window_half_size = win_len_ / 2;
00262       double bin_size = std::max(1.0, max_intensity_ / bin_count_); // at least size of 1 for intensity bins
00263       int bin_count_minus_1 = bin_count_ - 1;
00264 
00265       std::vector<int> histogram(bin_count_, 0);
00266       std::vector<double> bin_value(bin_count_, 0);
00267       // calculate average intensity that is represented by a bin
00268       for (int bin = 0; bin < bin_count_; bin++)
00269       {
00270         histogram[bin] = 0;
00271         bin_value[bin] = (bin + 0.5) * bin_size;
00272       }
00273       // bin in which a datapoint would fall
00274       int to_bin = 0;
00275 
00276       // index of bin where the median is located
00277       int median_bin = 0;
00278       // additive number of elements from left to x in histogram
00279       int element_inc_count = 0;
00280 
00281       // tracks elements in current window, which may vary because of unevenly spaced data
00282       int elements_in_window = 0;
00283       // number of windows
00284       int window_count = 0;
00285 
00286       // number of elements where we find the median
00287       int element_in_window_half = 0;
00288 
00289       double noise;    // noise value of a datapoint
00290 
00291       // determine how many elements we need to estimate (for progress estimation)
00292       int windows_overall = 0;
00293       PeakIterator run = scan_first_;
00294       while (run != scan_last_)
00295       {
00296         ++windows_overall;
00297         ++run;
00298       }
00299       SignalToNoiseEstimator<Container>::startProgress(0, windows_overall, "noise estimation of data");
00300 
00301       // MAIN LOOP
00302       while (window_pos_center != scan_last_)
00303       {
00304 
00305         // erase all elements from histogram that will leave the window on the LEFT side
00306         while ((*window_pos_borderleft).getMZ() <  (*window_pos_center).getMZ() - window_half_size)
00307         {
00308           to_bin = std::max(std::min<int>((int)((*window_pos_borderleft).getIntensity() / bin_size), bin_count_minus_1), 0);
00309           --histogram[to_bin];
00310           --elements_in_window;
00311           ++window_pos_borderleft;
00312         }
00313 
00314         // add all elements to histogram that will enter the window on the RIGHT side
00315         while ((window_pos_borderright != scan_last_)
00316               && ((*window_pos_borderright).getMZ() <= (*window_pos_center).getMZ() + window_half_size))
00317         {
00318           //std::cerr << (*window_pos_borderright).getIntensity() << " " << bin_size << " " << bin_count_minus_1 << std::endl;
00319           to_bin = std::max(std::min<int>((int)((*window_pos_borderright).getIntensity() / bin_size), bin_count_minus_1), 0);
00320           ++histogram[to_bin];
00321           ++elements_in_window;
00322           ++window_pos_borderright;
00323         }
00324 
00325         if (elements_in_window < min_required_elements_)
00326         {
00327           noise = noise_for_empty_window_;
00328           ++sparse_window_percent;
00329         }
00330         else
00331         {
00332           // find bin i where ceil[elements_in_window/2] <= sum_c(0..i){ histogram[c] }
00333           median_bin = -1;
00334           element_inc_count = 0;
00335           element_in_window_half = (elements_in_window + 1) / 2;
00336           while (median_bin < bin_count_minus_1 && element_inc_count < element_in_window_half)
00337           {
00338             ++median_bin;
00339             element_inc_count += histogram[median_bin];
00340           }
00341 
00342           // increase the error count
00343           if (median_bin == bin_count_minus_1) {++histogram_oob_percent; }
00344 
00345           // just avoid division by 0
00346           noise = std::max(1.0, bin_value[median_bin]);
00347         }
00348 
00349         // store result
00350         stn_estimates_[*window_pos_center] = (*window_pos_center).getIntensity() / noise;
00351 
00352 
00353         // advance the window center by one datapoint
00354         ++window_pos_center;
00355         ++window_count;
00356         // update progress
00357         SignalToNoiseEstimator<Container>::setProgress(window_count);
00358 
00359       } // end while
00360 
00361       SignalToNoiseEstimator<Container>::endProgress();
00362 
00363       sparse_window_percent = sparse_window_percent * 100 / window_count;
00364       histogram_oob_percent = histogram_oob_percent * 100 / window_count;
00365 
00366       // warn if percentage of sparse windows is above 20%
00367       if (sparse_window_percent > 20)
00368       {
00369         LOG_WARN << "WARNING in SignalToNoiseEstimatorMedian: "
00370                  << sparse_window_percent
00371                  << "% of all windows were sparse. You should consider increasing 'win_len' or decreasing 'min_required_elements'"
00372                  << std::endl;
00373       }
00374 
00375       // warn if percentage of possibly wrong median estimates is above 1%
00376       if (histogram_oob_percent > 1)
00377       {
00378         LOG_WARN << "WARNING in SignalToNoiseEstimatorMedian: "
00379                  << histogram_oob_percent
00380                  << "% of all Signal-to-Noise estimates are too high, because the median was found in the rightmost histogram-bin. "
00381                  << "You should consider increasing 'max_intensity' (and maybe 'bin_count' with it, to keep bin width reasonable)"
00382                  << std::endl;
00383       }
00384 
00385     } // end of shiftWindow_
00386 
00388     void updateMembers_()
00389     {
00390       max_intensity_         = (double)param_.getValue("max_intensity");
00391       auto_max_stdev_Factor_ = (double)param_.getValue("auto_max_stdev_factor");
00392       auto_max_percentile_   = param_.getValue("auto_max_percentile");
00393       auto_mode_             = param_.getValue("auto_mode");
00394       win_len_               = (double)param_.getValue("win_len");
00395       bin_count_             = param_.getValue("bin_count");
00396       min_required_elements_ = param_.getValue("min_required_elements");
00397       noise_for_empty_window_ = (double)param_.getValue("noise_for_empty_window");
00398       is_result_valid_ = false;
00399     }
00400 
00402     double max_intensity_;
00404     double auto_max_stdev_Factor_;
00406     double auto_max_percentile_;
00408     int    auto_mode_;
00410     double win_len_;
00412     int    bin_count_;
00414     int min_required_elements_;
00417     double noise_for_empty_window_;
00418 
00419 
00420 
00421   };
00422 
00423 } // namespace OpenMS
00424 
00425 #endif //OPENMS_FILTERING_NOISEESTIMATION_DSIGNALTONOISEESTIMATORMEDIAN_H

OpenMS / TOPP release 1.10.0 Documentation generated on Thu Mar 7 2013 09:42:44 using doxygen 1.7.1