Example #1
0
int main()
{

  // create a peak map containing 4 dummy spectra and peaks
  MSExperiment exp;

  // The following examples creates a MSExperiment containing four MSSpectrum instances.
  for (Size i = 0; i < 4; ++i)
  {
    MSSpectrum spectrum;
    spectrum.setRT(i);
    spectrum.setMSLevel(1);
    for (float mz = 500.0; mz <= 900; mz += 100.0)
    {
      Peak1D peak;
      peak.setMZ(mz + i);
      spectrum.push_back(peak);
    }
    
    exp.addSpectrum(spectrum);
  }

  // Iteration over the RT range (2,3) and the m/z range (603,802) and print the peak positions.
  for (auto it = exp.areaBegin(2.0, 3.0, 603.0, 802.0); it != exp.areaEnd(); ++it)
  {
    cout << it.getRT() << " - " << it->getMZ() << endl;
  }

  // Iteration over all peaks in the experiment. 
  // Output: RT, m/z, and intensity
  // Note that the retention time is stored in the spectrum (not in the peak object)
  for (auto s_it = exp.begin(); s_it != exp.end(); ++s_it)
  {
    for (auto p_it = s_it->begin(); p_it != s_it->end(); ++p_it)
    {
      cout << s_it->getRT() << " - " << p_it->getMZ() << " " << p_it->getIntensity() << endl;
    }
  }

  // We could store the spectra to a mzML file with:
  // MzMLFile mzml;
  // mzml.store(filename, exp);
  
  // And load it with
  // mzml.load(filename, exp);
  // If we wanted to load only the MS2 spectra we could speed up reading by setting:
  // mzml.getOptions().addMSLevel(2);
  // before executing: mzml.load(filename, exp);

  return 0;
} //end of main
  void ElutionPeakDetection::smoothData(MassTrace& mt, int win_size) const
  {
    // alternative smoothing using SavitzkyGolay
    // looking at the unit test, this method gives better fits than lowess smoothing
    // reference paper uses lowess smoothing

    MSSpectrum<PeakType> spectrum;
    spectrum.insert(spectrum.begin(), mt.begin(), mt.end());
    SavitzkyGolayFilter sg;
    Param param;
    param.setValue("polynomial_order", 2);
    param.setValue("frame_length", std::max(3, win_size)); // frame length must be at least polynomial_order+1, otherwise SG will fail
    sg.setParameters(param);
    sg.filter(spectrum);
    MSSpectrum<PeakType>::iterator iter = spectrum.begin();
    std::vector<double> smoothed_intensities;
    for (; iter != spectrum.end(); ++iter)
    {
      smoothed_intensities.push_back(iter->getIntensity());
    }
    mt.setSmoothedIntensities(smoothed_intensities);
    //alternative end

    // std::cout << "win_size elution: " << scan_time << " " << win_size << std::endl;

    // if there is no previous FWHM estimation... do it now
    //    if (win_size == 0)
    //    {
    //        mt.estimateFWHM(false); // estimate FWHM
    //        win_size = mt.getFWHMScansNum();
    //    }

    // use one global window size for all mass traces to smooth
    //  std::vector<double> rts, ints;
    //
    //  for (MassTrace::const_iterator c_it = mt.begin(); c_it != mt.end(); ++c_it)
    //  {
    //      rts.push_back(c_it->getRT());
    //      ints.push_back(c_it->getIntensity());
    //  }
    //  LowessSmoothing lowess_smooth;
    //  Param lowess_params;
    //  lowess_params.setValue("window_size", win_size);
    //  lowess_smooth.setParameters(lowess_params);
    //  std::vector<double> smoothed_data;
    //  lowess_smooth.smoothData(rts, ints, smoothed_data);
    //  mt.setSmoothedIntensities(smoothed_data);
  }
