OpenMS
OpenSwathBase.h
Go to the documentation of this file.
1 // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
2 // SPDX-License-Identifier: BSD-3-Clause
3 //
4 // --------------------------------------------------------------------------
5 // $Maintainer: Hannes Roest$
6 // $Authors: Hannes Roest$
7 // --------------------------------------------------------------------------
8 
9 #pragma once
10 
11 // Consumers
14 
15 // Files
24 
25 // Kernel and implementations
31 
32 // Helpers
36 
37 // Algorithms
43 
45 
46 #include <cassert>
47 #include <limits>
48 
50 namespace OpenMS
51 {
52 
54  public TOPPBase
55 {
56 
57 public:
58 
59  TOPPOpenSwathBase(String name, String description, bool official = true) :
60  TOPPBase(name, description, official)
61  {
62  }
63 
64 private:
65 
66  void loadSwathFiles_(const StringList& file_list,
67  const bool split_file,
68  const String& tmp,
69  const String& readoptions,
70  boost::shared_ptr<ExperimentalSettings > & exp_meta,
71  std::vector< OpenSwath::SwathMap > & swath_maps,
72  Interfaces::IMSDataConsumer* plugin_consumer)
73  {
74  SwathFile swath_file;
75  swath_file.setLogType(log_type_);
76 
77  if (split_file || file_list.size() > 1)
78  {
79  // TODO cannot use data reduction here any more ...
80  swath_maps = swath_file.loadSplit(file_list, tmp, exp_meta, readoptions);
81  }
82  else
83  {
84  FileTypes::Type in_file_type = FileHandler::getTypeByFileName(file_list[0]);
85  if (in_file_type == FileTypes::MZML)
86  {
87  swath_maps = swath_file.loadMzML(file_list[0], tmp, exp_meta, readoptions, plugin_consumer);
88  }
89  else if (in_file_type == FileTypes::MZXML)
90  {
91  swath_maps = swath_file.loadMzXML(file_list[0], tmp, exp_meta, readoptions);
92  }
93  else if (in_file_type == FileTypes::SQMASS)
94  {
95  swath_maps = swath_file.loadSqMass(file_list[0], exp_meta);
96  }
97  else
98  {
99  throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
100  "Input file needs to have ending mzML or mzXML");
101  }
102  }
103  }
104 
105 protected:
106 
133  bool loadSwathFiles(const StringList& file_list,
134  boost::shared_ptr<ExperimentalSettings >& exp_meta,
135  std::vector< OpenSwath::SwathMap >& swath_maps,
136  const bool split_file,
137  const String& tmp,
138  const String& readoptions,
139  const String& swath_windows_file,
140  const double min_upper_edge_dist,
141  const bool force,
142  const bool sort_swath_maps,
143  const bool sonar,
144  const bool prm,
145  const bool pasef,
146  Interfaces::IMSDataConsumer* plugin_consumer = nullptr)
147  {
148  // (i) Load files
149  loadSwathFiles_(file_list, split_file, tmp, readoptions, exp_meta, swath_maps, plugin_consumer);
150 
151  // (ii) Allow the user to specify the SWATH windows
152  if (!swath_windows_file.empty())
153  {
154  SwathWindowLoader::annotateSwathMapsFromFile(swath_windows_file, swath_maps, sort_swath_maps, force);
155  }
156 
157  for (Size i = 0; i < swath_maps.size(); i++)
158  {
159  OPENMS_LOG_DEBUG << "Found swath map " << i
160  << " with lower " << swath_maps[i].lower
161  << " and upper " << swath_maps[i].upper
162  << " and im Lower bounds of " << swath_maps[i].imLower
163  << " and im Upper bounds of " << swath_maps[i].imUpper
164  << " and " << swath_maps[i].sptr->getNrSpectra()
165  << " spectra." << std::endl;
166  }
167 
168  // (iii) Sanity check: there should be no overlap between the windows:
169  std::vector<std::pair<double, double>> sw_windows;
170  for (Size i = 0; i < swath_maps.size(); i++)
171  {
172  if (!swath_maps[i].ms1)
173  {
174  sw_windows.push_back(std::make_pair(swath_maps[i].lower, swath_maps[i].upper));
175  }
176  }
177  // sort by lower bound (first entry in pair)
178  std::sort(sw_windows.begin(), sw_windows.end());
179 
180  for (Size i = 1; i < sw_windows.size(); i++)
181  {
182  double lower_map_end = sw_windows[i-1].second - min_upper_edge_dist;
183  double upper_map_start = sw_windows[i].first;
184  OPENMS_LOG_DEBUG << "Extraction will go up to " << lower_map_end << " and continue at " << upper_map_start << std::endl;
185 
186  if (prm) {continue;} // skip next step as expect them to overlap and have gaps...
187 
188  if (upper_map_start - lower_map_end > 0.01)
189  {
190  OPENMS_LOG_WARN << "Extraction will have a gap between " << lower_map_end << " and " << upper_map_start << std::endl;
191  if (!force)
192  {
193  OPENMS_LOG_ERROR << "Extraction windows have a gap. Will abort (override with -force)" << std::endl;
194  return false;
195  }
196  }
197 
198  if (sonar) {continue;} // skip next step as expect them to overlap ...
199 
200  if (pasef) {continue;} // skip this step, expect there to be overlap ...
201 
202  if (lower_map_end - upper_map_start > 0.01)
203  {
204  OPENMS_LOG_WARN << "Extraction will overlap between " << lower_map_end << " and " << upper_map_start << "!\n"
205  << "This will lead to multiple extraction of the transitions in the overlapping region "
206  << "which will lead to duplicated output. It is very unlikely that you want this." << "\n"
207  << "Please fix this by providing an appropriate extraction file with -swath_windows_file" << "\n"
208  << "Did you mean to set the -sonar or -pasef Flag?" << std::endl;
209  if (!force)
210  {
211  OPENMS_LOG_ERROR << "Extraction windows overlap. Will abort (override with -force)" << std::endl;
212  return false;
213  }
214  }
215  }
216  return true;
217  }
218 
232  void prepareChromOutput(Interfaces::IMSDataConsumer ** chromatogramConsumer,
233  const boost::shared_ptr<ExperimentalSettings>& exp_meta,
234  const OpenSwath::LightTargetedExperiment& transition_exp,
235  const String& out_chrom,
236  const UInt64 run_id)
237  {
238  if (!out_chrom.empty())
239  {
240  String tmp = out_chrom;
241  if (tmp.toLower().hasSuffix(".sqmass"))
242  {
243  bool full_meta = false; // can lead to very large files in memory
244  bool lossy_compression = true;
245  *chromatogramConsumer = new MSDataSqlConsumer(out_chrom, run_id, 500, full_meta, lossy_compression);
246  }
247  else
248  {
249  PlainMSDataWritingConsumer * chromConsumer = new PlainMSDataWritingConsumer(out_chrom);
250  int expected_chromatograms = transition_exp.transitions.size();
251  chromConsumer->setExpectedSize(0, expected_chromatograms);
252  chromConsumer->setExperimentalSettings(*exp_meta);
253  chromConsumer->getOptions().setWriteIndex(true); // ensure that we write the index
255 
256  // prepare data structures for lossy compression
258  MSNumpressCoder::NumpressConfig npconfig_int;
259  npconfig_mz.estimate_fixed_point = true; // critical
260  npconfig_int.estimate_fixed_point = true; // critical
261  npconfig_mz.numpressErrorTolerance = -1.0; // skip check, faster
262  npconfig_int.numpressErrorTolerance = -1.0; // skip check, faster
263  npconfig_mz.setCompression("linear");
264  npconfig_int.setCompression("slof");
265  npconfig_mz.linear_fp_mass_acc = 0.05; // set the desired RT accuracy in seconds
266 
267  chromConsumer->getOptions().setNumpressConfigurationMassTime(npconfig_mz);
268  chromConsumer->getOptions().setNumpressConfigurationIntensity(npconfig_int);
269  chromConsumer->getOptions().setCompression(true);
270 
271  *chromatogramConsumer = chromConsumer;
272  }
273  }
274  else
275  {
276  *chromatogramConsumer = new NoopMSDataWritingConsumer("");
277  }
278  }
279 
289  const String& tr_file,
290  const Param& tsv_reader_param)
291  {
292  OpenSwath::LightTargetedExperiment transition_exp;
293  ProgressLogger progresslogger;
294  progresslogger.setLogType(log_type_);
295  if (tr_type == FileTypes::TRAML)
296  {
297  progresslogger.startProgress(0, 1, "Load TraML file");
298  TargetedExperiment targeted_exp;
299  FileHandler().loadTransitions(tr_file, targeted_exp, {FileTypes::TRAML});
300  OpenSwathDataAccessHelper::convertTargetedExp(targeted_exp, transition_exp);
301  progresslogger.endProgress();
302  }
303  else if (tr_type == FileTypes::PQP)
304  {
305  progresslogger.startProgress(0, 1, "Load PQP file");
306  TransitionPQPFile().convertPQPToTargetedExperiment(tr_file.c_str(), transition_exp);
307  progresslogger.endProgress();
308  }
309  else if (tr_type == FileTypes::TSV)
310  {
311  progresslogger.startProgress(0, 1, "Load TSV file");
312  TransitionTSVFile tsv_reader;
313  tsv_reader.setParameters(tsv_reader_param);
314  tsv_reader.convertTSVToTargetedExperiment(tr_file.c_str(), tr_type, transition_exp);
315  progresslogger.endProgress();
316  }
317  else
318  {
319  OPENMS_LOG_ERROR << "Provide valid TraML, TSV or PQP transition file." << std::endl;
320  throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Need to provide valid input file.");
321  }
322  return transition_exp;
323  }
324 
359  String irt_tr_file,
360  std::vector< OpenSwath::SwathMap > & swath_maps,
361  double min_rsq,
362  double min_coverage,
363  const Param& feature_finder_param,
364  const ChromExtractParams& cp_irt,
365  const Param& irt_detection_param,
366  const Param& calibration_param,
367  Size debug_level,
368  bool sonar,
369  bool pasef,
370  bool load_into_memory,
371  const String& irt_trafo_out,
372  const String& irt_mzml_out)
373  {
374  TransformationDescription trafo_rtnorm;
375 
376  if (!trafo_in.empty())
377  {
378  // get read RT normalization file
379  FileHandler().loadTransformations(trafo_in, trafo_rtnorm, false, {FileTypes::TRANSFORMATIONXML});
380  Param model_params = getParam_().copy("model:", true);
381  model_params.setValue("symmetric_regression", "false");
382  model_params.setValue("span", irt_detection_param.getValue("lowess:span"));
383  model_params.setValue("num_nodes", irt_detection_param.getValue("b_spline:num_nodes"));
384  String model_type = irt_detection_param.getValue("alignmentMethod").toString();
385  trafo_rtnorm.fitModel(model_type, model_params);
386  }
387  else if (!irt_tr_file.empty())
388  {
389  // Loading iRT file
390  std::cout << "Will load iRT transitions and try to find iRT peptides" << std::endl;
391  FileTypes::Type tr_type = FileHandler::getType(irt_tr_file);
392  Param tsv_reader_param = TransitionTSVFile().getDefaults();
393  OpenSwath::LightTargetedExperiment irt_transitions = loadTransitionList(tr_type, irt_tr_file, tsv_reader_param);
394 
395  // If pasef flag is set, validate that IM is present
396  if (pasef)
397  {
398  const auto& transitions = irt_transitions.getTransitions();
399 
400  for ( Size k=0; k < (Size)transitions.size(); k++ )
401  {
402  if (transitions[k].precursor_im == -1)
403  {
404  throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Error: iRT Transition " + transitions[k].getNativeID() + " does not have a valid IM value, this must be set to use the -pasef flag");
405  }
406  }
407  }
408 
409  // perform extraction
411  wf.setLogType(log_type_);
412  TransformationDescription im_trafo;
413  trafo_rtnorm = wf.performRTNormalization(irt_transitions, swath_maps, im_trafo,
414  min_rsq, min_coverage,
415  feature_finder_param,
416  cp_irt, irt_detection_param,
417  calibration_param, irt_mzml_out, debug_level, sonar, pasef,
418  load_into_memory);
419 
420  if (!irt_trafo_out.empty())
421  {
422  FileHandler().storeTransformations(irt_trafo_out, trafo_rtnorm, {FileTypes::TRANSFORMATIONXML});
423  }
424  }
425  return trafo_rtnorm;
426  }
427 
428 
429 };
430 
431 }
#define OPENMS_LOG_DEBUG
Macro for general debugging information.
Definition: LogStream.h:454
#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_ERROR
Macro to be used if non-fatal error are reported (processing continues)
Definition: LogStream.h:439
@ SMOOTHING
Smoothing of the signal to reduce noise.
Definition: DataProcessing.h:37
void setParameters(const Param &param)
Sets the parameters.
const Param & getDefaults() const
Non-mutable access to the default parameters.
A method or algorithm argument contains illegal values.
Definition: Exception.h:616
Facilitates file handling by file type recognition.
Definition: FileHandler.h:45
void storeTransformations(const String &filename, const TransformationDescription &map, const std::vector< FileTypes::Type > allowed_types={})
Store Transformations.
static FileTypes::Type getType(const String &filename)
Tries to determine the file type (by name or content)
static FileTypes::Type getTypeByFileName(const String &filename)
Try to get the file type from the filename.
void loadTransformations(const String &filename, TransformationDescription &map, bool fit_model=true, const std::vector< FileTypes::Type > allowed_types={})
Loads a file into Transformations.
void loadTransitions(const String &filename, TargetedExperiment &library, const std::vector< FileTypes::Type > allowed_types={}, ProgressLogger::LogType log=ProgressLogger::NONE)
Load transitions of a spectral library.
The interface of a consumer of spectra and chromatograms.
Definition: IMSDataConsumer.h:46
PeakFileOptions & getOptions()
Get the peak file options.
A data consumer that inserts MS data into a SQLite database.
Definition: MSDataSqlConsumer.h:36
void setExpectedSize(Size expectedSpectra, Size expectedChromatograms) override
Set expected size of spectra and chromatograms to be written.
virtual void addDataProcessing(DataProcessing d)
Optionally add a data processing method to each chromatogram and spectrum.
void setExperimentalSettings(const ExperimentalSettings &exp) override
Set experimental settings for the whole file.
Consumer class that perform no operation.
Definition: MSDataWritingConsumer.h:233
Execute all steps for retention time and m/z calibration of SWATH-MS data.
Definition: OpenSwathWorkflow.h:232
TransformationDescription performRTNormalization(const OpenSwath::LightTargetedExperiment &irt_transitions, std::vector< OpenSwath::SwathMap > &swath_maps, TransformationDescription &im_trafo, double min_rsq, double min_coverage, const Param &feature_finder_param, const ChromExtractParams &cp_irt, const Param &irt_detection_param, const Param &calibration_param, const String &irt_mzml_out, Size debug_level, bool sonar=false, bool pasef=false, bool load_into_memory=false)
Perform RT and m/z correction of the input data using RT-normalization peptides.
static void convertTargetedExp(const OpenMS::TargetedExperiment &transition_exp_, OpenSwath::LightTargetedExperiment &transition_exp)
convert from the OpenMS TargetedExperiment to the LightTargetedExperiment
std::string toString(bool full_precision=true) const
Convert ParamValue to string.
Management and storage of parameters / INI files.
Definition: Param.h:44
Param copy(const std::string &prefix, bool remove_prefix=false) const
Returns a new Param object containing all entries that start with prefix.
const ParamValue & getValue(const std::string &key) const
Returns a value of a parameter.
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.
void setNumpressConfigurationIntensity(MSNumpressCoder::NumpressConfig config)
Get numpress configuration options for intensity dimension.
void setCompression(bool compress)
void setWriteIndex(bool write_index)
Whether to write an index at the end of the file (e.g. indexedmzML file format)
void setNumpressConfigurationMassTime(MSNumpressCoder::NumpressConfig config)
Get numpress configuration options for m/z or rt dimension.
Consumer class that writes MS data to disk using the mzML format.
Definition: MSDataWritingConsumer.h:215
Base class for all classes that want to report their progress.
Definition: ProgressLogger.h:27
void setLogType(LogType type) const
Sets the progress log that should be used. The default type is NONE!
void startProgress(SignedSize begin, SignedSize end, const String &label) const
Initializes the progress display.
void endProgress(UInt64 bytes_processed=0) const
A more convenient string class.
Definition: String.h:34
String & toLower()
Converts the string to lowercase.
bool hasSuffix(const String &string) const
true if String ends with string, false otherwise
File adapter for Swath files.
Definition: SwathFile.h:43
std::vector< OpenSwath::SwathMap > loadMzML(const String &file, const String &tmp, boost::shared_ptr< ExperimentalSettings > &exp_meta, const String &readoptions="normal", Interfaces::IMSDataConsumer *plugin_consumer=nullptr)
Loads a Swath run from a single mzML file.
std::vector< OpenSwath::SwathMap > loadSqMass(const String &file, boost::shared_ptr< ExperimentalSettings > &)
Loads a Swath run from a single sqMass file.
std::vector< OpenSwath::SwathMap > loadSplit(StringList file_list, const String &tmp, boost::shared_ptr< ExperimentalSettings > &exp_meta, const String &readoptions="normal")
Loads a Swath run from a list of split mzML files.
std::vector< OpenSwath::SwathMap > loadMzXML(const String &file, const String &tmp, boost::shared_ptr< ExperimentalSettings > &exp_meta, const String &readoptions="normal")
Loads a Swath run from a single mzXML file.
static void annotateSwathMapsFromFile(const std::string &filename, std::vector< OpenSwath::SwathMap > &swath_maps, bool do_sort, bool force)
Annotate a Swath map using a Swath window file specifying the individual windows.
Base class for TOPP applications.
Definition: TOPPBase.h:122
Param const & getParam_() const
Return all parameters relevant to this TOPP tool.
ProgressLogger::LogType log_type_
Type of progress logging.
Definition: TOPPBase.h:948
DataProcessing getProcessingInfo_(DataProcessing::ProcessingAction action) const
Returns the data processing information.
Definition: OpenSwathBase.h:55
void prepareChromOutput(Interfaces::IMSDataConsumer **chromatogramConsumer, const boost::shared_ptr< ExperimentalSettings > &exp_meta, const OpenSwath::LightTargetedExperiment &transition_exp, const String &out_chrom, const UInt64 run_id)
Prepare chromatogram output.
Definition: OpenSwathBase.h:232
TOPPOpenSwathBase(String name, String description, bool official=true)
Definition: OpenSwathBase.h:59
bool loadSwathFiles(const StringList &file_list, boost::shared_ptr< ExperimentalSettings > &exp_meta, std::vector< OpenSwath::SwathMap > &swath_maps, const bool split_file, const String &tmp, const String &readoptions, const String &swath_windows_file, const double min_upper_edge_dist, const bool force, const bool sort_swath_maps, const bool sonar, const bool prm, const bool pasef, Interfaces::IMSDataConsumer *plugin_consumer=nullptr)
Load the DIA files into internal data structures.
Definition: OpenSwathBase.h:133
TransformationDescription performCalibration(String trafo_in, String irt_tr_file, std::vector< OpenSwath::SwathMap > &swath_maps, double min_rsq, double min_coverage, const Param &feature_finder_param, const ChromExtractParams &cp_irt, const Param &irt_detection_param, const Param &calibration_param, Size debug_level, bool sonar, bool pasef, bool load_into_memory, const String &irt_trafo_out, const String &irt_mzml_out)
Perform retention time and m/z calibration.
Definition: OpenSwathBase.h:358
OpenSwath::LightTargetedExperiment loadTransitionList(const FileTypes::Type &tr_type, const String &tr_file, const Param &tsv_reader_param)
Loads transition list from TraML / TSV or PQP.
Definition: OpenSwathBase.h:288
void loadSwathFiles_(const StringList &file_list, const bool split_file, const String &tmp, const String &readoptions, boost::shared_ptr< ExperimentalSettings > &exp_meta, std::vector< OpenSwath::SwathMap > &swath_maps, Interfaces::IMSDataConsumer *plugin_consumer)
Definition: OpenSwathBase.h:66
A description of a targeted experiment containing precursor and production ions.
Definition: TargetedExperiment.h:39
Generic description of a coordinate transformation.
Definition: TransformationDescription.h:37
void fitModel(const String &model_type, const Param &params=Param())
Fits a model to the data.
This class supports reading and writing of PQP files.
Definition: TransitionPQPFile.h:191
void convertPQPToTargetedExperiment(const char *filename, OpenMS::TargetedExperiment &targeted_exp, bool legacy_traml_id=false)
Read in a PQP file and construct a targeted experiment (TraML structure)
Definition: TransitionTSVFile.h:121
void convertTSVToTargetedExperiment(const char *filename, FileTypes::Type filetype, OpenMS::TargetedExperiment &targeted_exp)
Read in a tsv/mrm file and construct a targeted experiment (TraML structure)
uint64_t UInt64
Unsigned integer type (64bit)
Definition: Types.h:47
size_t Size
Size type e.g. used as variable which can hold result of size()
Definition: Types.h:97
std::vector< String > StringList
Vector of String.
Definition: ListUtils.h:44
const double k
Definition: Constants.h:132
Main OpenMS namespace.
Definition: openswathalgo/include/OpenMS/OPENSWATHALGO/DATAACCESS/ISpectrumAccess.h:19
ChromatogramExtractor parameters.
Definition: OpenSwathWorkflow.h:57
Type
Actual file types enum.
Definition: FileTypes.h:31
@ TRAML
TraML (HUPO PSI format) for transitions (.traML)
Definition: FileTypes.h:53
@ PQP
OpenSWATH Peptide Query Parameter (PQP) SQLite DB, see TransitionPQPFile.
Definition: FileTypes.h:75
@ TSV
any TSV file, for example msInspect file or OpenSWATH transition file (see TransitionTSVFile)
Definition: FileTypes.h:59
@ TRANSFORMATIONXML
Transformation description file (.trafoXML)
Definition: FileTypes.h:43
@ MZML
MzML file (.mzML)
Definition: FileTypes.h:44
@ SQMASS
SqLite format for mass and chromatograms, see SqMassFile.
Definition: FileTypes.h:74
@ MZXML
MzXML file (.mzXML)
Definition: FileTypes.h:36
Configuration class for MSNumpress.
Definition: MSNumpressCoder.h:63
double numpressErrorTolerance
Check error tolerance after encoding.
Definition: MSNumpressCoder.h:82
void setCompression(const std::string &compression)
Set compression using a string mapping to enum NumpressCompression.
Definition: MSNumpressCoder.h:123
double linear_fp_mass_acc
Desired mass accuracy for linear encoding.
Definition: MSNumpressCoder.h:105
bool estimate_fixed_point
Whether to estimate the fixed point used for encoding (highly recommended)
Definition: MSNumpressCoder.h:97
Definition: TransitionExperiment.h:185
std::vector< LightTransition > transitions
Definition: TransitionExperiment.h:193
std::vector< LightTransition > & getTransitions()
Definition: TransitionExperiment.h:196