OpenMS  2.4.0
SpectraMerger.h
Go to the documentation of this file.
1 // --------------------------------------------------------------------------
2 // OpenMS -- Open-Source Mass Spectrometry
3 // --------------------------------------------------------------------------
4 // Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
5 // ETH Zurich, and Freie Universitaet Berlin 2002-2018.
6 //
7 // This software is released under a three-clause BSD license:
8 // * Redistributions of source code must retain the above copyright
9 // notice, this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above copyright
11 // notice, this list of conditions and the following disclaimer in the
12 // documentation and/or other materials provided with the distribution.
13 // * Neither the name of any author or any participating institution
14 // may be used to endorse or promote products derived from this software
15 // without specific prior written permission.
16 // For a full list of authors, refer to the file AUTHORS.
17 // --------------------------------------------------------------------------
18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19 // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21 // ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING
22 // INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
23 // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24 // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
25 // OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
26 // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
27 // OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
28 // ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 //
30 // --------------------------------------------------------------------------
31 // $Maintainer: Chris Bielow $
32 // $Authors: Chris Bielow, Andreas Bertsch, Lars Nilse $
33 // --------------------------------------------------------------------------
34 //
35 #pragma once
36 
49 #include <vector>
50 
51 namespace OpenMS
52 {
53 
62  class OPENMS_DLLAPI SpectraMerger :
63  public DefaultParamHandler, public ProgressLogger
64  {
65 
66 protected:
67 
68  /* Determine distance between two spectra
69 
70  Distance is determined as
71 
72  (d_rt/rt_max_ + d_mz/mz_max_) / 2
73 
74  */
76  public DefaultParamHandler
77  {
78 public:
80  DefaultParamHandler("SpectraDistance")
81  {
82  defaults_.setValue("rt_tolerance", 10.0, "Maximal RT distance (in [s]) for two spectra's precursors.");
83  defaults_.setValue("mz_tolerance", 1.0, "Maximal m/z distance (in Da) for two spectra's precursors.");
84  defaultsToParam_();
85  }
86 
87  void updateMembers_() override
88  {
89  rt_max_ = (double) param_.getValue("rt_tolerance");
90  mz_max_ = (double) param_.getValue("mz_tolerance");
91 
92  return;
93  }
94 
95  double getSimilarity(const double d_rt, const double d_mz) const
96  {
97  // 1 - distance
98  return 1 - ((d_rt / rt_max_ + d_mz / mz_max_) / 2);
99  }
100 
101  // measure of SIMILARITY (not distance, i.e. 1-distance)!!
102  double operator()(const BaseFeature& first, const BaseFeature& second) const
103  {
104  // get RT distance:
105  double d_rt = fabs(first.getRT() - second.getRT());
106  double d_mz = fabs(first.getMZ() - second.getMZ());
107 
108  if (d_rt > rt_max_ || d_mz > mz_max_)
109  {
110  return 0;
111  }
112 
113  // calculate similarity (0-1):
114  double sim = getSimilarity(d_rt, d_mz);
115 
116  return sim;
117  }
118 
119 protected:
120  double rt_max_;
121  double mz_max_;
122 
123  }; // end of SpectraDistance
124 
125 public:
126 
129 
132 
133  // @name Constructors and Destructors
134  // @{
136  SpectraMerger();
137 
139  SpectraMerger(const SpectraMerger& source);
140 
142  ~SpectraMerger() override;
143  // @}
144 
145  // @name Operators
146  // @{
148  SpectraMerger& operator=(const SpectraMerger& source);
149  // @}
150 
151  // @name Merging functions
152  // @{
154  template <typename MapType>
156  {
157  IntList ms_levels = param_.getValue("block_method:ms_levels");
158  Int rt_block_size(param_.getValue("block_method:rt_block_size"));
159  double rt_max_length = (param_.getValue("block_method:rt_max_length"));
160 
161  if (rt_max_length == 0) // no rt restriction set?
162  {
163  rt_max_length = (std::numeric_limits<double>::max)(); // set max rt span to very large value
164  }
165 
166  for (IntList::iterator it_mslevel = ms_levels.begin(); it_mslevel < ms_levels.end(); ++it_mslevel)
167  {
168  MergeBlocks spectra_to_merge;
169  Size idx_block(0);
170  SignedSize block_size_count(rt_block_size + 1);
171  Size idx_spectrum(0);
172  for (typename MapType::const_iterator it1 = exp.begin(); it1 != exp.end(); ++it1)
173  {
174  if (Int(it1->getMSLevel()) == *it_mslevel)
175  {
176  // block full if it contains a maximum number of scans or if maximum rt length spanned
177  if (++block_size_count >= rt_block_size ||
178  exp[idx_spectrum].getRT() - exp[idx_block].getRT() > rt_max_length)
179  {
180  block_size_count = 0;
181  idx_block = idx_spectrum;
182  }
183  else
184  {
185  spectra_to_merge[idx_block].push_back(idx_spectrum);
186  }
187  }
188 
189  ++idx_spectrum;
190  }
191  // check if last block had sacrifice spectra
192  if (block_size_count == 0) //block just got initialized
193  {
194  spectra_to_merge[idx_block] = std::vector<Size>();
195  }
196 
197  // merge spectra, remove all old MS spectra and add new consensus spectra
198  mergeSpectra_(exp, spectra_to_merge, *it_mslevel);
199  }
200 
201  exp.sortSpectra();
202 
203  return;
204  }
205 
207  template <typename MapType>
209  {
210 
211  // convert spectra's precursors to clusterizable data
212  Size data_size;
213  std::vector<BinaryTreeNode> tree;
214  Map<Size, Size> index_mapping;
215  // local scope to save memory - we do not need the clustering stuff later
216  {
217  std::vector<BaseFeature> data;
218 
219  for (Size i = 0; i < exp.size(); ++i)
220  {
221  if (exp[i].getMSLevel() != 2)
222  {
223  continue;
224  }
225 
226  // remember which index in distance data ==> experiment index
227  index_mapping[data.size()] = i;
228 
229  // make cluster element
230  BaseFeature bf;
231  bf.setRT(exp[i].getRT());
232  std::vector<Precursor> pcs = exp[i].getPrecursors();
233  if (pcs.empty())
234  {
235  throw Exception::MissingInformation(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Scan #") + String(i) + " does not contain any precursor information! Unable to cluster!");
236  }
237  if (pcs.size() > 1)
238  {
239  LOG_WARN << "More than one precursor found. Using first one!" << std::endl;
240  }
241  bf.setMZ(pcs[0].getMZ());
242  data.push_back(bf);
243  }
244  data_size = data.size();
245 
246  SpectraDistance_ llc;
247  llc.setParameters(param_.copy("precursor_method:", true));
248  SingleLinkage sl;
249  DistanceMatrix<float> dist; // will be filled
251 
252  //ch.setThreshold(0.99);
253  // clustering ; threshold is implicitly at 1.0, i.e. distances of 1.0 (== similarity 0) will not be clustered
254  ch.cluster<BaseFeature, SpectraDistance_>(data, llc, sl, tree, dist);
255  }
256 
257  // extract the clusters
258  ClusterAnalyzer ca;
259  std::vector<std::vector<Size> > clusters;
260  // count number of real tree nodes (not the -1 ones):
261  Size node_count = 0;
262  for (Size ii = 0; ii < tree.size(); ++ii)
263  {
264  if (tree[ii].distance >= 1)
265  {
266  tree[ii].distance = -1; // manually set to disconnect, as SingleLinkage does not support it
267  }
268  if (tree[ii].distance != -1)
269  {
270  ++node_count;
271  }
272  }
273  ca.cut(data_size - node_count, tree, clusters);
274 
275  //std::cerr << "Treesize: " << (tree.size()+1) << " #clusters: " << clusters.size() << std::endl;
276  //std::cerr << "tree:\n" << ca.newickTree(tree, true) << "\n";
277 
278  // convert to blocks
279  MergeBlocks spectra_to_merge;
280 
281  for (Size i_outer = 0; i_outer < clusters.size(); ++i_outer)
282  {
283  if (clusters[i_outer].size() <= 1)
284  {
285  continue;
286  }
287  // init block with first cluster element
288  Size cl_index0 = clusters[i_outer][0];
289  spectra_to_merge[index_mapping[cl_index0]] = std::vector<Size>();
290  // add all other elements
291  for (Size i_inner = 1; i_inner < clusters[i_outer].size(); ++i_inner)
292  {
293  Size cl_index = clusters[i_outer][i_inner];
294  spectra_to_merge[index_mapping[cl_index0]].push_back(index_mapping[cl_index]);
295  }
296  }
297 
298  // do it
299  mergeSpectra_(exp, spectra_to_merge, 2);
300 
301  exp.sortSpectra();
302 
303  return;
304  }
305 
312  template <typename MapType>
313  void average(MapType& exp, String average_type)
314  {
315  // MS level to be averaged
316  int ms_level = param_.getValue("average_gaussian:ms_level");
317  if (average_type == "tophat")
318  {
319  ms_level = param_.getValue("average_tophat:ms_level");
320  }
321 
322  // spectrum type (profile, centroid or automatic)
323  String spectrum_type = param_.getValue("average_gaussian:spectrum_type");
324  if (average_type == "tophat")
325  {
326  spectrum_type = param_.getValue("average_tophat:spectrum_type");
327  }
328 
329  // parameters for Gaussian averaging
330  double fwhm(param_.getValue("average_gaussian:rt_FWHM"));
331  double factor = -4 * log(2.0) / (fwhm * fwhm); // numerical factor within Gaussian
332  double cutoff(param_.getValue("average_gaussian:cutoff"));
333 
334  // parameters for Top-Hat averaging
335  bool unit(param_.getValue("average_tophat:rt_unit") == "scans"); // true if RT unit is 'scans', false if RT unit is 'seconds'
336  double range(param_.getValue("average_tophat:rt_range")); // range of spectra to be averaged over
337  double range_seconds = range / 2; // max. +/- <range_seconds> seconds from master spectrum
338  int range_scans = range;
339  if ((range_scans % 2) == 0)
340  {
341  ++range_scans;
342  }
343  range_scans = (range_scans - 1) / 2; // max. +/- <range_scans> scans from master spectrum
344 
345  AverageBlocks spectra_to_average_over;
346 
347  // loop over RT
348  int n(0); // spectrum index
349  for (typename MapType::const_iterator it_rt = exp.begin(); it_rt != exp.end(); ++it_rt)
350  {
351  if (Int(it_rt->getMSLevel()) == ms_level)
352  {
353  int m; // spectrum index
354  int steps;
355  bool terminate_now;
356  typename MapType::const_iterator it_rt_2;
357 
358  // go forward (start at next downstream spectrum; the current spectrum will be covered when looking backwards)
359  steps = 0;
360  m = n + 1;
361  it_rt_2 = it_rt + 1;
362  terminate_now = false;
363  while (it_rt_2 != exp.end() && !terminate_now)
364  {
365  if (Int(it_rt_2->getMSLevel()) == ms_level)
366  {
367  double weight = 1;
368  if (average_type == "gaussian")
369  {
370  weight = std::exp(factor * pow(it_rt_2->getRT() - it_rt->getRT(), 2));
371  }
372  std::pair<Size, double> p(m, weight);
373  spectra_to_average_over[n].push_back(p);
374  ++steps;
375  }
376  if (average_type == "gaussian")
377  {
378  // Gaussian
379  terminate_now = std::exp(factor * pow(it_rt_2->getRT() - it_rt->getRT(), 2)) < cutoff;
380  }
381  else if (unit)
382  {
383  // Top-Hat with RT unit = scans
384  terminate_now = (steps > range_scans);
385  }
386  else
387  {
388  // Top-Hat with RT unit = seconds
389  terminate_now = (std::abs(it_rt_2->getRT() - it_rt->getRT()) > range_seconds);
390  }
391  ++m;
392  ++it_rt_2;
393  }
394 
395  // go backward
396  steps = 0;
397  m = n;
398  it_rt_2 = it_rt;
399  terminate_now = false;
400  while (it_rt_2 != exp.begin() && !terminate_now)
401  {
402  if (Int(it_rt_2->getMSLevel()) == ms_level)
403  {
404  double weight = 1;
405  if (average_type == "gaussian")
406  {
407  weight = std::exp(factor * pow(it_rt_2->getRT() - it_rt->getRT(), 2));
408  }
409  std::pair<Size, double> p(m, weight);
410  spectra_to_average_over[n].push_back(p);
411  ++steps;
412  }
413  if (average_type == "gaussian")
414  {
415  // Gaussian
416  terminate_now = std::exp(factor * pow(it_rt_2->getRT() - it_rt->getRT(), 2)) < cutoff;
417  }
418  else if (unit)
419  {
420  // Top-Hat with RT unit = scans
421  terminate_now = (steps > range_scans);
422  }
423  else
424  {
425  // Top-Hat with RT unit = seconds
426  terminate_now = (std::abs(it_rt_2->getRT() - it_rt->getRT()) > range_seconds);
427  }
428  --m;
429  --it_rt_2;
430  }
431 
432  }
433  ++n;
434  }
435 
436  // normalize weights
437  for (AverageBlocks::Iterator it = spectra_to_average_over.begin(); it != spectra_to_average_over.end(); ++it)
438  {
439  double sum(0.0);
440  for (std::vector<std::pair<Size, double> >::const_iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2)
441  {
442  sum += it2->second;
443  }
444 
445  for (std::vector<std::pair<Size, double> >::iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2)
446  {
447  (*it2).second /= sum;
448  }
449  }
450 
451  // determine type of spectral data (profile or centroided)
453  if (spectrum_type == "automatic")
454  {
455  Size idx = spectra_to_average_over.begin()->first; // index of first spectrum to be averaged
456  type = exp[idx].getType(true);
457  }
458  else if (spectrum_type == "profile")
459  {
461  }
462  else if (spectrum_type == "centroid")
463  {
465  }
466 
467  // generate new spectra
468  if (type == SpectrumSettings::CENTROID)
469  {
470  averageCentroidSpectra_(exp, spectra_to_average_over, ms_level);
471  }
472  else
473  {
474  averageProfileSpectra_(exp, spectra_to_average_over, ms_level);
475  }
476 
477  exp.sortSpectra();
478 
479  return;
480  }
481 
482  // @}
483 
484 protected:
485 
496  template <typename MapType>
497  void mergeSpectra_(MapType& exp, const MergeBlocks& spectra_to_merge, const UInt ms_level)
498  {
499  double mz_binning_width(param_.getValue("mz_binning_width"));
500  String mz_binning_unit(param_.getValue("mz_binning_width_unit"));
501 
502  // merge spectra
503  MapType merged_spectra;
504 
505  Map<Size, Size> cluster_sizes;
506  std::set<Size> merged_indices;
507 
508  // set up alignment
509  SpectrumAlignment sas;
510  Param p;
511  p.setValue("tolerance", mz_binning_width);
512  if (!(mz_binning_unit == "Da" || mz_binning_unit == "ppm"))
513  {
514  throw Exception::IllegalSelfOperation(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION); // sanity check
515  }
516 
517  p.setValue("is_relative_tolerance", mz_binning_unit == "Da" ? "false" : "true");
518  sas.setParameters(p);
519  std::vector<std::pair<Size, Size> > alignment;
520 
521  Size count_peaks_aligned(0);
522  Size count_peaks_overall(0);
523 
524  // each BLOCK
525  for (auto it = spectra_to_merge.begin(); it != spectra_to_merge.end(); ++it)
526  {
527  ++cluster_sizes[it->second.size() + 1]; // for stats
528 
529  typename MapType::SpectrumType consensus_spec = exp[it->first];
530  consensus_spec.setMSLevel(ms_level);
531 
532  //consensus_spec.unify(exp[it->first]); // append meta info
533  merged_indices.insert(it->first);
534 
535  //typename MapType::SpectrumType all_peaks = exp[it->first];
536  double rt_average = consensus_spec.getRT();
537  double precursor_mz_average = 0.0;
538  Size precursor_count(0);
539  if (!consensus_spec.getPrecursors().empty())
540  {
541  precursor_mz_average = consensus_spec.getPrecursors()[0].getMZ();
542  ++precursor_count;
543  }
544 
545  count_peaks_overall += consensus_spec.size();
546 
547  // block elements
548  for (auto sit = it->second.begin(); sit != it->second.end(); ++sit)
549  {
550  consensus_spec.unify(exp[*sit]); // append meta info
551  merged_indices.insert(*sit);
552 
553  rt_average += exp[*sit].getRT();
554  if (ms_level >= 2 && exp[*sit].getPrecursors().size() > 0)
555  {
556  precursor_mz_average += exp[*sit].getPrecursors()[0].getMZ();
557  ++precursor_count;
558  }
559 
560  // merge data points
561  sas.getSpectrumAlignment(alignment, consensus_spec, exp[*sit]);
562  //std::cerr << "alignment of " << it->first << " with " << *sit << " yielded " << alignment.size() << " common peaks!\n";
563  count_peaks_aligned += alignment.size();
564  count_peaks_overall += exp[*sit].size();
565 
566  Size align_index(0);
567  Size spec_b_index(0);
568 
569  // sanity check for number of peaks
570  Size spec_a = consensus_spec.size(), spec_b = exp[*sit].size(), align_size = alignment.size();
571  for (auto pit = exp[*sit].begin(); pit != exp[*sit].end(); ++pit)
572  {
573  if (alignment.size() == 0 || alignment[align_index].second != spec_b_index)
574  // ... add unaligned peak
575  {
576  consensus_spec.push_back(*pit);
577  }
578  // or add aligned peak height to ALL corresponding existing peaks
579  else
580  {
581  Size counter(0);
582  Size copy_of_align_index(align_index);
583 
584  while (alignment.size() > 0 &&
585  copy_of_align_index < alignment.size() &&
586  alignment[copy_of_align_index].second == spec_b_index)
587  {
588  ++copy_of_align_index;
589  ++counter;
590  } // Count the number of peaks in a which correspond to a single b peak.
591 
592  while (alignment.size() > 0 &&
593  align_index < alignment.size() &&
594  alignment[align_index].second == spec_b_index)
595  {
596  consensus_spec[alignment[align_index].first].setIntensity(consensus_spec[alignment[align_index].first].getIntensity() +
597  (pit->getIntensity() / (double)counter)); // add the intensity divided by the number of peaks
598  ++align_index; // this aligned peak was explained, wait for next aligned peak ...
599  if (align_index == alignment.size())
600  {
601  alignment.clear(); // end reached -> avoid going into this block again
602  }
603  }
604  align_size = align_size + 1 - counter; //Decrease align_size by number of
605  }
606  ++spec_b_index;
607  }
608  consensus_spec.sortByPosition(); // sort, otherwise next alignment will fail
609  if (spec_a + spec_b - align_size != consensus_spec.size())
610  {
611  LOG_WARN << "wrong number of features after merge. Expected: " << spec_a + spec_b - align_size << " got: " << consensus_spec.size() << "\n";
612  }
613  }
614  rt_average /= it->second.size() + 1;
615  consensus_spec.setRT(rt_average);
616 
617  if (ms_level >= 2)
618  {
619  if (precursor_count)
620  {
621  precursor_mz_average /= precursor_count;
622  }
623  std::vector<Precursor> pcs = consensus_spec.getPrecursors();
624  //if (pcs.size()>1) LOG_WARN << "Removing excessive precursors - leaving only one per MS2 spectrum.\n";
625  pcs.resize(1);
626  pcs[0].setMZ(precursor_mz_average);
627  consensus_spec.setPrecursors(pcs);
628  }
629 
630  if (consensus_spec.empty())
631  {
632  continue;
633  }
634  else
635  {
636  merged_spectra.addSpectrum(consensus_spec);
637  }
638  }
639 
640  LOG_INFO << "Cluster sizes:\n";
641  for (Map<Size, Size>::const_iterator it = cluster_sizes.begin(); it != cluster_sizes.end(); ++it)
642  {
643  LOG_INFO << " size " << it->first << ": " << it->second << "x\n";
644  }
645 
646  char buffer[200];
647  sprintf(buffer, "%d/%d (%.2f %%) of blocked spectra", (int)count_peaks_aligned,
648  (int)count_peaks_overall, float(count_peaks_aligned) / float(count_peaks_overall) * 100.);
649  LOG_INFO << "Number of merged peaks: " << String(buffer) << "\n";
650 
651  // remove all spectra that were within a cluster
652  typename MapType::SpectrumType empty_spec;
653  MapType exp_tmp;
654  for (Size i = 0; i < exp.size(); ++i)
655  {
656  if (merged_indices.count(i) == 0) // save unclustered ones
657  {
658  exp_tmp.addSpectrum(exp[i]);
659  exp[i] = empty_spec;
660  }
661  }
662 
663  //typedef std::vector<typename MapType::SpectrumType> Base;
664  //exp.Base::operator=(exp_tmp);
665  exp.clear(false);
666  exp.getSpectra().insert(exp.end(), exp_tmp.begin(), exp_tmp.end());
667 
668  // exp.erase(remove_if(exp.begin(), exp.end(), InMSLevelRange<typename MapType::SpectrumType>(ListUtils::create<int>(String(ms_level)), false)), exp.end());
669 
670  // ... and add consensus spectra
671  exp.getSpectra().insert(exp.end(), merged_spectra.begin(), merged_spectra.end());
672 
673  }
674 
695  template <typename MapType>
696  void averageProfileSpectra_(MapType& exp, const AverageBlocks& spectra_to_average_over, const UInt ms_level)
697  {
698  MapType exp_tmp; // temporary experiment for averaged spectra
699 
700  double mz_binning_width(param_.getValue("mz_binning_width"));
701  String mz_binning_unit(param_.getValue("mz_binning_width_unit"));
702 
703  unsigned progress = 0;
704  std::stringstream progress_message;
705  progress_message << "averaging profile spectra of MS level " << ms_level;
706  startProgress(0, spectra_to_average_over.size(), progress_message.str());
707 
708  // loop over blocks
709  for (AverageBlocks::ConstIterator it = spectra_to_average_over.begin(); it != spectra_to_average_over.end(); ++it)
710  {
711  setProgress(++progress);
712 
713  // loop over spectra in blocks
714  std::vector<double> mz_positions_all; // m/z positions from all spectra
715  for (std::vector<std::pair<Size, double> >::const_iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2)
716  {
717  // loop over m/z positions
718  for (typename MapType::SpectrumType::ConstIterator it_mz = exp[it2->first].begin(); it_mz < exp[it2->first].end(); ++it_mz)
719  {
720  mz_positions_all.push_back(it_mz->getMZ());
721  }
722  }
723 
724  sort(mz_positions_all.begin(), mz_positions_all.end());
725 
726  std::vector<double> mz_positions; // positions at which the averaged spectrum should be evaluated
727  std::vector<double> intensities;
728  double last_mz = std::numeric_limits<double>::min(); // last m/z position pushed through from mz_position to mz_position_2
729  double delta_mz(mz_binning_width); // for m/z unit Da
730  for (std::vector<double>::iterator it_mz = mz_positions_all.begin(); it_mz < mz_positions_all.end(); ++it_mz)
731  {
732  if (mz_binning_unit == "ppm")
733  {
734  delta_mz = mz_binning_width * (*it_mz) / 1000000;
735  }
736 
737  if (((*it_mz) - last_mz) > delta_mz)
738  {
739  mz_positions.push_back(*it_mz);
740  intensities.push_back(0.0);
741  last_mz = *it_mz;
742  }
743  }
744 
745  // loop over spectra in blocks
746  for (std::vector<std::pair<Size, double> >::const_iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2)
747  {
748  SplineInterpolatedPeaks spline(exp[it2->first]);
750 
751  // loop over m/z positions
752  for (Size i = 0; i < mz_positions.size(); ++i)
753  {
754  if ((spline.getPosMin() < mz_positions[i]) && (mz_positions[i] < spline.getPosMax()))
755  {
756  intensities[i] += nav.eval(mz_positions[i]) * (it2->second); // spline-interpolated intensity * weight
757  }
758  }
759  }
760 
761  // update spectrum
762  typename MapType::SpectrumType average_spec = exp[it->first];
763  average_spec.clear(false); // Precursors are part of the meta data, which are not deleted.
764  //average_spec.setMSLevel(ms_level);
765 
766  // refill spectrum
767  for (Size i = 0; i < mz_positions.size(); ++i)
768  {
769  typename MapType::PeakType peak;
770  peak.setMZ(mz_positions[i]);
771  peak.setIntensity(intensities[i]);
772  average_spec.push_back(peak);
773  }
774 
775  // store spectrum temporarily
776  exp_tmp.addSpectrum(average_spec);
777  }
778 
779  endProgress();
780 
781  // loop over blocks
782  int n(0);
783  //typename MapType::SpectrumType empty_spec;
784  for (AverageBlocks::ConstIterator it = spectra_to_average_over.begin(); it != spectra_to_average_over.end(); ++it)
785  {
786  exp[it->first] = exp_tmp[n];
787  //exp_tmp[n] = empty_spec;
788  ++n;
789  }
790 
791  }
792 
808  template <typename MapType>
809  void averageCentroidSpectra_(MapType& exp, const AverageBlocks& spectra_to_average_over, const UInt ms_level)
810  {
811  MapType exp_tmp; // temporary experiment for averaged spectra
812 
813  double mz_binning_width(param_.getValue("mz_binning_width"));
814  String mz_binning_unit(param_.getValue("mz_binning_width_unit"));
815 
816  unsigned progress = 0;
817  ProgressLogger logger;
818  std::stringstream progress_message;
819  progress_message << "averaging centroid spectra of MS level " << ms_level;
820  logger.startProgress(0, spectra_to_average_over.size(), progress_message.str());
821 
822  // loop over blocks
823  for (AverageBlocks::ConstIterator it = spectra_to_average_over.begin(); it != spectra_to_average_over.end(); ++it)
824  {
825  logger.setProgress(++progress);
826 
827  // collect peaks from all spectra
828  // loop over spectra in blocks
829  std::vector<std::pair<double, double> > mz_intensity_all; // m/z positions and peak intensities from all spectra
830  for (std::vector<std::pair<Size, double> >::const_iterator it2 = it->second.begin(); it2 != it->second.end(); ++it2)
831  {
832  // loop over m/z positions
833  for (typename MapType::SpectrumType::ConstIterator it_mz = exp[it2->first].begin(); it_mz < exp[it2->first].end(); ++it_mz)
834  {
835  std::pair<double, double> mz_intensity(it_mz->getMZ(), (it_mz->getIntensity() * it2->second)); // m/z, intensity * weight
836  mz_intensity_all.push_back(mz_intensity);
837  }
838  }
839 
840  sort(mz_intensity_all.begin(), mz_intensity_all.end(), SpectraMerger::compareByFirst);
841 
842  // generate new spectrum
843  std::vector<double> mz_new;
844  std::vector<double> intensity_new;
845  double last_mz = std::numeric_limits<double>::min();
846  double delta_mz = mz_binning_width;
847  double sum_mz(0);
848  double sum_intensity(0);
849  Size count(0);
850  for (std::vector<std::pair<double, double> >::const_iterator it_mz = mz_intensity_all.begin(); it_mz != mz_intensity_all.end(); ++it_mz)
851  {
852  if (mz_binning_unit == "ppm")
853  {
854  delta_mz = mz_binning_width * (it_mz->first) / 1000000;
855  }
856 
857  if (((it_mz->first - last_mz) > delta_mz) && (count > 0))
858  {
859  mz_new.push_back(sum_mz / count);
860  intensity_new.push_back(sum_intensity); // intensities already weighted
861 
862  sum_mz = 0;
863  sum_intensity = 0;
864 
865  last_mz = it_mz->first;
866  count = 0;
867  }
868 
869  sum_mz += it_mz->first;
870  sum_intensity += it_mz->second;
871  ++count;
872  }
873  if (count > 0)
874  {
875  mz_new.push_back(sum_mz / count);
876  intensity_new.push_back(sum_intensity); // intensities already weighted
877  }
878 
879  // update spectrum
880  typename MapType::SpectrumType average_spec = exp[it->first];
881  average_spec.clear(false); // Precursors are part of the meta data, which are not deleted.
882  //average_spec.setMSLevel(ms_level);
883 
884  // refill spectrum
885  for (Size i = 0; i < mz_new.size(); ++i)
886  {
887  typename MapType::PeakType peak;
888  peak.setMZ(mz_new[i]);
889  peak.setIntensity(intensity_new[i]);
890  average_spec.push_back(peak);
891  }
892 
893  // store spectrum temporarily
894  exp_tmp.addSpectrum(average_spec);
895 
896  }
897 
898  logger.endProgress();
899 
900  // loop over blocks
901  int n(0);
902  for (AverageBlocks::ConstIterator it = spectra_to_average_over.begin(); it != spectra_to_average_over.end(); ++it)
903  {
904  exp[it->first] = exp_tmp[n];
905  ++n;
906  }
907 
908  }
909 
913  bool static compareByFirst(std::pair<double, double> i, std::pair<double, double> j)
914  {
915  return i.first < j.first;
916  }
917 
918  };
919 
920 }
Map< Size, std::vector< std::pair< Size, double > > > AverageBlocks
blocks of spectra (master-spectrum index to update to spectra to average over)
Definition: SpectraMerger.h:131
void setValue(const String &key, const DataValue &value, const String &description="", const StringList &tags=StringList())
Sets a value.
A more convenient string class.
Definition: String.h:58
Base::iterator Iterator
Definition: Map.h:80
static double sum(IteratorType begin, IteratorType end)
Calculates the sum of a range of values.
Definition: StatisticFunctions.h:120
void setMZ(CoordinateType coordinate)
Mutable access to the m/z coordinate (index 1)
Definition: Peak2D.h:202
#define LOG_INFO
Macro if a information, e.g. a status should be reported.
Definition: LogStream.h:456
void sortByPosition()
Lexicographically sorts the peaks by their position.
void addSpectrum(const MSSpectrum &spectrum)
adds a spectrum to the list
Bundles analyzing tools for a clustering (given as sequence of BinaryTreeNode&#39;s)
Definition: ClusterAnalyzer.h:51
void endProgress() const
Ends the progress display.
SpectrumType
Spectrum peak type.
Definition: SpectrumSettings.h:70
static bool compareByFirst(std::pair< double, double > i, std::pair< double, double > j)
comparator for sorting peaks (m/z, intensity)
Definition: SpectraMerger.h:913
void mergeSpectra_(MapType &exp, const MergeBlocks &spectra_to_merge, const UInt ms_level)
merges blocks of spectra of a certain level
Definition: SpectraMerger.h:497
A two-dimensional distance matrix, similar to OpenMS::Matrix.
Definition: DistanceMatrix.h:67
unsigned int UInt
Unsigned integer type.
Definition: Types.h:94
SplineInterpolatedPeaks::Navigator getNavigator(double scaling=0.7)
returns an iterator for access of spline packages
profile data
Definition: SpectrumSettings.h:74
void mergeSpectraBlockWise(MapType &exp)
Definition: SpectraMerger.h:155
Iterator begin()
Definition: MSExperiment.h:157
std::vector< Int > IntList
Vector of signed integers.
Definition: ListUtils.h:58
Merges blocks of MS or MS2 spectra.
Definition: SpectraMerger.h:62
ptrdiff_t SignedSize
Signed Size type e.g. used as pointer difference.
Definition: Types.h:134
void sortSpectra(bool sort_mz=true)
Sorts the data points by retention time.
Base::const_iterator const_iterator
Definition: MSExperiment.h:125
Size size() const
Definition: MSExperiment.h:127
Main OpenMS namespace.
Definition: FeatureDeconvolution.h:46
void setMZ(CoordinateType mz)
Mutable access to m/z.
Definition: Peak1D.h:119
void setIntensity(IntensityType intensity)
Mutable access to the data point intensity (height)
Definition: Peak1D.h:110
void setParameters(const Param &param)
Sets the parameters.
SpectraDistance_()
Definition: SpectraMerger.h:79
A basic LC-MS feature.
Definition: BaseFeature.h:55
#define LOG_WARN
Macro if a warning, a piece of information which should be read by the user, should be logged...
Definition: LogStream.h:452
Iterator end()
Definition: MSExperiment.h:167
void updateMembers_() override
This method is used to update extra member variables at the end of the setParameters() method...
Definition: SpectraMerger.h:87
The representation of a 1D spectrum.
Definition: MSSpectrum.h:66
void setRT(CoordinateType coordinate)
Mutable access to the RT coordinate (index 0)
Definition: Peak2D.h:214
CoordinateType getMZ() const
Returns the m/z coordinate (index 1)
Definition: Peak2D.h:196
double getPosMax() const
returns the maximum m/z (or RT) of the spectrum
void getSpectrumAlignment(std::vector< std::pair< Size, Size > > &alignment, const SpectrumType1 &s1, const SpectrumType2 &s2) const
Definition: SpectrumAlignment.h:86
double rt_max_
Definition: SpectraMerger.h:120
double operator()(const BaseFeature &first, const BaseFeature &second) const
Definition: SpectraMerger.h:102
double getSimilarity(const double d_rt, const double d_mz) const
Definition: SpectraMerger.h:95
double eval(double pos)
returns spline interpolated intensity at this position (fast access since we can start search from la...
void setProgress(SignedSize value) const
Sets the current progress.
A 1-dimensional raw data point or peak.
Definition: Peak1D.h:54
void average(MapType &exp, String average_type)
average over neighbouring spectra
Definition: SpectraMerger.h:313
void setMSLevel(UInt ms_level)
Sets the MS level.
Definition: SpectraMerger.h:75
Aligns the peaks of two sorted spectra Method 1: Using a banded (width via &#39;tolerance&#39; parameter) ali...
Definition: SpectrumAlignment.h:65
Base::const_iterator ConstIterator
Definition: Map.h:81
void clear(bool clear_meta_data)
Clears all data and meta data.
void setRT(double rt)
Sets the absolute retention time (in seconds)
Management and storage of parameters / INI files.
Definition: Param.h:74
Map< Size, std::vector< Size > > MergeBlocks
blocks of spectra (master-spectrum index to sacrifice-spectra(the ones being merged into the master-s...
Definition: SpectraMerger.h:128
void averageCentroidSpectra_(MapType &exp, const AverageBlocks &spectra_to_average_over, const UInt ms_level)
average spectra (centroid mode)
Definition: SpectraMerger.h:809
In-Memory representation of a mass spectrometry experiment.
Definition: MSExperiment.h:77
CoordinateType getRT() const
Returns the RT coordinate (index 0)
Definition: Peak2D.h:208
SingleLinkage ClusterMethod.
Definition: SingleLinkage.h:57
double getPosMin() const
returns the minimum m/z (or RT) of the spectrum
void unify(const SpectrumSettings &rhs)
merge another spectrum setting into this one (data is usually appended, except for spectrum type whic...
const std::vector< Precursor > & getPrecursors() const
returns a const reference to the precursors
Data structure for spline interpolation of MS1 spectra and chromatograms.
Definition: SplineInterpolatedPeaks.h:61
Illegal self operation exception.
Definition: Exception.h:378
std::vector< SpectrumType >::const_iterator ConstIterator
Non-mutable iterator.
Definition: MSExperiment.h:113
void setPrecursors(const std::vector< Precursor > &precursors)
sets the precursors
void startProgress(SignedSize begin, SignedSize end, const String &label) const
Initializes the progress display.
double mz_max_
Definition: SpectraMerger.h:121
iterator class for access of spline packages
Definition: SplineInterpolatedPeaks.h:111
size_t Size
Size type e.g. used as variable which can hold result of size()
Definition: Types.h:127
void clear(bool clear_meta_data)
Clears all data and meta data.
Base class for all classes that want to report their progress.
Definition: ProgressLogger.h:54
void averageProfileSpectra_(MapType &exp, const AverageBlocks &spectra_to_average_over, const UInt ms_level)
average spectra (profile mode)
Definition: SpectraMerger.h:696
A base class for all classes handling default parameters.
Definition: DefaultParamHandler.h:91
void cut(const Size cluster_quantity, const std::vector< BinaryTreeNode > &tree, std::vector< std::vector< Size > > &clusters)
Method to calculate a partition resulting from a certain step in clustering given by the number of cl...
void mergeSpectraPrecursors(MapType &exp)
merges spectra with similar precursors (must have MS2 level)
Definition: SpectraMerger.h:208
const std::vector< MSSpectrum > & getSpectra() const
returns the spectrum list
Hierarchical clustering with generic clustering functions.
Definition: ClusterHierarchical.h:63
double getRT() const
centroid data or stick data
Definition: SpectrumSettings.h:73
int Int
Signed integer type.
Definition: Types.h:102
Map class based on the STL map (containing several convenience functions)
Definition: Map.h:50
void cluster(std::vector< Data > &data, const SimilarityComparator &comparator, const ClusterFunctor &clusterer, std::vector< BinaryTreeNode > &cluster_tree, DistanceMatrix< float > &original_distance)
Clustering function.
Definition: ClusterHierarchical.h:112
Not all required information provided.
Definition: Exception.h:195