Example #3
0
bool IDEvaluationBase::addSearchFile(const String& file_name)
{
    MSSpectrum<> points;
    if (!loadCurve(file_name, points)) return false;

    data_.addSpectrum(points);

    MSExperiment<>* exp = new MSExperiment<>();
    exp->addSpectrum(points);
    spec_1d_->canvas()->addLayer(SpectrumCanvas::ExperimentSharedPtrType(exp));
    spec_1d_->canvas()->setLayerName(spec_1d_->canvas()->getLayerCount() - 1, points.getMetaValue("search_engine"));
    // set intensity mode (after spectrum has been added!)
    setIntensityMode((int) SpectrumCanvas::IM_SNAP);

    return true;
}
Example #4
0
bool IDEvaluationBase::getPoints(std::vector<PeptideIdentification>& peptides /* cannot be const, to avoid copy */,
                                 const std::vector<double>& q_value_thresholds, MSSpectrum<>& points)
{
    points.clear(true);

    FalseDiscoveryRate fdr;
    fdr.setParameters(param_.copy("fdr:", true));
    try
    {
        fdr.apply(peptides); // computes a q-value (if its params are correct)
    }
    catch (Exception::MissingInformation)
    {
        LOG_FATAL_ERROR << "Tool failed due to missing information (see above)." << std::endl;
        return false;
    }

    // get list of q-values and sort them
    std::vector<double> q_values;
    q_values.reserve(peptides.size());
    for (vector<PeptideIdentification>::iterator it = peptides.begin(); it != peptides.end(); ++it)
    {
        it->assignRanks();
        if (it->getHits().size() > 0)
            q_values.push_back(it->getHits()[0].getScore());
    }
    std::sort(q_values.begin(), q_values.end());


    for (Size i = 0; i < q_value_thresholds.size(); ++i)
    {
        // get position in sorted q-values where cutoff is reached
        std::vector<double>::iterator pos = std::upper_bound(q_values.begin(), q_values.end(), q_value_thresholds[i]);
        Peak1D p;
        p.setMZ(q_value_thresholds[i] * 100);
        p.setIntensity(std::distance(q_values.begin(), pos));
        points.push_back(p);
    }

    return true;
}
int main(int argc, const char** argv)
{
  if (argc < 2) return 1;
  // the path to the data should be given on the command line
  String tutorial_data_path(argv[1]);
  
  IndexedMzMLFileLoader imzml;

  // load data from an indexed MzML file
  OnDiscMSExperiment<> map;
  imzml.load(tutorial_data_path + "/data/Tutorial_FileIO_indexed.mzML", map);
  // Get the first spectrum in memory, do some constant (non-changing) data processing
  MSSpectrum<> s = map.getSpectrum(0);
  std::cout << "There are " << map.getNrSpectra() << " spectra in the input file." << std::endl;
  std::cout << "The first spectrum has " << s.size() << " peaks." << std::endl;

  // store the (unmodified) data in a different file
  imzml.store("Tutorial_FileIO_output.mzML", map);

  return 0;
} //end of main
Int main()
{
  MSSpectrum<> spectrum;
  Peak1D peak;

  for (float mz = 1500.0; mz >= 500; mz -= 100.0)
  {
    peak.setMZ(mz);
    spectrum.push_back(peak);
  }

  spectrum.sortByPosition();

  MSSpectrum<>::Iterator it;
  for (it = spectrum.MZBegin(800.0); it != spectrum.MZEnd(1000.0); ++it)
  {
    cout << it->getMZ() << endl;
  }

  return 0;
} //end of main
  MSChromatogram<> toChromatogram(const MSSpectrum<>& in)
  {
    MSChromatogram<> out;
    for (Size ic = 0; ic < in.size(); ++ic)
    {
      ChromatogramPeak peak;
      peak.setMZ(in[ic].getMZ());
      peak.setIntensity(in[ic].getIntensity());
      out.push_back(peak);
    }
    out.setChromatogramType(ChromatogramSettings::SELECTED_ION_CURRENT_CHROMATOGRAM);

    return out;
  }
Example #8
0
bool IDEvaluationBase::loadCurve(const String& file_name, MSSpectrum<>& points)
{
    if (FileHandler::getType(file_name) != FileTypes::IDXML)
    {
        LOG_ERROR << "The file '" << file_name << "' is not an .idXML file" << std::endl;
        return false;
    }

    std::vector<ProteinIdentification> prot_ids;
    std::vector<PeptideIdentification> pep_ids;
    IdXMLFile().load(file_name, prot_ids, pep_ids);
    String ln = pep_ids[0].getScoreType(); // grab name here, since FDR-calculation will overwrite it with "q-value"
    bool ret = getPoints(pep_ids, q_value_thresholds_, points); // FDR calculation failed?
    points.setMetaValue("search_engine", ln);

    return ret;
}
void getSwathFile(PeakMap& exp, int nr_swathes=32, bool ms1=true)
{
  if (ms1)
  {
    MSSpectrum s;
    s.setMSLevel(1);
    Peak1D p; p.setMZ(100); p.setIntensity(200);
    s.push_back(p);
    exp.addSpectrum(s);
  }
  for (int i = 0; i< nr_swathes; i++)
  {
    MSSpectrum s;
    s.setMSLevel(2);
    std::vector<Precursor> prec(1);
    prec[0].setIsolationWindowLowerOffset(12.5);
    prec[0].setIsolationWindowUpperOffset(12.5);
    prec[0].setMZ(400 + i*25 + 12.5);
    s.setPrecursors(prec);
    Peak1D p; p.setMZ(101 + i); p.setIntensity(201 + i);
    s.push_back(p);
    exp.addSpectrum(s);
  }
}
START_TEST(SignalToNoiseEstimatorMedian, "$Id$")

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

