OpenMS
SpectraMerger.h
Go to the documentation of this file.
1 // Copyright (c) 2002-2023, The OpenMS Team -- EKU Tuebingen, ETH Zurich, and FU Berlin
2 // SPDX-License-Identifier: BSD-3-Clause
3 //
4 // --------------------------------------------------------------------------
5 // $Maintainer: Chris Bielow $
6 // $Authors: Chris Bielow, Andreas Bertsch, Lars Nilse $
7 // --------------------------------------------------------------------------
8 //
9 #pragma once
10 
23 
24 #include <vector>
25 
26 namespace OpenMS
27 {
28 
37  class OPENMS_DLLAPI SpectraMerger :
38  public DefaultParamHandler, public ProgressLogger
39  {
40 
41 protected:
42 
43  /* Determine distance between two spectra
44 
45  Distance is determined as
46 
47  (d_rt/rt_max_ + d_mz/mz_max_) / 2
48 
49  */
51  public DefaultParamHandler
52  {
53 public:
55  DefaultParamHandler("SpectraDistance")
56  {
57  defaults_.setValue("rt_tolerance", 10.0, "Maximal RT distance (in [s]) for two spectra's precursors.");
58  defaults_.setValue("mz_tolerance", 1.0, "Maximal m/z distance (in Da) for two spectra's precursors.");
59  defaultsToParam_(); // calls updateMembers_
60  }
61 
62  void updateMembers_() override
63  {
64  rt_max_ = (double) param_.getValue("rt_tolerance");
65  mz_max_ = (double) param_.getValue("mz_tolerance");
66  }
67 
68  double getSimilarity(const double d_rt, const double d_mz) const
69  {
70  // 1 - distance
71  return 1 - ((d_rt / rt_max_ + d_mz / mz_max_) / 2);
72  }
73 
74  // measure of SIMILARITY (not distance, i.e. 1-distance)!!
75  double operator()(const BaseFeature& first, const BaseFeature& second) const
76  {
77  // get RT distance:
78  double d_rt = fabs(first.getRT() - second.getRT());
79  double d_mz = fabs(first.getMZ() - second.getMZ());
80 
81  if (d_rt > rt_max_ || d_mz > mz_max_)
82  {
83  return 0;
84  }
85 
86  // calculate similarity (0-1):
87  double sim = getSimilarity(d_rt, d_mz);
88 
89  return sim;
90  }
91 
92 protected:
93  double rt_max_;
94  double mz_max_;
95 
96  }; // end of SpectraDistance
97 
98 public:
99 
101  typedef std::map<Size, std::vector<Size> > MergeBlocks;
102 
104  typedef std::map<Size, std::vector<std::pair<Size, double> > > AverageBlocks;
105 
106  // @name Constructors and Destructors
107  // @{
110 
112  SpectraMerger(const SpectraMerger& source);
113 
115  SpectraMerger(SpectraMerger&& source) = default;
116 
118  ~SpectraMerger() override;
119  // @}
120 
121  // @name Operators
122  // @{
125 
127  SpectraMerger& operator=(SpectraMerger&& source) = default;
128  // @}
129 
130  // @name Merging functions
131  // @{
133  template <typename MapType>
135  {
136  IntList ms_levels = param_.getValue("block_method:ms_levels");
137  Int rt_block_size(param_.getValue("block_method:rt_block_size"));
138  double rt_max_length = (param_.getValue("block_method:rt_max_length"));
139 
140  if (rt_max_length == 0) // no rt restriction set?
141  {
142  rt_max_length = (std::numeric_limits<double>::max)(); // set max rt span to very large value
143  }
144 
145  for (IntList::iterator it_mslevel = ms_levels.begin(); it_mslevel < ms_levels.end(); ++it_mslevel)
146  {
147  MergeBlocks spectra_to_merge;
148  Size idx_block(0);
149  SignedSize block_size_count(rt_block_size + 1);
150  Size idx_spectrum(0);
151  for (typename MapType::const_iterator it1 = exp.begin(); it1 != exp.end(); ++it1)
152  {
153  if (Int(it1->getMSLevel()) == *it_mslevel)
154  {
155  // block full if it contains a maximum number of scans or if maximum rt length spanned
156  if (++block_size_count >= rt_block_size ||
157  exp[idx_spectrum].getRT() - exp[idx_block].getRT() > rt_max_length)
158  {
159  block_size_count = 0;
160  idx_block = idx_spectrum;
161  }
162  else
163  {
164  spectra_to_merge[idx_block].push_back(idx_spectrum);
165  }
166  }
167 
168  ++idx_spectrum;
169  }
170  // check if last block had sacrifice spectra
171  if (block_size_count == 0) //block just got initialized
172  {
173  spectra_to_merge[idx_block] = std::vector<Size>();
174  }
175 
176  // merge spectra, remove all old MS spectra and add new consensus spectra
177  mergeSpectra_(exp, spectra_to_merge, *it_mslevel);
178  }
179 
180  exp.sortSpectra();
181  }
182 
184  template <typename MapType>
186  {
187 
188  // convert spectra's precursors to clusterizable data
189  Size data_size;
190  std::vector<BinaryTreeNode> tree;
191  std::map<Size, Size> index_mapping;
192  // local scope to save memory - we do not need the clustering stuff later
193  {
194  std::vector<BaseFeature> data;
195 
196  for (Size i = 0; i < exp.size(); ++i)
197  {
198  if (exp[i].getMSLevel() != 2)
199  {
200  continue;
201  }
202 
203  // remember which index in distance data ==> experiment index
204  index_mapping[data.size()] = i;
205 
206  // make cluster element
207  BaseFeature bf;
208  bf.setRT(exp[i].getRT());
209  const auto& pcs = exp[i].getPrecursors();
210  // keep the first Precursor
211  if (pcs.empty())
212  {
213  throw Exception::MissingInformation(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Scan #") + String(i) + " does not contain any precursor information! Unable to cluster!");
214  }
215  if (pcs.size() > 1)
216  {
217  OPENMS_LOG_WARN << "More than one precursor found. Using first one!" << std::endl;
218  }
219  bf.setMZ(pcs[0].getMZ());
220  data.push_back(bf);
221  }
222  data_size = data.size();
223 
224  SpectraDistance_ llc;
225  llc.setParameters(param_.copy("precursor_method:", true));
226  SingleLinkage sl;
227  DistanceMatrix<float> dist; // will be filled
229 
230  // clustering ; threshold is implicitly at 1.0, i.e. distances of 1.0 (== similarity 0) will not be clustered
231  ch.cluster<BaseFeature, SpectraDistance_>(data, llc, sl, tree, dist);
232  }
233 
234  // extract the clusters
235  ClusterAnalyzer ca;
236  std::vector<std::vector<Size> > clusters;
237  // count number of real tree nodes (not the -1 ones):
238  Size node_count = 0;
239  for (Size ii = 0; ii < tree.size(); ++ii)
240  {
241  if (tree[ii].distance >= 1)
242  {
243  tree[ii].distance = -1; // manually set to disconnect, as SingleLinkage does not support it
244  }
245  if (tree[ii].distance != -1)
246  {
247  ++node_count;
248  }
249  }
250  ca.cut(data_size - node_count, tree, clusters);
251 
252  // convert to blocks
253  MergeBlocks spectra_to_merge;
254 
255  for (Size i_outer = 0; i_outer < clusters.size(); ++i_outer)
256  {
257  if (clusters[i_outer].size() <= 1)
258  {
259  continue;
260  }
261  // init block with first cluster element
262  Size cl_index0 = clusters[i_outer][0];
263  spectra_to_merge[index_mapping[cl_index0]] = std::vector<Size>();
264  // add all other elements
265  for (Size i_inner = 1; i_inner < clusters[i_outer].size(); ++i_inner)
266  {
267  spectra_to_merge[index_mapping[cl_index0]].push_back(index_mapping[clusters[i_outer][i_inner]]);
268  }
269  }
270 
271  // do it
272  mergeSpectra_(exp, spectra_to_merge, 2);
273 
274  exp.sortSpectra();
275  }
276 
285  static bool areMassesMatched(double mz1, double mz2, double tol_ppm, int max_c)
286  {
287  if (mz1 == mz2 || tol_ppm <= 0)
288  {
289  return true;
290  }
291 
292  const int min_c = 1;
293  const int max_iso_diff = 5; // maximum charge difference 5 is more than enough
294  const double max_charge_diff_ratio = 3.0; // maximum ratio between charges (large / small charge)
295 
296  for (int c1 = min_c; c1 <= max_c; ++c1)
297  {
298  double mass1 = (mz1 - Constants::PROTON_MASS_U) * c1;
299 
300  for (int c2 = min_c; c2 <= max_c; ++c2)
301  {
302  if (c1 / c2 > max_charge_diff_ratio)
303  {
304  continue;
305  }
306  if (c2 / c1 > max_charge_diff_ratio)
307  {
308  break;
309  }
310 
311  double mass2 = (mz2 - Constants::PROTON_MASS_U) * c2;
312 
313  if (fabs(mass1 - mass2) > max_iso_diff)
314  {
315  continue;
316  }
317  for (int i = -max_iso_diff; i <= max_iso_diff; ++i)
318  {
319  if (fabs(mass1 - mass2 + i * Constants::ISOTOPE_MASSDIFF_55K_U) < mass1 * tol_ppm * 1e-6)
320  {
321  return true;
322  }
323  }
324  }
325  }
326  return false;
327  }
328 
336  template <typename MapType>
337  void average(MapType& exp, const String& average_type, int ms_level = -1)
338  {
339  // MS level to be averaged
340  if (ms_level < 0)
341  {
342  ms_level = param_.getValue("average_gaussian:ms_level");
343  if (average_type == "tophat")
344  {
345  ms_level = param_.getValue("average_tophat:ms_level");
346  }
347  }
348 
349  // spectrum type (profile, centroid or automatic)
350  std::string spectrum_type = param_.getValue("average_gaussian:spectrum_type");
351  if (average_type == "tophat")
352  {
353  spectrum_type = std::string(param_.getValue("average_tophat:spectrum_type"));
354  }
355 
356  // parameters for Gaussian averaging
357  double fwhm(param_.getValue("average_gaussian:rt_FWHM"));
358  double factor = -4 * log(2.0) / (fwhm * fwhm); // numerical factor within Gaussian
359  double cutoff(param_.getValue("average_gaussian:cutoff"));
360  double precursor_mass_ppm = param_.getValue("average_gaussian:precursor_mass_tol");
361  int precursor_max_charge = param_.getValue("average_gaussian:precursor_max_charge");
362 
363  // parameters for Top-Hat averaging
364  bool unit(param_.getValue("average_tophat:rt_unit") == "scans"); // true if RT unit is 'scans', false if RT unit is 'seconds'
365  double range(param_.getValue("average_tophat:rt_range")); // range of spectra to be averaged over
366  double range_seconds = range / 2; // max. +/- <range_seconds> seconds from master spectrum
367  int range_scans = static_cast<int>(range); // in case of unit scans, the param is used as integer
368  if ((range_scans % 2) == 0)
369  {
370  ++range_scans;
371  }
372  range_scans = (range_scans - 1) / 2; // max. +/- <range_scans> scans from master spectrum
373 
374  AverageBlocks spectra_to_average_over;
375 
376  // loop over RT
377  int n(0); // spectrum index
378  int cntr(0); // spectrum counter
379  for (typename MapType::const_iterator it_rt = exp.begin(); it_rt != exp.end(); ++it_rt)
380  {
381  if (Int(it_rt->getMSLevel()) == ms_level)
382  {
383  int m; // spectrum index
384  int steps;
385  bool terminate_now;
386  typename MapType::const_iterator it_rt_2;
387 
388  // go forward (start at next downstream spectrum; the current spectrum will be covered when looking backwards)
389  steps = 0;
390  m = n + 1;
391  it_rt_2 = it_rt + 1;
392  terminate_now = false;
393  while (it_rt_2 != exp.end() && !terminate_now)
394  {
395  if (Int(it_rt_2->getMSLevel()) == ms_level)
396  {
397  bool add = true;
398  // if precursor_mass_ppm >=0, two spectra should have the same mass. otherwise it_rt_2 is skipped.
399  if (precursor_mass_ppm >= 0 && ms_level >= 2 && it_rt->getPrecursors().size() > 0 &&
400  it_rt_2->getPrecursors().size() > 0)
401  {
402  double mz1 = it_rt->getPrecursors()[0].getMZ();
403  double mz2 = it_rt_2->getPrecursors()[0].getMZ();
404  add = areMassesMatched(mz1, mz2, precursor_mass_ppm, precursor_max_charge);
405  }
406 
407  if (add)
408  {
409  double weight = 1;
410  if (average_type == "gaussian")
411  {
412  //factor * (rt_2 -rt)^2
413  double base = it_rt_2->getRT() - it_rt->getRT();
414  weight = std::exp(factor * base * base);
415  }
416  std::pair<Size, double> p(m, weight);
417  spectra_to_average_over[n].push_back(p);
418  }
419  ++steps;
420  }
421  if (average_type == "gaussian")
422  {
423  // Gaussian
424  double base = it_rt_2->getRT() - it_rt->getRT();
425  terminate_now = std::exp(factor * base * base) < cutoff;
426  }
427  else if (unit)
428  {
429  // Top-Hat with RT unit = scans
430  terminate_now = (steps > range_scans);
431  }
432  else
433  {
434  // Top-Hat with RT unit = seconds
435  terminate_now = (std::abs(it_rt_2->getRT() - it_rt->getRT()) > range_seconds);
436  }
437  ++m;
438  ++it_rt_2;
439  }
440 
441  // go backward
442  steps = 0;
443  m = n;
444  it_rt_2 = it_rt;
445  terminate_now = false;
446  while (it_rt_2 != exp.begin() && !terminate_now)
447  {
448  if (Int(it_rt_2->getMSLevel()) == ms_level)
449  {
450  bool add = true;
451  // if precursor_mass_ppm >=0, two spectra should have the same mass. otherwise it_rt_2 is skipped.
452  if (precursor_mass_ppm >= 0 && ms_level >= 2 && it_rt->getPrecursors().size() > 0 &&
453  it_rt_2->getPrecursors().size() > 0)
454  {
455  double mz1 = it_rt->getPrecursors()[0].getMZ();
456  double mz2 = it_rt_2->getPrecursors()[0].getMZ();
457  add = areMassesMatched(mz1, mz2, precursor_mass_ppm, precursor_max_charge);
458  }
459  if (add)
460  {
461  double weight = 1;
462  if (average_type == "gaussian")
463  {
464  double base = it_rt_2->getRT() - it_rt->getRT();
465  weight = std::exp(factor * base * base);
466  }
467  std::pair<Size, double> p(m, weight);
468  spectra_to_average_over[n].push_back(p);
469  }
470  ++steps;
471  }
472  if (average_type == "gaussian")
473  {
474  // Gaussian
475  double base = it_rt_2->getRT() - it_rt->getRT();
476  terminate_now = std::exp(factor * base * base) < cutoff;
477  }
478  else if (unit)
479  {
480  // Top-Hat with RT unit = scans
481  terminate_now = (steps > range_scans);
482  }
483  else
484  {
485  // Top-Hat with RT unit = seconds
486  terminate_now = (std::abs(it_rt_2->getRT() - it_rt->getRT()) > range_seconds);
487  }
488  --m;
489  --it_rt_2;
490  }
491  ++cntr;
492  }
493  ++n;
494  }
495 
496  if (cntr == 0)
497  {
498  //return;
499  throw Exception::InvalidParameter(__FILE__,
500  __LINE__,
501  OPENMS_PRETTY_FUNCTION,
502  "Input mzML does not have any spectra of MS level specified by ms_level.");
503  }
504 
505  // normalize weights
506  for (AverageBlocks::iterator it = spectra_to_average_over.begin(); it != spectra_to_average_over.end(); ++it)
507  {
508  double sum(0.0);
509  for (const auto& weight: it->second)
510  {
511  sum += weight.second;
512  }
513 
514  for (auto& weight: it->second)
515  {
516  weight.second /= sum;
517  }
518  }
519 
520  // determine type of spectral data (profile or centroided)
522  if (spectrum_type == "automatic")
523  {
524  Size idx = spectra_to_average_over.begin()->first; // index of first spectrum to be averaged
525  type = exp[idx].getType(true);
526  }
527  else if (spectrum_type == "profile")
528  {
530  }
531  else if (spectrum_type == "centroid")
532  {
534  }
535  else
536  {
537  throw Exception::InvalidParameter(__FILE__,__LINE__,OPENMS_PRETTY_FUNCTION, "Spectrum type has to be one of automatic, profile or centroid.");
538  }
539 
540  // generate new spectra
541  if (type == SpectrumSettings::CENTROID)
542  {
543  averageCentroidSpectra_(exp, spectra_to_average_over, ms_level);
544  }
545  else
546  {
547  averageProfileSpectra_(exp, spectra_to_average_over, ms_level);
548  }
549 
550  exp.sortSpectra();
551  }
552 
553  // @}
554 
555 protected:
556 
567  template <typename MapType>
568  void mergeSpectra_(MapType& exp, const MergeBlocks& spectra_to_merge, const UInt ms_level)
569  {
570  double mz_binning_width(param_.getValue("mz_binning_width"));
571  std::string mz_binning_unit(param_.getValue("mz_binning_width_unit"));
572 
573  // merge spectra
574  MapType merged_spectra;
575 
576  std::map<Size, Size> cluster_sizes;
577  std::set<Size> merged_indices;
578 
579  // set up alignment
580  SpectrumAlignment sas;
581  Param p;
582  p.setValue("tolerance", mz_binning_width);
583  if (!(mz_binning_unit == "Da" || mz_binning_unit == "ppm"))
584  {
585  throw Exception::IllegalSelfOperation(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION); // sanity check
586  }
587 
588  p.setValue("is_relative_tolerance", mz_binning_unit == "Da" ? "false" : "true");
589  sas.setParameters(p);
590  std::vector<std::pair<Size, Size> > alignment;
591 
592  Size count_peaks_aligned(0);
593  Size count_peaks_overall(0);
594 
595  // each BLOCK
596  for (auto it = spectra_to_merge.begin(); it != spectra_to_merge.end(); ++it)
597  {
598  ++cluster_sizes[it->second.size() + 1]; // for stats
599 
600  typename MapType::SpectrumType consensus_spec = exp[it->first];
601  consensus_spec.setMSLevel(ms_level);
602 
603  merged_indices.insert(it->first);
604 
605  double rt_average = consensus_spec.getRT();
606  double precursor_mz_average = 0.0;
607  Size precursor_count(0);
608  if (!consensus_spec.getPrecursors().empty())
609  {
610  precursor_mz_average = consensus_spec.getPrecursors()[0].getMZ();
611  ++precursor_count;
612  }
613 
614  count_peaks_overall += consensus_spec.size();
615 
616  String consensus_native_id = consensus_spec.getNativeID();
617 
618  // block elements
619  for (auto sit = it->second.begin(); sit != it->second.end(); ++sit)
620  {
621  consensus_spec.unify(exp[*sit]); // append meta info
622  merged_indices.insert(*sit);
623 
624  rt_average += exp[*sit].getRT();
625  if (ms_level >= 2 && exp[*sit].getPrecursors().size() > 0)
626  {
627  precursor_mz_average += exp[*sit].getPrecursors()[0].getMZ();
628  ++precursor_count;
629  }
630 
631  // add native ID to consensus native ID, comma separated
632  consensus_native_id += ",";
633  consensus_native_id += exp[*sit].getNativeID();
634 
635  // merge data points
636  sas.getSpectrumAlignment(alignment, consensus_spec, exp[*sit]);
637  count_peaks_aligned += alignment.size();
638  count_peaks_overall += exp[*sit].size();
639 
640  Size align_index(0);
641  Size spec_b_index(0);
642 
643  // sanity check for number of peaks
644  Size spec_a = consensus_spec.size(), spec_b = exp[*sit].size(), align_size = alignment.size();
645  for (auto pit = exp[*sit].begin(); pit != exp[*sit].end(); ++pit)
646  {
647  if (alignment.empty() || alignment[align_index].second != spec_b_index)
648  // ... add unaligned peak
649  {
650  consensus_spec.push_back(*pit);
651  }
652  // or add aligned peak height to ALL corresponding existing peaks
653  else
654  {
655  Size counter(0);
656  Size copy_of_align_index(align_index);
657 
658  while (!alignment.empty() &&
659  copy_of_align_index < alignment.size() &&
660  alignment[copy_of_align_index].second == spec_b_index)
661  {
662  ++copy_of_align_index;
663  ++counter;
664  } // Count the number of peaks in a which correspond to a single b peak.
665 
666  while (!alignment.empty() &&
667  align_index < alignment.size() &&
668  alignment[align_index].second == spec_b_index)
669  {
670  consensus_spec[alignment[align_index].first].setIntensity(consensus_spec[alignment[align_index].first].getIntensity() +
671  (pit->getIntensity() / (double)counter)); // add the intensity divided by the number of peaks
672  ++align_index; // this aligned peak was explained, wait for next aligned peak ...
673  if (align_index == alignment.size())
674  {
675  alignment.clear(); // end reached -> avoid going into this block again
676  }
677  }
678  align_size = align_size + 1 - counter; //Decrease align_size by number of
679  }
680  ++spec_b_index;
681  }
682  consensus_spec.sortByPosition(); // sort, otherwise next alignment will fail
683  if (spec_a + spec_b - align_size != consensus_spec.size())
684  {
685  OPENMS_LOG_WARN << "wrong number of features after merge. Expected: " << spec_a + spec_b - align_size << " got: " << consensus_spec.size() << "\n";
686  }
687  }
688  rt_average /= it->second.size() + 1;
689  consensus_spec.setRT(rt_average);
690 
691  // set new consensus native ID
692  consensus_spec.setNativeID(consensus_native_id);
693 
694  if (ms_level >= 2)
695  {
696  if (precursor_count)
697  {
698  precursor_mz_average /= precursor_count;
699  }
700  auto& pcs = consensus_spec.getPrecursors();
701  pcs.resize(1);
702  pcs[0].setMZ(precursor_mz_average);
703  consensus_spec.setPrecursors(pcs);
704  }
705 
706  if (consensus_spec.empty())
707  {
708  continue;
709  }
710  else
711  {
712  merged_spectra.addSpectrum(std::move(consensus_spec));
713  }
714  }
715 
716  OPENMS_LOG_INFO << "Cluster sizes:\n";
717  for (const auto& cl_size : cluster_sizes)
718  {
719  OPENMS_LOG_INFO << " size " << cl_size.first << ": " << cl_size.second << "x\n";
720  }
721 
722  char buffer[200];
723  sprintf(buffer, "%d/%d (%.2f %%) of blocked spectra", (int)count_peaks_aligned,
724  (int)count_peaks_overall, float(count_peaks_aligned) / float(count_peaks_overall) * 100.);
725  OPENMS_LOG_INFO << "Number of merged peaks: " << String(buffer) << "\n";
726 
727  // remove all spectra that were within a cluster
728  typename MapType::SpectrumType empty_spec;
729  MapType exp_tmp;
730  for (Size i = 0; i < exp.size(); ++i)
731  {
732  if (merged_indices.count(i) == 0) // save unclustered ones
733  {
734  exp_tmp.addSpectrum(exp[i]);
735  exp[i] = empty_spec;
736  }
737  }
738 
739  //Meta_Data will not be cleared
740  exp.clear(false);
741  exp.getSpectra().insert(exp.end(), std::make_move_iterator(exp_tmp.begin()),
742  std::make_move_iterator(exp_tmp.end()));
743 
744  // ... and add consensus spectra
745  exp.getSpectra().insert(exp.end(), std::make_move_iterator(merged_spectra.begin()),
746  std::make_move_iterator(merged_spectra.end()));
747 
748  }
749 
770  template <typename MapType>
771  void averageProfileSpectra_(MapType& exp, const AverageBlocks& spectra_to_average_over, const UInt ms_level)
772  {
773  MapType exp_tmp; // temporary experiment for averaged spectra
774 
775  double mz_binning_width(param_.getValue("mz_binning_width"));
776  std::string mz_binning_unit(param_.getValue("mz_binning_width_unit"));
777 
778  unsigned progress = 0;
779  std::stringstream progress_message;
780  progress_message << "averaging profile spectra of MS level " << ms_level;
781  startProgress(0, spectra_to_average_over.size(), progress_message.str());
782 
783  // loop over blocks
784  for (AverageBlocks::const_iterator it = spectra_to_average_over.begin(); it != spectra_to_average_over.end(); ++it)
785  {
786  setProgress(++progress);
787 
788  // loop over spectra in blocks
789  std::vector<double> mz_positions_all; // m/z positions from all spectra
790  for (const auto& spec : it->second)
791  {
792  // loop over m/z positions
793  for (typename MapType::SpectrumType::ConstIterator it_mz = exp[spec.first].begin(); it_mz < exp[spec.first].end(); ++it_mz)
794  {
795  mz_positions_all.push_back(it_mz->getMZ());
796  }
797  }
798 
799  sort(mz_positions_all.begin(), mz_positions_all.end());
800 
801  std::vector<double> mz_positions; // positions at which the averaged spectrum should be evaluated
802  std::vector<double> intensities;
803  double last_mz = std::numeric_limits<double>::min(); // last m/z position pushed through from mz_position to mz_position_2
804  double delta_mz(mz_binning_width); // for m/z unit Da
805  for (const auto mz_pos : mz_positions_all)
806  {
807  if (mz_binning_unit == "ppm")
808  {
809  delta_mz = mz_binning_width * mz_pos / 1000000;
810  }
811 
812  if ((mz_pos - last_mz) > delta_mz)
813  {
814  mz_positions.push_back(mz_pos);
815  intensities.push_back(0.0);
816  last_mz = mz_pos;
817  }
818  }
819 
820  // loop over spectra in blocks
821  for (const auto& spec : it->second)
822  {
823  SplineInterpolatedPeaks spline(exp[spec.first]);
825 
826  // loop over m/z positions
827  for (Size i = spline.getPosMin(); i < mz_positions.size(); ++i)
828  {
829  if ((spline.getPosMin() < mz_positions[i]) && (mz_positions[i] < spline.getPosMax()))
830  {
831  intensities[i] += nav.eval(mz_positions[i]) * (spec.second); // spline-interpolated intensity * weight
832  }
833  }
834  }
835 
836  // update spectrum
837  typename MapType::SpectrumType average_spec = exp[it->first];
838  average_spec.clear(false); // Precursors are part of the meta data, which are not deleted.
839 
840  // refill spectrum
841  for (Size i = 0; i < mz_positions.size(); ++i)
842  {
843  typename MapType::PeakType peak;
844  peak.setMZ(mz_positions[i]);
845  peak.setIntensity(intensities[i]);
846  average_spec.push_back(peak);
847  }
848 
849  // store spectrum temporarily
850  exp_tmp.addSpectrum(std::move(average_spec));
851  }
852 
853  endProgress();
854 
855  // loop over blocks
856  int n(0);
857  for (AverageBlocks::const_iterator it = spectra_to_average_over.begin(); it != spectra_to_average_over.end(); ++it)
858  {
859  exp[it->first] = exp_tmp[n];
860  ++n;
861  }
862  }
863 
879  template <typename MapType>
880  void averageCentroidSpectra_(MapType& exp, const AverageBlocks& spectra_to_average_over, const UInt ms_level)
881  {
882  MapType exp_tmp; // temporary experiment for averaged spectra
883 
884  double mz_binning_width(param_.getValue("mz_binning_width"));
885  std::string mz_binning_unit(param_.getValue("mz_binning_width_unit"));
886 
887  unsigned progress = 0;
888  ProgressLogger logger;
889  std::stringstream progress_message;
890  progress_message << "averaging centroid spectra of MS level " << ms_level;
891  logger.startProgress(0, spectra_to_average_over.size(), progress_message.str());
892 
893  // loop over blocks
894  for (AverageBlocks::const_iterator it = spectra_to_average_over.begin(); it != spectra_to_average_over.end(); ++it)
895  {
896  logger.setProgress(++progress);
897 
898  // collect peaks from all spectra
899  // loop over spectra in blocks
900  std::vector<std::pair<double, double> > mz_intensity_all; // m/z positions and peak intensities from all spectra
901  for (const auto& weightedMZ: it->second)
902  {
903  // loop over m/z positions
904  for (typename MapType::SpectrumType::ConstIterator it_mz = exp[weightedMZ.first].begin(); it_mz < exp[weightedMZ.first].end(); ++it_mz)
905  {
906  std::pair<double, double> mz_intensity(it_mz->getMZ(), (it_mz->getIntensity() * weightedMZ.second)); // m/z, intensity * weight
907  mz_intensity_all.push_back(mz_intensity);
908  }
909  }
910 
911  sort(mz_intensity_all.begin(), mz_intensity_all.end());
912 
913  // generate new spectrum
914  std::vector<double> mz_new;
915  std::vector<double> intensity_new;
916  double last_mz = std::numeric_limits<double>::min();
917  double delta_mz = mz_binning_width;
918  double sum_mz(0);
919  double sum_intensity(0);
920  Size count(0);
921  for (const auto& mz_pos : mz_intensity_all)
922  {
923  if (mz_binning_unit == "ppm")
924  {
925  delta_mz = mz_binning_width * (mz_pos.first) / 1000000;
926  }
927 
928  if (((mz_pos.first - last_mz) > delta_mz) && (count > 0))
929  {
930  mz_new.push_back(sum_mz / count);
931  intensity_new.push_back(sum_intensity); // intensities already weighted
932 
933  sum_mz = 0;
934  sum_intensity = 0;
935 
936  last_mz = mz_pos.first;
937  count = 0;
938  }
939 
940  sum_mz += mz_pos.first;
941  sum_intensity += mz_pos.second;
942  ++count;
943  }
944  if (count > 0)
945  {
946  mz_new.push_back(sum_mz / count);
947  intensity_new.push_back(sum_intensity); // intensities already weighted
948  }
949 
950  // update spectrum
951  typename MapType::SpectrumType average_spec = exp[it->first];
952  average_spec.clear(false); // Precursors are part of the meta data, which are not deleted.
953 
954  // refill spectrum
955  for (Size i = 0; i < mz_new.size(); ++i)
956  {
957  typename MapType::PeakType peak;
958  peak.setMZ(mz_new[i]);
959  peak.setIntensity(intensity_new[i]);
960  average_spec.push_back(peak);
961  }
962 
963  // store spectrum temporarily
964  exp_tmp.addSpectrum(std::move(average_spec));
965  }
966 
967  logger.endProgress();
968 
969  // loop over blocks
970  int n(0);
971  for (const auto& spectral_index : spectra_to_average_over)
972  {
973  exp[spectral_index.first] = std::move(exp_tmp[n]);
974  ++n;
975  }
976  }
977  };
978 }
#define OPENMS_LOG_WARN
Macro if a warning, a piece of information which should be read by the user, should be logged.
Definition: LogStream.h:444
#define OPENMS_LOG_INFO
Macro if a information, e.g. a status should be reported.
Definition: LogStream.h:449
A basic LC-MS feature.
Definition: BaseFeature.h:33
Bundles analyzing tools for a clustering (given as sequence of BinaryTreeNode's)
Definition: ClusterAnalyzer.h:26
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...
Hierarchical clustering with generic clustering functions.
Definition: ClusterHierarchical.h:38
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:86
A base class for all classes handling default parameters.
Definition: DefaultParamHandler.h:66
void setParameters(const Param &param)
Sets the parameters.
A two-dimensional distance matrix, similar to OpenMS::Matrix.
Definition: DistanceMatrix.h:42
Illegal self operation exception.
Definition: Exception.h:346
Exception indicating that an invalid parameter was handed over to an algorithm.
Definition: Exception.h:315
Not all required information provided.
Definition: Exception.h:162
In-Memory representation of a mass spectrometry run.
Definition: MSExperiment.h:46
void addSpectrum(const MSSpectrum &spectrum)
adds a spectrum to the list
Iterator begin()
Definition: MSExperiment.h:156
const std::vector< MSSpectrum > & getSpectra() const
returns the spectrum list
Iterator end()
Definition: MSExperiment.h:166
void sortSpectra(bool sort_mz=true)
Sorts the data points by retention time.
Size size() const
The number of spectra.
Definition: MSExperiment.h:121
Base::const_iterator const_iterator
Definition: MSExperiment.h:91
std::vector< SpectrumType >::const_iterator ConstIterator
Non-mutable iterator.
Definition: MSExperiment.h:79
void clear(bool clear_meta_data)
Clears all data and meta data.
The representation of a 1D spectrum.
Definition: MSSpectrum.h:44
double getRT() const
void setMSLevel(UInt ms_level)
Sets the MS level.
void sortByPosition()
Lexicographically sorts the peaks by their position.
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:44
void setValue(const std::string &key, const ParamValue &value, const std::string &description="", const std::vector< std::string > &tags=std::vector< std::string >())
Sets a value.
A 1-dimensional raw data point or peak.
Definition: Peak1D.h:28
void setIntensity(IntensityType intensity)
Mutable access to the data point intensity (height)
Definition: Peak1D.h:84
void setMZ(CoordinateType mz)
Mutable access to m/z.
Definition: Peak1D.h:93
CoordinateType getMZ() const
Returns the m/z coordinate (index 1)
Definition: Peak2D.h:172
void setMZ(CoordinateType coordinate)
Mutable access to the m/z coordinate (index 1)
Definition: Peak2D.h:178
void setRT(CoordinateType coordinate)
Mutable access to the RT coordinate (index 0)
Definition: Peak2D.h:190
CoordinateType getRT() const
Returns the RT coordinate (index 0)
Definition: Peak2D.h:184
Base class for all classes that want to report their progress.
Definition: ProgressLogger.h:27
void setProgress(SignedSize value) const
Sets the current progress.
void startProgress(SignedSize begin, SignedSize end, const String &label) const
Initializes the progress display.
void endProgress(UInt64 bytes_processed=0) const
SingleLinkage ClusterMethod.
Definition: SingleLinkage.h:31
Definition: SpectraMerger.h:52
double getSimilarity(const double d_rt, const double d_mz) const
Definition: SpectraMerger.h:68
SpectraDistance_()
Definition: SpectraMerger.h:54
double operator()(const BaseFeature &first, const BaseFeature &second) const
Definition: SpectraMerger.h:75
double mz_max_
Definition: SpectraMerger.h:94
void updateMembers_() override
This method is used to update extra member variables at the end of the setParameters() method.
Definition: SpectraMerger.h:62
double rt_max_
Definition: SpectraMerger.h:93
Merges blocks of MS or MS2 spectra.
Definition: SpectraMerger.h:39
void average(MapType &exp, const String &average_type, int ms_level=-1)
average over neighbouring spectra
Definition: SpectraMerger.h:337
static bool areMassesMatched(double mz1, double mz2, double tol_ppm, int max_c)
check if the first and second mzs might be from the same mass
Definition: SpectraMerger.h:285
void averageCentroidSpectra_(MapType &exp, const AverageBlocks &spectra_to_average_over, const UInt ms_level)
average spectra (centroid mode)
Definition: SpectraMerger.h:880
SpectraMerger(const SpectraMerger &source)
copy constructor
SpectraMerger()
default constructor
std::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:104
~SpectraMerger() override
destructor
void mergeSpectraPrecursors(MapType &exp)
merges spectra with similar precursors (must have MS2 level)
Definition: SpectraMerger.h:185
SpectraMerger & operator=(SpectraMerger &&source)=default
move-assignment operator
void averageProfileSpectra_(MapType &exp, const AverageBlocks &spectra_to_average_over, const UInt ms_level)
average spectra (profile mode)
Definition: SpectraMerger.h:771
SpectraMerger & operator=(const SpectraMerger &source)
assignment operator
void mergeSpectra_(MapType &exp, const MergeBlocks &spectra_to_merge, const UInt ms_level)
merges blocks of spectra of a certain level
Definition: SpectraMerger.h:568
std::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:101
SpectraMerger(SpectraMerger &&source)=default
move constructor
void mergeSpectraBlockWise(MapType &exp)
Definition: SpectraMerger.h:134
Aligns the peaks of two sorted spectra Method 1: Using a banded (width via 'tolerance' parameter) ali...
Definition: SpectrumAlignment.h:43
void getSpectrumAlignment(std::vector< std::pair< Size, Size > > &alignment, const SpectrumType1 &s1, const SpectrumType2 &s2) const
Definition: SpectrumAlignment.h:62
void unify(const SpectrumSettings &rhs)
merge another spectrum setting into this one (data is usually appended, except for spectrum type whic...
SpectrumType
Spectrum peak type.
Definition: SpectrumSettings.h:45
@ PROFILE
profile data
Definition: SpectrumSettings.h:48
@ CENTROID
centroid data or stick data
Definition: SpectrumSettings.h:47
const std::vector< Precursor > & getPrecursors() const
returns a const reference to the precursors
void setPrecursors(const std::vector< Precursor > &precursors)
sets the precursors
const String & getNativeID() const
returns the native identifier for the spectrum, used by the acquisition software.
void setNativeID(const String &native_id)
sets the native identifier for the spectrum, used by the acquisition software.
iterator class for access of spline packages
Definition: SplineInterpolatedPeaks.h:84
double eval(double pos)
returns spline interpolated intensity at this position (fast access since we can start search from la...
Data structure for spline interpolation of MS1 spectra and chromatograms.
Definition: SplineInterpolatedPeaks.h:34
SplineInterpolatedPeaks::Navigator getNavigator(double scaling=0.7)
returns an iterator for access of spline packages
double getPosMax() const
returns the maximum m/z (or RT) of the spectrum
double getPosMin() const
returns the minimum m/z (or RT) of the spectrum
A more convenient string class.
Definition: String.h:34
int Int
Signed integer type.
Definition: Types.h:76
unsigned int UInt
Unsigned integer type.
Definition: Types.h:68
ptrdiff_t SignedSize
Signed Size type e.g. used as pointer difference.
Definition: Types.h:108
size_t Size
Size type e.g. used as variable which can hold result of size()
Definition: Types.h:101
std::vector< Int > IntList
Vector of signed integers.
Definition: ListUtils.h:29
static double sum(IteratorType begin, IteratorType end)
Calculates the sum of a range of values.
Definition: StatisticFunctions.h:81
const double ISOTOPE_MASSDIFF_55K_U
Definition: Constants.h:100
const double PROTON_MASS_U
Definition: Constants.h:90
Main OpenMS namespace.
Definition: FeatureDeconvolution.h:22