SignalToNoiseEstimatorMedian< >* ptr = nullptr;
SignalToNoiseEstimatorMedian< >* nullPointer = nullptr;
START_SECTION((SignalToNoiseEstimatorMedian()))
	ptr = new SignalToNoiseEstimatorMedian<>;
	TEST_NOT_EQUAL(ptr, nullPointer)
	SignalToNoiseEstimatorMedian<> sne;
END_SECTION

START_SECTION((SignalToNoiseEstimatorMedian& operator=(const SignalToNoiseEstimatorMedian &source)))
  MSSpectrum raw_data;
  SignalToNoiseEstimatorMedian<> sne;
	sne.init(raw_data);
  SignalToNoiseEstimatorMedian<> sne2 = sne;
	NOT_TESTABLE
END_SECTION

START_SECTION((SignalToNoiseEstimatorMedian(const SignalToNoiseEstimatorMedian &source)))
  MSSpectrum raw_data;
  SignalToNoiseEstimatorMedian<> sne;
	sne.init(raw_data);
  SignalToNoiseEstimatorMedian<> sne2(sne);
	NOT_TESTABLE
END_SECTION

START_SECTION((virtual ~SignalToNoiseEstimatorMedian()))
    // Wrong assignment of the mono-isotopic mass for precursors are assumed:
    // - if precursor_mz matches the mz of a non-monoisotopic feature mass trace
    // - and in the case that believe_charge is true: if feature_charge matches the precursor_charge
    // In the case of wrong mono-isotopic assignment several options for correction are available:
    // keep_original will create a copy of the precursor and tandem spectrum for the new mono-isotopic mass trace and retain the original one
    // all_matching_features does this not for only the closest feature but all features in a question
    set<Size> correctToNearestFeature(const FeatureMap& features, PeakMap & exp, double rt_tolerance_s = 0.0, double mz_tolerance = 0.0, bool ppm = true, bool believe_charge = false, bool keep_original = false, bool all_matching_features = false, int max_trace = 2)
    {
      set<Size> corrected_precursors;
      // for each precursor/MS2 find all features that are in the given tolerance window (bounding box + rt tolerances)
      // if believe_charge is set, only add features that match the precursor charge
      map<Size, set<Size> > scan_idx_to_feature_idx;

      for (Size scan = 0; scan != exp.size(); ++scan)
      {
        // skip non-tandem mass spectra
        if (exp[scan].getMSLevel() != 2 || exp[scan].getPrecursors().empty()) continue;

        // extract precusor / MS2 information
        const double pc_mz = exp[scan].getPrecursors()[0].getMZ();
        const double rt = exp[scan].getRT();
        const int pc_charge = exp[scan].getPrecursors()[0].getCharge();

        for (Size f = 0; f != features.size(); ++f)
        {
          // feature  is incompatible if believe_charge is set and charges don't match
          if (believe_charge && features[f].getCharge() != pc_charge) continue;

          // check if precursor/MS2 position overlap with feature
          if (overlaps_(features[f], rt, pc_mz, rt_tolerance_s))
          {
            scan_idx_to_feature_idx[scan].insert(f);
          }
        }
      }

      // filter sets to retain compatible features:
      // if precursor_mz = feature_mz + n * feature_charge (+/- mz_tolerance) a feature is compatible, others are removed from the set
      for (map<Size, set<Size> >::iterator it = scan_idx_to_feature_idx.begin(); it != scan_idx_to_feature_idx.end(); ++it)
      {
        const Size scan = it->first;
        const double pc_mz = exp[scan].getPrecursors()[0].getMZ();
        const double mz_tolerance_da = ppm ? pc_mz * mz_tolerance * 1e-6  : mz_tolerance;

        // Note: This is the "delete while iterating" pattern so mind the pre- and postincrement
        for (set<Size>::iterator sit = it->second.begin(); sit != it->second.end(); )
        {
          if (!compatible_(features[*sit], pc_mz, mz_tolerance_da, max_trace))
          {
            it->second.erase(sit++);
          }
          else
          {
            ++sit;
          }
        }
      }

      // remove entries with no compatible features (empty sets).
      // Note: This is the "delete while iterating" pattern so mind the pre- and postincrement
      for (map<Size, set<Size> >::iterator it = scan_idx_to_feature_idx.begin(); it != scan_idx_to_feature_idx.end(); )
      {
        if (it->second.empty())
        {
          scan_idx_to_feature_idx.erase(it++);
        }
        else
        {
          ++it;
        }
      }

      if (debug_level_ > 0)
      {
        LOG_INFO << "Number of precursors with compatible features: " << scan_idx_to_feature_idx.size() << endl;
      }

      if (!all_matching_features)
      {
        // keep only nearest features in set
        for (map<Size, set<Size> >::iterator it = scan_idx_to_feature_idx.begin(); it != scan_idx_to_feature_idx.end(); ++it)
        {
          const Size scan = it->first;
          const double pc_rt = exp[scan].getRT();

          double min_distance = 1e16;
          set<Size>::iterator best_feature = it->second.begin();

          // determine nearest/best feature
          for (set<Size>::iterator sit = it->second.begin(); sit != it->second.end(); ++sit)
          {
            const double current_distance = fabs(pc_rt - features[*sit].getRT());
            if (current_distance < min_distance)
            {
              min_distance = current_distance;
              best_feature = sit;
            }
          }

          // delete all except the nearest/best feature
          // Note: This is the "delete while iterating" pattern so mind the pre- and postincrement
          for (set<Size>::iterator sit = it->second.begin(); sit != it->second.end(); )
          {
            if (sit != best_feature)
            {
              it->second.erase(sit++);
            }
            else
            {
              ++sit;
            }
          }
        }
      }

      // depending on all_matching_features option, only the nearest or all features are contained in the sets
      // depending on options: move/copy corrected precursor and tandem spectrum
      if (keep_original)
      {
        // duplicate spectra for each feature in set and adapt precursor_mz and precursor_charge to feature_mz and feature_charge
        for (map<Size, set<Size> >::iterator it = scan_idx_to_feature_idx.begin(); it != scan_idx_to_feature_idx.end(); ++it)
        {
          const Size scan = it->first;
          MSSpectrum<> spectrum = exp[scan];
          corrected_precursors.insert(scan);
          for (set<Size>::iterator f_it = it->second.begin(); f_it != it->second.end(); ++f_it)
          {
            spectrum.getPrecursors()[0].setMZ(features[*f_it].getMZ());
            spectrum.getPrecursors()[0].setCharge(features[*f_it].getCharge());
            exp.addSpectrum(spectrum);
          }
        }
      }
      else
      {
        // set precursor_mz and _charge to the feature_mz and _charge
        for (map<Size, set<Size> >::iterator it = scan_idx_to_feature_idx.begin(); it != scan_idx_to_feature_idx.end(); ++it)
        {
          const Size scan = it->first;
          exp[scan].getPrecursors()[0].setMZ(features[*it->second.begin()].getMZ());
          exp[scan].getPrecursors()[0].setCharge(features[*it->second.begin()].getCharge());
          corrected_precursors.insert(scan);
        }
      }
      return corrected_precursors;
    }
Example #12
0
  void PeakPickerHiRes::pick(const MSSpectrum& input, MSSpectrum& output, std::vector<PeakBoundary>& boundaries, bool check_spacings) const
  {
    // copy meta data of the input spectrum
    output.clear(true);
    output.SpectrumSettings::operator=(input);
    output.MetaInfoInterface::operator=(input);
    output.setRT(input.getRT());
    output.setMSLevel(input.getMSLevel());
    output.setName(input.getName());
    output.setType(SpectrumSettings::CENTROID);
    if (report_FWHM_)
    {
      output.getFloatDataArrays().resize(1);
      output.getFloatDataArrays()[0].setName( report_FWHM_as_ppm_ ? "FWHM_ppm" : "FWHM");
    }

    // don't pick a spectrum with less than 5 data points
    if (input.size() < 5) return;

    // if both spacing constraints are disabled, don't check spacings at all:
    if ((spacing_difference_ == std::numeric_limits<double>::infinity()) &&
      (spacing_difference_gap_ == std::numeric_limits<double>::infinity()))
    {
      check_spacings = false;
    }

    // signal-to-noise estimation
    SignalToNoiseEstimatorMedian<MSSpectrum > snt;
    snt.setParameters(param_.copy("SignalToNoise:", true));

    if (signal_to_noise_ > 0.0)
    {
      snt.init(input);
    }

    // find local maxima in profile data
    for (Size i = 2; i < input.size() - 2; ++i)
    {
      double central_peak_mz = input[i].getMZ(), central_peak_int = input[i].getIntensity();
      double left_neighbor_mz = input[i - 1].getMZ(), left_neighbor_int = input[i - 1].getIntensity();
      double right_neighbor_mz = input[i + 1].getMZ(), right_neighbor_int = input[i + 1].getIntensity();

      // do not interpolate when the left or right support is a zero-data-point
      if (std::fabs(left_neighbor_int) < std::numeric_limits<double>::epsilon()) continue;
      if (std::fabs(right_neighbor_int) < std::numeric_limits<double>::epsilon()) continue;

      // MZ spacing sanity checks
      double left_to_central = 0.0, central_to_right = 0.0, min_spacing = 0.0;
      if (check_spacings)
      {
        left_to_central = central_peak_mz - left_neighbor_mz;
        central_to_right = right_neighbor_mz - central_peak_mz;
        min_spacing = (left_to_central < central_to_right) ? left_to_central : central_to_right;
      }

      double act_snt = 0.0, act_snt_l1 = 0.0, act_snt_r1 = 0.0;
      if (signal_to_noise_ > 0.0)
      {
        act_snt = snt.getSignalToNoise(input[i]);
        act_snt_l1 = snt.getSignalToNoise(input[i - 1]);
        act_snt_r1 = snt.getSignalToNoise(input[i + 1]);
      }

      // look for peak cores meeting MZ and intensity/SNT criteria
      if ((central_peak_int > left_neighbor_int) && 
        (central_peak_int > right_neighbor_int) && 
        (act_snt >= signal_to_noise_) && 
        (act_snt_l1 >= signal_to_noise_) && 
        (act_snt_r1 >= signal_to_noise_) &&
        (!check_spacings || 
        ((left_to_central < spacing_difference_ * min_spacing) && 
          (central_to_right < spacing_difference_ * min_spacing))))
      {
        // special case: if a peak core is surrounded by more intense
        // satellite peaks (indicates oscillation rather than
        // real peaks) -> remove

        double act_snt_l2 = 0.0, act_snt_r2 = 0.0;

        if (signal_to_noise_ > 0.0)
        {
          act_snt_l2 = snt.getSignalToNoise(input[i - 2]);
          act_snt_r2 = snt.getSignalToNoise(input[i + 2]);
        }

        // checking signal-to-noise?
        if ((i > 1) &&
          (i + 2 < input.size()) &&
          (left_neighbor_int < input[i - 2].getIntensity()) &&
          (right_neighbor_int < input[i + 2].getIntensity()) &&
          (act_snt_l2 >= signal_to_noise_) &&
          (act_snt_r2 >= signal_to_noise_) &&
          (!check_spacings ||
          ((left_neighbor_mz - input[i - 2].getMZ() < spacing_difference_ * min_spacing) && 
            (input[i + 2].getMZ() - right_neighbor_mz < spacing_difference_ * min_spacing))))
        {
          ++i;
          continue;
        }

        std::map<double, double> peak_raw_data;

        peak_raw_data[central_peak_mz] = central_peak_int;
        peak_raw_data[left_neighbor_mz] = left_neighbor_int;
        peak_raw_data[right_neighbor_mz] = right_neighbor_int;

        // peak core found, now extend it
        // to the left
        Size k = 2;

        bool previous_zero_left(false); // no need to extend peak if previous intensity was zero
        Size missing_left(0);
        Size left_boundary(i - 1); // index of the left boundary for the spline interpolation

        while ((k <= i) && // prevent underflow
          (i - k + 1 > 0) && 
          !previous_zero_left && 
          (missing_left <= missing_) && 
          (input[i - k].getIntensity() <= peak_raw_data.begin()->second) &&
          (!check_spacings || 
          (peak_raw_data.begin()->first - input[i - k].getMZ() < spacing_difference_gap_ * min_spacing)))
        {
          double act_snt_lk = 0.0;

          if (signal_to_noise_ > 0.0)
          {
            act_snt_lk = snt.getSignalToNoise(input[i - k]);
          }

          if ((act_snt_lk >= signal_to_noise_) && 
            (!check_spacings ||
            (peak_raw_data.begin()->first - input[i - k].getMZ() < spacing_difference_ * min_spacing)))
          {
            peak_raw_data[input[i - k].getMZ()] = input[i - k].getIntensity();
          }
          else
          {
            ++missing_left;
            if (missing_left <= missing_)
            {
              peak_raw_data[input[i - k].getMZ()] = input[i - k].getIntensity();
            }
          }

          previous_zero_left = (input[i - k].getIntensity() == 0);
          left_boundary = i - k;
          ++k;
        }

        // to the right
        k = 2;

        bool previous_zero_right(false); // no need to extend peak if previous intensity was zero
        Size missing_right(0);
        Size right_boundary(i+1); // index of the right boundary for the spline interpolation

        while ((i + k < input.size()) && 
          !previous_zero_right && 
          (missing_right <= missing_) && 
          (input[i + k].getIntensity() <= peak_raw_data.rbegin()->second) &&
          (!check_spacings ||
          (input[i + k].getMZ() - peak_raw_data.rbegin()->first < spacing_difference_gap_ * min_spacing)))
        {
          double act_snt_rk = 0.0;

          if (signal_to_noise_ > 0.0)
          {
            act_snt_rk = snt.getSignalToNoise(input[i + k]);
          }

          if ((act_snt_rk >= signal_to_noise_) && 
            (!check_spacings ||
            (input[i + k].getMZ() - peak_raw_data.rbegin()->first < spacing_difference_ * min_spacing)))
          {
            peak_raw_data[input[i + k].getMZ()] = input[i + k].getIntensity();
          }
          else
          {
            ++missing_right;
            if (missing_right <= missing_)
            {
              peak_raw_data[input[i + k].getMZ()] = input[i + k].getIntensity();
            }
          }

          previous_zero_right = (input[i + k].getIntensity() == 0);
          right_boundary = i + k;
          ++k;
        }

        // skip if the minimal number of 3 points for fitting is not reached
        if (peak_raw_data.size() < 3) continue;

        CubicSpline2d peak_spline (peak_raw_data);

        // calculate maximum by evaluating the spline's 1st derivative
        // (bisection method)
        double max_peak_mz = central_peak_mz;
        double max_peak_int = central_peak_int;
        double threshold = 1e-6;
        OpenMS::Math::spline_bisection(peak_spline, left_neighbor_mz, right_neighbor_mz, max_peak_mz, max_peak_int, threshold);

        //
        // compute FWHM
        //
        if (report_FWHM_)
        {
          double fwhm_int = max_peak_int / 2.0;
          threshold = 0.01 * fwhm_int;
          double mz_mid, int_mid; 
          // left:
          double mz_left = peak_raw_data.begin()->first;
          double mz_center = max_peak_mz;
          if (peak_spline.eval(mz_left) > fwhm_int)
          { // the spline ends before half max is reached -- take the leftmost point (probably an underestimation)
            mz_mid = mz_left;
          }
          else
          {
            do 
            {
              mz_mid = mz_left / 2 + mz_center / 2;
              int_mid = peak_spline.eval(mz_mid);
              if (int_mid < fwhm_int)
              {
                mz_left = mz_mid;
              }
              else
              {
                mz_center = mz_mid;
              }
            } while (fabs(int_mid - fwhm_int) > threshold);
          }
          const double fwhm_left_mz = mz_mid;

          // right ...
          double mz_right = peak_raw_data.rbegin()->first;
          mz_center = max_peak_mz;
          if (peak_spline.eval(mz_right) > fwhm_int)
          { // the spline ends before half max is reached -- take the rightmost point (probably an underestimation)
            mz_mid = mz_right;
          }
          else
          {
            do 
            {
              mz_mid = mz_right / 2 + mz_center / 2;
              int_mid = peak_spline.eval(mz_mid);
              if (int_mid < fwhm_int)
              {
                mz_right = mz_mid;
              }
              else
              {
                mz_center = mz_mid;
              }

            } while (fabs(int_mid - fwhm_int) > threshold);
          }
          const double fwhm_right_mz = mz_mid;
          const double fwhm_absolute = fwhm_right_mz - fwhm_left_mz;
          output.getFloatDataArrays()[0].push_back( report_FWHM_as_ppm_ ? fwhm_absolute / max_peak_mz  * 1e6 : fwhm_absolute);
        } // FWHM

          // save picked peak into output spectrum
        Peak1D peak;
        PeakBoundary peak_boundary;
        peak.setMZ(max_peak_mz);
        peak.setIntensity(max_peak_int);
        peak_boundary.mz_min = input[left_boundary].getMZ();
        peak_boundary.mz_max = input[right_boundary].getMZ();
        output.push_back(peak);

        boundaries.push_back(peak_boundary);

        // jump over profile data points that have been considered already
        i = i + k - 1;
      }
    }

    return;
  }
SavitzkyGolayFilter* dsg_nullPointer = 0;
START_SECTION((SavitzkyGolayFilter()))
  dsg_ptr = new SavitzkyGolayFilter;
  TEST_NOT_EQUAL(dsg_ptr, dsg_nullPointer)
END_SECTION

START_SECTION((virtual ~SavitzkyGolayFilter()))
  delete dsg_ptr;
END_SECTION

Param param;
param.setValue("polynomial_order",2);
param.setValue("frame_length",3);

START_SECTION((template < typename PeakType > void filter(MSSpectrum< PeakType > &spectrum)))
  MSSpectrum<Peak1D> spectrum;
  spectrum.resize(5);
  MSSpectrum<Peak1D>::Iterator it = spectrum.begin();
  for (int i=0; i<5; ++i, ++it)
  {
  	it->setIntensity(0.0f);
    if (i==2)
    {
      it->setIntensity(1.0f);
    }
  }

  SavitzkyGolayFilter sgolay;
	sgolay.setParameters(param);
  sgolay.filter(spectrum);
  
c_feature_1.setIntensity(1000.00f);
c_feature_1.setCharge(4);
c_feature_1.setQuality((QualityType) 31.3334);

ConsensusFeature c_feature_2;
c_feature_2.setIntensity(122.01f);
c_feature_2.setCharge(3);
c_feature_2.setQuality((QualityType) 0.002);

ConsensusFeature c_feature_3;
c_feature_3.setIntensity(55.0f);
c_feature_3.setCharge(4);
c_feature_3.setQuality((QualityType) 1.);

///construct some test peaks
MSSpectrum spec;
Peak1D peak;
peak.setIntensity(201.334f);
spec.push_back(peak);
peak.setIntensity(2008.2f);
spec.push_back(peak);
peak.setIntensity(0.001f);
spec.push_back(peak);

MSSpectrum::FloatDataArrays& mdas = spec.getFloatDataArrays();
mdas.resize(3);

mdas[0].setName("test_int");
mdas[0].resize(3);
mdas[0][0] = 5;
mdas[0][1] = 10;
Example #15
0
  /**
  @brief Applies the peak-picking algorithm to a map (MSExperiment). This
  method picks peaks for each scan in the map consecutively. The resulting
  picked peaks are written to the output map.

  Currently we have to give up const-correctness but we know that everything on disc is constant
  */
  void PeakPickerHiRes::pickExperiment(/* const */ OnDiscMSExperiment& input, PeakMap& output, const bool check_spectrum_type) const
  {
    // make sure that output is clear
    output.clear(true);

    // copy experimental settings
    static_cast<ExperimentalSettings &>(output) = *input.getExperimentalSettings();

    Size progress = 0;
    startProgress(0, input.size() + input.getNrChromatograms(), "picking peaks");

    // resize output with respect to input
    output.resize(input.size());

    if (input.getNrSpectra() > 0)
    {
      for (Size scan_idx = 0; scan_idx != input.size(); ++scan_idx)
      {
        if (ms_levels_.empty()) //auto mode
        {
          MSSpectrum s = input[scan_idx];
          s.sortByPosition();

          // determine type of spectral data (profile or centroided)
          SpectrumSettings::SpectrumType spectrumType = s.getType();
          if (spectrumType == SpectrumSettings::CENTROID)
          {
            output[scan_idx] = input[scan_idx];
          }
          else
          {
            pick(s, output[scan_idx]);
          }
        }
        else if (!ListUtils::contains(ms_levels_, input[scan_idx].getMSLevel())) // manual mode
        {
          output[scan_idx] = input[scan_idx];
        }
        else
        {
          MSSpectrum s = input[scan_idx];
          s.sortByPosition();

          // determine type of spectral data (profile or centroided)
          SpectrumSettings::SpectrumType spectrum_type = s.getType();

          if (spectrum_type == SpectrumSettings::CENTROID && check_spectrum_type)
          {
            throw OpenMS::Exception::IllegalArgument(__FILE__, __LINE__, __FUNCTION__, "Error: Centroided data provided but profile spectra expected.");
          }

          pick(s, output[scan_idx]);
        }
        setProgress(++progress);
      }
    }

    for (Size i = 0; i < input.getNrChromatograms(); ++i)
    {
      MSChromatogram chromatogram;
      pick(input.getChromatogram(i), chromatogram);
      output.addChromatogram(chromatogram);
      setProgress(++progress);
    }
    endProgress();

    return;
  }
Example #16
0
  ExitCodes main_(int, const char**)
  {
    //----------------------------------------------------------------
    // load data
    //----------------------------------------------------------------
    StringList in_list = getStringList_("in");
    String out = getStringOption_("out");
    String out_csv = getStringOption_("out_csv");
    String format = getStringOption_("out_type");

    if (out.empty() && out_csv.empty())
    {
      LOG_ERROR << "Neither 'out' nor 'out_csv' were provided. Please assign at least one of them." << std::endl;
      return ILLEGAL_PARAMETERS;
    }

    if (!out.empty() && format == "") // get from filename
    {
      try
      {
        format = out.suffix('.');
      }
      catch (Exception::ElementNotFound& /*e*/)
      {
        format = "nosuffix";
      }
      // check if format is valid:
      if (!ListUtils::contains(out_formats_, format.toLower()))
      {
        LOG_ERROR << "No explicit image output format was provided via 'out_type', and the suffix ('" << format << "') does not resemble a valid type. Please fix one of them." << std::endl;
        return ILLEGAL_PARAMETERS;
      }
    }

    double q_min = getDoubleOption_("q_min");
    double q_max = getDoubleOption_("q_max");
    if (q_min >= q_max)
    {
      LOG_ERROR << "The parameter 'q_min' must be smaller than 'q_max'. Quitting..." << std::endl;
      return ILLEGAL_PARAMETERS;
    }


    IDEvaluationBase* mw = new IDEvaluationBase();
    Param alg_param = mw->getParameters();
    alg_param.insert("", getParam_().copy("algorithm:", true));
    mw->setParameters(alg_param);

    if (!mw->loadFiles(in_list))
    {
      LOG_ERROR << "Tool failed. See above." << std::endl;
      return INCOMPATIBLE_INPUT_DATA;
    }
    mw->setVisibleArea(q_min, q_max);

    if (!out.empty()) // save as image and exit
    {
      String error;
      bool r = mw->exportAsImage(out.toQString(), error, format.toQString());
      if (r) return EXECUTION_OK;
      else
      {
        LOG_ERROR << error << std::endl;
        return ILLEGAL_PARAMETERS;
      }
    }

    if (!out_csv.empty())
    {
      TextFile tf;
      for (Size i = 0; i < mw->getPoints().size(); ++i)
      {
        MSSpectrum s = mw->getPoints()[i];
        StringList sl1;
        StringList sl2;
        for (Size j = 0; j < s.size(); ++j)
        {
          sl1.push_back(s[j].getMZ());
          sl2.push_back(s[j].getIntensity());
        }
        tf.addLine(String("# ") + String(s.getMetaValue("search_engine")));
        tf.addLine(ListUtils::concatenate(sl1, ","));
        tf.addLine(ListUtils::concatenate(sl2, ","));
      }
      tf.store(out_csv);
    }

    delete(mw);
    return EXECUTION_OK;
  }
Example #17
0
using namespace OpenMS;

GaussFilter* dgauss_ptr = nullptr;
GaussFilter* dgauss_nullPointer = nullptr;

START_SECTION((GaussFilter()))
  dgauss_ptr = new GaussFilter;
  TEST_NOT_EQUAL(dgauss_ptr, dgauss_nullPointer)
END_SECTION

START_SECTION((virtual ~GaussFilter()))
    delete dgauss_ptr;
END_SECTION

START_SECTION((template <typename PeakType> void filter(MSSpectrum& spectrum)))
  MSSpectrum spectrum;
  spectrum.resize(5);

  MSSpectrum::Iterator it = spectrum.begin();
  for (Size i=0; i<5; ++i, ++it)
  {
    it->setIntensity(1.0f);
    it->setMZ(500.0+0.2*i);
  }

  GaussFilter gauss;
  Param param;
  param.setValue( "gaussian_width", 1.0);
  gauss.setParameters(param);
  gauss.filter(spectrum);
  it=spectrum.begin();
Example #18
0
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

MSSpectrum* ptr = 0;
MSSpectrum* nullPointer = 0;
START_SECTION((MSSpectrum()))
  ptr = new MSSpectrum();
  TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION

START_SECTION((~MSSpectrum()))
  delete ptr;
END_SECTION

START_SECTION(([EXTRA] MSSpectrum()))
  MSSpectrum tmp;
  Peak1D peak;
  peak.getPosition()[0] = 47.11;
  tmp.push_back(peak);
  TEST_EQUAL(tmp.size(),1);
  TEST_REAL_SIMILAR(tmp[0].getMZ(),47.11);
END_SECTION

/////////////////////////////////////////////////////////////
// Member accessors

START_SECTION((UInt getMSLevel() const))
  MSSpectrum spec;
  TEST_EQUAL(spec.getMSLevel(),1)
END_SECTION
Example #19
0
PeakTypeEstimator* ptr = nullptr;
PeakTypeEstimator* nullPointer = nullptr;

START_SECTION(([EXTRA]PeakTypeEstimator()))
	ptr = new PeakTypeEstimator();
	TEST_NOT_EQUAL(ptr, nullPointer)
END_SECTION

START_SECTION(([EXTRA] ~PeakTypeEstimator()))
	delete ptr;
END_SECTION

START_SECTION((template<typename PeakConstIterator> SpectrumSettings::SpectrumType estimateType(const PeakConstIterator& begin, const PeakConstIterator& end) const))
	DTAFile file;
	MSSpectrum spec;
	// raw data (with zeros)
	file.load(OPENMS_GET_TEST_DATA_PATH("PeakTypeEstimator_raw.dta"), spec);
  TEST_EQUAL(PeakTypeEstimator::estimateType(spec.begin(), spec.end()), SpectrumSettings::PROFILE);
  // TOF raw data (without zeros)
	file.load(OPENMS_GET_TEST_DATA_PATH("PeakTypeEstimator_rawTOF.dta"), spec);
  TEST_EQUAL(PeakTypeEstimator::estimateType(spec.begin(), spec.end()), SpectrumSettings::PROFILE);
  // peak data
	file.load(OPENMS_GET_TEST_DATA_PATH("PeakTypeEstimator_peak.dta"), spec);
  TEST_EQUAL(PeakTypeEstimator::estimateType(spec.begin(), spec.end()), SpectrumSettings::CENTROID);
  // too few data points
  spec.resize(4);
	TEST_EQUAL(PeakTypeEstimator::estimateType(spec.begin(), spec.end()), SpectrumSettings::UNKNOWN);
END_SECTION

/////////////////////////////////////////////////////////////
Example #20
0
 bool MSSpectrum::RTLess::operator()(const MSSpectrum &a, const MSSpectrum &b) const {
   return a.getRT() < b.getRT();
 }