keyword
stringclasses
7 values
repo_name
stringlengths
8
98
file_path
stringlengths
4
244
file_extension
stringclasses
29 values
file_size
int64
0
84.1M
line_count
int64
0
1.6M
content
stringlengths
1
84.1M
language
stringclasses
14 values
3D
OpenMS/OpenMS
src/openms/include/OpenMS/FORMAT/PepXMLFileMascot.h
.h
2,625
84
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Nico Pfeifer $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/METADATA/ProteinIdentification.h> #include <OpenMS/METADATA/PeptideIdentification.h> #include <OpenMS/FORMAT/HANDLERS/XMLHandler.h> #include <OpenMS/FORMAT/XMLFile.h> #include <OpenMS/CHEMISTRY/AASequence.h> #include <vector> namespace OpenMS { /** @brief Used to load Mascot PepXML files A schema for this format can be found at http://www.matrixscience.com/xmlns/schema/pepXML_v18/pepXML_v18.xsd. @ingroup FileIO */ class OPENMS_DLLAPI PepXMLFileMascot : protected Internal::XMLHandler, public Internal::XMLFile { public: /// Constructor PepXMLFileMascot(); /** @brief Loads peptide sequences with modifications out of a PepXML file @exception Exception::FileNotFound is thrown if the file could not be opened @exception Exception::ParseError is thrown if an error occurs during parsing */ void load(const String & filename, std::map<String, std::vector<AASequence> > & peptides); protected: // Docu in base class void endElement(const XMLCh * const /*uri*/, const XMLCh * const /*local_name*/, const XMLCh * const qname) override; // Docu in base class void startElement(const XMLCh * const /*uri*/, const XMLCh * const /*local_name*/, const XMLCh * const qname, const xercesc::Attributes & attributes) override; void matchModification_(double mass, String & modification_description); /// @name members for loading data //@{ /// Pointer to fill in protein identifications /// The title of the actual spectrum String actual_title_; /// The sequence of the actual peptide hit String actual_sequence_; /// The modifications of the actual peptide hit (position is 1-based) std::vector<std::pair<String, UInt> > actual_modifications_; /// The peptides together with the spectrum title std::map<String, std::vector<AASequence> > * peptides_; /// stores the actual peptide sequences std::vector<AASequence> actual_aa_sequences_; /// stores the fixed residue modifications std::vector<String> fixed_modifications_; /// stores the variable residue modifications std::vector<std::pair<String, double> > variable_modifications_; //@} }; } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/FORMAT/MSstatsFile.h
.h
11,163
290
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Timo Sachsenberg, Lukas Heumos $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/METADATA/ExperimentalDesign.h> #include <OpenMS/KERNEL/ConsensusMap.h> #include <OpenMS/FORMAT/TextFile.h> #include <map> #include <utility> #include <unordered_map> #include <set> #include <vector> namespace OpenMS { using IndProtGrp = OpenMS::ProteinIdentification::ProteinGroup; using IndProtGrps = std::vector<IndProtGrp>; /** @brief File adapter for MSstats files @ingroup FileIO */ class OPENMS_DLLAPI MSstatsFile { public: /// Default constructor MSstatsFile() = default; /// Destructor ~MSstatsFile() = default; /// store label free experiment (MSstats) void storeLFQ(const String& filename, const ConsensusMap &consensus_map, // we might add singleton protein groups const ExperimentalDesign& design, const StringList& reannotate_filenames, const bool is_isotope_label_type, const String& bioreplicate, const String& condition, const String& retention_time_summarization_method); /// store isobaric experiment (MSstatsTMT) void storeISO(const String& filename, const ConsensusMap &consensus_map, const ExperimentalDesign& design, const StringList& reannotate_filenames, const String& bioreplicate, const String& condition, const String& mixture, const String& retention_time_summarization_method); private: typedef OpenMS::Peak2D::IntensityType Intensity; typedef OpenMS::Peak2D::CoordinateType Coordinate; static const String na_string_; static const char delim_ = ','; static const char accdelim_ = ';'; static const char quote_ = '"'; /* * @brief: Struct to aggregate intermediate information from ConsensusFeature and ConsensusMap, * such as filenames, intensities, retention times, labels and features (for further processing) */ struct AggregatedConsensusInfo { std::vector< std::vector< String > > consensus_feature_filenames; //< Filenames of ConsensusFeature std::vector< std::vector< Intensity > > consensus_feature_intensities; //< Intensities of ConsensusFeature std::vector< std::vector< Coordinate > > consensus_feature_retention_times; //< Retention times of ConsensusFeature std::vector< std::vector< unsigned > > consensus_feature_labels; //< Labels of ConsensusFeature std::vector<BaseFeature> features; //<s Features of ConsensusMap }; /* * @brief: Aggregates information from ConsensusFeature and ConsensusMap, * such as filenames, intensities, retention times, labels and features. * Stores them in AggregatedConsensusInfo for later processing */ MSstatsFile::AggregatedConsensusInfo aggregateInfo_(const ConsensusMap& consensus_map, const std::vector<String>& spectra_paths); /* * @brief: Internal function to check if MSstats_BioReplicate and MSstats_Condition exists in Experimental Design */ static void checkConditionLFQ_(const ExperimentalDesign::SampleSection& sampleSection, const String& bioreplicate, const String& condition); /* * @brief: Internal function to check if MSstats_BioReplicate, MSstats_Condition and MSstats_Mixture in Experimental Design */ static void checkConditionISO_(const ExperimentalDesign::SampleSection& sampleSection, const String& bioreplicate, const String& condition, const String& mixture); /* * @brief MSstats treats runs differently than OpenMS. In MSstats, runs are an enumeration of (SpectraFilePath, Fraction) * In OpenMS, a run is split into multiple fractions. */ static void assembleRunMap_( std::map< std::pair< String, unsigned>, unsigned> &run_map, const ExperimentalDesign &design); /* * @brief checks two vectors for same content */ static bool checkUnorderedContent_(const std::vector< String> &first, const std::vector< String > &second); OpenMS::Peak2D::IntensityType sumIntensity_(const std::set< OpenMS::Peak2D::IntensityType > &intensities) const { OpenMS::Peak2D::IntensityType result = 0; for (const OpenMS::Peak2D::IntensityType &intensity : intensities) { result += intensity; } return result; } OpenMS::Peak2D::IntensityType meanIntensity_(const std::set< OpenMS::Peak2D::IntensityType > &intensities) const { return sumIntensity_(intensities) / intensities.size(); } class MSstatsLine_ { public : MSstatsLine_( bool _has_fraction, const String& _accession, const String& _sequence, const String& _precursor_charge, const String& _fragment_ion, const String& _frag_charge, const String& _isotope_label_type, const String& _condition, const String& _bioreplicate, const String& _run, const String& _fraction ): has_fraction_(_has_fraction), accession_(_accession), sequence_(_sequence), precursor_charge_(_precursor_charge), fragment_ion_(_fragment_ion), frag_charge_(_frag_charge), isotope_label_type_(_isotope_label_type), condition_(_condition), bioreplicate_(_bioreplicate), run_(_run), fraction_(_fraction) {} const String& accession() const {return this->accession_;} const String& sequence() const {return this->sequence_;} const String& precursor_charge() const {return this->precursor_charge_;} const String& run() const {return this->run_;} String toString() const { const String delim(","); return accession_ + delim + sequence_ + delim + precursor_charge_ + delim + fragment_ion_ + delim + frag_charge_ + delim + isotope_label_type_ + delim + condition_ + delim + bioreplicate_ + delim + run_ + (this->has_fraction_ ? delim + String(fraction_) : ""); } friend bool operator<(const MSstatsLine_ &l, const MSstatsLine_ &r) { return std::tie(l.accession_, l.run_, l.condition_, l.bioreplicate_, l.precursor_charge_, l.sequence_) < std::tie(r.accession_, r.run_, r.condition_, r.bioreplicate_, r.precursor_charge_, r.sequence_); } private: bool has_fraction_; String accession_; String sequence_; String precursor_charge_; String fragment_ion_; String frag_charge_; String isotope_label_type_; String condition_; String bioreplicate_; String run_; String fraction_; }; class MSstatsTMTLine_ { public : MSstatsTMTLine_( const String& _accession, const String& _sequence, const String& _precursor_charge, const String& _channel, const String& _condition, const String& _bioreplicate, const String& _run, const String& _mixture, const String& _techrepmixture, const String& _fraction ): accession_(_accession), sequence_(_sequence), precursor_charge_(_precursor_charge), channel_(_channel), condition_(_condition), bioreplicate_(_bioreplicate), run_(_run), mixture_(_mixture), techrepmixture_(_techrepmixture), fraction_(_fraction) {} const String& accession() const {return this->accession_;} const String& sequence() const {return this->sequence_;} const String& precursor_charge() const {return this->precursor_charge_;} const String& run() const {return this->run_;} String toString() const { const String delim(","); return accession_ + delim + sequence_ + delim + precursor_charge_ + delim + channel_ + delim + condition_ + delim + bioreplicate_ + delim + run_ + delim + mixture_ + delim + techrepmixture_ + delim + String(fraction_); } friend bool operator<(const MSstatsTMTLine_ &l, const MSstatsTMTLine_ &r) { return std::tie(l.accession_, l.run_, l.condition_, l.bioreplicate_, l.mixture_, l.precursor_charge_, l.sequence_, l.channel_) < std::tie(r.accession_, r.run_, r.condition_, r.bioreplicate_, r.mixture_, r.precursor_charge_, r.sequence_, r.channel_); } private: String accession_; String sequence_; String precursor_charge_; String channel_; String condition_; String bioreplicate_; String run_; String mixture_; String techrepmixture_; String fraction_; }; /* * @brief Constructs the lines and adds them to the TextFile * @param[out] peptideseq_quantifyable Has to be a set (only) for deterministic ordered output */ template <class LineType> void constructFile_(const String& retention_time_summarization_method, const bool rt_summarization_manual, TextFile& csv_out, const std::set<String>& peptideseq_quantifyable, LineType & peptideseq_to_prefix_to_intensities) const; /* * @brief Constructs the accession to indist. group mapping */ static std::unordered_map<OpenMS::String, const IndProtGrp* > getAccessionToGroupMap_(const IndProtGrps& ind_prots); /* * @brief Based on the evidence accession set in a PeptideHit, checks if is unique and therefore quantifyable * in a group context. * */ bool isQuantifyable_( const std::set<String>& accs, const std::unordered_map<String, const IndProtGrp*>& accession_to_group) const; }; } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/FORMAT/IdXMLFile.h
.h
6,791
165
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Marc Sturm $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/CONCEPT/ProgressLogger.h> #include <OpenMS/METADATA/ProteinIdentification.h> #include <OpenMS/METADATA/PeptideIdentification.h> #include <OpenMS/METADATA/PeptideIdentificationList.h> #include <OpenMS/FORMAT/HANDLERS/XMLHandler.h> #include <OpenMS/FORMAT/XMLFile.h> #include <vector> namespace OpenMS { namespace Internal { class FeatureXMLHandler; class ConsensusXMLHandler; } /** @brief Used to load and store idXML files This class is used to load and store documents that implement the schema of idXML files. A documented schema for this format can be found at https://github.com/OpenMS/OpenMS/tree/develop/share/OpenMS/SCHEMAS One file can contain several ProteinIdentification runs. Each run consists of peptide hits stored in PeptideIdentification and (optional) protein hits stored in Identification. Peptide and protein hits are connected via a string identifier. We use the search engine and the date as identifier. @ingroup FileIO */ class OPENMS_DLLAPI IdXMLFile : protected Internal::XMLHandler, public Internal::XMLFile, public ProgressLogger { public: // both ConsensusXMLFile and FeatureXMLFile use some protected IdXML helper functions to parse identifications without code duplication friend class Internal::ConsensusXMLHandler; friend class Internal::FeatureXMLHandler; /// Constructor IdXMLFile(); /** @brief Loads the identifications of an idXML file without identifier The information is read in and the information is stored in the corresponding variables @exception Exception::FileNotFound is thrown if the file could not be opened @exception Exception::ParseError is thrown if an error occurs during parsing */ void load(const String& filename, std::vector<ProteinIdentification>& protein_ids, PeptideIdentificationList& peptide_ids); /** @brief Loads the identifications of an idXML file The information is read in and the information is stored in the corresponding variables @exception Exception::FileNotFound is thrown if the file could not be opened @exception Exception::ParseError is thrown if an error occurs during parsing */ void load(const String& filename, std::vector<ProteinIdentification>& protein_ids, PeptideIdentificationList& peptide_ids, String& document_id); /** @brief Stores the data in an idXML file The data is read in and stored in the file 'filename'. PeptideHits are sorted by score. Note that ranks are not stored and need to be reassigned after loading. @exception Exception::UnableToCreateFile is thrown if the file could not be created */ void store(const String& filename, const std::vector<ProteinIdentification>& protein_ids, const PeptideIdentificationList& peptide_ids, const String& document_id = ""); protected: // Docu in base class void endElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname) override; // Docu in base class void startElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname, const xercesc::Attributes& attributes) override; /// Add data from ProteinGroups to a MetaInfoInterface /// Since it can be used during load and store, it needs to take a param for the current mode (LOAD/STORE) /// to throw appropriate warnings/errors void addProteinGroups_(MetaInfoInterface& meta, const std::vector<ProteinIdentification::ProteinGroup>& groups, const String& group_name, const std::unordered_map<std::string, UInt>& accession_to_id, XMLHandler::ActionMode mode); /// Read and store ProteinGroup data void getProteinGroups_(std::vector<ProteinIdentification::ProteinGroup>& groups, const String& group_name); /** * Helper function to create the XML string for the amino acids before and after the peptide position in a protein. * Can be reused by e.g. ConsensusXML, FeatureXML to write PeptideHit elements */ static std::ostream& createFlankingAAXMLString_(const std::vector<PeptideEvidence> & pes, std::ostream& os); /** * Helper function to create the XML string for the position of the peptide in a protein. * Can be reused by e.g. ConsensusXML, FeatureXML to write PeptideHit elements */ static std::ostream& createPositionXMLString_(const std::vector<PeptideEvidence> & pes, std::ostream& os); /** * Helper function to write out fragment annotations as user param fragment_annotation */ static void writeFragmentAnnotations_(const String & tag_name, std::ostream & os, const std::vector<PeptideHit::PeakAnnotation>& annotations, UInt indent); /** * Helper function to parse fragment annotations from string */ static void parseFragmentAnnotation_(const String& s, std::vector<PeptideHit::PeakAnnotation> & annotations); /// @name members for loading data //@{ /// Pointer to fill in protein identifications std::vector<ProteinIdentification>* prot_ids_; /// Pointer to fill in peptide identifications PeptideIdentificationList* pep_ids_; /// Pointer to last read object with MetaInfoInterface MetaInfoInterface* last_meta_; /// Search parameters map (key is the "id") std::map<String, ProteinIdentification::SearchParameters> parameters_; /// Temporary search parameters variable ProteinIdentification::SearchParameters param_; /// Temporary id String id_; /// Temporary protein ProteinIdentification ProteinIdentification prot_id_; /// Temporary peptide ProteinIdentification PeptideIdentification pep_id_; /// Temporary protein hit ProteinHit prot_hit_; /// Temporary peptide hit PeptideHit pep_hit_; /// Temporary analysis result instance PeptideHit::PepXMLAnalysisResult current_analysis_result_; /// Temporary peptide evidences std::vector<PeptideEvidence> peptide_evidences_; /// Map from protein id to accession std::unordered_map<std::string, String> proteinid_to_accession_; /// Document identifier String* document_id_; /// true if a prot id is contained in the current run bool prot_id_in_run_; //@} }; } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/FORMAT/MzTabM.h
.h
14,634
292
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Oliver Alka $ // $Authors: Oliver Alka $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/FORMAT/MzTabBase.h> #include <OpenMS/KERNEL/FeatureMap.h> #include <OpenMS/METADATA/ID/IdentificationData.h> #include <OpenMS/METADATA/MetaInfoInterface.h> #include <set> namespace OpenMS { /** @brief Data model of MzTabM files. Please see the official MzTabM specification at https://github.com/HUPO-PSI/mzTab/tree/master/specification_document-releases/2_0-Metabolomics-Release @ingroup FileIO */ struct CompareMzTabMMatchRef { bool operator() (const IdentificationDataInternal::ObservationMatchRef& lhs, const IdentificationDataInternal::ObservationMatchRef& rhs) const { return lhs->identified_molecule_var.getIdentifiedCompoundRef()->identifier < rhs->identified_molecule_var.getIdentifiedCompoundRef()->identifier; } }; /** @brief MztabM Assay Metadata */ class OPENMS_DLLAPI MzTabMAssayMetaData { public: MzTabString name; ///< Name of the assay std::map<Size,MzTabParameter> custom; ///< Additional parameters or values for a given assay MzTabString external_uri; ///< A reference to further information about the assay MzTabInteger sample_ref; ///< An association from a given assay to the sample analysed MzTabInteger ms_run_ref; ///< An association from a given assay to the source MS run }; /** @brief MztabM MSRun Metadata */ class OPENMS_DLLAPI MzTabMMSRunMetaData { public: MzTabString location; ///< Location of the external data file MzTabInteger instrument_ref; ///< Link to a specific instrument MzTabParameter format; ///< Parameter specifying the data format of the external MS data file MzTabParameter id_format; ///< Parameter specifying the id format used in the external data file std::map<Size, MzTabParameter> fragmentation_method; ///< The type of fragmentation used in a given ms run std::map<Size, MzTabParameter> scan_polarity; ///< The polarity mode of a given run MzTabString hash; ///< Hash value of the corresponding external MS data file MzTabParameter hash_method; ///< Parameter specifying the hash methods }; /** @brief MztabM StudyVariable Metadata */ class OPENMS_DLLAPI MzTabMStudyVariableMetaData { public: MzTabString name; ///< Name of the study variable std::vector<int> assay_refs; ///< References to the IDs of assays grouped in the study variable MzTabParameter average_function; ///< The function used to calculate the study variable quantification value MzTabParameter variation_function; ///< The function used to calculate the study variable quantification variation value MzTabString description; ///< A textual description of the study variable MzTabParameterList factors; ///< Additional parameters or factors }; /** @brief MztabM Database Metadata */ class OPENMS_DLLAPI MzTabMDatabaseMetaData // mztab-m { public: MzTabParameter database; ///< The description of databases used MzTabString prefix; ///< The prefix used in the “identifier” column of data tables MzTabString version; ///< The database version MzTabString uri; ///< The URI to the database }; /** @brief MztabM Metadata */ class OPENMS_DLLAPI MzTabMMetaData { public: MzTabMMetaData(); MzTabString mz_tab_version; ///< MzTab-M Version MzTabString mz_tab_id; ///< MzTab-M file id (e.g. repository-, local identifier) MzTabString title; ///< Title MzTabString description; ///< Description std::map<Size, MzTabParameterList> sample_processing; ///< List of parameters describing the sample processing/preparation/handling std::map<Size, MzTabInstrumentMetaData> instrument; ///< List of parameters describing the instrument std::map<Size, MzTabSoftwareMetaData> software; ///< Software used to analyze the data std::map<Size, MzTabString> publication; ///< Associated publication(s) std::map<Size, MzTabContactMetaData> contact; ///< Contact name std::map<Size, MzTabString> uri; ///< Pointing to file source (e.g. MetaboLights) std::map<Size, MzTabString> external_study_uri; ///< Pointing to an external file with more details about the study (e.g. ISA-TAB file) MzTabParameter quantification_method; ///< Quantification method used in the experiment std::map<Size, MzTabSampleMetaData> sample; ///< Sample details std::map<Size, MzTabMMSRunMetaData> ms_run; ///< MS run details std::map<Size, MzTabMAssayMetaData> assay; ///< Assay details std::map<Size, MzTabMStudyVariableMetaData> study_variable; ///< Study Variable details std::map<Size, MzTabParameter> custom; ///< Custom parameters std::map<Size, MzTabCVMetaData> cv; ///< Controlled Vocabulary details std::map<Size, MzTabMDatabaseMetaData> database; ///< Database details std::map<Size, MzTabParameter> derivatization_agent; ///< A description of derivatization agents applied to small molecules MzTabParameter small_molecule_quantification_unit; ///< Description of the unit type used MzTabParameter small_molecule_feature_quantification_unit; ///< Description of the unit type used MzTabParameter small_molecule_identification_reliability; ///< Reliability of identification (4-level schema) std::map<Size, MzTabParameter> id_confidence_measure; ///< Confidence measures / scores std::vector<MzTabString> colunit_small_molecule; ///< Defines the unit used for a specific column std::vector<MzTabString> colunit_small_molecule_feature; ///< Defines the unit used for a specific column std::vector<MzTabString> colunit_small_molecule_evidence; ///< Defines the unit used for a specific column }; /** @brief SML Small molecule section (mztab-m) */ class OPENMS_DLLAPI MzTabMSmallMoleculeSectionRow { public: MzTabString sml_identifier; ///< The small molecule’s identifier. MzTabStringList smf_id_refs; ///< References to all the features on which quantification has been based. MzTabStringList database_identifier; ///< Names of the used databases. MzTabStringList chemical_formula; ///< Potential chemical formula of the reported compound. MzTabStringList smiles; ///< Molecular structure in SMILES format. MzTabStringList inchi; ///< InChi of the potential compound identifications. MzTabStringList chemical_name; ///< Possible chemical/common names or general description MzTabStringList uri; ///< The source entry’s location. MzTabDoubleList theoretical_neutral_mass; ///< Precursor theoretical neutral mass MzTabStringList adducts; ///< Adducts // Reliability information of the used indentificavtion method has to be stored in the ID data structure MzTabString reliability; ///< Reliability of the given small molecule identification MzTabParameter best_id_confidence_measure; ///< The identification approach with the highest confidence MzTabDouble best_id_confidence_value; ///< The best confidence measure std::map<Size, MzTabDouble> small_molecule_abundance_assay; ///< The small molecule’s abundance in every assay described in the metadata section std::map<Size, MzTabDouble> small_molecule_abundance_study_variable; ///< The small molecule’s abundance in all the study variables described in the metadata section std::map<Size, MzTabDouble> small_molecule_abundance_variation_study_variable; ///< A measure of the variability of the study variable abundance measurement std::vector<MzTabOptionalColumnEntry> opt_; ///< Optional columns must start with “opt_”. }; /** @brief SMF Small molecule feature section (mztab-m) */ class OPENMS_DLLAPI MzTabMSmallMoleculeFeatureSectionRow { public: MzTabString smf_identifier; ///< Within file unique identifier for the small molecule feature. MzTabStringList sme_id_refs; ///< Reference to the identification evidence. MzTabInteger sme_id_ref_ambiguity_code; ///< Ambiguity in identifications. MzTabString adduct; ///< Adduct MzTabParameter isotopomer; ///< If de-isotoping has not been performed, then the isotopomer quantified MUST be reported here. MzTabDouble exp_mass_to_charge; ///< Precursor ion’s m/z. MzTabInteger charge; ///< Precursor ion’s charge. MzTabDouble retention_time; ///< Time point in seconds. MzTabDouble rt_start; ///< The start time of the feature on the retention time axis. MzTabDouble rt_end; ///< The end time of the feature on the retention time axis std::map<Size, MzTabDouble> small_molecule_feature_abundance_assay; ///< Feature abundance in every assay std::vector<MzTabOptionalColumnEntry> opt_; ///< Optional columns must start with “opt_”. }; /** @brief SME Small molecule evidence section (mztab-m) */ class OPENMS_DLLAPI MzTabMSmallMoleculeEvidenceSectionRow { public: MzTabString sme_identifier; ///< Within file unique identifier for the small molecule evidence result. MzTabString evidence_input_id; ///< Within file unique identifier for the input data used to support this identification e.g. fragment spectrum, RT and m/z pair. MzTabString database_identifier; ///< The putative identification for the small molecule sourced from an external database. MzTabString chemical_formula; ///< The putative molecular formula. MzTabString smiles; ///< Potential molecular structure as SMILES. MzTabString inchi; ///< InChi of the potential compound identifications. MzTabString chemical_name; ///< Possible chemical/common names or general description MzTabString uri; ///< The source entry’s location. MzTabParameter derivatized_form; ///< derivatized form. MzTabString adduct; ///< Adduct MzTabDouble exp_mass_to_charge; ///< Precursor ion’s m/z. MzTabInteger charge; ///< Precursor ion’s charge. MzTabDouble calc_mass_to_charge; ///< Precursor ion’s m/z. MzTabSpectraRef spectra_ref; ///< Reference to a spectrum MzTabParameter identification_method; ///< Database search, search engine or process that was used to identify this small molecule MzTabParameter ms_level; ///< The highest MS level used to inform identification std::map<Size, MzTabDouble> id_confidence_measure; ///< Statistical value or score for the identification MzTabInteger rank; ///< Rank of the identification (1 = best) std::vector<MzTabOptionalColumnEntry> opt_; ///< Optional columns must start with “opt_”. }; typedef std::vector<MzTabMSmallMoleculeSectionRow> MzTabMSmallMoleculeSectionRows; typedef std::vector<MzTabMSmallMoleculeFeatureSectionRow> MzTabMSmallMoleculeFeatureSectionRows; typedef std::vector<MzTabMSmallMoleculeEvidenceSectionRow> MzTabMSmallMoleculeEvidenceSectionRows; /** @brief Data model of MzTab-M files Please see the MzTab-M specification at https://github.com/HUPO-PSI/mzTab/blob/master/specification_document-releases/2_0-Metabolomics-Release/mzTab_format_specification_2_0-M_release.adoc#use-cases-for-mztab */ class OPENMS_DLLAPI MzTabM : public MzTabBase { public: /// Default constructor MzTabM() = default; /// Destructor ~MzTabM() = default; /// Extract MzTabMMetaData const MzTabMMetaData& getMetaData() const; /// Set MzTabMMetaData void setMetaData(const MzTabMMetaData& m_md); /// Extract MzTabMSmallMoleculeSectionRows const MzTabMSmallMoleculeSectionRows& getMSmallMoleculeSectionRows() const; /// Set MzTabMSmallMoleculeSectionRows void setMSmallMoleculeSectionRows(const MzTabMSmallMoleculeSectionRows& m_smsd); /// Extract MzTabMSmallMoleculeFeatureSectionRows const MzTabMSmallMoleculeFeatureSectionRows& getMSmallMoleculeFeatureSectionRows() const; /// Set MzTabMSmallMoleculeFeatureSectionRows void setMSmallMoleculeFeatureSectionRows(const MzTabMSmallMoleculeFeatureSectionRows& m_smfsd); /// Extract MzTabMSmallMoleculeEvidenceSectionRows const MzTabMSmallMoleculeEvidenceSectionRows& getMSmallMoleculeEvidenceSectionRows() const; /// Set MzTabMSmallMoleculeEvidenceSectionRows void setMSmallMoleculeEvidenceSectionRows(const MzTabMSmallMoleculeEvidenceSectionRows& m_smesd); /// Set comment rows void setCommentRows(const std::map<Size, String>& com); /// Set empty rows void setEmptyRows(const std::vector<Size>& empty); /// Get empty rows const std::vector<Size>& getEmptyRows() const; /// Get comment rows const std::map<Size, String>& getCommentRows() const; /// Extract opt_ (custom, optional column names) std::vector<String> getMSmallMoleculeOptionalColumnNames() const; /// Extract opt_ (custom, optional column names) std::vector<String> getMSmallMoleculeFeatureOptionalColumnNames() const; /// Extract opt_ (custom, optional column names) std::vector<String> getMSmallMoleculeEvidenceOptionalColumnNames() const; static void addMetaInfoToOptionalColumns(const std::set<String>& keys, std::vector<MzTabOptionalColumnEntry>& opt, const String& id, const MetaInfoInterface& meta); /** * @brief Export FeatureMap with Identifications to MzTabM * * @return MzTabM object */ static MzTabM exportFeatureMapToMzTabM(const FeatureMap& feature_map); protected: MzTabMMetaData m_meta_data_; MzTabMSmallMoleculeSectionRows m_small_molecule_data_; MzTabMSmallMoleculeFeatureSectionRows m_small_molecule_feature_data_; MzTabMSmallMoleculeEvidenceSectionRows m_small_molecule_evidence_data_; std::vector<Size> empty_rows_; ///< index of empty rows std::map<Size, String> comment_rows_; ///< comments std::vector<String> sml_optional_column_names_; std::vector<String> smf_optional_column_names_; std::vector<String> sme_optional_column_names_; static String getAdductString_(const IdentificationDataInternal::ObservationMatchRef& match_ref); static void getFeatureMapMetaValues_(const FeatureMap& feature_map, std::set<String>& feature_user_value_keys, std::set<String>& observationmatch_user_value_keys, std::set<String>& compound_user_value_keys); }; } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/FORMAT/VALIDATORS/MzMLValidator.h
.h
1,993
77
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Marc Sturm $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/FORMAT/VALIDATORS/SemanticValidator.h> #include <map> namespace OpenMS { class ControlledVocabulary; namespace Internal { /** @brief Semantically validates MzXML files. */ class OPENMS_DLLAPI MzMLValidator : public SemanticValidator { public: /** @brief Constructor @param[in] mapping The mapping rules @param[in] cv @em All controlled vocabularies required for the mapping */ MzMLValidator(const CVMappings & mapping, const ControlledVocabulary & cv); /// Destructor ~MzMLValidator() override; protected: // Docu in base class void startElement(const XMLCh * const /*uri*/, const XMLCh * const /*local_name*/, const XMLCh * const qname, const xercesc::Attributes & attributes) override; // Docu in base class String getPath_(UInt remove_from_end = 0) const override; // Docu in base class void handleTerm_(const String & path, const CVTerm & parsed_term) override; ///CV terms which can have a value (term => value type) std::map<String, std::vector<CVTerm> > param_groups_; ///Current referenceableParamGroup identifier String current_id_; ///Binary data array name String binary_data_array_; ///Binary data array type String binary_data_type_; private: /// Not implemented MzMLValidator(); /// Not implemented MzMLValidator(const MzMLValidator & rhs); /// Not implemented MzMLValidator & operator=(const MzMLValidator & rhs); }; } // namespace Internal } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/FORMAT/VALIDATORS/MzDataValidator.h
.h
1,395
59
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Marc Sturm $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/FORMAT/VALIDATORS/SemanticValidator.h> namespace OpenMS { class ControlledVocabulary; namespace Internal { /** @brief Semantically validates MzXML files. */ class OPENMS_DLLAPI MzDataValidator : public SemanticValidator { public: /** @brief Constructor @param[in] mapping The mapping rules @param[in] cv @em All controlled vocabularies required for the mapping */ MzDataValidator(const CVMappings & mapping, const ControlledVocabulary & cv); /// Destructor ~MzDataValidator() override; protected: //Docu in base class void handleTerm_(const String & path, const CVTerm & parsed_term) override; private: /// Not implemented MzDataValidator(); /// Not implemented MzDataValidator(const MzDataValidator & rhs); /// Not implemented MzDataValidator & operator=(const MzDataValidator & rhs); }; } // namespace Internal } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/FORMAT/VALIDATORS/MzIdentMLValidator.h
.h
1,302
54
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Andreas Bertsch $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/FORMAT/VALIDATORS/SemanticValidator.h> namespace OpenMS { class ControlledVocabulary; namespace Internal { /** @brief Semantically validates MzXML files. */ class OPENMS_DLLAPI MzIdentMLValidator : public SemanticValidator { public: /** @brief Constructor @param[in] mapping The mapping rules @param[in] cv @em All controlled vocabularies required for the mapping */ MzIdentMLValidator(const CVMappings & mapping, const ControlledVocabulary & cv); /// Destructor ~MzIdentMLValidator() override; private: /// Not implemented MzIdentMLValidator(); /// Not implemented MzIdentMLValidator(const MzIdentMLValidator & rhs); /// Not implemented MzIdentMLValidator & operator=(const MzIdentMLValidator & rhs); }; } // namespace Internal } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/FORMAT/VALIDATORS/XMLValidator.h
.h
1,968
66
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Marc Sturm $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/DATASTRUCTURES/String.h> #include <xercesc/sax/ErrorHandler.hpp> #include <iostream> namespace OpenMS { /** @brief Validator for XML files. Validates an XML file against a given schema. @ingroup FileIO */ class OPENMS_DLLAPI XMLValidator : private xercesc::ErrorHandler { public: /// Constructor XMLValidator(); /** @brief Returns if an XML file is valid for given a schema file Error messages are printed to the error stream, unless redirected with the attribute @p os . @param[in] filename The file to validated. @param[in] schema The filename of the schema that should be used for validation. @param[in] os The stream where error messages should be send to. @exception Exception::FileNotFound is thrown if the file cannot be found @exception Exception::ParseError is thrown if the parser could not be initialized */ bool isValid(const String& filename, const String& schema, std::ostream& os = std::cerr); protected: /// Flag if the validated file is valid bool valid_; /// File name of validated file (for error messages) String filename_; //output stream reference (for error messages) std::ostream* os_; /// @name Implementation of Xerces ErrorHandler methods //@{ void warning(const xercesc::SAXParseException& exception) override; void error(const xercesc::SAXParseException& exception) override; void fatalError(const xercesc::SAXParseException& exception) override; void resetErrors() override; //@} }; } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/FORMAT/VALIDATORS/TraMLValidator.h
.h
1,270
54
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Andreas Bertsch $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/FORMAT/VALIDATORS/SemanticValidator.h> namespace OpenMS { class ControlledVocabulary; namespace Internal { /** @brief Semantically validates MzXML files. */ class OPENMS_DLLAPI TraMLValidator : public SemanticValidator { public: /** @brief Constructor @param[in] mapping The mapping rules @param[in] cv @em All controlled vocabularies required for the mapping */ TraMLValidator(const CVMappings & mapping, const ControlledVocabulary & cv); /// Destructor ~TraMLValidator() override; private: /// Not implemented TraMLValidator(); /// Not implemented TraMLValidator(const TraMLValidator & rhs); /// Not implemented TraMLValidator & operator=(const TraMLValidator & rhs); }; } // namespace Internal } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/FORMAT/VALIDATORS/SemanticValidator.h
.h
6,512
189
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Marc Sturm, Andreas Bertsch $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/FORMAT/XMLFile.h> #include <OpenMS/FORMAT/HANDLERS/XMLHandler.h> #include <OpenMS/DATASTRUCTURES/CVMappings.h> #include <map> namespace OpenMS { class ControlledVocabulary; namespace Internal { /** @brief Semantically validates XML files using CVMappings and a ControlledVocabulary. This is the general validator. @n Specialized validators for specific file formats are derived from this class. */ class OPENMS_DLLAPI SemanticValidator : protected Internal::XMLHandler, public Internal::XMLFile { public: /** @brief Constructor @param[in] mapping The mapping rules @param[in] cv @em All controlled vocabularies required for the mapping */ SemanticValidator(const CVMappings & mapping, const ControlledVocabulary & cv); /// Destructor ~SemanticValidator() override; ///Representation of a parsed CV term struct CVTerm { String accession; String name; String value; bool has_value{}; String unit_accession; bool has_unit_accession{}; String unit_name; bool has_unit_name{}; }; /** @brief Semantically validates an XML file. @param[in] filename The file to validate @param[out] errors Errors during the validation are returned in this output parameter. @param[out] warnings Warnings during the validation are returned in this output parameter. @return @em true if the validation was successful, @em false otherwise. @exception Exception::FileNotFound is thrown if the file could not be opened */ bool validate(const String & filename, StringList & errors, StringList & warnings); /// Checks if a CVTerm is allowed in a given path bool locateTerm(const String & path, const CVTerm & parsed_term) const; /// Sets the CV parameter tag name (default: 'cvParam') void setTag(const String & tag); /// Sets the name of the attribute for accessions in the CV parameter tag name (default: 'accession') void setAccessionAttribute(const String & accession); /// Sets the name of the attribute for accessions in the CV parameter tag name (default: 'name') void setNameAttribute(const String & name); /// Sets the name of the attribute for accessions in the CV parameter tag name (default: 'value') void setValueAttribute(const String & value); /** @brief Set if CV term value types should be check (enabled by default) If set to true, the xsd value types are checked, and errors are given in the cases - CVTerm needs value but has none - CVTerm has value but must not have one - CVTerm has value, needs value but value is of wrong type */ void setCheckTermValueTypes(bool check); /** @brief Set if CV term units should be check (disabled by default) If set to true additional checks for CVTerms are performed: - CVTerm that must have a unit, but has none - CVTerm that has a wrong unit */ void setCheckUnits(bool check); /// Sets the name of the unit accession attribute (default: 'unitAccession') void setUnitAccessionAttribute(const String & accession); /// Sets the name of the unit name attribute (default: 'unitName') void setUnitNameAttribute(const String & name); protected: // Docu in base class void startElement(const XMLCh * const /*uri*/, const XMLCh * const /*local_name*/, const XMLCh * const qname, const xercesc::Attributes & attributes) override; // Docu in base class void endElement(const XMLCh * const /*uri*/, const XMLCh * const /*local_name*/, const XMLCh * const qname) override; // Docu in base class void characters(const XMLCh * const chars, const XMLSize_t /*length*/) override; /// Returns the current element path virtual String getPath_(UInt remove_from_end = 0) const; /// Parses the CV term accession (required), name (required) and value (optional) from the XML attributes virtual void getCVTerm_(const xercesc::Attributes & attributes, CVTerm & parsed_term); //~ forward dekl. of a inner struct/class not possible in C++ - or our Library is overtemplated //~ /// make a SemanticValidator::CVTerm from a ControlledVocabulary::CVTerm (without any value or unit), needed for writing only cvs at the right places in the xml (i.e. with cvmapping) //~ virtual void makeCVTerm_(const ControlledVocabulary::CVTerm & lc, CVTerm & parsed_term); /// Handling of the term virtual void handleTerm_(const String & path, const CVTerm & parsed_term); /// Reference to the mappings const CVMappings & mapping_; /// Reference to the CVs const ControlledVocabulary & cv_; /// Validation errors StringList errors_; /// Validation warnings StringList warnings_; /// List of open tags StringList open_tags_; /// Rules (location => rule) std::map<String, std::vector<CVMappingRule> > rules_; /// Fulfilled rules (location => rule ID => term ID => term count ) /// When a tag is closed, the fulfilled rules of the current location are checked against the required rules /// The fulfilled rules for that location are then deleted. std::map<String, std::map<String, std::map<String, UInt> > > fulfilled_; ///@name Tag and attribute names //@{ String cv_tag_; String accession_att_; String name_att_; String value_att_; String unit_accession_att_; String unit_name_att_; bool check_term_value_types_; bool check_units_; //@} private: /// Not implemented SemanticValidator(); /// Not implemented SemanticValidator(const SemanticValidator & rhs); /// Not implemented SemanticValidator & operator=(const SemanticValidator & rhs); }; } // namespace Internal } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/FORMAT/OPTIONS/PeakFileOptions.h
.h
10,309
255
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Marc Sturm $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/DATASTRUCTURES/DRange.h> #include <OpenMS/FORMAT/MSNumpressCoder.h> #include <vector> namespace OpenMS { /** @brief Options for loading files containing peak data. */ class OPENMS_DLLAPI PeakFileOptions { public: ///Default constructor PeakFileOptions(); ///Copy constructor PeakFileOptions(const PeakFileOptions &); ///Copy assignment PeakFileOptions& operator=(const PeakFileOptions&) = default; ///Destructor ~PeakFileOptions(); ///@name Meta data and file format option //@{ ///sets whether or not to load only meta data void setMetadataOnly(bool only); ///returns whether or not to load only meta data bool getMetadataOnly() const; /// [mzXML only!] Whether to write a scan-index and meta data to indicate a Thermo FTMS/ITMS instrument (required to have parameter control in MQ) void setForceMQCompatability(bool forceMQ); /// [mzXML only!] Whether to write a scan-index and meta data to indicate a Thermo FTMS/ITMS instrument (required to have parameter control in MQ) bool getForceMQCompatability() const; /// [mzML only!] Whether to skip writing the \<isolationWindow\> tag so that TPP finds the correct precursor m/z void setForceTPPCompatability(bool forceTPP); /// [mzML only!] Whether to skip writing the \<isolationWindow\> tag so that TPP finds the correct precursor m/z bool getForceTPPCompatability() const; //@} ///@name Supplemental data option //@{ ///sets whether or not to write supplemental peak data in MzData files void setWriteSupplementalData(bool write); ///returns whether or not to write supplemental peak data in MzData files bool getWriteSupplementalData() const; //@} ///@name RT range option //@{ ///restricts the range of RT values for peaks to load void setRTRange(const DRange<1> & range); ///returns @c true if an RT range has been set bool hasRTRange() const; ///returns the RT range const DRange<1> & getRTRange() const; //@} ///@name m/z range option //@{ ///restricts the range of MZ values for peaks to load void setMZRange(const DRange<1> & range); ///returns @c true if an MZ range has been set bool hasMZRange() const; ///returns the MZ range const DRange<1> & getMZRange() const; //@} ///@name Intensity range option //@{ ///restricts the range of intensity values for peaks to load void setIntensityRange(const DRange<1> & range); ///returns @c true if an intensity range has been set bool hasIntensityRange() const; ///returns the intensity range const DRange<1> & getIntensityRange() const; //@} ///@name Precursor m/z range option //@{ ///restricts the range of precursor m/z values for MS2+ spectra to load void setPrecursorMZRange(const DRange<1> & range); ///returns @c true if a precursor m/z range has been set bool hasPrecursorMZRange() const; ///returns the precursor m/z range const DRange<1> & getPrecursorMZRange() const; //@} /** @name MS levels option With this option, MS level filters can be set. @note The original spectrum identifiers are stored as the nativeID of the spectrum. */ //@{ ///sets the desired MS levels for peaks to load void setMSLevels(const std::vector<Int> & levels); ///adds a desired MS level for peaks to load void addMSLevel(int level); ///clears the MS levels void clearMSLevels(); ///returns @c true, if MS levels have been set bool hasMSLevels() const; ///returns @c true, if MS level @p level has been set bool containsMSLevel(int level) const; ///returns the set MS levels const std::vector<Int> & getMSLevels() const; //@} /** @name Compression options @note This option is ignored if the format does not support compression */ //@{ //Sets if data should be compressed when writing void setCompression(bool compress); /// returns @c true, if data should be compressed when writing bool getCompression() const; //@} ///@name lazyload option ///sets whether or not to always append the data to the given map (even if a consumer is given) void setAlwaysAppendData(bool only); ///returns whether or not to always append the data to the given map (even if a consumer is given) bool getAlwaysAppendData() const; ///sets whether to fill the actual data into the container (spectrum/chromatogram) void setFillData(bool only); /// returns whether to fill the actual data into the container (spectrum/chromatogram) or leave containers empty bool getFillData() const; ///sets whether to skip some XML checks and be fast instead void setSkipXMLChecks(bool only); ///returns whether to skip some XML checks and be fast instead bool getSkipXMLChecks() const; /// @name sort peaks in spectra / chromatograms by position ///sets whether or not to sort peaks in spectra void setSortSpectraByMZ(bool sort); ///gets whether or not peaks in spectra should be sorted bool getSortSpectraByMZ() const; ///sets whether or not to sort peaks in chromatograms void setSortChromatogramsByRT(bool sort); ///gets whether or not peaks in chromatograms should be sorted bool getSortChromatogramsByRT() const; /** @name Precision options Note that m/z and RT are controlled with the same flag (for spectra and chromatograms) while there is a separate flag for intensity. @note This option is ignored if the format does not support multiple precisions */ //@{ //Sets if mz-data and rt-data should be stored with 32bit or 64bit precision void setMz32Bit(bool mz_32_bit); //returns @c true, if mz-data and rt-data should be stored with 32bit precision bool getMz32Bit() const; //Sets if intensity data should be stored with 32bit or 64bit precision void setIntensity32Bit(bool int_32_bit); //returns @c true, if intensity data should be stored with 32bit precision bool getIntensity32Bit() const; //@} /// Whether to write an index at the end of the file (e.g. indexedmzML file format) bool getWriteIndex() const; /// Whether to write an index at the end of the file (e.g. indexedmzML file format) void setWriteIndex(bool write_index); /// Set numpress configuration options for m/z or rt dimension MSNumpressCoder::NumpressConfig getNumpressConfigurationMassTime() const; /// Get numpress configuration options for m/z or rt dimension void setNumpressConfigurationMassTime(MSNumpressCoder::NumpressConfig config); /// Set numpress configuration options for intensity dimension MSNumpressCoder::NumpressConfig getNumpressConfigurationIntensity() const; /// Get numpress configuration options for intensity dimension void setNumpressConfigurationIntensity(MSNumpressCoder::NumpressConfig config); /// Set numpress configuration options for float data arrays MSNumpressCoder::NumpressConfig getNumpressConfigurationFloatDataArray() const; /// Get numpress configuration options for float data arrays void setNumpressConfigurationFloatDataArray(MSNumpressCoder::NumpressConfig config); /** @name Data pool size options Some file readers and writers can process the data in parallel by reading in parts of the file and keeping it in memory and then process this partial data in parallel. This parameter specifies how many data points (spectra/chromatograms) should be read before parallel processing is initiated. */ //@{ /// Get maximal size of the data pool Size getMaxDataPoolSize() const; /// Set maximal size of the data pool void setMaxDataPoolSize(Size size); //@} /// [mzML only!] Whether to use the "selected ion m/z" value as the precursor m/z value (alternative: use the "isolation window target m/z" value) bool getPrecursorMZSelectedIon() const; /// [mzML only!] Set whether to use the "selected ion m/z" value as the precursor m/z value (alternative: use the "isolation window target m/z" value) void setPrecursorMZSelectedIon(bool choice); /// do these options skip spectra or chromatograms due to RT or MSLevel filters? bool hasFilters() const; void setSkipChromatograms(bool skip); bool getSkipChromatograms() const; private: bool metadata_only_ = false; ///< only load header information, no spectra lists / chromatograms bool force_maxquant_compatibility_ = false; ///< for mzXML-writing only: set a fixed vendor (Thermo Scientific), mass analyzer (FTMS) bool force_tpp_compatibility_ = false; ///< for mzML-writing only: work around some bugs in TPP file parsers bool write_supplemental_data_ = true; bool has_rt_range_ = false; bool has_mz_range_ = false; bool has_intensity_range_ = false; bool has_precursor_mz_range_ = false; bool mz_32_bit_ = false; bool int_32_bit_ = true; DRange<1> rt_range_{}; DRange<1> mz_range_{}; DRange<1> intensity_range_{}; DRange<1> precursor_mz_range_{}; std::vector<Int> ms_levels_{}; bool zlib_compression_ = false; bool always_append_data_ = false; bool skip_xml_checks_ = false; bool sort_spectra_by_mz_ = true; bool sort_chromatograms_by_rt_ = true; bool fill_data_ = true; ///< populate spectra/chromatograms with base64 data; spectrum metadata is always loaded bool write_index_ = true; MSNumpressCoder::NumpressConfig np_config_mz_{}; MSNumpressCoder::NumpressConfig np_config_int_{}; MSNumpressCoder::NumpressConfig np_config_fda_{}; Size maximal_data_pool_size_ = 100; bool precursor_mz_selected_ion_ = true; bool skip_chromatograms_ = false; }; } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/FORMAT/OPTIONS/FeatureFileOptions.h
.h
2,695
92
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow $ // $Authors: Marc Sturm, Chris Bielow $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/DATASTRUCTURES/DRange.h> #include <vector> namespace OpenMS { /** @brief Options for loading files containing features. */ class OPENMS_DLLAPI FeatureFileOptions { public: ///Default constructor FeatureFileOptions(); ///Destructor ~FeatureFileOptions(); ///@name convex hull option ///sets whether or not to load convex hull void setLoadConvexHull(bool convex); ///returns whether or not to load convex hull bool getLoadConvexHull() const; ///@name subordinate option ///sets whether or not load subordinates void setLoadSubordinates(bool sub); ///returns whether or not to load subordinates bool getLoadSubordinates() const; ///@name metadata option ///sets whether or not to load only meta data void setMetadataOnly(bool only); ///returns whether or not to load only meta data bool getMetadataOnly() const; ///@name lazyload option ///sets whether or not to load only feature count void setSizeOnly(bool only); ///returns whether or not to load only meta data bool getSizeOnly() const; ///@name RT range option ///restricts the range of RT values for peaks to load void setRTRange(const DRange<1> & range); ///returns @c true if an RT range has been set bool hasRTRange() const; ///returns the RT range const DRange<1> & getRTRange() const; ///@name m/z range option ///restricts the range of MZ values for peaks to load void setMZRange(const DRange<1> & range); ///returns @c true if an MZ range has been set bool hasMZRange() const; ///returns the MZ range const DRange<1> & getMZRange() const; ///@name Intensity range option ///restricts the range of intensity values for peaks to load void setIntensityRange(const DRange<1> & range); ///returns @c true if an intensity range has been set bool hasIntensityRange() const; ///returns the intensity range const DRange<1> & getIntensityRange() const; private: bool loadConvexhull_; bool loadSubordinates_; bool metadata_only_; bool has_rt_range_; bool has_mz_range_; bool has_intensity_range_; bool size_only_; DRange<1> rt_range_; DRange<1> mz_range_; DRange<1> intensity_range_; }; } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/FORMAT/MSNUMPRESS/MSNumpress.h
.h
13,973
358
/* MSNumpress.hpp johan.teleman@immun.lth.se This distribution goes under the BSD 3-clause license. If you prefer to use Apache version 2.0, that is also available at https://github.com/fickludd/ms-numpress Copyright (c) 2013, Johan Teleman All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Lund University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* ==================== encodeInt ==================== Some of the encodings described below use a integer compression referred to simply as encodeInt() The algorithm is similar to other variable length integer encodings, such as the SQLite Variable-Length Integers encoding, but it uses half bytes in its encoding procedure. This encoding works on a 4 byte integer, by truncating initial zeros or ones. If the initial (most significant) half byte is 0x0 or 0xf, the number of such halfbytes starting from the most significant is stored in a halfbyte. This initial count is then followed by the rest of the ints halfbytes, in little-endian order. A count halfbyte c of 0 <= c <= 8 is interpreted as an initial c 0x0 halfbytes 9 <= c <= 15 is interpreted as an initial (c-8) 0xf halfbytes Example: int c rest 0 => 0x8 -1 => 0xf 0xf 2 => 0x7 0x2 23 => 0x6 0x7 0x1 2047 => 0x5 0xf 0xf 0xf Note that the algorithm returns a char array in which the half bytes are stored in the lower 4 bits of each element. Since the first element is a count half byte, the maximal length of the encoded data is 9 half bytes (1 count half byte + 8 half bytes for a 4-byte integer). */ #pragma once #include <cstddef> #include <vector> // defines whether to throw an exception when a number cannot be encoded safely // with the given parameters #ifndef MS_NUMPRESS_THROW_ON_OVERFLOW #define MS_NUMPRESS_THROW_ON_OVERFLOW true #endif namespace ms { namespace numpress { namespace MSNumpress { /** * Compute the maximal linear fixed point that prevents integer overflow. * * @param[in] data pointer to array of double to be encoded (need memorycont. repr.) * @param[in] dataSize number of doubles from *data to encode * * @return the linear fixed point safe to use */ double optimalLinearFixedPoint( const double *data, size_t dataSize); /** * Compute the optimal linear fixed point with a desired m/z accuracy. * * @note If the desired accuracy cannot be reached without overflowing 64 * bit integers, then a negative value is returned. You need to check for * this and in that case abandon numpress or use optimalLinearFixedPoint * which returns the largest safe value. * * @param[in] data pointer to array of double to be encoded (need memorycont. repr.) * @param[in] dataSize number of doubles from *data to encode * @param[in] mass_acc desired m/z accuracy in Th * * @return the linear fixed point that satisfies the accuracy requirement (or -1 in case of failure). */ double optimalLinearFixedPointMass( const double *data, size_t dataSize, double mass_acc); /** * Encodes the doubles in data by first using a * - lossy conversion to a 4 byte 5 decimal fixed point representation * - storing the residuals from a linear prediction after first two values * - encoding by encodeInt (see above) * * The resulting binary is maximally 8 + dataSize * 5 bytes, but much less if the * data is reasonably smooth on the first order. * * This encoding is suitable for typical m/z or retention time binary arrays. * On a test set, the encoding was empirically show to be accurate to at least 0.002 ppm. * * @param[in] data pointer to array of double to be encoded (need memorycont. repr.) * @param[in] dataSize number of doubles from *data to encode * @param[out] result pointer to where resulting bytes should be stored * @param[out] fixedPoint the scaling factor used for getting the fixed point repr. * This is stored in the binary and automatically extracted * on decoding. * @return the number of encoded bytes */ size_t encodeLinear( const double *data, const size_t dataSize, unsigned char *result, double fixedPoint); /** * Calls lower level encodeLinear while handling vector sizes appropriately * * @param[in] data vector of doubles to be encoded * @param[out] result vector of resulting bytes (will be resized to the number of bytes) * @param[out] fixedPoint the scaling factor used for getting the fixed point repr. This is stored in the binary and automatically extracted on decoding. */ void encodeLinear( const std::vector<double> &data, std::vector<unsigned char> &result, double fixedPoint); /** * Decodes data encoded by encodeLinear. * * result vector guaranteed to be shorter or equal to (|data| - 8) * 2 * * Note that this method may throw a const char* if it deems the input data to be corrupt, i.e. * that the last encoded int does not use the last byte in the data. In addition the last encoded * int need to use either the last halfbyte, or the second last followed by a 0x0 halfbyte. * * @param[in] data pointer to array of bytes to be decoded (need memorycont. repr.) * @param[in] dataSize number of bytes from *data to decode * @param[out] result pointer to were resulting doubles should be stored * @return the number of decoded doubles, or -1 if dataSize < 4 or 4 < dataSize < 8 */ size_t decodeLinear( const unsigned char *data, const size_t dataSize, double *result); /** * Calls lower level decodeLinear while handling vector sizes appropriately * * Note that this method may throw a const char* if it deems the input data to be corrupt, i.e.. * that the last encoded int does not use the last byte in the data. In addition the last encoded * int need to use either the last halfbyte, or the second last followed by a 0x0 halfbyte. * * @param[in] data vector of bytes to be decoded * @param[out] result vector of resulting double (will be resized to the number of doubles) */ void decodeLinear( const std::vector<unsigned char> &data, std::vector<double> &result); ///////////////////////////////////////////////////////////// /** * Encodes the doubles in data by storing the residuals from a linear prediction after first two values. * * The resulting binary is the same size as the input data. * * This encoding is suitable for typical m/z or retention time binary arrays, and is * intended to be used before zlib compression to improve compression. * * @param[in] data pointer to array of doubles to be encoded (need memorycont. repr.) * @param[in] dataSize number of doubles from *data to encode * @param[out] result pointer to were resulting bytes should be stored */ size_t encodeSafe( const double *data, const size_t dataSize, unsigned char *result); /** * Decodes data encoded by encodeSafe. * * result vector is the same size as the input data. * * Might throw const char* is something goes wrong during decoding. * * @param[in] data pointer to array of bytes to be decoded (need memorycont. repr.) * @param[in] dataSize number of bytes from *data to decode * @param[out] result pointer to were resulting doubles should be stored * @return the number of decoded bytes */ size_t decodeSafe( const unsigned char *data, const size_t dataSize, double *result); ///////////////////////////////////////////////////////////// /** * Encodes ion counts by simply rounding to the nearest 4 byte integer, * and compressing each integer with encodeInt. * * The handleable range is therefore 0 -> 4294967294. * The resulting binary is maximally dataSize * 5 bytes, but much less if the * data is close to 0 on average. * * @param[in] data pointer to array of double to be encoded (need memorycont. repr.) * @param[in] dataSize number of doubles from *data to encode * @param[out] result pointer to where resulting bytes should be stored * @return the number of encoded bytes */ size_t encodePic( const double *data, const size_t dataSize, unsigned char *result); /** * Calls lower level encodePic while handling vector sizes appropriately * * @param[in] data vector of doubles to be encoded * @param[out] result vector of resulting bytes (will be resized to the number of bytes) */ void encodePic( const std::vector<double> &data, std::vector<unsigned char> &result); /** * Decodes data encoded by encodePic * * result vector guaranteed to be shorter of equal to |data| * 2 * * Note that this method may throw a const char* if it deems the input data to be corrupt, i.e. * that the last encoded int does not use the last byte in the data. In addition the last encoded * int need to use either the last halfbyte, or the second last followed by a 0x0 halfbyte. * * @param[in] data pointer to array of bytes to be decoded (need memorycont. repr.) * @param[in] dataSize number of bytes from *data to decode * @param[out] result pointer to were resulting doubles should be stored * @return the number of decoded doubles */ size_t decodePic( const unsigned char *data, const size_t dataSize, double *result); /** * Calls lower level decodePic while handling vector sizes appropriately * * Note that this method may throw a const char* if it deems the input data to be corrupt, i.e. * that the last encoded int does not use the last byte in the data. In addition the last encoded * int need to use either the last halfbyte, or the second last followed by a 0x0 halfbyte. * * @param[in] data vector of bytes to be decoded * @param[out] result vector of resulting double (will be resized to the number of doubles) */ void decodePic( const std::vector<unsigned char> &data, std::vector<double> &result); ///////////////////////////////////////////////////////////// double optimalSlofFixedPoint( const double *data, size_t dataSize); /** * Encodes ion counts by taking the natural logarithm, and storing a * fixed point representation of this. This is calculated as * * unsigned short fp = log(d + 1) * fixedPoint + 0.5 * * the result vector is exactly |data| * 2 + 8 bytes long * * @param[in] data pointer to array of double to be encoded (need memorycont. repr.) * @param[in] dataSize number of doubles from *data to encode * @param[out] result pointer to were resulting bytes should be stored * @param[out] fixedPoint the scaling factor used for getting the fixed point repr. This is stored in the binary and automatically extracted on decoding. * @return the number of encoded bytes */ size_t encodeSlof( const double *data, const size_t dataSize, unsigned char *result, double fixedPoint); /** * Calls lower level encodeSlof while handling vector sizes appropriately * * @param[in] data vector of doubles to be encoded * @param[out] result vector of resulting bytes (will be resized to the number of bytes) * @param[in] fixedPoint the scaling factor used for getting the fixed point repr. This is stored in the binary and automatically extracted on decoding. */ void encodeSlof( const std::vector<double> &data, std::vector<unsigned char> &result, double fixedPoint); /** * Decodes data encoded by encodeSlof * * The return will include exactly (|data| - 8) / 2 doubles. * * Note that this method may throw a const char* if it deems the input data to be corrupt. * * @param[in] data pointer to array of bytes to be decoded (need memorycont. repr.) * @param[in] dataSize number of bytes from *data to decode * @param[out] result pointer to were resulting doubles should be stored * @return the number of decoded doubles */ size_t decodeSlof( const unsigned char *data, const size_t dataSize, double *result); /** * Calls lower level decodeSlof while handling vector sizes appropriately * * Note that this method may throw a const char* if it deems the input data to be corrupt. * * @param[in] data vector of bytes to be decoded * @param[out] result vector of resulting double (will be resized to the number of doubles) */ void decodeSlof( const std::vector<unsigned char> &data, std::vector<double> &result); } // namespace MSNumpress } // namespace msdata } // namespace pwiz
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/FORMAT/HANDLERS/MzIdentMLHandler.h
.h
14,259
369
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Mathias Walzer $ // $Authors: Mathias Walzer, Andreas Bertsch $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/KERNEL/StandardTypes.h> #include <OpenMS/FORMAT/HANDLERS/XMLHandler.h> #include <OpenMS/FORMAT/ControlledVocabulary.h> #include <OpenMS/METADATA/ProteinHit.h> #include <OpenMS/CHEMISTRY/AASequence.h> #include <OpenMS/CHEMISTRY/DigestionEnzymeProtein.h> #include <OpenMS/METADATA/ProteinIdentification.h> #include <OpenMS/METADATA/PeptideIdentification.h> #include <OpenMS/METADATA/PeptideIdentificationList.h> #include <vector> #include <map> namespace OpenMS { class ProgressLogger; namespace Internal { /** @brief Represents a object which can store the information of an analysisXML instance @ingroup Metadata */ class OPENMS_DLLAPI IdentificationHit : public MetaInfoInterface { public: /// @name Constructors, Destructors, Assignment Operators //@{ /// Default constructor IdentificationHit() = default; /// Copy constructor IdentificationHit(const IdentificationHit&) = default; /// Virtual destructor virtual ~IdentificationHit() = default; /// Move constructor IdentificationHit(IdentificationHit&&) noexcept = default; /// Copy assignment operator IdentificationHit& operator=(const IdentificationHit&) = default; /// Move assignment operator IdentificationHit& operator=(IdentificationHit&&) noexcept = default; //@} /// @name Equality and Inequality Operators //@{ /// Checks for equality with another IdentificationHit object bool operator==(const IdentificationHit& rhs) const noexcept; /// Checks for inequality with another IdentificationHit object bool operator!=(const IdentificationHit& rhs) const noexcept; //@} /// @name Accessors //@{ /// Sets the identifier void setId(const std::string& id) noexcept; /// Returns the identifier const std::string& getId() const noexcept; /// Sets the charge state of the peptide void setCharge(int charge) noexcept; /// Returns the charge state of the peptide int getCharge() const noexcept; /// Sets the calculated mass to charge ratio void setCalculatedMassToCharge(double mz) noexcept; /// Returns the calculated mass to charge ratio double getCalculatedMassToCharge() const noexcept; /// Sets the experimental mass to charge ratio void setExperimentalMassToCharge(double mz) noexcept; /// Returns the experimental mass to charge ratio double getExperimentalMassToCharge() const noexcept; /// Sets the name void setName(const std::string& name) noexcept; /// Returns the name const std::string& getName() const noexcept; /// Sets whether the peptide passed the threshold void setPassThreshold(bool pass) noexcept; /// Returns whether the peptide passed the threshold bool getPassThreshold() const noexcept; /// Sets the rank of the peptide void setRank(int rank) noexcept; /// Returns the rank of the peptide int getRank() const noexcept; //@} private: std::string id_; ///< Identifier int charge_ = 0; ///< Peptide charge double calculated_mass_to_charge_ = 0.0; ///< Calculated mass to charge ratio double experimental_mass_to_charge_ = 0.0; ///< Experimental mass to charge ratio std::string name_; ///< Name bool pass_threshold_ = true; ///< Pass threshold int rank_ = 0; ///< Rank of the peptide }; /** @brief Represents a object which can store the information of an analysisXML instance //@todo docu (Andreas) @ingroup Metadata */ class OPENMS_DLLAPI SpectrumIdentification : public MetaInfoInterface { public: /// @name constructors,destructors,assignment operator //@{ /// Default constructor SpectrumIdentification() = default; /// Destructor virtual ~SpectrumIdentification(); /// Copy constructor SpectrumIdentification(const SpectrumIdentification &) = default; /// Move constructor SpectrumIdentification(SpectrumIdentification&&) = default; /// Assignment operator SpectrumIdentification & operator=(const SpectrumIdentification &) = default; /// Move assignment operator SpectrumIdentification& operator=(SpectrumIdentification&&) & = default; /// Equality operator bool operator==(const SpectrumIdentification & rhs) const; /// Inequality operator bool operator!=(const SpectrumIdentification & rhs) const; //@} // @name Accessors //@{ /// sets the identification hits of this spectrum identification (corresponds to single peptide hit in the list) void setHits(const std::vector<IdentificationHit> & hits); /// adds a single identification hit to the hits void addHit(const IdentificationHit & hit); /// returns the identification hits of this spectrum identification const std::vector<IdentificationHit> & getHits() const; //@} protected: String id_; ///< Identifier std::vector<IdentificationHit> hits_; ///< Single peptide hits }; /** @brief Represents a object which can store the information of an analysisXML instance //@todo docu (Andreas) @ingroup Metadata */ class OPENMS_DLLAPI Identification : public MetaInfoInterface { public: /// @name constructors,destructors,assignment operator //@{ /// Default constructor Identification() = default; /// Copy constructor Identification(const Identification & source) = default; /// Move constructor Identification(Identification&&) = default; /// Destructor virtual ~Identification(); /// Assignment operator Identification & operator=(const Identification & source) = default; /// Move assignment operator Identification& operator=(Identification&&) & = default; /// Equality operator bool operator==(const Identification & rhs) const; /// Inequality operator bool operator!=(const Identification & rhs) const; //@} /// @name Accessors //@{ /// sets the date and time the file was written void setCreationDate(const DateTime & date); /// returns the date and time the file was created const DateTime & getCreationDate() const; /// sets the spectrum identifications void setSpectrumIdentifications(const std::vector<SpectrumIdentification> & ids); /// adds a spectrum identification void addSpectrumIdentification(const SpectrumIdentification & id); /// returns the spectrum identifications stored const std::vector<SpectrumIdentification> & getSpectrumIdentifications() const; //@} protected: String id_; ///< Identifier DateTime creation_date_; ///< Date and time the search was performed std::vector<SpectrumIdentification> spectrum_identifications_; }; /** @brief XML STREAM handler for MzIdentMLFile In read-mode, this class will parse an MzIdentML XML file and append the input identifications to the provided PeptideIdentifications and ProteinIdentifications. @note Do not use this class. It is only needed in MzIdentMLFile. @note DOM and STREAM handler for MzIdentML have the same interface for legacy id structures. */ class OPENMS_DLLAPI MzIdentMLHandler : public XMLHandler { public: /**@name Constructors and destructor */ //@{ /// Constructor for a write-only handler for internal identification structures MzIdentMLHandler(const std::vector<ProteinIdentification>& pro_id, const PeptideIdentificationList& pep_id, const String& filename, const String& version, const ProgressLogger& logger); /// Constructor for a read-only handler for internal identification structures MzIdentMLHandler(std::vector<ProteinIdentification>& pro_id, PeptideIdentificationList& pep_id, const String& filename, const String& version, const ProgressLogger& logger); /// Destructor ~MzIdentMLHandler() override; //@} // Docu in base class void endElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname) override; // Docu in base class void startElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname, const xercesc::Attributes& attributes) override; // Docu in base class void characters(const XMLCh* const chars, const XMLSize_t length) override; //Docu in base class void writeTo(std::ostream& os) override; protected: /// Progress logger const ProgressLogger& logger_; ///Controlled vocabulary (psi-ms from OpenMS/share/OpenMS/CV/psi-ms.obo) ControlledVocabulary cv_; ///Controlled vocabulary for modifications (unimod from OpenMS/share/OpenMS/CV/unimod.obo) ControlledVocabulary unimod_; //~ PeakMap* ms_exp_; ///XML tag parse element String tag_; ///Identification Item Identification* id_; ///internal Identification Item for proteins std::vector<ProteinIdentification>* pro_id_; ///Identification Item for peptides PeptideIdentificationList* pep_id_; const Identification* cid_; const std::vector<ProteinIdentification>* cpro_id_; const PeptideIdentificationList* cpep_id_; ///SpectrumIdentification Item SpectrumIdentification current_spectrum_id_; ///IdentificationHit Item IdentificationHit current_id_hit_; /// Handles CV terms void handleCVParam_(const String& parent_parent_tag, const String& parent_tag, const String& accession, /* const String& name, */ /* const String& value, */ const xercesc::Attributes& attributes, const String& cv_ref /* , const String& unit_accession="" */); /// Handles user terms void handleUserParam_(const String& parent_parent_tag, const String& parent_tag, const String& name, const String& type, const String& value); /// Writes user terms void writeMetaInfos_(String& s, const MetaInfoInterface& meta, UInt indent) const; /// Looks up a child CV term of @p parent_accession with the name @p name. If no such term is found, an empty term is returned. ControlledVocabulary::CVTerm getChildWithName_(const String& parent_accession, const String& name) const; /// Helper method that writes a source file //void writeSourceFile_(std::ostream& os, const String& id, const SourceFile& software); /// Helper method that writes the Enzymes void writeEnzyme_(String& s, const DigestionEnzymeProtein& enzy, UInt miss, UInt indent) const; /// Helper method that writes the modification search params (fixed or variable) void writeModParam_(String& s, const std::vector<String>& mod_names, bool fixed, UInt indent) const; /// Helper method that writes the FragmentAnnotations section of a spectrum identification void writeFragmentAnnotations_(String& s, const std::vector<PeptideHit::PeakAnnotation>& annotations, UInt indent, bool is_ppxl) const; /// Convenience method to remove the [] from OpenMS internal file uri representation String trimOpenMSfileURI(const String& file) const; /// Abstraction of PeptideHit loop for most PeptideHits void writePeptideHit(const PeptideHit& hit, PeptideIdentificationList::const_iterator& it, std::map<String, String>& pep_ids, const String& cv_ns, std::set<String>& sen_set, std::map<String, String>& sen_ids, std::map<String, std::vector<String> >& pep_evis, std::map<String, double>& pp_identifier_2_thresh, String& sidres); /// Abstraction of PeptideHit loop for XL-MS data from OpenPepXL void writeXLMSPeptideHit(const PeptideHit& hit, PeptideIdentificationList::const_iterator& it, const String& ppxl_linkid, std::map<String, String>& pep_ids, const String& cv_ns, std::set<String>& sen_set, std::map<String, String>& sen_ids, std::map<String, std::vector<String> >& pep_evis, std::map<String, double>& pp_identifier_2_thresh, double ppxl_crosslink_mass, std::map<String, String>& ppxl_specref_2_element, String& sid, bool alpha_peptide); private: MzIdentMLHandler(); MzIdentMLHandler(const MzIdentMLHandler& rhs); MzIdentMLHandler& operator=(const MzIdentMLHandler& rhs); std::map<String, AASequence> pep_sequences_; std::map<String, String> pp_identifier_2_sil_; ///< mapping peptide/proteinidentification identifier_ to spectrumidentificationlist std::map<String, String> sil_2_sdb_; ///< mapping spectrumidentificationlist to the search data bases std::map<String, String> sil_2_sdat_; ///< mapping spectrumidentificationlist to the search input std::map<String, String> ph_2_sdat_; ///< mapping identification runs (mapping PeptideIdentifications and ProteinIdentifications via .getIdentifier()) to spectra data std::map<String, String> sil_2_sip_; ///< mapping spectrumidentificationlist to the search protocol (where the params are at) AASequence actual_peptide_; Int current_mod_location_; ProteinHit actual_protein_; }; } // namespace Internal } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/FORMAT/HANDLERS/UnimodXMLHandler.h
.h
2,040
72
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Andreas Bertsch $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/FORMAT/HANDLERS/XMLHandler.h> #include <OpenMS/CHEMISTRY/EmpiricalFormula.h> #include <OpenMS/CHEMISTRY/ResidueModification.h> #include <vector> namespace OpenMS { namespace Internal { /** @brief Handler that is used for parsing XTandemXML data */ class OPENMS_DLLAPI UnimodXMLHandler : public XMLHandler { public: /// Default constructor UnimodXMLHandler(std::vector<ResidueModification*>& mods, const String& filename); /// Destructor ~UnimodXMLHandler() override; // Docu in base class void endElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname) override; // Docu in base class void startElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname, const xercesc::Attributes& attributes) override; // Docu in base class void characters(const XMLCh* const chars, const XMLSize_t /*length*/) override; private: String tag_; double avge_mass_; double mono_mass_; EmpiricalFormula diff_formula_; std::vector<EmpiricalFormula> neutral_loss_diff_formula_; bool was_valid_peptide_modification_; std::vector<std::vector<EmpiricalFormula>> neutral_loss_diff_formulas_; std::vector<double> neutral_loss_mono_masses_; std::vector<double> neutral_loss_avg_masses_; ResidueModification* modification_; std::vector<ResidueModification*>& modifications_; std::vector<char> sites_; std::vector<ResidueModification::TermSpecificity> term_specs_; }; } // namespace Internal } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/FORMAT/HANDLERS/XQuestResultXMLHandler.h
.h
7,399
189
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Eugen Netz $ // $Authors: Lukas Zimmermann $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/FORMAT/HANDLERS/XMLHandler.h> #include <OpenMS/METADATA/MetaInfoInterface.h> #include <OpenMS/METADATA/PeptideIdentification.h> #include <OpenMS/METADATA/PeptideIdentificationList.h> #include <OpenMS/METADATA/ProteinIdentification.h> #include <OpenMS/METADATA/PeptideHit.h> #include <OpenMS/CHEMISTRY/ProteaseDB.h> namespace OpenMS { namespace Internal { /** @brief XMLHandler for the result files of XQuest */ class OPENMS_DLLAPI XQuestResultXMLHandler : public XMLHandler { public: /// Maps enzyme_num in xQuest result file to the enzyme name used by OpenMS static std::map< Size, String > enzymes; /// Maps String encoding month to the numeric value static std::map<String, UInt> months; /// Constructor for a read-only handler for internal identification structures XQuestResultXMLHandler(const String & filename, PeptideIdentificationList & pep_ids, std::vector< ProteinIdentification > & prot_ids ); /// Constructor for a write-only handler for internal identification structures XQuestResultXMLHandler(const std::vector<ProteinIdentification>& pro_id, const PeptideIdentificationList& pep_id, const String& filename, const String& version ); ~XQuestResultXMLHandler() override; // Docu in base class void endElement(const XMLCh * const uri, const XMLCh * const local_name, const XMLCh * const qname) override; // Docu in base class void startElement(const XMLCh * const uri, const XMLCh * const local_name, const XMLCh * const qname, const xercesc::Attributes & attributes) override; /** * @brief Returns the minimum score encountered in the file. * @return Minimum score encountered in the file. */ double getMinScore() const; /** * @brief Returns the maximum score encountered in the file. * @return Maximum score encountered in the file. */ double getMaxScore() const; /** * @brief Returns the total number of hits in the file. * @return Total number of hits in the file. */ UInt getNumberOfHits() const; //Docu in base class void writeTo(std::ostream& os) override; // TODO move these to StringUtils? /** * @brief splits the @p input string at the nth occurrence of the @p separator If the separator does not occur in the input string n times, then the first output string will be the entire input string and the second one will be empty. * @return StringList with two elements, the two parts of the input without the nth separator */ static StringList splitByNth(const String& input, const char separator, const Size n); /** * @brief counts occurrences of the @p separator and splits the @p string into two at the middle If the separator occurs 5 times in the input string, the string will be split at the 3rd occurrence. If 7 times, then at the 4th. The separator has to occur in the string an uneven number of times. If the separator occurs once, the string will be split at this one instance. If this one occurrence is at the beginning or end, one of the result strings will be empty. * @exception Exception::IllegalArgument is thrown if the @p separator does not occur in the @p input string an uneven number of times and at least once * @return StringList with two elements, the two halves of the input without the middle separator */ static StringList splitByMiddle(const String& input, const char separator); private: // Decoy string used by xQuest, initialize to a default value String decoy_string_ = "decoy_"; int spectrum_index_light_; int spectrum_index_heavy_; String cross_linker_name_; // Main data structures that are populated during loading the file PeptideIdentificationList* pep_ids_; std::vector< ProteinIdentification >* prot_ids_; // internal ID items for writing files const std::vector<ProteinIdentification>* cpro_id_; const PeptideIdentificationList* cpep_id_; UInt n_hits_; ///< Total no. of hits found in the result XML file // Keeps track of the minscore and maxscore encountered double min_score_; double max_score_; /// Whether or not current xquest result tag comes from OpenPepXL (xQuest otherwise) bool is_openpepxl_; /// Set of all protein accessions that are within the ProteinHits. std::set< String > accessions_; /// The enzyme database for enzyme lookup ProteaseDB* enzymes_db_; /// Keeps track of the charges of the hits std::set< UInt > charges_; UInt min_precursor_charge_; UInt max_precursor_charge_; // Current Retention time of spectrum pair double rt_light_; double rt_heavy_; // Current experimental m/z of spectrum pair double mz_light_; double mz_heavy_; // primary MS run path StringList ms_run_path_; String spectrum_input_file_; /// The current spectrum search std::vector< PeptideIdentification > current_spectrum_search_; /// Stores the attributes of a record (peptide identification) std::map<String, DataValue> peptide_id_meta_values_; /** * @brief Extracts the DateTime from datetime string from xQuest * @param[in] xquest_datetime_string The DateTime String to be processed * @param[in] date_time DateTime that reflects the value given in the `xquest_datetime_string` */ inline void extractDateTime_(const String & xquest_datetime_string, DateTime & date_time) const; /** * @brief Assigns all meta values stored in the peptide_id_attributes * member to an meta info interface * * @param[in] meta_info_interface Where the meta values from the peptide_id_attributes member should be assigned to */ void addMetaValues_(MetaInfoInterface & meta_info_interface); /** * @brief Gets the link location of a xQuest xlinkPositionString. * @param[in] attributes XML attributes of Xerces. * @param[out] pair Pair to be populated with the xlinkposition in xQuest. */ void getLinkPosition_(const xercesc::Attributes & attributes, std::pair<SignedSize, SignedSize> & pair); /** * @brief Sets the peptide evidence for Alpha and Beta. * @param[out] prot_string Protein string of the xquest file the peptide evidence should be populated from. * @param[in] pep_hit For which peptide hit the peptide evidence should be set. */ void setPeptideEvidence_(const String & prot_string, PeptideHit & pep_hit); }; } // namespace Internal } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/FORMAT/HANDLERS/IndexedMzMLHandler.h
.h
7,472
228
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Hannes Roest $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/config.h> #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/DATASTRUCTURES/String.h> #include <OpenMS/INTERFACES/DataStructures.h> #include <OpenMS/INTERFACES/ISpectrumAccess.h> #include <OpenMS/KERNEL/MSSpectrum.h> #include <OpenMS/KERNEL/MSChromatogram.h> #include <string> #include <fstream> #include <unordered_map> namespace OpenMS { namespace Internal { /** @brief A low-level class to read an indexedmzML file. This class provides low-level access to the underlying data structures, if you simply want to read an indexed mzML file you probably want to use IndexedMzMLFileLoader instead. This class implements access to an indexedmzML file and the contained spectra and chromatogram data through the getSpectrumById and getChromatogramById functions. It thus allows random access to spectra and chromatograms data without having to read the whole file into memory. It does not provide the same interface as MSExperiment, if this is desired, please use IndexedMzMLFileLoader and OnDiscMSExperiment. Internally, it uses the IndexedMzMLDecoder for initial parsing and extracting all the offsets of the &lt;chromatogram&gt; and &lt;spectrum&gt; tags. These offsets are stored as members of this class as well as the offset to the &lt;indexList&gt; element @note This implementation is @a not thread-safe since it keeps internally a single file access pointer which it moves when accessing a specific data item. The caller is responsible to ensure that access is performed atomically. */ class OPENMS_DLLAPI IndexedMzMLHandler { /// Name of the file String filename_; /// Binary offsets to all spectra std::vector< std::streampos > spectra_offsets_; /// Mapping of spectra native ids to offsets std::unordered_map< std::string, Size > spectra_native_ids_; /// Binary offsets to all chromatograms std::vector< std::streampos > chromatograms_offsets_; /// Mapping of chromatogram native ids to offsets std::unordered_map< std::string, Size > chromatograms_native_ids_; /// offset to the \<indexList\> element std::streampos index_offset_; /// Whether spectra are written before chromatograms in this file bool spectra_before_chroms_; /// The current filestream (opened by openFile) std::ifstream filestream_; /// Whether parsing the indexedmzML file was successful bool parsing_success_; /// Whether to skip XML checks bool skip_xml_checks_; /** @brief Try to parse the footer of the indexedmzML Upon success, the chromatogram and spectra offsets will be populated and parsing_success_ will be set to true. @note You *need* to check getParsingSuccess after calling this! */ void parseFooter_(); std::string getChromatogramById_helper_(int id); std::string getSpectrumById_helper_(int id); public: /** @brief Default constructor */ IndexedMzMLHandler(); /** @brief Constructor Tries to parse the file, success can be checked with getParsingSuccess() */ explicit IndexedMzMLHandler(const String& filename); /// Copy constructor IndexedMzMLHandler(const IndexedMzMLHandler& source); /// Destructor ~IndexedMzMLHandler(); /** @brief Open a file Tries to parse the file, success can be checked with getParsingSuccess() */ void openFile(const String& filename); /** @brief Returns whether parsing was successful @note Callable after openFile or the constructor using a filename @note It is invalid to call getSpectrumById or getChromatogramById if this function returns false @return Whether the parsing of the file was successful (if false, the file most likely was not an indexed mzML file) */ bool getParsingSuccess() const; /// Returns the number of spectra available size_t getNrSpectra() const; /// Returns the number of chromatograms available size_t getNrChromatograms() const; /** @brief Retrieve the raw data for the spectrum at position "id" @throw Exception if getParsingSuccess() returns false @throw Exception if id is not within [0, getNrSpectra()-1] @return The spectrum at position id */ OpenMS::Interfaces::SpectrumPtr getSpectrumById(int id); /** @brief Retrieve the raw data for the spectrum at position "id" @throw Exception if getParsingSuccess() returns false @throw Exception if id is not within [0, getNrSpectra()-1] @return The spectrum at position id */ const OpenMS::MSSpectrum getMSSpectrumById(int id); /** @brief Retrieve the raw data for the spectrum with native id "id" @throw Exception if getParsingSuccess() returns false @throw Exception if id cannot be found @param[in] id The spectrum native id @param[out] s The spectrum to be used and filled with data */ void getMSSpectrumByNativeId(const std::string& id, OpenMS::MSSpectrum& s); /** @brief Retrieve the raw data for the spectrum at position "id" @throw Exception if getParsingSuccess() returns false @throw Exception if id is not within [0, getNrSpectra()-1] @param[in] id The spectrum id @param[out] s The spectrum to be used and filled with data */ void getMSSpectrumById(int id, OpenMS::MSSpectrum& s); /** @brief Retrieve the raw data for the chromatogram at position "id" @throw Exception if getParsingSuccess() returns false @throw Exception if id is not within [0, getNrChromatograms()-1] @return The chromatogram at position id */ OpenMS::Interfaces::ChromatogramPtr getChromatogramById(int id); /** @brief Retrieve the raw data for the chromatogram at position "id" @throw Exception if getParsingSuccess() returns false @throw Exception if id is not within [0, getNrChromatograms()-1] @return The chromatogram at position id */ const OpenMS::MSChromatogram getMSChromatogramById(int id); /** @brief Retrieve the raw data for the chromatogram with native id "id" @throw Exception if getParsingSuccess() returns false @throw Exception if id cannot be found @param[in] id The chromatogram native id @param[out] c The chromatogram to be used and filled with data */ void getMSChromatogramByNativeId(const std::string& id, OpenMS::MSChromatogram& c); /** @brief Retrieve the raw data for the chromatogram at position "id" @throw Exception if getParsingSuccess() returns false @throw Exception if id is not within [0, getNrChromatograms()-1] @param[in] id The chromatogram id @param[out] c The chromatogram to be used and filled with data */ void getMSChromatogramById(int id, OpenMS::MSChromatogram& c); /// Whether to skip some XML checks (removing whitespace from base64 arrays) and be fast instead void setSkipXMLChecks(bool skip) { skip_xml_checks_ = skip; } }; } }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/FORMAT/HANDLERS/MzMLHandler.h
.h
20,329
487
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Marc Sturm, Chris Bielow, Hannes Roest $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/CONCEPT/Helpers.h> #include <OpenMS/CONCEPT/ProgressLogger.h> #include <OpenMS/DATASTRUCTURES/CVMappings.h> #include <OpenMS/KERNEL/StandardTypes.h> #include <OpenMS/KERNEL/MSExperiment.h> #include <OpenMS/FORMAT/HANDLERS/XMLHandler.h> #include <OpenMS/FORMAT/HANDLERS/MzMLHandlerHelper.h> #include <OpenMS/FORMAT/OPTIONS/PeakFileOptions.h> #include <OpenMS/FORMAT/ControlledVocabulary.h> #include <OpenMS/FORMAT/VALIDATORS/SemanticValidator.h> #include <map> //MISSING: // - more than one selected ion per precursor (warning if more than one) // - scanWindowList for each acquisition separately (currently for the whole spectrum only) // - instrumentConfigurationRef attribute for scan (why should the instrument change between scans? - warning if used) // - scanSettingsRef attribute for instrumentConfiguration tag (currently no information there because of missing mapping file entry - warning if used) // xs:id/xs:idref prefix list // - sf_ru : sourceFile (run) // - sf_sp : sourceFile (spectrum) // - sf_pr : sourceFile (precursor) // - sf_ac : sourceFile (acquisition) // - sa : sample // - ic : instrumentConfiguration // - so_dp : software (data processing) // - so_in : software (instrument) // - dp_sp : dataProcessing (spectrum) // - dp_bi : dataProcessing (binary data array) // - dp_ch : dataProcessing (chromatogram) namespace OpenMS { namespace Interfaces { class IMSDataConsumer; } namespace Internal { class MzMLValidator; typedef PeakMap MapType; typedef MSSpectrum SpectrumType; typedef MSChromatogram ChromatogramType; /**@brief Handler for mzML file format * * This class handles parsing and writing of the mzML file format. It * supports reading data directly into memory or parsing on-the-fly using a * consumer (see @ref consumer_a "Setting a consumer"). In read-mode, this * class will parse an MzML XML file and append the input spectra to the * provided MSExperiment object or to the provided * Interfaces::IMSDataConsumer (needs to be provided separately through * setMSDataConsumer()). * * Functions constituting the XML reading/writing interface can be found * under @ref xml_handling "XML Handling functions", helper functions * specifically used for writing out to XML are organized under @ref * helper_write "Writing functions" and helper functions used for reading * in XML from disk are organized under @ref helper_read "Reading * functions". * * See the MzMLHandlerHelper for additional helper functions that are * independent of state. * * @note Do not use this class directly. It is only needed in MzMLFile. * * @note Only upon destruction of this class it can be guaranteed that all * data has been appended to the appropriate consumer of the data. Do not * try to access the data before that. * * @todo replace hardcoded cv stuff with more flexible handling via obo r/w. * **/ class OPENMS_DLLAPI MzMLHandler : public XMLHandler { public: /**@name Constructors and destructor */ //@{ /// Constructor for a read-only handler MzMLHandler(MapType& exp, const String& filename, const String& version, const ProgressLogger& logger); /// Constructor for a write-only handler MzMLHandler(const MapType& exp, const String& filename, const String& version, const ProgressLogger& logger); /// Destructor ~MzMLHandler() override; //@} /** * @anchor xml_handling * @name XML Handling and data parsing **/ //@{ /// Docu in base class XMLHandler::endElement void endElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname) override; /// Docu in base class XMLHandler::startElelement void startElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname, const xercesc::Attributes& attributes) override; /// Docu in base class XMLHandler::characters void characters(const XMLCh* const chars, const XMLSize_t length) override; /// Docu in base class XMLHandler::writeTo void writeTo(std::ostream& os) override; //@} /**@name PeakFileOptions setters/getters The PeakFileOptions object determine the reading and writing of the MzML file. In read-mode the lazy-loading options determine whether meta-data only or the full raw data is read into memory and how this data should be handled. The MS-level, m/z, RT and Intensity range options determine which part of the MzML file is read into memory. */ //@{ /// Set the peak file options void setOptions(const PeakFileOptions& opt); /// Get the peak file options PeakFileOptions& getOptions(); //@} /// Get the spectra and chromatogram counts of a file void getCounts(Size& spectra_counts, Size& chromatogram_counts); /**@name IMSDataConsumer setter @anchor consumer_a The IMSDataConsumer object allows the user to specify a callback object which can consume spectra and chromatograms on the fly. The consumer does not have to wait until data is read fully into memory, but will start receiving data as soon as it is available (read from disk). */ //@{ /// Set the IMSDataConsumer consumer which will consume the read data void setMSDataConsumer(Interfaces::IMSDataConsumer* consumer); //@} /// handler which support partial loading, implement this method LOADDETAIL getLoadDetail() const override; /// handler which support partial loading, implement this method void setLoadDetail(const LOADDETAIL d) override; protected: /// delegated constructor for the two public versions MzMLHandler(const String& filename, const String& version, const ProgressLogger& logger); /// Peak type typedef MapType::PeakType PeakType; /// Chromatogram peak type typedef MapType::ChromatogramPeakType ChromatogramPeakType; /// Spectrum type typedef MSSpectrum SpectrumType; /// Spectrum type typedef MSChromatogram ChromatogramType; typedef MzMLHandlerHelper::BinaryData BinaryData; /**@name Helper functions for storing data in memory * @anchor helper_read */ //@{ /** @brief Populate all spectra on the stack with data from input Will populate all spectra on the current work stack with data (using multiple threads if available) and append them to the result. */ void populateSpectraWithData_(); /** @brief Populate all chromatograms on the stack with data from input Will populate all chromatograms on the current work stack with data (using multiple threads if available) and append them to the result. */ void populateChromatogramsWithData_(); /** @brief Fill a single spectrum with data from input @note Do not modify any internal state variables of the class since this function will be executed in parallel. @note This function takes about 50 % of total load time with a single thread and parallelizes linearly up to at least 10 threads. @param[out] input_data The input data with which to fill the spectra @param[in] length The input data length (number of data points) @param[in] peak_file_options Will be used if only part of the data should be copied (RT, mz or intensity range) @param[out] spectrum The output spectrum */ void populateSpectraWithData_(std::vector<MzMLHandlerHelper::BinaryData>& input_data, Size& length, const PeakFileOptions& peak_file_options, SpectrumType& spectrum); /** @brief Fill a single chromatogram with data from input @note Do not modify any internal state variables of the class since this function will be executed in parallel. @param[out] input_data The input data with which to fill the spectra @param[in] length The input data length (number of data points) @param[in] peak_file_options Will be used if only part of the data should be copied (RT, mz or intensity range) @param[out] chromatogram The output chromatogram */ void populateChromatogramsWithData_(std::vector<MzMLHandlerHelper::BinaryData>& input_data, Size& length, const PeakFileOptions& peak_file_options, ChromatogramType& chromatogram); /// Fills the current chromatogram with data points and meta data void fillChromatogramData_(); /// Handles CV terms void handleCVParam_(const String& parent_parent_tag, const String& parent_tag, const String& accession, const String& name, const String& value, const String& unit_accession = ""); /// Handles user terms void handleUserParam_(const String& parent_parent_tag, const String& parent_tag, const String& name, const String& type, const String& value, const String& unit_accession = ""); //@} /** * @anchor helper_write * @name Helper functions for writing data */ //@{ /// Write out XML header including (everything up to spectrumList / chromatogramList void writeHeader_(std::ostream& os, const MapType& exp, std::vector<std::vector< ConstDataProcessingPtr > >& dps, const Internal::MzMLValidator& validator); /// Write out a single spectrum void writeSpectrum_(std::ostream& os, const SpectrumType& spec, Size spec_idx, const Internal::MzMLValidator& validator, bool renew_native_ids, std::vector<std::vector< ConstDataProcessingPtr > >& dps); /// Write out a single chromatogram void writeChromatogram_(std::ostream& os, const ChromatogramType& chromatogram, Size chrom_idx, const Internal::MzMLValidator& validator); template <typename ContainerT> void writeContainerData_(std::ostream& os, const PeakFileOptions& pf_options_, const ContainerT& container, const String& array_type); /** @brief Write a single \<binaryDataArray\> element to the output @param[in] os The stream into which to write @param[in] options The PeakFileOptions which determines the compression type to use @param[in] data The data to write (32bit float or 64 bit double) @param[in] is32bit Whether data is 32bit @param[in] array_type Which type of data array is written (mz, time, intensity or float_data) @note The data argument may be modified by the function (see Base64 for reasons why) */ template <typename DataType> void writeBinaryDataArray_(std::ostream& os, const PeakFileOptions& options, std::vector<DataType>& data, bool is32bit, String array_type); /** @brief Write a single \<binaryDataArray\> element for a float data array to the output This is only for non-standard data arrays which are treated slightly differently by the standard. @param[in] os The stream into which to write @param[in] options The PeakFileOptions which determines the compression type to use @param[in] array The data to write @param[in] spec_chrom_idx The index of the current spectrum or chromatogram @param[in] array_idx The index of the current float data array @param[in] is_spectrum Whether data is associated with a spectrum (if false, a chromatogram is assumed) @param[in] validator Validator object */ void writeBinaryFloatDataArray_(std::ostream& os, const PeakFileOptions& options, const OpenMS::DataArrays::FloatDataArray& array, const Size spec_chrom_idx, const Size array_idx, bool is_spectrum, const Internal::MzMLValidator& validator); /// Writes user terms void writeUserParam_(std::ostream& os, const MetaInfoInterface& meta, UInt indent, const String& path, const Internal::MzMLValidator& validator, const std::set<String>& exclude = {}) const; /// Helper method that writes a software void writeSoftware_(std::ostream& os, const String& id, const Software& software, const Internal::MzMLValidator& validator); /// Helper method that writes a source file void writeSourceFile_(std::ostream& os, const String& id, const SourceFile& software, const Internal::MzMLValidator& validator); /// Helper method that writes a data processing list void writeDataProcessing_(std::ostream& os, const String& id, const std::vector< ConstDataProcessingPtr >& dps, const Internal::MzMLValidator& validator); /// Helper method that write precursor information from spectra and chromatograms void writePrecursor_(std::ostream& os, const Precursor& precursor, const Internal::MzMLValidator& validator); /// Helper method that write precursor information from spectra and chromatograms void writeProduct_(std::ostream& os, const Product& product, const Internal::MzMLValidator& validator); /// Helper method to write an CV based on a meta value String writeCV_(const ControlledVocabulary::CVTerm& c, const DataValue& metaValue) const; /// Helper method to validate if the given CV is allowed in the current location (path) bool validateCV_(const ControlledVocabulary::CVTerm& c, const String& path, const Internal::MzMLValidator& validator) const; /// Helper method to look up a child CV term of @p parent_accession with the name @p name. If no such term is found, an empty term is returned. ControlledVocabulary::CVTerm getChildWithName_(const String& parent_accession, const String& name) const; //@} // MEMBERS /// map pointer for reading MapType* exp_{ nullptr }; /// map pointer for writing const MapType* cexp_{ nullptr }; /// Options that can be set for loading/storing PeakFileOptions options_; /**@name temporary data structures to hold parsed data */ //@{ /// The current spectrum SpectrumType spec_; /// The current chromatogram ChromatogramType chromatogram_; /// The spectrum data (or chromatogram data) std::vector<BinaryData> bin_data_; /// The default number of peaks in the current spectrum Size default_array_length_; /// Flag that indicates that we're inside a spectrum (in contrast to a chromatogram) bool in_spectrum_list_{ false }; /// Flag that indicates whether this spectrum should be skipped (e.g. due to options) bool skip_spectrum_{ false }; /// Flag that indicates whether this chromatogram should be skipped (e.g. due to options) bool skip_chromatogram_{ false }; /// Remember whether the RT of the spectrum was set or not bool rt_set_{ false }; /// Id of the current list. Used for referencing param group, source file, sample, software, ... String current_id_; /// The referencing param groups: id => array (accession, value) std::map<String, std::vector<SemanticValidator::CVTerm> > ref_param_; /// The source files: id => SourceFile std::map<String, SourceFile> source_files_; /// The sample list: id => Sample std::map<String, Sample> samples_; /// The software list: id => Software std::map<String, Software> software_; /// The data processing list: id => Instrument std::map<String, Instrument> instruments_; /// CV terms-path-combinations that have been checked in validateCV_() mutable std::map<std::pair<String, String>, bool> cached_terms_; /// The data processing list: id => Instrument std::map<String, std::vector< DataProcessingPtr > > processing_; /// id of the default data processing (used when no processing is defined) String default_processing_; /// Count of selected ions UInt selected_ion_count_{ 0 }; /** @brief Data necessary to generate a single spectrum Small struct holds all data necessary to populate a spectrum at a later timepoint (since reading of the base64 data and generation of spectra can be done at distinct timepoints). */ struct SpectrumData { std::vector<BinaryData> data; Size default_array_length; SpectrumType spectrum; }; /// Vector of spectrum data stored for later parallel processing std::vector<SpectrumData> spectrum_data_; /** @brief Data necessary to generate a single chromatogram Small struct holds all data necessary to populate a chromatogram at a later timepoint (since reading of the base64 data and generation of chromatogram can be done at distinct timepoints). */ struct ChromatogramData { std::vector<BinaryData> data; Size default_array_length; ChromatogramType chromatogram; }; /// Vector of chromatogram data stored for later parallel processing std::vector<ChromatogramData> chromatogram_data_; //@} /**@name temporary data structures to hold written data * * These data structures are used to store binary offsets required by the * indexedMzML format, specifically the start of each \<spectrum\> and * \<chromatogram\> tag is stored and will then be stored at the end of the file. **/ //@{ std::vector<std::pair<std::string, Int64> > spectra_offsets_; ///< Stores binary offsets for each \<spectrum\> tag std::vector<std::pair<std::string, Int64> > chromatograms_offsets_; ///< Stores binary offsets for each \<chromatogram\> tag //@} /// Progress logger const ProgressLogger& logger_; /// Consumer class to work on spectra Interfaces::IMSDataConsumer* consumer_{ nullptr }; /**@name temporary data structures for counting spectra and chromatograms */ UInt scan_count_{ 0 }; ///< number of scans which pass the options-filter UInt chromatogram_count_{ 0 }; ///< number of chromatograms which pass the options-filter Int scan_count_total_{ -1 }; ///< total number of scans in mzML file (according to 'count' attribute) Int chrom_count_total_{ -1 }; ///< total number of chromatograms in mzML file (according to 'count' attribute) //@} ///Controlled vocabulary (psi-ms from OpenMS/share/OpenMS/CV/psi-ms.obo) const ControlledVocabulary& cv_; CVMappings mapping_; }; //-------------------------------------------------------------------------------- } // namespace Internal } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/FORMAT/HANDLERS/ToolDescriptionHandler.h
.h
2,327
83
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow $ // $Authors: Chris Bielow $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/FORMAT/HANDLERS/XMLHandler.h> #include <OpenMS/FORMAT/ControlledVocabulary.h> #include <OpenMS/DATASTRUCTURES/ToolDescription.h> #include <OpenMS/FORMAT/HANDLERS/ParamXMLHandler.h> namespace OpenMS { class ProgressLogger; namespace Internal { /** @brief XML handler for ToolDescriptionFile @note Do not use this class. It is only needed in ToolDescriptionFile. */ class OPENMS_DLLAPI ToolDescriptionHandler : public ParamXMLHandler { public: /**@name Constructors and destructor */ //@{ /// Constructor ToolDescriptionHandler(const String & filename, const String & version); /// Destructor ~ToolDescriptionHandler() override; //@} // Docu in base class void endElement(const XMLCh * const /*uri*/, const XMLCh * const /*local_name*/, const XMLCh * const qname) override; // Docu in base class void startElement(const XMLCh * const /*uri*/, const XMLCh * const /*local_name*/, const XMLCh * const qname, const xercesc::Attributes & attributes) override; // Docu in base class void characters(const XMLCh * const chars, const XMLSize_t length) override; // NOT IMPLEMENTED void writeTo(std::ostream & os) override; // Retrieve parsed tool description const std::vector<ToolDescription> & getToolDescriptions() const; // Set tool description for writing void setToolDescriptions(const std::vector<ToolDescription> & td); protected: Param p_; Internal::ToolExternalDetails tde_; Internal::ToolDescription td_; std::vector<Internal::ToolDescription> td_vec_; String tag_; bool in_ini_section_; private: ToolDescriptionHandler(); ToolDescriptionHandler(const ToolDescriptionHandler & rhs); ToolDescriptionHandler & operator=(const ToolDescriptionHandler & rhs); }; } // namespace Internal } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/FORMAT/HANDLERS/PTMXMLHandler.h
.h
1,619
56
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/FORMAT/HANDLERS/XMLHandler.h> #include <vector> #include <map> #include <fstream> namespace OpenMS { namespace Internal { /** @brief Handler that is used for parsing PTMXML data */ class OPENMS_DLLAPI PTMXMLHandler : public XMLHandler { public: /// Constructor for loading PTMXMLHandler(std::map<String, std::pair<String, String> > & ptm_informations, const String & filename); /// Destructor ~PTMXMLHandler() override; /// Writes the xml file to the ostream 'os' void writeTo(std::ostream & os) override; // Docu in base class void endElement(const XMLCh * const /*uri*/, const XMLCh * const /*local_name*/, const XMLCh * const qname) override; // Docu in base class void startElement(const XMLCh * const /*uri*/, const XMLCh * const /*local_name*/, const XMLCh * const qname, const xercesc::Attributes & attributes) override; // Docu in base class void characters(const XMLCh * const chars, const XMLSize_t /*length*/) override; protected: std::map<String, std::pair<String, String> > & ptm_informations_; String name_, tag_, composition_; bool open_tag_; }; } // namespace Internal } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/FORMAT/HANDLERS/FidHandler.h
.h
1,434
58
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Guillaume Belz $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/DATASTRUCTURES/String.h> #include <fstream> namespace OpenMS { namespace Internal { /** @brief Read-only fid File handler for XMass Analysis. fid File contains intensity array. Intensity for each point are coded in 4 bytes integer. @note Do not use this class directly. It is only needed for XMassFile. */ class OPENMS_DLLAPI FidHandler : public std::ifstream { public: /** @brief Constructor with filename. Open fid File as stream and initialize index. @param[in] filename to fid File. */ explicit FidHandler(const String & filename); /// Destructor ~FidHandler() override; /// Get index of current position (without position moving). Size getIndex() const; /// Get intensity of current position and move to next position. Size getIntensity(); private: /// Private default constructor FidHandler(); /// Index of position Size index_; }; } // namespace Internal } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/FORMAT/HANDLERS/IndexedMzMLDecoder.h
.h
5,326
124
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Hannes Roest $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/config.h> #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/CONCEPT/Exception.h> #include <OpenMS/DATASTRUCTURES/String.h> namespace OpenMS { /** @brief A class to analyze indexedmzML files and extract the offsets of individual tags Specifically, this class allows one to extract the offsets of the \<indexList\> tag and of all \<spectrum\> and \<chromatogram\> tag using the indices found at the end of the indexedmzML XML structure. While findIndexListOffset tries extracts the offset of the indexList tag from the last 1024 bytes of the file, this offset allows the function parseOffsets to extract all elements contained in the \<indexList\> tag and thus get access to all spectra and chromatogram offsets. */ class OPENMS_DLLAPI IndexedMzMLDecoder { public: /// The vector containing binary offsets typedef std::vector< std::pair<std::string, std::streampos> > OffsetVector; /** @brief Tries to extract the offsets of all spectra and chromatograms from an indexedmzML. Given the start of the \<indexList\> element, this function tries to read this tag from the given the indexedmzML file. It stores the result in the spectra and chromatogram offset vectors. @param[in] filename Filename of the input indexedmzML file @param[in] indexoffset Offset at which position in the file the XML tag '\<indexList\>' is expected to occur @param[out] spectra_offsets Output vector containing the positions of all spectra in the file @param[out] chromatograms_offsets Output vector containing the positions of all chromatograms in the file @return 0 in case of success and -1 otherwise (failure, no offset was found) */ int parseOffsets(const String& filename, std::streampos indexoffset, OffsetVector& spectra_offsets, OffsetVector& chromatograms_offsets); /** @brief Tries to extract the indexList offset from an indexedmzML. This function reads by default the last few (1024) bytes of the given input file and tries to read the content of the \<indexListOffset\> tag. The idea is that somewhere in the last parts of the file specified by the input string, the string \<indexListOffset\>xxx\</indexListOffset\> occurs. This function returns the xxx part converted to an integer. @note Since this function cannot determine where it will start reading the XML, no regular XML parser can be used for this. Therefore it uses regex to do its job. It matches the \<indexListOffset\> part and any numerical characters that follow. @param[in] filename Filename of the input indexedmzML file @param[in] buffersize How many bytes of the input file should be searched for the tag @return A positive integer containing the content of the indexListOffset tag, returns -1 in case of failure no tag was found (you can re-try with a larger buffersize but most likely its not an indexed mzML). Using -1 is what the reference docu recommends: http://en.cppreference.com/w/cpp/io/streamoff @throw FileNotFound is thrown if file cannot be found @throw ParseError if offset cannot be parsed */ std::streampos findIndexListOffset(const String& filename, int buffersize = 1023); protected: /** @brief Extract data from a string containing an \<indexList\> tag This function parses the contained \<offset\> tags inside the indexList tag and stores the contents in the spectra and chromatogram offset vectors. This function expects an input string that contains a root XML tag and as one of its child an \<indexList\> tag as defined by the mzML 1.1.0 index wrapper schema. Usually the root would be an indexedmzML tag and _must_ contain an indexList tag, while the dx:mzML, indexListOffset and fileChecksum are optional(their presence is not checked). Still this means, don't stick non-valid XML in here (e.g. non matching open/close tags). Usually this means that you will at least have to add an opening \</indexedmzML\>. Valid input for this function would for example be: @code <indexedmzML> <indexList count="1"> <index name="chromatogram"> <offset idRef="1">9752</offset> </index> </indexList> <indexListOffset>26795</indexListOffset> <fileChecksum>0</fileChecksum> </indexedmzML> @endcode @param[in] in String containing the XML with a indexedmzML parent and an indexList child tag @param[out] spectra_offsets Output vector containing the positions of all spectra in the file @param[out] chromatograms_offsets Output vector containing the positions of all chromatograms in the file */ int domParseIndexedEnd_(const std::string& in, OffsetVector & spectra_offsets, OffsetVector& chromatograms_offsets); }; }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/FORMAT/HANDLERS/CachedMzMLHandler.h
.h
6,979
203
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Hannes Roest $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/OPENSWATHALGO/DATAACCESS/ISpectrumAccess.h> #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/CONCEPT/Exception.h> #include <OpenMS/CONCEPT/Macros.h> #include <OpenMS/KERNEL/StandardTypes.h> #include <OpenMS/CONCEPT/ProgressLogger.h> #include <fstream> #define CACHED_MZML_FILE_IDENTIFIER 8094 namespace OpenMS { namespace Internal { /** @brief An class that uses on-disk caching to read and write spectra and chromatograms This class provides functions to read and write spectra and chromatograms to disk using a time-efficient format. Reading the data items from disk can be very fast and done in random order (once the in-memory index is built for the file). */ class OPENMS_DLLAPI CachedMzMLHandler : public ProgressLogger { typedef int IntType; typedef double DoubleType; public: typedef PeakMap MapType; typedef MSSpectrum SpectrumType; typedef MSChromatogram ChromatogramType; // using double precision to store all data (has to agree with type of BinaryDataArrayPtr) typedef double DatumSingleton; typedef std::vector<DatumSingleton> Datavector; /** @name Constructors and Destructor */ //@{ /// Default constructor CachedMzMLHandler(); /// Default destructor ~CachedMzMLHandler() override; /// Assignment operator CachedMzMLHandler& operator=(const CachedMzMLHandler& rhs); //@} /** @name Read / Write a complete mass spectrometric experiment (or its meta data) */ //@{ /// Write complete spectra as a dump to the disk void writeMemdump(const MapType& exp, const String& out) const; /// Write only the meta data of an MSExperiment void writeMetadata(MapType exp, const String& out_meta, bool addCacheMetaValue=false); /// Write only the meta data of an MSExperiment void writeMetadata_x(const MapType& exp, const String& out_meta, bool addCacheMetaValue=false); /// Read all spectra from a dump from the disk void readMemdump(MapType& exp_reading, const String& filename) const; //@} /** @name Access and creation of the binary indices */ //@{ /// Create an index on the location of all the spectra and chromatograms void createMemdumpIndex(const String& filename); /// Access to a constant copy of the binary spectra index const std::vector<std::streampos>& getSpectraIndex() const; /// Access to a constant copy of the binary chromatogram index const std::vector<std::streampos>& getChromatogramIndex() const; //@} /** @name Direct access to a single Spectrum or Chromatogram */ //@{ /** @brief fast access to a spectrum (a direct copy of the data into the provided arrays) @param[out] data1 First data array (m/z) @param[out] data2 Second data array (Intensity) @param[in] ifs Input file stream (moved to the correct position) @param[out] ms_level Output parameter to store the MS level of the spectrum (1, 2, 3 ...) @param[out] rt Output parameter to store the retention time of the spectrum @throws Exception::ParseError is thrown if the spectrum cannot be read */ static inline void readSpectrumFast(OpenSwath::BinaryDataArrayPtr& data1, OpenSwath::BinaryDataArrayPtr& data2, std::ifstream& ifs, int& ms_level, double& rt) { std::vector<OpenSwath::BinaryDataArrayPtr> data = readSpectrumFast(ifs, ms_level, rt); data1 = data[0]; data2 = data[1]; } /** @brief Fast access to a spectrum @param[in] ifs Input file stream (moved to the correct position) @param[out] ms_level Output parameter to store the MS level of the spectrum (1, 2, 3 ...) @param[out] rt Output parameter to store the retention time of the spectrum @throws Exception::ParseError is thrown if the spectrum cannot be read */ static std::vector<OpenSwath::BinaryDataArrayPtr> readSpectrumFast(std::ifstream& ifs, int& ms_level, double& rt); /** @brief Fast access to a chromatogram @param[in] data1 First data array (RT) @param[in] data2 Second data array (Intensity) @param[in] ifs Input file stream (moved to the correct position) @throws Exception::ParseError is thrown if the chromatogram size cannot be read */ static inline void readChromatogramFast(OpenSwath::BinaryDataArrayPtr& data1, OpenSwath::BinaryDataArrayPtr& data2, std::ifstream& ifs) { std::vector<OpenSwath::BinaryDataArrayPtr> data = readChromatogramFast(ifs); data1 = data[0]; data2 = data[1]; } /** @brief Fast access to a chromatogram @param[in] ifs Input file stream (moved to the correct position) @throws Exception::ParseError is thrown if the chromatogram size cannot be read */ static std::vector<OpenSwath::BinaryDataArrayPtr> readChromatogramFast(std::ifstream& ifs); //@} /** @brief Read a single spectrum directly into an OpenMS MSSpectrum (assuming file is already at the correct position) @param[out] spectrum Output spectrum @param[in] ifs Input file stream (moved to the correct position) @throws Exception::ParseError is thrown if the chromatogram size cannot be read */ static void readSpectrum(SpectrumType& spectrum, std::ifstream& ifs); /** @brief Read a single chromatogram directly into an OpenMS MSChromatogram (assuming file is already at the correct position) @param[out] chromatogram Output chromatogram @param[in] ifs Input file stream (moved to the correct position) @throws Exception::ParseError is thrown if the chromatogram size cannot be read */ static void readChromatogram(ChromatogramType& chromatogram, std::ifstream& ifs); protected: /// write a single spectrum to filestream void writeSpectrum_(const SpectrumType& spectrum, std::ofstream& ofs) const; /// write a single chromatogram to filestream void writeChromatogram_(const ChromatogramType& chromatogram, std::ofstream& ofs) const; /// helper method for fast reading of spectra and chromatograms static inline void readDataFast_(std::ifstream& ifs, std::vector<OpenSwath::BinaryDataArrayPtr>& data, const Size& data_size, const Size& nr_float_arrays); /// Members std::vector<std::streampos> spectra_index_; std::vector<std::streampos> chrom_index_; }; } }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/FORMAT/HANDLERS/XMLHandler.h
.h
33,698
1,005
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow $ // $Authors: Marc Sturm, Chris Bielow $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/CONCEPT/Macros.h> #include <OpenMS/DATASTRUCTURES/DateTime.h> #include <OpenMS/DATASTRUCTURES/DataValue.h> #include <OpenMS/DATASTRUCTURES/ListUtils.h> #include <xercesc/sax2/Attributes.hpp> #include <xercesc/sax2/DefaultHandler.hpp> #include <xercesc/util/XMLString.hpp> #include <iosfwd> #include <string> #include <memory> namespace OpenMS { class ControlledVocabulary; class CVTerm; class MetaInfoInterface; class ProteinIdentification; namespace Internal { #define CONST_XMLCH(s) reinterpret_cast<const ::XMLCh*>(u ## s) static_assert(sizeof(::XMLCh) == sizeof(char16_t), "XMLCh is not sized correctly for UTF-16."); //Adapted from https://www.codeproject.com/articles/99551/redux-raii-adapter-for-xerces //Copyright 2010 Orjan Westin //Under BSD license //======================================================================================================== template<typename T> class OPENMS_DLLAPI shared_xerces_ptr { // Function to release Xerces data type with a release member function template<typename U> static void doRelease_(U* item) { // Only release this if it has no owner if (nullptr == item->getOwnerDocument()) item->release(); } static void doRelease_(char* item); static void doRelease_(XMLCh* item); // The actual data we're holding std::shared_ptr<T> item_; public: // Default constructor shared_xerces_ptr() = default; // Assignment constructor shared_xerces_ptr(T* item) : item_(item, doRelease_ ) {} // Assignment of data to guard shared_xerces_ptr& operator=(T* item) { assign(item); return *this; } // Give up hold on data void reset() { item_.reset(); } // Release currently held data, if any, to hold another void assign(T* item) { item_.reset(item, doRelease_ ); } // Get pointer to the currently held data, if any T* get() { return item_.get(); } const T* get() const { return item_.get(); } // Return true if no data is held bool is_released() const { return (nullptr == item_.get()); } }; template <typename T> class OPENMS_DLLAPI unique_xerces_ptr { private: template<typename U> static void doRelease_(U*& item) { // Only release this if it has no parent (otherwise // parent will release it) if (nullptr == item->getOwnerDocument()) item->release(); } static void doRelease_(char*& item); static void doRelease_(XMLCh*& item); T* item_; public: // Hide copy constructor and assignment operator unique_xerces_ptr(const unique_xerces_ptr<T>&) = delete; unique_xerces_ptr& operator=(const unique_xerces_ptr<T>&) = delete; unique_xerces_ptr() : item_(nullptr) {} explicit unique_xerces_ptr(T* i) : item_(i) {} ~unique_xerces_ptr() { xerces_release(); } unique_xerces_ptr(unique_xerces_ptr<T>&& other) noexcept : item_(nullptr) { this->swap(other); } void swap(unique_xerces_ptr<T>& other) noexcept { std::swap(item_, other.item_); } // Assignment of data to guard (not chainable) void operator=(T* i) { reassign(i); } // Release held data (i.e. delete/free it) void xerces_release() { if (!is_released()) { // Use type-specific release mechanism doRelease_(item_); item_ = nullptr; } } // Give up held data (i.e. return data without releasing) T* yield() { T* tempItem = item_; item_ = nullptr; return tempItem; } // Release currently held data, if any, to hold another void assign(T* i) { xerces_release(); item_ = i; } // Get pointer to the currently held data, if any T* get() const { return item_; } // Return true if no data is held bool is_released() const { return (nullptr == item_); } }; //======================================================================================================== /* * @brief Helper class for XML parsing that handles the conversions of Xerces strings * * It provides the convert() function which internally calls * XMLString::transcode and ensures that the memory is released properly * through XMLString::release internally. It returns a std::string or * std::basic_string<XMLCh> to the caller who takes ownership of the data. * */ class OPENMS_DLLAPI StringManager { typedef std::basic_string<XMLCh> XercesString; /// Converts from a narrow-character string to a wide-character string. inline static unique_xerces_ptr<XMLCh> fromNative_(const char* str) { return unique_xerces_ptr<XMLCh>(xercesc::XMLString::transcode(str)); } /// Converts from a narrow-character string to a wide-character string. inline static unique_xerces_ptr<XMLCh> fromNative_(const String& str) { return fromNative_(str.c_str()); } /// Converts from a wide-character string to a narrow-character string. inline static String toNative_(const XMLCh* str) { String r; XMLSize_t l = strLength(str); if(isASCII(str, l)) { appendASCII(str,l,r); } else { r = (unique_xerces_ptr<char>(xercesc::XMLString::transcode(str)).get()); } return r; } /// Converts from a wide-character string to a narrow-character string. inline static String toNative_(const unique_xerces_ptr<XMLCh>& str) { return toNative_(str.get()); } protected: /// Compresses eight 8x16bit Chars in XMLCh* to 8x8bit Chars by cutting upper byte static void compress64_ (const XMLCh * input_it, char* output_it); public: /// Constructor StringManager(); /// Destructor ~StringManager(); /// Calculates the length of a XMLCh* string using SIMDe // https://github.com/OpenMS/OpenMS/issues/8122 #if defined(__GNUC__) __attribute__((no_sanitize("address"))) #elif defined(_MSC_VER) __declspec(no_sanitize_address) #endif static XMLSize_t strLength(const XMLCh* input_ptr); /// Transcode the supplied C string to a xerces string inline static XercesString convert(const char * str) { return fromNative_(str).get(); } /// Transcode the supplied C++ string to a xerces string inline static XercesString convert(const std::string & str) { return fromNative_(str.c_str()).get(); } /// Transcode the supplied OpenMS string to a xerces string inline static XercesString convert(const String & str) { return fromNative_(str.c_str()).get(); } /// Transcode the supplied C string to a xerces string pointer inline static unique_xerces_ptr<XMLCh> convertPtr(const char * str) { return fromNative_(str); } /// Transcode the supplied C++ string to a xerces string pointer inline static unique_xerces_ptr<XMLCh> convertPtr(const std::string & str) { return fromNative_(str.c_str()); } /// Transcode the supplied OpenMS string to a xerces string pointer inline static unique_xerces_ptr<XMLCh> convertPtr(const String & str) { return fromNative_(str.c_str()); } /// Transcode the supplied XMLCh* to a String inline static String convert(const XMLCh * str) { return toNative_(str); } /// Checks if supplied chars in XMLCh* can be encoded with ASCII (i.e. the upper byte of each char is 0) static bool isASCII(const XMLCh * chars, const XMLSize_t length); /** * @brief Transcodes the supplied XMLCh* and appends it to the OpenMS String * * @note Assumes that the XMLCh* only contains ASCII characters * */ static void appendASCII(const XMLCh * str, const XMLSize_t length, String & result); }; /** @brief Base class for XML handlers. */ class OPENMS_DLLAPI XMLHandler : public xercesc::DefaultHandler { public: /// Exception that is thrown if the parsing is ended by some event (e.g. if only a prefix of the XML file is needed). class OPENMS_DLLAPI EndParsingSoftly : public Exception::BaseException { public: EndParsingSoftly(const char * file, int line, const char * function) : Exception::BaseException(file, line, function) { } }; ///Action to set the current mode (for error messages) enum ActionMode { LOAD, ///< Loading a file STORE ///< Storing a file }; enum LOADDETAIL { LD_ALLDATA, // default; load all data LD_RAWCOUNTS, // only count the total number of spectra and chromatograms (usually very fast) LD_COUNTS_WITHOPTIONS // count the number of spectra, while respecting PeakFileOptions (msLevel and RTRange) and chromatograms (fast) }; /// Default constructor XMLHandler(const String & filename, const String & version); /// Destructor ~XMLHandler() override; /// Release internal memory used for parsing (call void reset(); /** @name Reimplemented XERCES-C error handlers These methods forward the error message to our own error handlers below. */ //@{ void fatalError(const xercesc::SAXParseException & exception) override; void error(const xercesc::SAXParseException & exception) override; void warning(const xercesc::SAXParseException & exception) override; //@} /// Fatal error handler. Throws a ParseError exception void fatalError(ActionMode mode, const String & msg, UInt line = 0, UInt column = 0) const; /// Error handler for recoverable errors. void error(ActionMode mode, const String & msg, UInt line = 0, UInt column = 0) const; /// Warning handler. void warning(ActionMode mode, const String & msg, UInt line = 0, UInt column = 0) const; /// Parsing method for character data void characters(const XMLCh * const chars, const XMLSize_t length) override; /// Parsing method for opening tags void startElement(const XMLCh * const uri, const XMLCh * const localname, const XMLCh * const qname, const xercesc::Attributes & attrs) override; /// Parsing method for closing tags void endElement(const XMLCh * const uri, const XMLCh * const localname, const XMLCh * const qname) override; /// Writes the contents to a stream. virtual void writeTo(std::ostream & /*os*/); /// handler which support partial loading, implement this method virtual LOADDETAIL getLoadDetail() const; /// handler which support partial loading, implement this method virtual void setLoadDetail(const LOADDETAIL d); /** @brief Escapes a string and returns the escaped string Some characters must be escaped which are allowed in user params. E.g. > and & are not in XML and need to be escaped. Parsing those escaped strings from file again is automatically done by Xerces. Escaped characters are: & < > " ' */ static String writeXMLEscape(const String& to_escape) { String _copy = to_escape; // has() is cheap, so check before calling substitute(), since substitute() will usually happen rarely if (_copy.has('&')) _copy.substitute("&","&amp;"); if (_copy.has('>')) _copy.substitute(">","&gt;"); if (_copy.has('"')) _copy.substitute("\"","&quot;"); if (_copy.has('<')) _copy.substitute("<","&lt;"); if (_copy.has('\'')) _copy.substitute("'","&apos;"); return _copy; } /** * @brief Convert an XSD type (e.g. 'xsd:double') to a DataValue. * * Not all conversions are supported yet, due to DataValue using an Int64 as the largest possible integer. * Thus, if the @p value contains a large UInt64, conversion will fail. * Value ranges are currently also not checked, only for XSD types which happen to match the internal representation. * * @param[out] type An XSD type. If the type is not supported, the returned type will be a string * @param[in] value The value in sting format, e.g. "123.34" * @return The Datavalue with the respective type (double, int or string) * @throws Exception::ConversionError if the value does not fit into the internal representation or (for few types) exceeds the XSD specs. * */ static DataValue fromXSDString(const String& type, const String& value) { DataValue data_value; // float type if (type == "xsd:double" || type == "xsd:float" || type == "xsd:decimal") { data_value = DataValue(value.toDouble()); } // <=32 bit integer types else if (type == "xsd:byte" || // 8bit signed type == "xsd:int" || // 32bit signed type == "xsd:unsignedShort" || // 16bit unsigned type == "xsd:short" || // 16bit signed type == "xsd:unsignedByte" || type == "xsd:unsignedInt") { data_value = DataValue(value.toInt32()); } // 64 bit integer types else if (type == "xsd:long" || type == "xsd:unsignedLong" || // 64bit signed or unsigned respectively type == "xsd:integer" || type == "xsd:negativeInteger" || // any 'integer' has arbitrary size... but we have to cope with 64bit for now. type == "xsd:nonNegativeInteger" || type == "xsd:nonPositiveInteger" || type == "xsd:positiveInteger") { data_value = DataValue(value.toInt64()); // internally a signed 64-bit integer. So if someone uses 2^64-1 as value, toInt64() will raise an exception... } // everything else is treated as a string else { data_value = DataValue(value); } return data_value; } /** @brief Convert the value of a <em>\<cvParam value=.\></em> (as commonly found in PSI schemata) to the DataValue with the correct type (e.g. int) according to the type stored in the CV (usually PSI-MS CV), as well as set its unit. @param[in] cv A CV, usually the PSI-MS CV, see ControlledVocabulary::getPSIMSCV() @param[in] parent_tag The tag which encloses the \<cvParam\> @param[in] accession The accession from the 'accession' attribute of the \<cvParam\> @param[in] name The name from the 'name' attribute of the \<cvParam\> @param[in] value The value from the 'value' attribute of the \<cvParam\> @param[in] unit_accession The unit_accession from the 'unitAccession' attribute of the \<cvParam\> @return DataValue::EMPTY if a conversion error occured (e.g. if @p value could not be converted to an integer for an @p accession which requires an integer) or the DataValue upon success */ DataValue cvParamToValue(const ControlledVocabulary& cv, const String& parent_tag, const String& accession, const String& name, const String& value, const String& unit_accession) const; /** @brief Convert the value of a <em>\<cvParam value=.\></em> (as commonly found in PSI schemata) to the DataValue with the correct type (e.g. int) according to the type stored in the CV (usually PSI-MS CV), as well as set its unit. @param[in] cv A CV, usually the PSI-MS CV, see ControlledVocabulary::getPSIMSCV() @param[in] raw_term Represenation of the raw data (i.e. all strings) from a \<cvParam ...\> without the conversion to a specific value type @return DataValue::EMPTY if a conversion error occured (e.g. if @p value could not be converted to an integer for an @p accession which requires an integer) or the DataValue upon success */ DataValue cvParamToValue(const ControlledVocabulary& cv, const CVTerm& raw_term) const; /// throws a ParseError if protIDs are not unique, i.e. PeptideIDs will be randomly assigned (bad!) /// Should be called before writing any ProtIDs to file void checkUniqueIdentifiers_(const std::vector<ProteinIdentification>& prot_ids) const; protected: /// File name String file_; /// Schema version String version_; /// Helper class for string conversion StringManager sm_; /** @brief Stack of open XML tags This member is used only in those XML parsers that need this information. */ std::vector<String> open_tags_; /// parse only until total number of scans and chroms have been determined from attributes LOADDETAIL load_detail_; /// Returns if two Xerces strings are equal inline bool equal_(const XMLCh * a, const XMLCh * b) const { return xercesc::XMLString::compareString(a, b) == 0; } ///@name General MetaInfo handling (for idXML, featureXML, consensusXML) //@{ /// Writes the content of MetaInfoInterface to the file void writeUserParam_(const String & tag_name, std::ostream & os, const MetaInfoInterface & meta, UInt indent) const; //@} ///@name controlled vocabulary handling methods //@{ /// Array of CV term lists (one sublist denotes one term and it's children) std::vector<std::vector<String> > cv_terms_; /// Converts @p term to the index of the term in the cv_terms_ entry @p section /// If the term is not found, @p result_on_error is returned (0 by default) SignedSize cvStringToEnum_(const Size section, const String & term, const char * message, const SignedSize result_on_error = 0); //@} ///@name String conversion //@{ /// Conversion of a String to an integer value inline Int asInt_(const String & in) const { Int res = 0; try { res = in.toInt(); } catch (Exception::ConversionError&) { error(LOAD, String("Int conversion error of \"") + in + "\""); } return res; } /// Conversion of a Xerces string to an integer value inline Int asInt_(const XMLCh * in) const { return xercesc::XMLString::parseInt(in); } /// Conversion of a String to an unsigned integer value inline UInt asUInt_(const String & in) const { UInt res = 0; try { Int tmp = in.toInt(); if (tmp < 0) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, ""); } res = UInt(tmp); } catch (Exception::ConversionError& ) { error(LOAD, String("UInt conversion error of \"") + in + "\""); } return res; } /// Conversion of a String to a double value inline double asDouble_(const String & in) const { double res = 0.0; try { res = in.toDouble(); } catch (Exception::ConversionError& ) { error(LOAD, String("Double conversion error of \"") + in + "\""); } return res; } /// Conversion of a String to a float value inline float asFloat_(const String & in) const { float res = 0.0; try { res = in.toFloat(); } catch (Exception::ConversionError& ) { error(LOAD, String("Float conversion error of \"") + in + "\""); } return res; } /** @brief Conversion of a string to a boolean value 'true', 'false', '1' and '0' are accepted. @n For all other values a parse error is produced. */ inline bool asBool_(const String & in) const { if (in == "true" || in == "TRUE" || in == "True" || in == "1") { return true; } else if (in == "false" || in == "FALSE" || in == "False" || in == "0") { return false; } else { error(LOAD, String("Boolean conversion error of \"") + in + "\""); } return false; } /// Conversion of a xs:datetime string to a DateTime value inline DateTime asDateTime_(String date_string) const { DateTime date_time; if (!date_string.empty()) { try { //strip away milliseconds date_string.trim(); date_string = date_string.substr(0, 19); date_time.set(date_string); } catch (Exception::ParseError& /*err*/ ) { error(LOAD, String("DateTime conversion error of \"") + date_string + "\""); } } return date_time; } //@} ///@name Accessing attributes //@{ /// Converts an attribute to a String inline String attributeAsString_(const xercesc::Attributes & a, const char * name) const { const XMLCh * val = a.getValue(sm_.convertPtr(name).get()); if (val == nullptr) fatalError(LOAD, String("Required attribute '") + name + "' not present!"); return sm_.convert(val); } /// Converts an attribute to a Int inline Int attributeAsInt_(const xercesc::Attributes & a, const char * name) const { const XMLCh * val = a.getValue(sm_.convertPtr(name).get()); if (val == nullptr) fatalError(LOAD, String("Required attribute '") + name + "' not present!"); return xercesc::XMLString::parseInt(val); } /// Converts an attribute to a double inline double attributeAsDouble_(const xercesc::Attributes & a, const char * name) const { const XMLCh * val = a.getValue(sm_.convertPtr(name).get()); if (val == nullptr) fatalError(LOAD, String("Required attribute '") + name + "' not present!"); return String(sm_.convert(val)).toDouble(); } /// Converts an attribute to a DoubleList inline DoubleList attributeAsDoubleList_(const xercesc::Attributes & a, const char * name) const { String tmp(expectList_(attributeAsString_(a, name))); return ListUtils::create<double>(tmp.substr(1, tmp.size() - 2)); } /// Converts an attribute to an IntList inline IntList attributeAsIntList_(const xercesc::Attributes & a, const char * name) const { String tmp(expectList_(attributeAsString_(a, name))); return ListUtils::create<Int>(tmp.substr(1, tmp.size() - 2)); } /// Converts an attribute to an StringList inline StringList attributeAsStringList_(const xercesc::Attributes & a, const char * name) const { String tmp(expectList_(attributeAsString_(a, name))); StringList tmp_list = ListUtils::create<String>(tmp.substr(1, tmp.size() - 2)); // between [ and ] if (tmp.hasSubstring("\\|")) // check full string for escaped comma { for (String& s : tmp_list) { s.substitute("\\|", ","); } } return tmp_list; } /** @brief Assigns the attribute content to the String @a value if the attribute is present @return if the attribute was present */ inline bool optionalAttributeAsString_(String & value, const xercesc::Attributes & a, const char * name) const { const XMLCh * val = a.getValue(sm_.convertPtr(name).get()); if (val != nullptr) { value = sm_.convert(val); return true; } return false; } /** @brief Assigns the attribute content to the Int @a value if the attribute is present @return if the attribute was present */ inline bool optionalAttributeAsInt_(Int & value, const xercesc::Attributes & a, const char * name) const { const XMLCh * val = a.getValue(sm_.convertPtr(name).get()); if (val != nullptr) { value = xercesc::XMLString::parseInt(val); return true; } return false; } /** @brief Assigns the attribute content to the UInt @a value if the attribute is present @return if the attribute was present */ inline bool optionalAttributeAsUInt_(UInt & value, const xercesc::Attributes & a, const char * name) const { const XMLCh * val = a.getValue(sm_.convertPtr(name).get()); if (val != nullptr) { value = xercesc::XMLString::parseInt(val); return true; } return false; } /** @brief Assigns the attribute content to the double @a value if the attribute is present @return if the attribute was present */ inline bool optionalAttributeAsDouble_(double & value, const xercesc::Attributes & a, const char * name) const { const XMLCh * val = a.getValue(sm_.convertPtr(name).get()); if (val != nullptr) { value = String(sm_.convert(val)).toDouble(); return true; } return false; } /** @brief Assigns the attribute content to the DoubleList @a value if the attribute is present @return if the attribute was present */ inline bool optionalAttributeAsDoubleList_(DoubleList & value, const xercesc::Attributes & a, const char * name) const { const XMLCh * val = a.getValue(sm_.convertPtr(name).get()); if (val != nullptr) { value = attributeAsDoubleList_(a, name); return true; } return false; } /** @brief Assigns the attribute content to the StringList @a value if the attribute is present @return if the attribute was present */ inline bool optionalAttributeAsStringList_(StringList & value, const xercesc::Attributes & a, const char * name) const { const XMLCh * val = a.getValue(sm_.convertPtr(name).get()); if (val != nullptr) { value = attributeAsStringList_(a, name); return true; } return false; } /** @brief Assigns the attribute content to the IntList @a value if the attribute is present @return if the attribute was present */ inline bool optionalAttributeAsIntList_(IntList & value, const xercesc::Attributes & a, const char * name) const { const XMLCh * val = a.getValue(sm_.convertPtr(name).get()); if (val != nullptr) { value = attributeAsIntList_(a, name); return true; } return false; } /// Converts an attribute to a String inline String attributeAsString_(const xercesc::Attributes & a, const XMLCh * name) const { const XMLCh * val = a.getValue(name); if (val == nullptr) fatalError(LOAD, String("Required attribute '") + sm_.convert(name) + "' not present!"); return sm_.convert(val); } /// Converts an attribute to a Int inline Int attributeAsInt_(const xercesc::Attributes & a, const XMLCh * name) const { const XMLCh * val = a.getValue(name); if (val == nullptr) fatalError(LOAD, String("Required attribute '") + sm_.convert(name) + "' not present!"); return xercesc::XMLString::parseInt(val); } /// Converts an attribute to a double inline double attributeAsDouble_(const xercesc::Attributes & a, const XMLCh * name) const { const XMLCh * val = a.getValue(name); if (val == nullptr) fatalError(LOAD, String("Required attribute '") + sm_.convert(name) + "' not present!"); return sm_.convert(val).toDouble(); } /// Converts an attribute to a DoubleList inline DoubleList attributeAsDoubleList_(const xercesc::Attributes & a, const XMLCh * name) const { String tmp(expectList_(attributeAsString_(a, name))); return ListUtils::create<double>(tmp.substr(1, tmp.size() - 2)); } /// Converts an attribute to a IntList inline IntList attributeAsIntList_(const xercesc::Attributes & a, const XMLCh * name) const { String tmp(expectList_(attributeAsString_(a, name))); return ListUtils::create<Int>(tmp.substr(1, tmp.size() - 2)); } /// Converts an attribute to a StringList inline StringList attributeAsStringList_(const xercesc::Attributes & a, const XMLCh * name) const { String tmp(expectList_(attributeAsString_(a, name))); StringList tmp_list = ListUtils::create<String>(tmp.substr(1, tmp.size() - 2)); // between [ and ] if (tmp.hasSubstring("\\|")) // check full string for escaped comma { for (String& s : tmp_list) { s.substitute("\\|", ","); } } return tmp_list; } /// Assigns the attribute content to the String @a value if the attribute is present inline bool optionalAttributeAsString_(String& value, const xercesc::Attributes & a, const XMLCh * name) const { const XMLCh * val = a.getValue(name); if (val != nullptr) { value = sm_.convert(val); return !value.empty(); } return false; } /// Assigns the attribute content to the Int @a value if the attribute is present inline bool optionalAttributeAsInt_(Int & value, const xercesc::Attributes & a, const XMLCh * name) const { const XMLCh * val = a.getValue(name); if (val != nullptr) { value = xercesc::XMLString::parseInt(val); return true; } return false; } /// Assigns the attribute content to the UInt @a value if the attribute is present inline bool optionalAttributeAsUInt_(UInt & value, const xercesc::Attributes & a, const XMLCh * name) const { const XMLCh * val = a.getValue(name); if (val != nullptr) { value = xercesc::XMLString::parseInt(val); return true; } return false; } /// Assigns the attribute content to the double @a value if the attribute is present inline bool optionalAttributeAsDouble_(double & value, const xercesc::Attributes & a, const XMLCh * name) const { const XMLCh * val = a.getValue(name); if (val != nullptr) { value = sm_.convert(val).toDouble(); return true; } return false; } /** @brief Assigns the attribute content to the DoubleList @a value if the attribute is present @return if the attribute was present */ inline bool optionalAttributeAsDoubleList_(DoubleList & value, const xercesc::Attributes & a, const XMLCh * name) const { const XMLCh * val = a.getValue(name); if (val != nullptr) { value = attributeAsDoubleList_(a, name); return true; } return false; } /** @brief Assigns the attribute content to the IntList @a value if the attribute is present @return if the attribute was present */ inline bool optionalAttributeAsIntList_(IntList & value, const xercesc::Attributes & a, const XMLCh * name) const { const XMLCh * val = a.getValue(name); if (val != nullptr) { value = attributeAsIntList_(a, name); return true; } return false; } /** @brief Assigns the attribute content to the StringList @a value if the attribute is present @return if the attribute was present */ inline bool optionalAttributeAsStringList_(StringList & value, const xercesc::Attributes & a, const XMLCh * name) const { const XMLCh * val = a.getValue(name); if (val != nullptr) { value = attributeAsStringList_(a, name); return true; } return false; } //@} private: /// Not implemented XMLHandler(); inline const String& expectList_(const String& str) const { if (!(str.hasPrefix('[') && str.hasSuffix(']'))) { fatalError(LOAD, String("List argument is not a string representation of a list!")); } return str; } }; } // namespace Internal } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/FORMAT/HANDLERS/MzXMLHandler.h
.h
5,589
187
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Marc Sturm, Chris Bielow $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/CONCEPT/ProgressLogger.h> #include <OpenMS/KERNEL/StandardTypes.h> #include <OpenMS/FORMAT/OPTIONS/PeakFileOptions.h> #include <OpenMS/FORMAT/HANDLERS/XMLHandler.h> #include <OpenMS/DATASTRUCTURES/String.h> #include <OpenMS/KERNEL/MSExperiment.h> namespace OpenMS { class MetaInfoInterface; namespace Interfaces { class IMSDataConsumer; } namespace Internal { /** @brief XML handlers for MzXMLFile MapType has to be a MSExperiment or have the same interface. Do not use this class. It is only needed in MzXMLFile. */ typedef PeakMap MapType; typedef MSSpectrum SpectrumType; class OPENMS_DLLAPI MzXMLHandler : public XMLHandler { public: /**@name Constructors and destructor */ //@{ /// Constructor for a read-only handler MzXMLHandler(MapType& exp, const String& filename, const String& version, ProgressLogger& logger); /// Constructor for a write-only handler MzXMLHandler(const MapType& exp, const String& filename, const String& version, const ProgressLogger& logger); /// Destructor ~MzXMLHandler() override {} //@} /// handler which support partial loading, implement this method LOADDETAIL getLoadDetail() const override; /// handler which support partial loading, implement this method void setLoadDetail(const LOADDETAIL d) override; // Docu in base class void endElement(const XMLCh* const uri, const XMLCh* const local_name, const XMLCh* const qname) override; // Docu in base class void startElement(const XMLCh* const uri, const XMLCh* const local_name, const XMLCh* const qname, const xercesc::Attributes& attributes) override; // Docu in base class void characters(const XMLCh* const chars, const XMLSize_t length) override; /// Write the contents to a stream void writeTo(std::ostream& os) override; /// Sets the options void setOptions(const PeakFileOptions& options) { options_ = options; } ///Gets the scan count UInt getScanCount() const { return scan_count_; } /// Set the IMSDataConsumer consumer which will consume the read data void setMSDataConsumer(Interfaces::IMSDataConsumer * consumer) { consumer_ = consumer; } protected: /// Peak type typedef MapType::PeakType PeakType; /// Spectrum type typedef MSSpectrum SpectrumType; /// map pointer for reading MapType* exp_; /// map pointer for writing const MapType* cexp_; /// Options for loading and storing PeakFileOptions options_; /**@name temporary data structures to hold parsed data */ //@{ Int nesting_level_; /** @brief Data necessary to generate a single spectrum Small struct holds all data necessary to populate a spectrum at a later timepoint (since reading of the base64 data and generation of spectra can be done at distinct timepoints). */ struct SpectrumData { UInt peak_count_; String precision_; String compressionType_; String char_rest_; SpectrumType spectrum; bool skip_data; }; /// Vector of spectrum data stored for later parallel processing std::vector< SpectrumData > spectrum_data_; //@} /// Flag that indicates whether this spectrum should be skipped (due to options) bool skip_spectrum_; /// spectrum counter (spectra without peaks are not written) UInt spec_write_counter_; /// Consumer class to work on spectra Interfaces::IMSDataConsumer* consumer_; /// Consumer class to work on spectra UInt scan_count_; /// Progress logging class const ProgressLogger& logger_; /// write metaInfo to xml (usually in nameValue-tag) /// returns true if metavalue existed and data was written to the stream inline bool writeAttributeIfExists_(std::ostream& os, const MetaInfoInterface& meta, const String& metakey, const String& attname); /// write metaInfo to xml (usually in nameValue-tag) inline void writeUserParam_(std::ostream& os, const MetaInfoInterface& meta, int indent = 4, const String& tag = "nameValue"); /** @brief Fill a single spectrum with data from input @note Do not modify any internal state variables of the class since this function will be executed in parallel. */ void doPopulateSpectraWithData_(SpectrumData & spectrum_data); /** @brief Populate all spectra on the stack with data from input Will populate all spectra on the current work stack with data (using multiple threads if available) and append them to the result. */ void populateSpectraWithData_(); /// data processing auxiliary variable std::vector< std::shared_ptr< DataProcessing> > data_processing_; private: /// Not implemented MzXMLHandler(); /// initialize members (call from C'tor) void init_(); }; } // namespace Internal } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/FORMAT/HANDLERS/MzMLSqliteHandler.h
.h
8,352
239
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Hannes Roest // -------------------------------------------------------------------------- #pragma once #include <OpenMS/KERNEL/MSExperiment.h> #include <OpenMS/METADATA/ExperimentalSettings.h> #include <OpenMS/OPENSWATHALGO/DATAACCESS/SwathMap.h> // forward declarations struct sqlite3; struct sqlite3_stmt; namespace OpenMS { class ProgressLogger; namespace Internal { /** @brief Sqlite handler for storing spectra and chromatograms in sqMass format. @note Do not use this class directly, rather use SqMassFile. @note Due to the performance characteristics of the underlying SQLite database, it is highly recommended to read and write data (spectra/chromatograms) in batch. This is supported in this class and essential for reasonable performance. The current class does support batching SQL statements which can be controlled using setConfig and it is recommended to set the batch size to at least 500. The underlying SQLite database only stores the most essential parameters of a MS experiment, to store the complete meta-data, a zipped representation of the mzML data structure can be written directly into the database (and will be retrieved when converting back). This class also supports writing data using the lossy numpress compression format. This class contains the internal data structures and SQL statements for communication with the SQLite database */ class OPENMS_DLLAPI MzMLSqliteHandler { public: /** @brief Constructor of sqMass file @param[in] filename The sqMass filename @param[in] run_id Unique identifier which links the sqMass and OSW file. It is currently only used for storing and ignored when reading an sqMass file. */ MzMLSqliteHandler(const String& filename, const UInt64 run_id); /**@name Functions for reading files * * ----------------------------------- * Reading of SQL file starts here * ----------------------------------- */ //@{ /** @brief Read an experiment into an MSExperiment structure @param[out] exp The result data structure @param[in] meta_only Only read the meta data */ void readExperiment(MSExperiment & exp, bool meta_only = false) const; /// extract the RUN::ID from the sqMass file /// @throws Exception::SqlOperationFailed more than on run exists UInt64 getRunID() const; /** @brief Read an set of spectra (potentially restricted to a subset) @param[in] exp The result @param[in] indices A list of indices restricting the resulting spectra only to those specified here @param[in] meta_only Only read the meta data */ void readSpectra(std::vector<MSSpectrum> & exp, const std::vector<int> & indices, bool meta_only = false) const; /** @brief Read an set of chromatograms (potentially restricted to a subset) @param[out] exp The result @param[out] indices A list of indices restricting the resulting chromatograms only to those specified here @param[in] meta_only Only read the meta data */ void readChromatograms(std::vector<MSChromatogram> & exp, const std::vector<int> & indices, bool meta_only = false) const; /** @brief Get number of spectra in the file @return The number of spectra */ Size getNrSpectra() const; /** @brief Get number of chromatograms in the file @return The number of chromatograms */ Size getNrChromatograms() const; /** @brief Set file configuration @param[in] write_full_meta Whether to write a complete mzML meta data structure into the RUN_EXTRA field (allows complete recovery of the input file) @param[in] use_lossy_compression Whether to use lossy compression (ms numpress) @param[in] linear_abs_mass_acc Accepted loss in mass accuracy (absolute m/z, in Th) @param[in] sql_batch_size Batch size of SQL insert statements */ void setConfig(bool write_full_meta, bool use_lossy_compression, double linear_abs_mass_acc, int sql_batch_size = 500) { write_full_meta_ = write_full_meta; use_lossy_compression_ = use_lossy_compression; linear_abs_mass_acc_ = linear_abs_mass_acc; sql_batch_size_ = sql_batch_size; } /** @brief Get spectral indices around a specific retention time @param[in] RT The retention time @param[out] deltaRT Tolerance window around RT (if less or equal than zero, only the first spectrum *after* RT is returned) @param[out] indices Spectra to consider (if empty, all spectra are considered) @return The indices of the spectra within RT +/- deltaRT */ std::vector<size_t> getSpectraIndicesbyRT(double RT, double deltaRT, const std::vector<int> & indices) const; protected: void populateChromatogramsWithData_(sqlite3 *db, std::vector<MSChromatogram>& chromatograms) const; void populateChromatogramsWithData_(sqlite3 *db, std::vector<MSChromatogram>& chromatograms, const std::vector<int> & indices) const; void populateSpectraWithData_(sqlite3 *db, std::vector<MSSpectrum>& spectra) const; void populateSpectraWithData_(sqlite3 *db, std::vector<MSSpectrum>& spectra, const std::vector<int> & indices) const; void prepareChroms_(sqlite3 *db, std::vector<MSChromatogram>& chromatograms, const std::vector<int> & indices = {}) const; void prepareSpectra_(sqlite3 *db, std::vector<MSSpectrum>& spectra, const std::vector<int> & indices = {}) const; //@} public: /**@name Functions for writing files * * ----------------------------------- * Writing to SQL file starts here * ----------------------------------- */ //@{ /** @brief Write an experiment to disk @param[out] exp The data to write */ void writeExperiment(const MSExperiment & exp); /** @brief Create data tables for a new file @note It is required to call this function first before writing any data to disk, otherwise the tables will not be set up! @note Be careful with this function, calling this on an existing file will delete the file! */ void createTables(); /** @brief Writes a set of spectra to disk @param[in] spectra The spectra to write */ void writeSpectra(const std::vector<MSSpectrum>& spectra); /** @brief Writes a set of chromatograms to disk @param[in] chroms The chromatograms to write */ void writeChromatograms(const std::vector<MSChromatogram>& chroms); /** @brief Write the run-level information for an experiment into tables @note This is a low level function, do not call this function unless you know what you are doing! @param[out] exp The result data structure @param[in] write_full_meta Add full meta information into sql tables */ void writeRunLevelInformation(const MSExperiment& exp, bool write_full_meta); protected: void createIndices_(); //@} String filename_; /* * These are spectra and chromatogram ids that are global for a specific * database file. Keeping track of them allows us to append spectra and * chromatograms multiple times to a database. * * However, currently they are initialized to zero when opening a new * file, so appending to an existing file won't work. */ Int spec_id_; Int chrom_id_; UInt64 run_id_; bool use_lossy_compression_; double linear_abs_mass_acc_; double write_full_meta_; int sql_batch_size_; }; } // namespace Internal } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/FORMAT/HANDLERS/MzDataHandler.h
.h
6,572
193
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Marc Sturm $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/KERNEL/StandardTypes.h> #include <OpenMS/CONCEPT/Exception.h> #include <OpenMS/CONCEPT/ProgressLogger.h> #include <OpenMS/FORMAT/HANDLERS/XMLHandler.h> #include <OpenMS/FORMAT/OPTIONS/PeakFileOptions.h> #include <OpenMS/KERNEL/MSExperiment.h> #include <sstream> namespace OpenMS { namespace Internal { /** @brief XML handler for MzDataFile MapType has to be a MSExperiment or have the same interface. Do not use this class. It is only needed in MzDataFile. @improvement Add implementation and tests of 'supDataArray' to store IntegerDataArray and StringDataArray of MSSpectrum (Hiwi) */ typedef PeakMap MapType; typedef MSSpectrum SpectrumType; typedef MSChromatogram ChromatogramType; class OPENMS_DLLAPI MzDataHandler : public XMLHandler { public: /**@name Constructors and destructor */ //@{ /// Constructor for a write-only handler MzDataHandler(MapType & exp, const String & filename, const String & version, ProgressLogger & logger); /// Constructor for a read-only handler MzDataHandler(const MapType & exp, const String & filename, const String & version, const ProgressLogger & logger); /// Destructor ~MzDataHandler() override { } //@} // Docu in base class void endElement(const XMLCh * const /*uri*/, const XMLCh * const /*local_name*/, const XMLCh * const qname) override; // Docu in base class void startElement(const XMLCh * const /*uri*/, const XMLCh * const /*local_name*/, const XMLCh * const qname, const xercesc::Attributes & attributes) override; // Docu in base class void characters(const XMLCh * const chars, const XMLSize_t length) override; /// Writes the contents to a stream void writeTo(std::ostream & os) override; ///Sets the options void setOptions(const PeakFileOptions & options) { options_ = options; } private: void init_(); protected: /// Peak type typedef MapType::PeakType PeakType; /// Spectrum type typedef MSSpectrum SpectrumType; /// map pointer for reading MapType * exp_; /// map pointer for writing const MapType * cexp_; ///Options that can be set for loading/storing PeakFileOptions options_; /**@name temporary datastructures to hold parsed data */ //@{ /// The number of peaks in the current spectrum (according to the length attribute -- which should not be trusted) UInt peak_count_; /// The current spectrum SpectrumType spec_; /// An array of pairs MetaInfodescriptions and their ids std::vector<std::pair<String, MetaInfoDescription> > meta_id_descs_; /// encoded data which is read and has to be decoded std::vector<String> data_to_decode_; /// floating point numbers which have to be encoded and written std::vector<float> data_to_encode_; std::vector<std::vector<float> > decoded_list_; std::vector<std::vector<double> > decoded_double_list_; std::vector<String> precisions_; std::vector<String> endians_; //@} /// Flag that indicates whether this spectrum should be skipped (due to options) bool skip_spectrum_; /// Progress logger const ProgressLogger & logger_; /// fills the current spectrum with peaks and meta data void fillData_(); ///@name cvParam and userParam handling methods (for mzData and featureXML) //@{ /** @brief write cvParam containing strings to stream @p value string value @p acc accession number defined by ontology @p name term defined by ontology @p indent number of tabs used in front of tag Example: &lt;cvParam cvLabel="psi" accession="PSI:@p acc" name="@p name" value="@p value"/&gt; */ inline void writeCVS_(std::ostream & os, double value, const String & acc, const String & name, UInt indent = 4) const; /** @brief write cvParam containing strings to stream @p value string value @p acc accession number defined by ontology @p name term defined by ontology @p indent number of tabs used in front of tag Example: &lt;cvParam cvLabel="psi" accession="PSI:@p acc" name="@p name" value="@p value"/&gt; */ inline void writeCVS_(std::ostream & os, const String & value, const String & acc, const String & name, UInt indent = 4) const; /** @brief write cvParam element to stream @p os Output stream @p value enumeration value @p map index if the terms in cv_terms_ @p acc accession number defined by ontology @p name term defined by ontology @p indent number of tabs used in front of tag Example: &lt;cvParam cvLabel="psi" accession="PSI:@p acc" name="@p name" value=""/&gt; */ inline void writeCVS_(std::ostream & os, UInt value, UInt map, const String & acc, const String & name, UInt indent = 4); ///Writing the MetaInfo as UserParam to the file inline void writeUserParam_(std::ostream & os, const MetaInfoInterface & meta, UInt indent = 4); /** @brief read attributes of MzData's cvParamType Example: &lt;cvParam cvLabel="psi" accession="PSI:1000001" name="@p name" value="@p value"/&gt; @p name and sometimes @p value are defined in the MzData ontology. */ void cvParam_(const String & name, const String & value); //@} /** @brief write binary data to stream (first one) The @p name and @p id are only used if the @p tag is @em supDataArrayBinary or @em supDataArray. */ inline void writeBinary_(std::ostream & os, Size size, const String & tag, const String & name = "", SignedSize id = -1); //Data processing auxiliary variable std::shared_ptr< DataProcessing > data_processing_; }; //-------------------------------------------------------------------------------- } // namespace Internal } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/FORMAT/HANDLERS/ConsensusXMLHandler.h
.h
5,039
124
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Clemens Groepl, Marc Sturm $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/CONCEPT/ProgressLogger.h> #include <OpenMS/FORMAT/HANDLERS/XMLHandler.h> #include <OpenMS/FORMAT/OPTIONS/PeakFileOptions.h> #include <OpenMS/KERNEL/ConsensusMap.h> #include <OpenMS/METADATA/PeptideEvidence.h> #include <OpenMS/METADATA/ProteinIdentification.h> #include <OpenMS/METADATA/PeptideIdentification.h> #include <unordered_map> #include <map> namespace OpenMS { namespace Internal { /** @brief This class provides Input functionality for ConsensusMaps and Output functionality for alignments and quantitation. This class can be used to load the content of a consensusXML file into a ConsensusMap or to save the content of an ConsensusMap object into an XML file. A documented schema for this format can be found at https://github.com/OpenMS/OpenMS/tree/develop/share/OpenMS/SCHEMAS @todo Take care that unique ids are assigned properly by TOPP tools before calling ConsensusXMLFile::store(). There will be a message on OPENMS_LOG_INFO but we will make no attempt to fix the problem in this class. (all developers) @ingroup FileIO */ class OPENMS_DLLAPI ConsensusXMLHandler : public Internal::XMLHandler, public ProgressLogger { public: ///Constructor ConsensusXMLHandler(ConsensusMap& map, const String& filename); ConsensusXMLHandler(const ConsensusMap& map, const String& filename); ///Destructor ~ConsensusXMLHandler() override; /// Mutable access to the options for loading/storing PeakFileOptions& getOptions(); void setOptions(const PeakFileOptions&); /// Non-mutable access to the options for loading/storing const PeakFileOptions& getOptions() const; /// Docu in base class XMLHandler::writeTo void writeTo(std::ostream& os) override; protected: // Docu in base class void endElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname) override; // Docu in base class void startElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname, const xercesc::Attributes& attributes) override; // Docu in base class void characters(const XMLCh* const chars, const XMLSize_t length) override; /// Writes a peptide identification to a stream (for assigned/unassigned peptide identifications) void writePeptideIdentification_(const String& filename, std::ostream& os, const PeptideIdentification& id, const String& tag_name, UInt indentation_level); /// Add data from ProteinGroups to a MetaInfoInterface /// Since it can be used during load and store, it needs to take a param for the current mode (LOAD/STORE) /// to throw appropriate warnings/errors void addProteinGroups_(MetaInfoInterface& meta, const std::vector<ProteinIdentification::ProteinGroup>& groups, const String& group_name, const std::unordered_map<std::string, UInt>& accession_to_id, const String& runid, XMLHandler::ActionMode mode); /// Read and store ProteinGroup data void getProteinGroups_(std::vector<ProteinIdentification::ProteinGroup>& groups, const String& group_name); /// Options that can be set PeakFileOptions options_; ///@name Temporary variables for parsing //@{ ConsensusMap* consensus_map_; const ConsensusMap* cconsensus_map_; ConsensusFeature act_cons_element_; DPosition<2> pos_; double it_; //@} /// Pointer to last read object as a MetaInfoInterface, or null. MetaInfoInterface* last_meta_; /// Temporary protein ProteinIdentification ProteinIdentification prot_id_; /// Temporary peptide ProteinIdentification PeptideIdentification pep_id_; /// Temporary protein hit ProteinHit prot_hit_; /// Temporary peptide hit PeptideHit pep_hit_; /// Temporary peptide evidences std::vector<PeptideEvidence> peptide_evidences_; /// Map from protein id to accession std::map<String, String> proteinid_to_accession_; /// Map from search identifier concatenated with protein accession to id std::unordered_map<std::string, UInt> accession_to_id_; /// Map from identification run identifier to file xs:id (for linking peptide identifications to the corresponding run) std::map<String, String> identifier_id_; /// Map from file xs:id to identification run identifier (for linking peptide identifications to the corresponding run) std::map<String, String> id_identifier_; /// Temporary search parameters file ProteinIdentification::SearchParameters search_param_; UInt progress_; }; } // namespace Internal } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/FORMAT/HANDLERS/MascotXMLHandler.h
.h
3,334
91
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Nico Pfeifer, Chris Bielow $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/CHEMISTRY/AASequence.h> #include <OpenMS/CHEMISTRY/ModificationsDB.h> #include <OpenMS/FORMAT/HANDLERS/XMLHandler.h> #include <OpenMS/METADATA/PeptideIdentification.h> #include <OpenMS/METADATA/PeptideIdentificationList.h> #include <OpenMS/METADATA/PeptideEvidence.h> #include <OpenMS/METADATA/ProteinIdentification.h> #include <OpenMS/METADATA/SpectrumMetaDataLookup.h> #include <vector> namespace OpenMS { namespace Internal { /** @brief Handler that is used for parsing MascotXML data */ class OPENMS_DLLAPI MascotXMLHandler : public XMLHandler { public: /// Constructor MascotXMLHandler(ProteinIdentification& protein_identification, PeptideIdentificationList& identifications, const String& filename, std::map<String, std::vector<AASequence> >& peptides, const SpectrumMetaDataLookup& lookup); /// Destructor ~MascotXMLHandler() override; // Docu in base class void endElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname) override; // Docu in base class void startElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname, const xercesc::Attributes& attributes) override; // Docu in base class void characters(const XMLCh* const chars, const XMLSize_t /*length*/) override; /// Split modification search parameter if for more than one amino acid specified e.g. Phospho (ST) static std::vector<String> splitModificationBySpecifiedAA(const String& mod); private: ProteinIdentification& protein_identification_; ///< the protein identifications PeptideIdentificationList& id_data_; ///< the identifications (storing the peptide hits) ProteinHit actual_protein_hit_; PeptideHit actual_peptide_hit_; PeptideEvidence actual_peptide_evidence_; UInt peptide_identification_index_; String tag_; DateTime date_; String date_time_string_; UInt actual_query_; ProteinIdentification::SearchParameters search_parameters_; String identifier_; String actual_title_; std::map<String, std::vector<AASequence> >& modified_peptides_; StringList tags_open_; ///< tracking the current XML tree String character_buffer_; ///< filled by MascotXMLHandler::characters String major_version_; String minor_version_; // list of modifications, which cannot be set as fixed and needs // to be removed, because added from mascot as variable modification std::vector<String> remove_fixed_mods_; /// Helper object for looking up RT information const SpectrumMetaDataLookup& lookup_; /// Error for missing RT information already reported? bool no_rt_error_; }; } // namespace Internal } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/FORMAT/HANDLERS/FeatureXMLHandler.h
.h
5,836
169
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow $ // $Authors: Marc Sturm, Chris Bielow, Clemens Groepl $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/FORMAT/OPTIONS/FeatureFileOptions.h> #include <OpenMS/FORMAT/XMLFile.h> #include <OpenMS/FORMAT/HANDLERS/XMLHandler.h> #include <OpenMS/CONCEPT/ProgressLogger.h> #include <OpenMS/METADATA/ProteinIdentification.h> #include <OpenMS/METADATA/PeptideIdentification.h> #include <OpenMS/DATASTRUCTURES/ConvexHull2D.h> #include <OpenMS/DATASTRUCTURES/Param.h> #include <iosfwd> #include <map> namespace OpenMS { class Feature; class FeatureMap; namespace Internal { /** @brief This class provides Input/Output functionality for feature maps A documented schema for this format can be found at https://github.com/OpenMS/OpenMS/tree/develop/share/OpenMS/SCHEMAS @todo Take care that unique ids are assigned properly by TOPP tools before calling FeatureXMLFile::store(). There will be a message on OPENMS_LOG_INFO but we will make no attempt to fix the problem in this class. (all developers) @ingroup FileIO */ class OPENMS_DLLAPI FeatureXMLHandler : public Internal::XMLHandler, public ProgressLogger { public: /** @name Constructors and Destructor */ //@{ ///Default constructor FeatureXMLHandler(FeatureMap& map, const String& filename); FeatureXMLHandler(const FeatureMap& map, const String& filename); ///Destructor ~FeatureXMLHandler() override; //@} /// Docu in base class XMLHandler::writeTo void writeTo(std::ostream& os) override; /// Mutable access to the options for loading/storing FeatureFileOptions& getOptions(); /// Non-mutable access to the options for loading/storing const FeatureFileOptions& getOptions() const; /// setter for options for loading/storing void setOptions(const FeatureFileOptions&); void setSizeOnly(const bool size_only) { size_only_ = size_only; } Size getSize() const { return expected_size_; } protected: // restore default state for next load/store operation void resetMembers_(); // Docu in base class void endElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname) override; // Docu in base class void startElement(const XMLCh* const /*uri*/, const XMLCh* const /*local_name*/, const XMLCh* const qname, const xercesc::Attributes& attributes) override; // Docu in base class void characters(const XMLCh* const chars, const XMLSize_t length) override; /// Writes a feature to a stream void writeFeature_(const String& filename, std::ostream& os, const Feature& feat, const String& identifier_prefix, UInt64 identifier, UInt indentation_level); /// Writes a peptide identification to a stream (for assigned/unassigned peptide identifications) void writePeptideIdentification_(const String& filename, std::ostream& os, const PeptideIdentification& id, const String& tag_name, UInt indentation_level); /** @brief update the pointer to the current feature @param[in] create If true, a new (empty) Feature is added at the appropriate subordinate_feature_level_ */ void updateCurrentFeature_(bool create); /// allows for early return in parsing functions when certain sections should be ignored /// <=0 - parsing ON /// >0 - this number of tags have been entered that forbid parsing and need to be exited before parsing continues Int disable_parsing_; /// points to the last open &lt;feature&gt; tag (possibly a subordinate feature) Feature* current_feature_; /// Feature map pointer for writing FeatureMap* map_; /// Feature map pointer for reading const FeatureMap* cmap_; /// Options that can be set FeatureFileOptions options_; /// only parse until "count" tag is reached (used in loadSize()) bool size_only_; /// holds the putative size given in count Size expected_size_; /**@name temporary data structures to hold parsed data */ //@{ Param param_; ConvexHull2D::PointArrayType current_chull_; DPosition<2> hull_position_; //@} /// current dimension of the feature position, quality, or convex hull point UInt dim_; /// for downward compatibility, all tags in the old description must be ignored bool in_description_; /// level in Feature stack during parsing Int subordinate_feature_level_; /// Pointer to last read object as a MetaInfoInterface, or null. MetaInfoInterface* last_meta_; /// Temporary protein ProteinIdentification ProteinIdentification prot_id_; /// Temporary peptide ProteinIdentification PeptideIdentification pep_id_; /// Temporary protein hit ProteinHit prot_hit_; /// Temporary peptide hit PeptideHit pep_hit_; /// Map from protein id to accession std::map<String, String> proteinid_to_accession_; /// Map from search identifier concatenated with protein accession to id std::map<String, Size> accession_to_id_; /// Map from identification run identifier to file xs:id (for linking peptide identifications to the corresponding run) std::map<String, String> identifier_id_; /// Map from file xs:id to identification run identifier (for linking peptide identifications to the corresponding run) std::map<String, String> id_identifier_; /// Temporary search parameters file ProteinIdentification::SearchParameters search_param_; }; } // namespace Internal } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/FORMAT/HANDLERS/MzMLHandlerHelper.h
.h
6,151
168
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Hannes Roest $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/FORMAT/OPTIONS/PeakFileOptions.h> #include <OpenMS/FORMAT/MSNumpressCoder.h> #include <OpenMS/METADATA/MetaInfoDescription.h> #include <vector> namespace OpenMS { namespace Internal { /** * @brief Helper for mzML file format * * This class provides common structures and re-useable helper functions * for parsing the mzML format. These are mainly used by MzMLHandler and MzMLSpectrumDecoder. * **/ class OPENMS_DLLAPI MzMLHandlerHelper { /// Also display some warning message when appropriate (see XMLHandler) static void warning(int mode, const String & msg, UInt line = 0, UInt column = 0); public: /** * @brief Representation for binary data in mzML * * Represents data in the `<binaryDataArray>` tag * **/ struct BinaryData { // ordered by size (alignment) and cache hotness in 'decode' enum PRECISION{ PRE_NONE, ///< unknown precision PRE_32, ///< 32bit precision PRE_64 ///< 64bit precision } precision; enum DATA_TYPE{ DT_NONE, ///< unknown data type DT_FLOAT, ///< float data type DT_INT, ///< integer data type DT_STRING ///< string data type } data_type; MSNumpressCoder::NumpressCompression np_compression; ///< numpress options bool compression; ///< zlib compression double unit_multiplier; ///< multiplier for unit (e.g. 60 for minutes) String base64; ///< Raw data in base64 encoding Size size; ///< Raw data length std::vector<float> floats_32; std::vector<double> floats_64; std::vector<Int32> ints_32; std::vector<Int64> ints_64; std::vector<String> decoded_char; MetaInfoDescription meta; ///< Meta data description /// Constructor BinaryData() : precision(PRE_NONE), data_type(DT_NONE), np_compression(), compression(false), unit_multiplier(1.0), base64(), size(0), floats_32(), floats_64(), ints_32(), ints_64(), decoded_char(), meta() { } BinaryData(const BinaryData&) = default; // Copy constructor BinaryData(BinaryData&&) = default; // Move constructor BinaryData& operator=(const BinaryData&) & = default; // Copy assignment operator BinaryData& operator=(BinaryData&&) & = default; // Move assignment operator ~BinaryData() = default; // Destructor }; /** @brief Returns the appropriate compression term given the PeakFileOptions and the NumpressConfig */ static String getCompressionTerm_(const PeakFileOptions& opt, MSNumpressCoder::NumpressConfig np_compression, const String& indent = "", bool use_numpress = false); /** @brief Write the indexed mzML footer the appropriate compression term given the PeakFileOptions and the NumpressConfig @param[out] os The output stream @param[in] options The PeakFileOptions used for writing @param[in] spectra_offsets Binary offsets of &lt;spectrum&gt; tags @param[in] chromatograms_offsets Binary offsets of &lt;chromatogram&gt; tags */ static void writeFooter_(std::ostream& os, const PeakFileOptions& options, const std::vector< std::pair<std::string, Int64> > & spectra_offsets, const std::vector< std::pair<std::string, Int64> > & chromatograms_offsets); /** @brief Decode Base64 arrays and write into data_ array @param[in,out] data_ The input and output @param[in] skipXMLCheck whether to skip cleaning the Base64 arrays and remove whitespaces */ static void decodeBase64Arrays(std::vector<BinaryData> & data_, const bool skipXMLCheck = false); /** @brief Identify a data array from a list. Given a specific array name, find it in the provided list and return its index and precision. @param[in] data_ The list of data arrays @param[in] precision_64 Whether the identified array has 64 bit precision @param[in] index The index of the identified array @param[in] index_name The name of the array to be identified */ static void computeDataProperties_(const std::vector<BinaryData>& data_, bool& precision_64, SignedSize& index, const String& index_name); /** @brief Handle a given CV parameter found in a binaryDataArray tag Given a CV parameter, properly set the members of the last entry of data_, this will properly handle all terms describing precision, compression, name of the data and units. @param[in,out] data_ The list of data arrays, whose last entry will be changed @param[in] accession The CV accession @param[in] value The CV value @param[in] name The CV name @param[in] unit_accession The CV unit accession (if a unit tag is present) */ static bool handleBinaryDataArrayCVParam(std::vector<BinaryData>& data_, const String& accession, const String& value, const String& name, const String& unit_accession); }; } // namespace Internal } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/FORMAT/HANDLERS/MzMLSpectrumDecoder.h
.h
6,086
168
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Hannes Roest $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/config.h> #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/CONCEPT/Exception.h> #include <OpenMS/DATASTRUCTURES/String.h> #include <OpenMS/FORMAT/Base64.h> #include <OpenMS/INTERFACES/DataStructures.h> #include <OpenMS/METADATA/MetaInfoDescription.h> #include <string> #include <xercesc/dom/DOMNode.hpp> #include <OpenMS/FORMAT/HANDLERS/MzMLHandlerHelper.h> #include <OpenMS/KERNEL/MSSpectrum.h> #include <OpenMS/KERNEL/MSChromatogram.h> namespace OpenMS { /** @brief A class to decode input strings that contain an mzML chromatogram or spectrum tag. It uses xercesc to parse a string containing either a exactly one mzML spectrum or chromatogram (from \<chromatogram\> to \</chromatogram\> or \<spectrum\> to \</spectrum\> tag). It returns the data contained in the binaryDataArray for Intensity / mass-to-charge or Intensity / time. */ class OPENMS_DLLAPI MzMLSpectrumDecoder { protected: bool skip_xml_checks_; ///< Whether to skip some XML checks (e.g. removing whitespace inside base64 arrays) and be fast instead typedef Internal::MzMLHandlerHelper::BinaryData BinaryData; /** @brief decode binary data @todo Duplicated code from MzMLHandler, need to clean up see MzMLHandler::fillData_() */ OpenMS::Interfaces::SpectrumPtr decodeBinaryDataSpectrum_(std::vector<BinaryData> & data) const; void decodeBinaryDataMSSpectrum_(std::vector<BinaryData>& data, OpenMS::MSSpectrum& s) const; void decodeBinaryDataMSChrom_(std::vector<BinaryData>& data, OpenMS::MSChromatogram& c) const; /** @brief decode binary data @todo Duplicated code from MzMLHandler, need to clean up see MzMLHandler::fillData_() */ OpenMS::Interfaces::ChromatogramPtr decodeBinaryDataChrom_(std::vector<BinaryData> & data) const; /** @brief Convert a single DOMNode of type binaryDataArray to BinaryData object. This function will extract the data from a xerces DOMNode which points to a binaryDataArray tag and store the result as a BinaryData object. The result will be appended to the data vector. @param[in] indexListNode DOMNode of type binaryDataArray @param[in] data Binary data extracted from the string */ void handleBinaryDataArray_(xercesc::DOMNode* indexListNode, std::vector<BinaryData>& data); /** @brief Extract data from a string containing multiple \<binaryDataArray\> tags. This may be a string from \<spectrum\> to \</spectrum\> or \<chromatogram\> to \</chromatogram\> tag which contains one or more \<binaryDataArray\>. These XML tags need to conform to the mzML standard. The function will return a vector with all binary data found in the string in the binaryDataArray tags. @param[in] in Input string containing the raw XML @param[in] data Binary data extracted from the string @pre in must have \<spectrum\> or \<chromatogram\> as root element. */ std::string domParseString_(const std::string& in, std::vector<BinaryData>& data); public: explicit MzMLSpectrumDecoder(bool skip_xml_checks = false) : skip_xml_checks_(skip_xml_checks) {} /** @brief Extract data from a string which contains a full mzML spectrum. Extracts data from the input string which is expected to contain exactly one \<spectrum\> tag (from \<spectrum\> to \</spectrum\>). This function will extract the contained binaryDataArray and provide the result as Spectrum. @param[in] in Input string containing the raw XML @param[out] sptr Resulting spectrum @pre in must have \<spectrum\> as root element. */ void domParseSpectrum(const std::string& in, OpenMS::Interfaces::SpectrumPtr & sptr); /** @brief Extract data from a string which contains a full mzML spectrum. Extracts data from the input string which is expected to contain exactly one \<spectrum\> tag (from \<spectrum\> to \</spectrum\>). This function will extract the contained binaryDataArray and provide the result as Spectrum. @param[in] in Input string containing the raw XML @param[out] s Resulting spectrum @pre in must have \<spectrum\> as root element. */ void domParseSpectrum(const std::string& in, MSSpectrum& s); /** @brief Extract data from a string which contains a full mzML chromatogram. Extracts data from the input string which is expected to contain exactly one \<chromatogram\> tag (from \<chromatogram\> to \</chromatogram\>). This function will extract the contained binaryDataArray and provide the result as Chromatogram. @param[in] in Input string containing the raw XML @param[out] c Resulting chromatogram @pre in must have \<chromatogram\> as root element. */ void domParseChromatogram(const std::string& in, MSChromatogram& c); /** @brief Extract data from a string which contains a full mzML chromatogram. Extracts data from the input string which is expected to contain exactly one \<chromatogram\> tag (from \<chromatogram\> to \</chromatogram\>). This function will extract the contained binaryDataArray and provide the result as Chromatogram. @param[in] in Input string containing the raw XML @param[out] cptr Resulting chromatogram @pre in must have \<chromatogram\> as root element. */ void domParseChromatogram(const std::string& in, OpenMS::Interfaces::ChromatogramPtr & cptr); /// Whether to skip some XML checks (e.g. removing whitespace inside base64 arrays) and be fast instead void setSkipXMLChecks(bool only); }; }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/FORMAT/HANDLERS/MzIdentMLDOMHandler.h
.h
12,420
268
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Mathias Walzer $ // $Authors: Mathias Walzer$ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/CHEMISTRY/AASequence.h> #include <OpenMS/CONCEPT/UniqueIdGenerator.h> #include <OpenMS/FORMAT/ControlledVocabulary.h> #include <OpenMS/FORMAT/HANDLERS/XMLHandler.h> #include <OpenMS/KERNEL/StandardTypes.h> #include <OpenMS/METADATA/CVTermList.h> #include <OpenMS/METADATA/PeptideIdentification.h> #include <OpenMS/METADATA/PeptideIdentificationList.h> #include <OpenMS/METADATA/ProteinHit.h> #include <OpenMS/METADATA/ProteinIdentification.h> #include <xercesc/dom/DOM.hpp> #include <xercesc/dom/DOMDocument.hpp> #include <xercesc/dom/DOMDocumentType.hpp> #include <xercesc/dom/DOMElement.hpp> #include <xercesc/dom/DOMImplementation.hpp> #include <xercesc/dom/DOMImplementationLS.hpp> #include <xercesc/dom/DOMNodeIterator.hpp> #include <xercesc/dom/DOMNodeList.hpp> #include <xercesc/dom/DOMText.hpp> #include <xercesc/framework/LocalFileFormatTarget.hpp> #include <xercesc/framework/psvi/XSValue.hpp> #include <xercesc/parsers/XercesDOMParser.hpp> #include <xercesc/util/OutOfMemoryException.hpp> #include <xercesc/util/PlatformUtils.hpp> #include <xercesc/util/XMLString.hpp> #include <xercesc/util/XMLUni.hpp> #include <list> #include <map> #include <stdexcept> #include <string> #include <vector> // Error codes //enum { // ERROR_ARGS = 1, // ERROR_XERCES_INIT, // ERROR_PARSE, // ERROR_EMPTY_DOCUMENT //}; namespace OpenMS { class ProgressLogger; namespace Internal { /** @brief XML DOM handler for MzIdentMLFile In read-mode, this class will parse an MzIdentML XML file and append the input identifications to the provided PeptideIdentifications and ProteinIdentifications. @note Do not use this class. It is only needed in MzIdentMLFile. @note DOM and STREAM handler for MzIdentML have the same interface for legacy id structures. @note Only upon destruction of this class it can be guaranteed that all data has been appended to the appropriate containers. Do not try to access the data before that. */ class OPENMS_DLLAPI MzIdentMLDOMHandler { public: /**@name Constructors and destructor */ //@{ /// Constructor for a write-only handler for internal identification structures MzIdentMLDOMHandler(const std::vector<ProteinIdentification>& pro_id, const PeptideIdentificationList& pep_id, const String& version, const ProgressLogger& logger); /// Constructor for a read-only handler for internal identification structures MzIdentMLDOMHandler(std::vector<ProteinIdentification>& pro_id, PeptideIdentificationList& pep_id, const String& version, const ProgressLogger& logger); /// Destructor virtual ~MzIdentMLDOMHandler(); //@} /// Provides the functionality of reading a mzid with a handler object void readMzIdentMLFile(const std::string& mzid_file); /// Provides the functionality to write a mzid with a handler object void writeMzIdentMLFile(const std::string& mzid_file); protected: /// Progress logger const ProgressLogger& logger_; ///Controlled vocabulary (psi-ms from OpenMS/share/OpenMS/CV/psi-ms.obo) ControlledVocabulary cv_; ///Controlled vocabulary for modifications (unimod from OpenMS/share/OpenMS/CV/unimod.obo) ControlledVocabulary unimod_; ///Internal +w Identification Item for proteins std::vector<ProteinIdentification>* pro_id_ = nullptr; ///Internal +w Identification Item for peptides PeptideIdentificationList* pep_id_ = nullptr; ///Internal -w Identification Item for proteins const std::vector<ProteinIdentification>* cpro_id_ = nullptr; ///Internal -w Identification Item for peptides const PeptideIdentificationList* cpep_id_ = nullptr; ///Internal version keeping const String schema_version_; /// Looks up a child CV term of @p parent_accession with the name @p name. If no such term is found, an empty term is returned. ControlledVocabulary::CVTerm getChildWithName_(const String& parent_accession, const String& name) const; /**@name Helper functions to build the internal id structures from the DOM tree */ //@{ /// First: CVparams, Second: userParams (independent of each other) std::pair<CVTermList, std::map<String, DataValue> > parseParamGroup_(xercesc::DOMNodeList* paramGroup); CVTerm parseCvParam_(xercesc::DOMElement* param); std::pair<String, DataValue> parseUserParam_(xercesc::DOMElement* param); void parseAnalysisSoftwareList_(xercesc::DOMNodeList* analysisSoftwareElements); void parseDBSequenceElements_(xercesc::DOMNodeList* dbSequenceElements); void parsePeptideElements_(xercesc::DOMNodeList* peptideElements); //AASequence parsePeptideSiblings_(xercesc::DOMNodeList* peptideSiblings); AASequence parsePeptideSiblings_(xercesc::DOMElement* peptide); void parsePeptideEvidenceElements_(xercesc::DOMNodeList* peptideEvidenceElements); void parseSpectrumIdentificationElements_(xercesc::DOMNodeList* spectrumIdentificationElements); void parseSpectrumIdentificationProtocolElements_(xercesc::DOMNodeList* spectrumIdentificationProtocolElements); void parseInputElements_(xercesc::DOMNodeList* inputElements); void parseSpectrumIdentificationListElements_(xercesc::DOMNodeList* spectrumIdentificationListElements); void parseSpectrumIdentificationItemSetXLMS(std::set<String>::const_iterator set_it, std::multimap<String, int> xl_val_map, xercesc::DOMElement* element_res, const String& spectrumID); void parseSpectrumIdentificationItemElement_(xercesc::DOMElement* spectrumIdentificationItemElement, PeptideIdentification& spectrum_identification, String& spectrumIdentificationList_ref); void parseProteinDetectionHypothesisElement_(xercesc::DOMElement* proteinDetectionHypothesisElement, ProteinIdentification& protein_identification); void parseProteinAmbiguityGroupElement_(xercesc::DOMElement* proteinAmbiguityGroupElement, ProteinIdentification& protein_identification); void parseProteinDetectionListElements_(xercesc::DOMNodeList* proteinDetectionListElements); static ProteinIdentification::SearchParameters findSearchParameters_(std::pair<CVTermList, std::map<String, DataValue> > as_params); //@} /**@name Helper functions to build a DOM tree from the internal id structures*/ void buildCvList_(xercesc::DOMElement* cvElements); void buildAnalysisSoftwareList_(xercesc::DOMElement* analysisSoftwareElements); void buildSequenceCollection_(xercesc::DOMElement* sequenceCollectionElements); void buildAnalysisCollection_(xercesc::DOMElement* analysisCollectionElements); void buildAnalysisProtocolCollection_(xercesc::DOMElement* protocolElements); void buildInputDataCollection_(xercesc::DOMElement* inputElements); void buildEnclosedCV_(xercesc::DOMElement* parentElement, const String& encel, const String& acc, const String& name, const String& cvref); void buildAnalysisDataCollection_(xercesc::DOMElement* analysisElements); //@} private: MzIdentMLDOMHandler(); MzIdentMLDOMHandler(const MzIdentMLDOMHandler& rhs); MzIdentMLDOMHandler& operator=(const MzIdentMLDOMHandler& rhs); ///Struct to hold the used analysis software for that file struct AnalysisSoftware { String name; String version; }; ///Struct to hold the PeptideEvidence information struct PeptideEvidence { int start; int stop; char pre; char post; bool idec; }; ///Struct to hold the information from the DBSequence xml tag struct DBSequence { String sequence; String database_ref; String accession; CVTermList cvs; }; ///Struct to hold the information from the SpectrumIdentification xml tag struct SpectrumIdentification { String spectra_data_ref; String search_database_ref; String spectrum_identification_protocol_ref; String spectrum_identification_list_ref; }; ///Struct to hold the information from the ModificationParam xml tag struct ModificationParam { String fixed_mod; long double mass_delta; String residues; CVTermList modification_param_cvs; CVTermList specificities; }; ///Struct to hold the information from the SpectrumIdentificationProtocol xml tag struct SpectrumIdentificationProtocol { CVTerm searchtype; String enzyme; CVTermList parameter_cvs; std::map<String, DataValue> parameter_ups; // std::vector<ModificationParam> modification_parameter; CVTermList modification_parameter; long double precursor_tolerance; long double fragment_tolerance; CVTermList threshold_cvs; std::map<String, DataValue> threshold_ups; }; ///Struct to hold the information from the DatabaseInput xml tag struct DatabaseInput { String name; String location; String version; DateTime date; }; XMLCh* xml_root_tag_ptr_; XMLCh* xml_cvparam_tag_ptr_; XMLCh* xml_name_attr_ptr_; xercesc::XercesDOMParser mzid_parser_; std::unique_ptr<XMLHandler> xml_handler_ = nullptr; //from AnalysisSoftware String search_engine_; String search_engine_version_; //mapping from AnalysisSoftware std::map<String, AnalysisSoftware> as_map_; ///< mapping AnalysisSoftware id -> AnalysisSoftware //mapping from DataCollection Inputs std::map<String, String> sr_map_; ///< mapping sourcefile id -> sourcefile location std::map<String, String> sd_map_; ///< mapping spectradata id -> spectradata location std::map<String, DatabaseInput> db_map_; ///< mapping database id -> DatabaseInput //mapping from SpectrumIdentification - SpectrumIdentification will be the new IdentificationRuns std::map<String, SpectrumIdentification> si_map_; ///< mapping SpectrumIdentification id -> SpectrumIdentification (id refs) std::map<String, size_t> si_pro_map_; ///< mapping SpectrumIdentificationList id -> index to ProteinIdentification in pro_id_ //mapping from SpectrumIdentificationProtocol std::map<String, SpectrumIdentificationProtocol> sp_map_; ///< mapping SpectrumIdentificationProtocol id -> SpectrumIdentificationProtocol //mapping from SequenceCollection std::map<String, AASequence> pep_map_; ///< mapping Peptide id -> Sequence std::map<String, PeptideEvidence> pe_ev_map_; ///< mapping PeptideEvidence id -> PeptideEvidence std::map<String, String> pv_db_map_; ///< mapping PeptideEvidence id -> DBSequence id std::multimap<String, String> p_pv_map_; ///< mapping Peptide id -> PeptideEvidence id, multiple PeptideEvidences can have equivalent Peptides. std::map<String, DBSequence> db_sq_map_; ///< mapping DBSequence id -> Sequence std::list<std::list<String> > hit_pev_; ///< writing help only bool xl_ms_search_; ///< is true when reading a file containing Cross-Linking MS search results std::map<String, String> xl_id_donor_map_; ///< mapping Peptide id -> crosslink donor value //std::map<String, String> xl_id_acceptor_map_; ///< mapping Peptide id -> crosslink acceptor value std::map<String, String> xl_id_acceptor_map_; ///< mapping peptide id of acceptor peptide -> crosslink acceptor value std::map<String, SignedSize> xl_donor_pos_map_; ///< mapping donor value -> cross-link modification location std::map<String, SignedSize> xl_acceptor_pos_map_; ///< mapping acceptor value -> cross-link modification location std::map<String, double> xl_mass_map_; ///< mapping Peptide id -> cross-link mass std::map<String, String> xl_mod_map_; ///< mapping peptide id -> cross-linking reagent name }; } // namespace Internal } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/FORMAT/HANDLERS/TraMLHandler.h
.h
5,363
152
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Andreas Bertsch, Hannes Roest $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/FORMAT/HANDLERS/XMLHandler.h> #include <OpenMS/FORMAT/ControlledVocabulary.h> #include <OpenMS/ANALYSIS/TARGETED/TargetedExperiment.h> #include <OpenMS/METADATA/SourceFile.h> #include <OpenMS/METADATA/CVTermList.h> #include <OpenMS/CONCEPT/ProgressLogger.h> #include <iosfwd> #include <map> namespace OpenMS { namespace Internal { /** @brief XML handler for TraMLFile @note Do not use this class. It is only needed in TraMLFile. */ class OPENMS_DLLAPI TraMLHandler : public XMLHandler { public: TraMLHandler() = delete; TraMLHandler(const TraMLHandler & rhs) = delete; TraMLHandler & operator=(const TraMLHandler & rhs) = delete; typedef std::vector<ReactionMonitoringTransition::Product> ProductListType; typedef std::vector<ReactionMonitoringTransition::Configuration> ConfigurationListType; /**@name Constructors and destructor */ //@{ /// Constructor for a write-only handler TraMLHandler(const TargetedExperiment & exp, const String & filename, const String & version, const ProgressLogger & logger); /// Constructor for a read-only handler TraMLHandler(TargetedExperiment & exp, const String & filename, const String & version, const ProgressLogger & logger); /// Destructor ~TraMLHandler() override; //@} // Docu in base class void endElement(const XMLCh * const /*uri*/, const XMLCh * const /*local_name*/, const XMLCh * const qname) override; // Docu in base class void startElement(const XMLCh * const /*uri*/, const XMLCh * const /*local_name*/, const XMLCh * const qname, const xercesc::Attributes & attributes) override; // Docu in base class void characters(const XMLCh * const chars, const XMLSize_t length) override; //Docu in base class void writeTo(std::ostream & os) override; protected: /// Progress logger const ProgressLogger& logger_; ///Controlled vocabulary (psi-ms from OpenMS/share/OpenMS/CV/psi-ms.obo) ControlledVocabulary cv_; String tag_; TargetedExperiment* exp_; const TargetedExperiment* cexp_; TargetedExperiment::Publication actual_publication_; TargetedExperiment::Contact actual_contact_; TargetedExperiment::Instrument actual_instrument_; TargetedExperiment::Prediction actual_prediction_; Software actual_software_; TargetedExperiment::Protein actual_protein_; TargetedExperiment::RetentionTime actual_rt_; TargetedExperiment::Peptide actual_peptide_; TargetedExperiment::Compound actual_compound_; ReactionMonitoringTransition actual_transition_; IncludeExcludeTarget actual_target_; CVTermList actual_validation_; TargetedExperiment::Interpretation actual_interpretation_; std::vector<ReactionMonitoringTransition::Product> actual_intermediate_products_; ReactionMonitoringTransition::Product actual_product_; ReactionMonitoringTransition::Configuration actual_configuration_; SourceFile actual_sourcefile_; /// Handles CV terms void handleCVParam_(const String & parent_parent_tag, const String & parent_tag, const CVTerm & cv_term); /// Handles user terms void handleUserParam_(const String & parent_parent_tag, const String & parent_tag, const String & name, const String & type, const String & value); /// Writes user terms void writeUserParam_(std::ostream & os, const MetaInfoInterface & meta, UInt indent) const; void writeUserParams_(std::ostream & os, const std::vector<MetaInfoInterface> & meta, UInt indent) const; void writeCVParams_(std::ostream & os, const CVTermList & cv_terms, UInt indent) const; void writeCVParams_(std::ostream & os, const CVTermListInterface & cv_terms, UInt indent) const; void writeCVList_(std::ostream & os, const std::map<String, std::vector<CVTerm>> & cv_terms, UInt indent) const; // subfunctions of write void writeTarget_(std::ostream & os, const std::vector<IncludeExcludeTarget>::const_iterator & it) const; void writeRetentionTime_(std::ostream& os, const TargetedExperimentHelper::RetentionTime& rt) const; void writeProduct_(std::ostream & os, const std::vector<ReactionMonitoringTransition::Product>::const_iterator & prod_it) const; void writeConfiguration_(std::ostream & os, const std::vector<ReactionMonitoringTransition::Configuration>::const_iterator & cit) const; /// Looks up a child CV term of @p parent_accession with the name @p name. If no such term is found, an empty term is returned. ControlledVocabulary::CVTerm getChildWithName_(const String & parent_accession, const String & name) const; /// Helper method that writes a source file //void writeSourceFile_(std::ostream& os, const String& id, const SourceFile& software); }; } // namespace Internal } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/FORMAT/HANDLERS/MzMLSqliteSwathHandler.h
.h
2,237
89
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Hannes Roest // -------------------------------------------------------------------------- #pragma once #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/DATASTRUCTURES/String.h> #include <OpenMS/OPENSWATHALGO/DATAACCESS/SwathMap.h> // forward declarations struct sqlite3; namespace OpenMS { namespace Internal { /** @brief Sqlite handler for SWATH data sets This class represents a single sqMass file acquired in SWATH / DIA mode and provides some useful access to the indices of the individual SWATH windows. */ class OPENMS_DLLAPI MzMLSqliteSwathHandler { public: /** @brief Constructor @param[in] filename The sqMass filename */ MzMLSqliteSwathHandler(const String& filename) : filename_(filename) {} /** @brief Read SWATH windows boundaries from file @return A vector populated with SwathMap, with the following attributes initialized: center, lower and upper */ std::vector<OpenSwath::SwathMap> readSwathWindows(); /** @brief Read indices of MS1 spectra from file @return A list of spectral indices for the MS1 spectra */ std::vector<int> readMS1Spectra(); /** @brief Read indices of spectra belonging to specified SWATH window from file @param[in] swath_map Contains the upper/lower boundaries of the SWATH window @return A list of spectral indices for the provided SWATH window */ std::vector<int> readSpectraForWindow(const OpenSwath::SwathMap & swath_map); protected: String filename_; /* * These are spectra and chromatogram ids that are global for a specific * database file. Keeping track of them allows us to append spectra and * chromatograms multiple times to a database. */ Int spec_id_; Int chrom_id_; }; } // namespace Internal } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/FORMAT/HANDLERS/ParamXMLHandler.h
.h
1,962
70
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Marc Sturm, Stephan Aiche $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/DATASTRUCTURES/Param.h> #include <OpenMS/FORMAT/HANDLERS/XMLHandler.h> #include <vector> #include <map> namespace OpenMS { namespace Internal { /** @brief XML Handler for Param files. */ class OPENMS_DLLAPI ParamXMLHandler : public XMLHandler { public: /// Default constructor ParamXMLHandler(Param& param, const String& filename, const String& version); /// Destructor ~ParamXMLHandler() override; // Docu in base class void endElement(const XMLCh* const uri, const XMLCh* const local_name, const XMLCh* const qname) override; // Docu in base class void startElement(const XMLCh* const uri, const XMLCh* const local_name, const XMLCh* const qname, const xercesc::Attributes& attributes) override; protected: /// The current absolute path (concatenation of nodes_ with <i>:</i> in between) String path_; /// Reference to the Param object to fill Param& param_; /// Map of node descriptions (they are set at the end of parsing) std::map<String, String> descriptions_; ///Temporary data for parsing of item lists struct { String name; String type; std::vector<std::string> stringlist; IntList intlist; DoubleList doublelist; std::vector<std::string> tags; String description; String restrictions; Int restrictions_index; } list_; private: /// Not implemented ParamXMLHandler(); }; } // namespace Internal } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/FORMAT/HANDLERS/AcqusHandler.h
.h
1,927
73
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Guillaume Belz $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/DATASTRUCTURES/String.h> #include <map> namespace OpenMS { namespace Internal { /** @brief Read-only acqus File handler for XMass Analysis. acqus File contains meta data about calibration (conversion for time to mz ratio), instrument specification and acquisition method. @note Do not use this class directly. It is only needed for XMassFile. */ class OPENMS_DLLAPI AcqusHandler { public: /** @brief Constructor with filename. Open acqus File as stream and import params. @param[in] filename to acqus File. @exception Exception::FileNotFound is thrown if the file could not be opened. @exception Exception::ConversionError is thrown if error conversion from String to calibration param. */ explicit AcqusHandler(const String & filename); /// Destructor virtual ~AcqusHandler(); /// Conversion from index to MZ ratio using internal calibration params double getPosition(Size index) const; /// Read param as string String getParam(const String & param); /// Get size of spectrum Size getSize() const; private: /// Private default constructor AcqusHandler(); /// Map for params saving std::map<String, String> params_; /**@name Internal params for calibration */ //@{ double dw_; Size delay_; double ml1_; double ml2_; double ml3_; Size td_; //@} }; } // namespace Internal } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/FORMAT/DATAACCESS/MSDataChainingConsumer.h
.h
3,769
121
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Hannes Roest $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/INTERFACES/IMSDataConsumer.h> #include <vector> #include <memory> namespace OpenMS { /** @brief Consumer class that passes all consumed data through a set of operations This consumer allows to chain multiple data consumers and applying them in a pre-specified order. This can be useful if a certain operation on a dataset needs to be performed but some pre-processing (data reduction etc.) or post-processing (writing to disk, caching on disk). The different processing steps can be added to the chaining consumer (in the correct order) without knowledge of the specific pre/post processing steps. Usage: @code MSDataTransformingConsumer * transforming_consumer_first = new MSDataTransformingConsumer(); // apply some transformation MSDataTransformingConsumer * transforming_consumer_second = new MSDataTransformingConsumer(); // apply second transformation MSDataWritingConsumer * writing_consumer = new MSDataWritingConsumer(outfile); // writing to disk std::vector<Interfaces::IMSDataConsumer *> consumer_list; consumer_list.push_back(transforming_consumer_first); consumer_list.push_back(transforming_consumer_second); consumer_list.push_back(writing_consumer); MSDataChainingConsumer * chaining_consumer = new MSDataChainingConsumer(consumer_list); // now chaining_consumer can be passed to a function expecting a IMSDataConsumer interface @endcode */ class OPENMS_DLLAPI MSDataChainingConsumer : public Interfaces::IMSDataConsumer { std::vector<Interfaces::IMSDataConsumer *> consumers_; public: /** * @brief Default Constructor * */ MSDataChainingConsumer(); /** * @brief Constructor * * Pass a list of consumers that should be called sequentially * * @note By default, this does not transfers ownership - it is the callers * responsibility to delete the pointer to consumer afterwards. * */ MSDataChainingConsumer(std::vector<Interfaces::IMSDataConsumer *> consumers); /** * @brief Destructor * * Does nothing. Does not destroy underlying consumers, therefore is the * responsibility of the caller to destroy all consumers. * */ ~MSDataChainingConsumer() override; /** * @brief Append a consumer to the chain of consumers to be executed * * @note This does not transfer ownership - it is the callers * responsibility to delete the pointer to consumer afterwards. * */ void appendConsumer(Interfaces::IMSDataConsumer * consumer); /** * @brief Set experimental settings for all consumers * * Will set the experimental settings for all chained consumers * */ void setExperimentalSettings(const ExperimentalSettings & settings) override; /** * @brief Set expected size for all consumers * * Will set the expected size for all chained consumers * */ void setExpectedSize(Size s_size, Size c_size) override; /** * @brief Call all consumers in the specified order for the given spectrum * */ void consumeSpectrum(SpectrumType & s) override; /** * @brief Call all consumers in the specified order for the given chromatogram * */ void consumeChromatogram(ChromatogramType & c) override; }; } //end namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/FORMAT/DATAACCESS/MSDataWritingConsumer.h
.h
8,490
252
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Hannes Roest $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/INTERFACES/IMSDataConsumer.h> #include <OpenMS/FORMAT/HANDLERS/MzMLHandler.h> #include <OpenMS/CONCEPT/ProgressLogger.h> #include <vector> #include <string> #include <fstream> #include <memory> namespace OpenMS { /** @brief Consumer class that writes MS data to disk using the mzML format. The MSDataWritingConsumer is able to write spectra and chromatograms to disk on the fly (as soon as they are consumed). This class is abstract and allows the derived class to define how spectra and chromatograms are processed before being written to disk. If you are looking for class that simply takes spectra and chromatograms and writes them to disk, please use the PlainMSDataWritingConsumer. Example usage: @code MSDataWritingConsumer * consumer = new MSDataWritingConsumer(outfile); // some implementation consumer->setExpectedSize(specsize, chromsize); consumer->setExperimentalSettings(exp_settings); consumer->addDataProcessing(dp); // optional, will be added to all spectra and chromatograms [...] // multiple times ... consumer->consumeSpectrum(spec); consumer->consumeChromatogram(chrom); [...] delete consumer; @endcode @note The first usage of consumeChromatogram or consumeSpectrum will start writing of the mzML header to disk (and the first element). @note Currently it is not possible to add spectra after having already added chromatograms since this could lead to a situation with multiple @a spectrumList tags appear in an mzML file. @note The expected size will @a not be enforced but it will lead to an inconsistent mzML if the count attribute of spectrumList or chromatogramList is incorrect. */ class OPENMS_DLLAPI MSDataWritingConsumer : public Internal::MzMLHandler, public Interfaces::IMSDataConsumer { public: typedef PeakMap MapType; typedef MapType::SpectrumType SpectrumType; typedef MapType::ChromatogramType ChromatogramType; /** @brief Constructor @param[out] filename Filename for the output mzML */ explicit MSDataWritingConsumer(const String& filename); /// Destructor ~MSDataWritingConsumer() override; /// @name IMSDataConsumer interface //@{ /** @brief Set experimental settings for the whole file @param[in] exp Experimental settings to be used for this file (from this and the first spectrum/chromatogram, the class will deduce most of the header of the mzML file) */ void setExperimentalSettings(const ExperimentalSettings& exp) override; /** @brief Set expected size of spectra and chromatograms to be written. These numbers will be written in the spectrumList and chromatogramList tag in the mzML file. Therefore, these will contain wrong numbers if the expected size is not set correctly. @param[in] expectedSpectra Number of spectra expected @param[in] expectedChromatograms Number of chromatograms expected */ void setExpectedSize(Size expectedSpectra, Size expectedChromatograms) override; /** @brief Consume a spectrum The spectrum will be processed using the processSpectrum_ method of the current implementation and then written to the mzML file. @param[out] s The spectrum to be written to mzML */ void consumeSpectrum(SpectrumType & s) override; /** @brief Consume a chromatogram The chromatogram will be processed using the processChromatogram_ method of the current implementation and then written to the mzML file. @param[out] c The chromatogram to be written to mzML */ void consumeChromatogram(ChromatogramType & c) override; //@} /** @brief Optionally add a data processing method to each chromatogram and spectrum. The provided DataProcessing object will be added to each chromatogram and spectrum written to to the mzML file. @param[in] d The DataProcessing object to be added */ virtual void addDataProcessing(DataProcessing d); /** @brief Return the number of spectra written. */ virtual Size getNrSpectraWritten(); /** @brief Return the number of chromatograms written. */ virtual Size getNrChromatogramsWritten(); private: /// @name Data Processing using the template method pattern //@{ /** @brief Process a spectrum before storing to disk Redefine this function to determine spectra processing before writing to disk. */ virtual void processSpectrum_(SpectrumType & s) = 0; /** @brief Process a chromatogram before storing to disk Redefine this function to determine chromatogram processing before writing to disk. */ virtual void processChromatogram_(ChromatogramType & c) = 0; //@} /** @brief Cleanup function called by the destructor. Will write the last tags to the file and close the file stream. */ virtual void doCleanup_(); protected: /// File stream (to write mzML) std::ofstream ofs_; /// Stores whether we have already started writing any data bool started_writing_; /// Stores whether we are currently writing spectra bool writing_spectra_; /// Stores whether we are currently writing chromatograms bool writing_chromatograms_; /// Number of spectra written Size spectra_written_; /// Number of chromatograms written Size chromatograms_written_; /// Number of spectra expected Size spectra_expected_; /// Number of chromatograms expected Size chromatograms_expected_; /// Whether to add dataprocessing term to the data before writing bool add_dataprocessing_; /// Validator that knows about CV terms Internal::MzMLValidator * validator_; /// Experimental settings to use for the whole file ExperimentalSettings settings_; /// Vector of data processing objects -> will be filled by writeHeader_ std::vector<std::vector< ConstDataProcessingPtr > > dps_; /// The dataprocessing to be added to each spectrum/chromatogram DataProcessingPtr additional_dataprocessing_; }; /** @brief Consumer class that writes MS data to disk using the mzML format. A very simple implementation of MSDataWritingConsumer, not offering the ability to modify the spectra before writing. This is probably the class you want if you want to write mzML files to disk by providing spectra and chromatograms sequentially. */ class OPENMS_DLLAPI PlainMSDataWritingConsumer : public MSDataWritingConsumer { void processSpectrum_(MapType::SpectrumType & /* s */) override {} void processChromatogram_(MapType::ChromatogramType & /* c */) override {} public: explicit PlainMSDataWritingConsumer(String filename) : MSDataWritingConsumer(filename) {} }; /** @brief Consumer class that perform no operation. This is sometimes necessary to fulfill the requirement of passing an valid MSDataWritingConsumer object or pointer but no operation is required. */ class OPENMS_DLLAPI NoopMSDataWritingConsumer : public MSDataWritingConsumer { public: explicit NoopMSDataWritingConsumer(String filename) : MSDataWritingConsumer(filename) {} void setExperimentalSettings(const ExperimentalSettings& /* exp */) override {} void consumeSpectrum(SpectrumType & /* s */) override {} void consumeChromatogram(ChromatogramType & /* c */) override {} private: void doCleanup_() override {} void processSpectrum_(MapType::SpectrumType & /* s */) override {} void processChromatogram_(MapType::ChromatogramType & /* c */) override {} }; } //end namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/FORMAT/DATAACCESS/SiriusFragmentAnnotation.h
.h
6,592
145
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Oliver Alka $ // $Authors: Oliver Alka $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/FORMAT/CsvFile.h> #include <OpenMS/KERNEL/MSSpectrum.h> namespace OpenMS { class OPENMS_DLLAPI SiriusFragmentAnnotation { public: /** @brief SiriusTargetDecoySpectra holds the target and/or decoy information for one entry (subdirectory from SIRIUS) */ class SiriusTargetDecoySpectra { public: MSSpectrum target; MSSpectrum decoy; SiriusTargetDecoySpectra() = default; SiriusTargetDecoySpectra(MSSpectrum target_spectrum, MSSpectrum decoy_spectrum) : target(std::move(target_spectrum)), decoy(std::move(decoy_spectrum)) {} }; /** @brief extractAndResolveSiriusAnnotations Extract and resolves SIRIUS target and/or decoy annotation for mapping native_id to MSSpectrum. @return map native_id to annotated MSSpectrum (target or decoy) If there are multiple identifications for a feature with the same MS2 spectras (concatenated native ids) the identification with the higher SIRIUS score is chosen (currently based on the explained peak intensities). @param[in] sirius_workspace_subdirs Vector of paths to SIRIUS subdirectories. @param[in] score_threshold Only use spectra over a certain score threshold (0-1) @param[in] use_exact_mass Option to use exact mass instead of peak mz in MSSpectrum. @param[out] decoy_generation Extract decoy spectra from SIRIUS subdirectories. */ static std::vector<SiriusTargetDecoySpectra> extractAndResolveSiriusAnnotations(const std::vector<String>& sirius_workspace_subdirs, double score_threshold, bool use_exact_mass, bool decoy_generation); /** @brief extractSiriusFragmentAnnotationMapping Extract concatenated native ids and concatenated m_ids (unique identifier) from (./spectrum.ms) and annotations from spectra/decoy subfolder If @p decoy is true, uses fragment annotation (./spectra/1_sumformula.tsv) from SIRIUS output (per compound) else uses fragment annotation (./decoy/1_sumformula.tsv) from SIRIUS/PASSATUTTO output (per compound). @return annotated decoy MSSpectrum with associated native id MetaValues: peak_mz annotated_sumformula annotated_adduct The data is stored in a MSSpectrum, which contains a Peak1D (mz or exact mass [depending on @p use_exact_mass], int), a FloatDataArray for targets only (exact mass or mz [depending on @p use_exact_mass]), a StringDataArray (explanation), and a StringDataArray (ionization). <table> <caption> MSSpectrum </caption> <tr><th> Peak1D <th> <th> [FloatDataArray] <th> StringDataArray <th> StringDataArray <tr><td> mz <td> intensity <td> [exact_mass] <td> explanation <td> ionization <tr><td> 56.050855 <td> 20794.85 <td> [56.049476] <td> C3H5N <td> [M + H]+ </table> @param[in] path_to_sirius_workspace Path to SIRIUS workspace. @param[in] max_rank Up to which rank to extract annotations maximally. Auto-stops at last candidate. @param[out] decoy Extract annotations for decoys? Or else targets. Run twice if you want both @param[in] use_exact_mass Option to use exact mass instead of peak mz in MSSpectrum. */ static std::vector<MSSpectrum> extractAnnotationsFromSiriusFile(const String& path_to_sirius_workspace, Size max_rank = 1, bool decoy = false, bool use_exact_mass = false); /** @brief Extract columnname and index based in SIRIUS entries */ static std::map< std::string, Size > extract_columnname_to_columnindex(const CsvFile& csvfile); protected: /** @brief extractConcatNativeIDsFromSiriusMS Extract concatenated native id from SIRIUS output (./spectrum.ms) and concatenates them. @return String native id of current SIRIUS compound @param[in] path_to_sirius_workspace Path to SIRIUS workspace. */ static OpenMS::String extractConcatNativeIDsFromSiriusMS_(const OpenMS::String& path_to_sirius_workspace); /** @brief extractConcatMIDsFromSiriusMS Extract m_ids from SIRIUS output (./spectrum.ms) and concatenates them. M_id is the native id + an index, which is incremented based on the number of possible identifications (accurate mass search). @return String m_id of current SIRIUS compound @param[in] path_to_sirius_workspace Path to SIRIUS workspace. */ static OpenMS::String extractConcatMIDsFromSiriusMS_(const String& path_to_sirius_workspace); /** @brief extractConcatMIDsFromSiriusMS Extract fid (i.e. original OpenMS feature ID) from SIRIUS output (./spectrum.ms). @return String fid of current SIRIUS workspace @param[in] path_to_sirius_workspace Path to SIRIUS workspace. */ static OpenMS::String extractFeatureIDFromSiriusMS_(const String& path_to_sirius_workspace); /** @brief extractCompoundRankingAndFilename Extract compound ranking and filename (./formula_candidates.tsv). @return a map with specified rank and filename (formula_adduct.tsv) (based on the annotation) @param[in] path_to_sirius_workspace Path to SIRIUS workspace. */ static std::map< Size, String > extractCompoundRankingAndFilename_(const String& path_to_sirius_workspace); /** @brief extractCompoundRankingAndFilename Extract compound ranking and score (./formula_candidates.tsv). @return a map with specified rank and score (explainedIntensity) (based on the annotation) @param[in] path_to_sirius_workspace Path to SIRIUS workspace. */ static std::map< Size, double > extractCompoundRankingAndScore_(const String& path_to_sirius_workspace); }; } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/FORMAT/DATAACCESS/MSDataTransformingConsumer.h
.h
3,480
91
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Hannes Roest, Chris Bielow $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/INTERFACES/IMSDataConsumer.h> #include <OpenMS/KERNEL/StandardTypes.h> #include <OpenMS/KERNEL/MSSpectrum.h> #include <OpenMS/KERNEL/MSChromatogram.h> #include <OpenMS/KERNEL/Peak1D.h> #include <OpenMS/KERNEL/ChromatogramPeak.h> namespace OpenMS { /** @brief Transforming consumer of MS data Is able to work on spectrum/chromatogram on the fly while it is read using a lambda function provided by the user. The lambda can transform the spectrum/chromatogram in-place or just extract some information and store it in locally captured variables. Just make sure the captured variables are still in scope when this consumer is used. */ class OPENMS_DLLAPI MSDataTransformingConsumer : public Interfaces::IMSDataConsumer { public: /** @brief Constructor */ MSDataTransformingConsumer(); /// Default destructor ~MSDataTransformingConsumer() override; /// ignored void setExpectedSize(Size /* expectedSpectra */, Size /* expectedChromatograms */) override; void consumeSpectrum(SpectrumType& s) override; /** @brief Sets the lambda function to be called for every spectrum which is passed to this interface The lambda can contain locally captured variables, which allow to change some state. Make sure that the captured variables are still in scope (i.e. not destroyed at the point of calling the lambda). Pass a nullptr if the spectrum should be left unchanged. */ virtual void setSpectraProcessingFunc( std::function<void (SpectrumType&)> f_spec ); void consumeChromatogram(ChromatogramType& c) override; /** @brief Sets the lambda function to be called for every chromatogram which is passed to this interface The lambda can contain locally captured variables, which allow to change some state. Make sure that the captured variables are still in scope (i.e. not destroyed at the point of calling the lambda). Pass a nullptr if the chromatogram should be left unchanged. */ virtual void setChromatogramProcessingFunc( std::function<void (ChromatogramType&)> f_chrom ); /** @brief Sets the lambda function to be called when setExperimentalSettings is called via this interface The lambda can contain locally captured variables, which allow to change some state. Make sure that the captured variables are still in scope (i.e. not destroyed at the point of calling the lambda). Pass a nullptr if nothing should happen (default). */ virtual void setExperimentalSettingsFunc( std::function<void (const OpenMS::ExperimentalSettings&)> f_exp_settings ); /// ignored void setExperimentalSettings(const OpenMS::ExperimentalSettings&) override; protected: std::function<void (SpectrumType&)> lambda_spec_; std::function<void (ChromatogramType&)> lambda_chrom_; std::function<void (const OpenMS::ExperimentalSettings&)> lambda_exp_settings_; }; } //end namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/FORMAT/DATAACCESS/MSDataCachedConsumer.h
.h
2,523
88
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Hannes Roest $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/INTERFACES/IMSDataConsumer.h> #include <OpenMS/KERNEL/StandardTypes.h> #include <OpenMS/FORMAT/HANDLERS/CachedMzMLHandler.h> namespace OpenMS { /** @brief Transforming and cached writing consumer of MS data Is able to transform a spectrum on the fly while it is read using a function pointer that can be set on the object. The spectra is then cached to disk using the functions provided in CachedMzMLHandler. */ class OPENMS_DLLAPI MSDataCachedConsumer : public Internal::CachedMzMLHandler, public Interfaces::IMSDataConsumer { typedef MSSpectrum SpectrumType; typedef MSChromatogram ChromatogramType; public: /** @brief Constructor Opens the output file and writes the header. @param[out] filename The output file name to which data is written @param[in] clearData Whether to clear the spectral and chromatogram data after writing (only keep meta-data) @note Clearing data from spectra and chromatograms also clears float and integer data arrays associated with the structure as these are written to disk as well. */ MSDataCachedConsumer(const String& filename, bool clearData=true); /** @brief Destructor Closes the output file and writes the footer. */ ~MSDataCachedConsumer() override; /** @brief Write a spectrum to the output file @note May delete data from spectrum (if clearData is set) */ void consumeSpectrum(SpectrumType & s) override; /** @brief Write a chromatogram to the output file @note May delete data from chromatogram (if clearData is set) */ void consumeChromatogram(ChromatogramType & c) override; void setExpectedSize(Size /* expectedSpectra */, Size /* expectedChromatograms */) override {;} void setExperimentalSettings(const ExperimentalSettings& /* exp */) override {;} protected: std::ofstream ofs_; bool clearData_; Size spectra_written_; Size chromatograms_written_; }; } //end namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/FORMAT/DATAACCESS/MSDataAggregatingConsumer.h
.h
2,021
76
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Hannes Roest $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/INTERFACES/IMSDataConsumer.h> #include <OpenMS/KERNEL/StandardTypes.h> #include <OpenMS/KERNEL/MSSpectrum.h> #include <OpenMS/KERNEL/MSChromatogram.h> namespace OpenMS { /** @brief Aggregates spectra by retention time This consumer will merge spectra passed to it that have the same retention time and will then pass them to the next consumer (see Constructor). Spectra are aggregated using SpectrumAddition::addUpSpectra() which merges the spectra. */ class OPENMS_DLLAPI MSDataAggregatingConsumer : public Interfaces::IMSDataConsumer { Interfaces::IMSDataConsumer* next_consumer_; double previous_rt_; bool rt_initialized_; SpectrumType s_tmp; std::vector<SpectrumType> s_list; public: /** @brief Constructor @note This does not transfer ownership of the consumer */ MSDataAggregatingConsumer(Interfaces::IMSDataConsumer* next_consumer) : next_consumer_(next_consumer), previous_rt_(0.0), rt_initialized_(false) {} /** @brief Constructor Flushes data to next consumer @note It is essential to not delete the underlying next_consumer before deleting this object, otherwise we risk a memory error */ ~MSDataAggregatingConsumer() override; void setExpectedSize(Size, Size) override {} void consumeSpectrum(SpectrumType& s) override; void consumeChromatogram(ChromatogramType& c) override; void setExperimentalSettings(const OpenMS::ExperimentalSettings&) override {} }; } //end namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/FORMAT/DATAACCESS/MSDataStoringConsumer.h
.h
1,198
50
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Hannes Roest $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/INTERFACES/IMSDataConsumer.h> #include <OpenMS/KERNEL/StandardTypes.h> #include <OpenMS/KERNEL/MSExperiment.h> namespace OpenMS { /** @brief Consumer class that simply stores the data. This class is able to keep spectra and chromatograms passed to it in memory and the data can be accessed through getData() */ class OPENMS_DLLAPI MSDataStoringConsumer : public Interfaces::IMSDataConsumer { private: PeakMap exp_; public: MSDataStoringConsumer(); void setExperimentalSettings(const ExperimentalSettings & settings) override; void setExpectedSize(Size s_size, Size c_size) override; void consumeSpectrum(SpectrumType& s) override; void consumeChromatogram(ChromatogramType& c) override; const PeakMap& getData() const; }; } //end namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/FORMAT/DATAACCESS/NoopMSDataConsumer.h
.h
1,054
38
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Hannes Roest $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/INTERFACES/IMSDataConsumer.h> namespace OpenMS { /** @brief Consumer class that performs no operation. This is sometimes necessary to fulfill the requirement of passing an valid Interfaces::IMSDataConsumer object or pointer but no operation is required. */ class OPENMS_DLLAPI NoopMSDataConsumer : public Interfaces::IMSDataConsumer { public: NoopMSDataConsumer() {} void setExperimentalSettings(const ExperimentalSettings &) override {} void setExpectedSize(Size, Size) override {} void consumeSpectrum(SpectrumType &) override {} void consumeChromatogram(ChromatogramType &) override {} }; } //end namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/FORMAT/DATAACCESS/SwathFileConsumer.h
.h
21,667
647
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Hannes Roest $ // -------------------------------------------------------------------------- #pragma once // Datastructures #include <OpenMS/OPENSWATHALGO/DATAACCESS/DataStructures.h> #include <OpenMS/OPENSWATHALGO/DATAACCESS/SwathMap.h> // Consumers #include <OpenMS/FORMAT/DATAACCESS/MSDataCachedConsumer.h> #include <OpenMS/FORMAT/DATAACCESS/MSDataWritingConsumer.h> #include <OpenMS/FORMAT/DATAACCESS/MSDataTransformingConsumer.h> #include <OpenMS/FORMAT/FileHandler.h> // Helpers #include <OpenMS/ANALYSIS/OPENSWATH/OpenSwathHelper.h> #include <OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/SimpleOpenMSSpectraAccessFactory.h> #include <OpenMS/CONCEPT/LogStream.h> #include <OpenMS/INTERFACES/IMSDataConsumer.h> #include <OpenMS/FORMAT/HANDLERS/CachedMzMLHandler.h> #include <OpenMS/KERNEL/StandardTypes.h> #ifdef _OPENMP #include <omp.h> #endif namespace OpenMS { /** * @brief Abstract base class which can consume spectra coming from SWATH experiment stored in a single file. * * The class consumes spectra which are coming from a complete SWATH * experiment. It will group MS2 spectra by their precursor m/z, assuming * that they correspond to the same SWATH window. For example, the spectra * could be arranged in the following fashion: * * - MS1 Spectrum (no precursor) * - MS2 Spectrum (precursor = [400,425]) * - MS2 Spectrum (precursor = [425,450]) * - [...] * - MS2 Spectrum (precursor = [1175,1200]) * - MS1 Spectrum (no precursor) * - MS2 Spectrum (precursor = [400,425]) * - MS2 Spectrum (precursor = [425,450]) * - [...] * * Base classes are expected to implement functions consuming a spectrum coming * from a specific SWATH or an MS1 spectrum and a final function * ensureMapsAreFilled_ after which the swath_maps_ vector needs to contain * valid pointers to MSExperiment. * * In addition it is possible to provide the swath boundaries and the read in * spectra will be matched by their precursor m/z to the "center" attribute * of the provided Swath maps. * * Usage: * * @code * FullSwathFileConsumer * dataConsumer; * // assign dataConsumer to an implementation of FullSwathFileConsumer * MzMLFile().transform(file, dataConsumer); * dataConsumer->retrieveSwathMaps(maps); * @endcode * */ class OPENMS_DLLAPI FullSwathFileConsumer : public Interfaces::IMSDataConsumer { public: typedef PeakMap MapType; typedef MapType::SpectrumType SpectrumType; typedef MapType::ChromatogramType ChromatogramType; FullSwathFileConsumer() : ms1_map_(), // initialize to null consuming_possible_(true), use_external_boundaries_(false), correct_window_counter_(0) { use_external_boundaries_ = !swath_map_boundaries_.empty(); } /** * @brief Constructor * * @param[in] swath_boundaries A vector of SwathMaps of which only the center, * lower and upper attributes will be used to infer the expected Swath maps. * */ FullSwathFileConsumer(std::vector<OpenSwath::SwathMap> swath_boundaries) : swath_map_boundaries_(swath_boundaries), ms1_map_(), // initialize to null consuming_possible_(true), use_external_boundaries_(false), correct_window_counter_(0) { use_external_boundaries_ = !swath_map_boundaries_.empty(); } ~FullSwathFileConsumer() override {} void setExpectedSize(Size, Size) override {} void setExperimentalSettings(const ExperimentalSettings& exp) override {settings_ = exp; } /** * @brief Populate the vector of swath maps after consuming all spectra. * * Will populate the input vector with SwathMap objects which correspond to * the MS1 map (if present) and the MS2 maps (SWATH maps). This should be * called after all spectra are consumed. * * @note It is not possible to consume any more spectra after calling this * function (it contains finalization code and may close file streams). * */ void retrieveSwathMaps(std::vector<OpenSwath::SwathMap>& maps) { consuming_possible_ = false; // make consumption of further spectra / chromatograms impossible ensureMapsAreFilled_(); if (ms1_map_) { OpenSwath::SwathMap map; map.sptr = SimpleOpenMSSpectraFactory::getSpectrumAccessOpenMSPtr(ms1_map_); map.lower = -1; map.upper = -1; map.center = -1; map.imLower = -1; map.imUpper = -1; map.ms1 = true; maps.push_back(map); } // Print warning if the lower/upper window could not be determined and we // required manual determination of the boundaries. if (!use_external_boundaries_ && correct_window_counter_ != swath_maps_.size()) { std::cout << "WARNING: Could not correctly read the upper/lower limits of the SWATH windows from your input file. Read " << correct_window_counter_ << " correct (non-zero) window limits (expected " << swath_maps_.size() << " windows)." << std::endl; } size_t nonempty_maps = 0; for (Size i = 0; i < swath_maps_.size(); i++) { OpenSwath::SwathMap map; map.sptr = SimpleOpenMSSpectraFactory::getSpectrumAccessOpenMSPtr(swath_maps_[i]); map.lower = swath_map_boundaries_[i].lower; map.upper = swath_map_boundaries_[i].upper; map.center = swath_map_boundaries_[i].center; map.imLower = swath_map_boundaries_[i].imLower; map.imUpper = swath_map_boundaries_[i].imUpper; map.ms1 = false; maps.push_back(map); if (map.sptr->getNrSpectra() > 0) {nonempty_maps++;} } if (nonempty_maps != swath_map_boundaries_.size()) { std::cout << "WARNING: The number nonempty maps found in the input file (" << nonempty_maps << ") is not equal to the number of provided swath window boundaries (" << swath_map_boundaries_.size() << "). Please check your input." << std::endl; } } /// Consume a chromatogram -> should not happen when dealing with SWATH maps void consumeChromatogram(MapType::ChromatogramType&) override { std::cerr << "Read chromatogram while reading SWATH files, did not expect that!" << std::endl; } /** * @brief * Consume a spectrum which may belong either to an MS1 scan or * one of n MS2 (SWATH) scans * */ void consumeSpectrum(MapType::SpectrumType& s) override { if (!consuming_possible_) { throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "FullSwathFileConsumer cannot consume any more spectra after retrieveSwathMaps has been called already"); } if (s.getMSLevel() == 1) { consumeMS1Spectrum_(s); } else { if (s.getPrecursors().empty()) { throw Exception::InvalidParameter(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Swath scan does not provide a precursor."); } const std::vector<Precursor> prec = s.getPrecursors(); double center = prec[0].getMZ(); double lower = prec[0].getMZ() - prec[0].getIsolationWindowLowerOffset(); double upper = prec[0].getMZ() + prec[0].getIsolationWindowUpperOffset(); double lowerIm = -1; // these initial values assume IM is not present double upperIm = -1; // add IM if present if (s.metaValueExists("ion mobility lower limit")) { lowerIm = s.getMetaValue("ion mobility lower limit"); // want this to be -1 if no ion mobility upperIm = s.getMetaValue("ion mobility upper limit"); } bool found = false; // Check if enough information is present to infer the swath if (center <= 0.0) { throw Exception::InvalidParameter(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Swath scan does not provide any precursor isolation information."); } // try to match the current scan to one of the already known windows for (Size i = 0; i < swath_map_boundaries_.size(); i++) { // We group by the precursor mz (center of the window) since this // should be present in all SWATH scans. // also specify ion mobility, if ion mobility not present will just be -1 if ( (std::fabs(center - swath_map_boundaries_[i].center) < 1e-6) && (std::fabs(lowerIm - swath_map_boundaries_[i].imLower) < 1e-6) && ( std::fabs(upperIm - swath_map_boundaries_[i].imUpper) < 1e-6)) { found = true; consumeSwathSpectrum_(s, i); break; } } if (!found) { if (use_external_boundaries_) { throw Exception::InvalidParameter(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Encountered SWATH scan with boundary ") + center + " m/z which was not present in the provided windows."); } else { consumeSwathSpectrum_(s, swath_map_boundaries_.size()); // we found a new SWATH window if (lower > 0.0 && upper > 0.0) {correct_window_counter_++;} OpenSwath::SwathMap boundary; boundary.lower = lower; boundary.upper = upper; boundary.center = center; boundary.imLower = lowerIm; boundary.imUpper = upperIm; swath_map_boundaries_.push_back(boundary); OPENMS_LOG_DEBUG << "Adding Swath centered at " << center << " m/z with an isolation window of " << lower << " to " << upper << " m/z and IM lower limit of " << lowerIm << " and upper limit of " << upperIm << std::endl; } } } } protected: /** * @brief Consume an MS2 spectrum belonging to SWATH "swath_nr" * * This function should handle a spectrum belonging to a specific SWATH * (indicated by swath_nr). * */ virtual void consumeSwathSpectrum_(MapType::SpectrumType& s, size_t swath_nr) = 0; /** * @brief Consume an MS1 spectrum * * This function should handle an MS1 spectrum. * */ virtual void consumeMS1Spectrum_(MapType::SpectrumType& s) = 0; /** * @brief Callback function after the reading is complete * * Has to ensure that swath_maps_ and ms1_map_ are correctly populated. */ virtual void ensureMapsAreFilled_() = 0; /// A list of Swath map identifiers (lower/upper boundary and center) std::vector<OpenSwath::SwathMap> swath_map_boundaries_; /// A list of SWATH maps and the MS1 map std::vector<std::shared_ptr<PeakMap > > swath_maps_; std::shared_ptr<PeakMap > ms1_map_; /// The Experimental settings // (MSExperiment has no constructor using ExperimentalSettings) PeakMap settings_; /// Whether further spectra can still be consumed bool consuming_possible_; /// Whether to use external input for SWATH boundaries bool use_external_boundaries_; /// How many windows were correctly annotated (non-zero window limits) size_t correct_window_counter_; }; /** * @brief In-memory implementation of FullSwathFileConsumer * * Keeps all the spectra in memory by just appending them to an MSExperiment. * */ class OPENMS_DLLAPI RegularSwathFileConsumer : public FullSwathFileConsumer { public: typedef PeakMap MapType; typedef MapType::SpectrumType SpectrumType; typedef MapType::ChromatogramType ChromatogramType; RegularSwathFileConsumer() {} RegularSwathFileConsumer(std::vector<OpenSwath::SwathMap> known_window_boundaries) : FullSwathFileConsumer(known_window_boundaries) {} protected: void addNewSwathMap_() { std::shared_ptr<PeakMap > exp(new PeakMap(settings_)); swath_maps_.push_back(exp); } void consumeSwathSpectrum_(MapType::SpectrumType& s, size_t swath_nr) override { while (swath_maps_.size() <= swath_nr) { addNewSwathMap_(); } swath_maps_[swath_nr]->addSpectrum(s); } void addMS1Map_() { std::shared_ptr<PeakMap > exp(new PeakMap(settings_)); ms1_map_ = exp; } void consumeMS1Spectrum_(MapType::SpectrumType& s) override { if (!ms1_map_) { addMS1Map_(); } ms1_map_->addSpectrum(s); } void ensureMapsAreFilled_() override {} }; /** * @brief On-disk cached implementation of FullSwathFileConsumer * * Writes all spectra immediately to disk in a user-specified caching * location using the MSDataCachedConsumer. Internally, it handles * n+1 (n SWATH + 1 MS1 map) objects of MSDataCachedConsumer which can consume the * spectra and write them to disk immediately. * */ class OPENMS_DLLAPI CachedSwathFileConsumer : public FullSwathFileConsumer { public: typedef PeakMap MapType; typedef MapType::SpectrumType SpectrumType; typedef MapType::ChromatogramType ChromatogramType; CachedSwathFileConsumer(String cachedir, String basename, Size nr_ms1_spectra, std::vector<int> nr_ms2_spectra) : ms1_consumer_(nullptr), swath_consumers_(), cachedir_(cachedir), basename_(basename), nr_ms1_spectra_(nr_ms1_spectra), nr_ms2_spectra_(nr_ms2_spectra) {} CachedSwathFileConsumer(std::vector<OpenSwath::SwathMap> known_window_boundaries, String cachedir, String basename, Size nr_ms1_spectra, std::vector<int> nr_ms2_spectra) : FullSwathFileConsumer(known_window_boundaries), ms1_consumer_(nullptr), swath_consumers_(), cachedir_(cachedir), basename_(basename), nr_ms1_spectra_(nr_ms1_spectra), nr_ms2_spectra_(nr_ms2_spectra) {} ~CachedSwathFileConsumer() override { // Properly delete the MSDataCachedConsumer -> free memory and _close_ file stream while (!swath_consumers_.empty()) { delete swath_consumers_.back(); swath_consumers_.pop_back(); } if (ms1_consumer_ != nullptr) { delete ms1_consumer_; ms1_consumer_ = nullptr; } } protected: void addNewSwathMap_() { String meta_file = cachedir_ + basename_ + "_" + String(swath_consumers_.size()) + ".mzML"; String cached_file = meta_file + ".cached"; MSDataCachedConsumer* consumer = new MSDataCachedConsumer(cached_file, true); consumer->setExpectedSize(nr_ms2_spectra_[swath_consumers_.size()], 0); swath_consumers_.push_back(consumer); // maps for meta data std::shared_ptr<PeakMap > exp(new PeakMap(settings_)); swath_maps_.push_back(exp); } void consumeSwathSpectrum_(MapType::SpectrumType& s, size_t swath_nr) override { while (swath_maps_.size() <= swath_nr) { addNewSwathMap_(); } swath_consumers_[swath_nr]->consumeSpectrum(s); // write data to cached file; clear data from spectrum s swath_maps_[swath_nr]->addSpectrum(s); // append for the metadata (actual data was deleted) } void addMS1Map_() { String meta_file = cachedir_ + basename_ + "_ms1.mzML"; String cached_file = meta_file + ".cached"; ms1_consumer_ = new MSDataCachedConsumer(cached_file, true); ms1_consumer_->setExpectedSize(nr_ms1_spectra_, 0); std::shared_ptr<PeakMap > exp(new PeakMap(settings_)); ms1_map_ = exp; } void consumeMS1Spectrum_(MapType::SpectrumType& s) override { if (ms1_consumer_ == nullptr) { addMS1Map_(); } ms1_consumer_->consumeSpectrum(s); ms1_map_->addSpectrum(s); // append for the metadata (actual data is deleted) } void ensureMapsAreFilled_() override { size_t swath_consumers_size = swath_consumers_.size(); bool have_ms1 = (ms1_consumer_ != nullptr); // Properly delete the MSDataCachedConsumer -> free memory and _close_ file stream // The file streams to the cached data on disc can and should be closed // here safely. Since ensureMapsAreFilled_ is called after consuming all // the spectra, there will be no more spectra to append but the client // might already want to read after this call, so all data needs to be // present on disc and the file streams closed. // // TODO merge with destructor code into own function! while (!swath_consumers_.empty()) { delete swath_consumers_.back(); swath_consumers_.pop_back(); } if (ms1_consumer_ != nullptr) { delete ms1_consumer_; ms1_consumer_ = nullptr; } if (have_ms1) { std::shared_ptr<PeakMap > exp(new PeakMap); String meta_file = cachedir_ + basename_ + "_ms1.mzML"; // write metadata to disk and store the correct data processing tag Internal::CachedMzMLHandler().writeMetadata(*ms1_map_, meta_file, true); FileHandler().loadExperiment(meta_file, *exp.get(), {FileTypes::MZML}); ms1_map_ = exp; } #ifdef _OPENMP #pragma omp parallel for #endif for (SignedSize i = 0; i < boost::numeric_cast<SignedSize>(swath_consumers_size); i++) { std::shared_ptr<PeakMap > exp(new PeakMap); String meta_file = cachedir_ + basename_ + "_" + String(i) + ".mzML"; // write metadata to disk and store the correct data processing tag Internal::CachedMzMLHandler().writeMetadata(*swath_maps_[i], meta_file, true); FileHandler().loadExperiment(meta_file, *exp.get(), {FileTypes::MZML}); swath_maps_[i] = exp; } } MSDataCachedConsumer* ms1_consumer_; std::vector<MSDataCachedConsumer*> swath_consumers_; String cachedir_; String basename_; int nr_ms1_spectra_; std::vector<int> nr_ms2_spectra_; }; /** * @brief On-disk mzML implementation of FullSwathFileConsumer * * Writes all spectra immediately to disk to an mzML file location using the * PlainMSDataWritingConsumer. Internally, it handles n+1 (n SWATH + 1 MS1 * map) objects of MSDataCachedConsumer which can consume the spectra and * write them to disk immediately. * * Warning: no swathmaps (MS1 nor MS2) will be available when calling retrieveSwathMaps() * for downstream use. * */ class OPENMS_DLLAPI MzMLSwathFileConsumer : public FullSwathFileConsumer { public: typedef PeakMap MapType; typedef MapType::SpectrumType SpectrumType; typedef MapType::ChromatogramType ChromatogramType; MzMLSwathFileConsumer(const String& cachedir, const String& basename, Size nr_ms1_spectra, const std::vector<int>& nr_ms2_spectra) : ms1_consumer_(nullptr), swath_consumers_(), cachedir_(cachedir), basename_(basename), nr_ms1_spectra_(nr_ms1_spectra), nr_ms2_spectra_(nr_ms2_spectra) {} MzMLSwathFileConsumer(std::vector<OpenSwath::SwathMap> known_window_boundaries, const String& cachedir, const String& basename, Size nr_ms1_spectra, const std::vector<int>& nr_ms2_spectra) : FullSwathFileConsumer(known_window_boundaries), ms1_consumer_(nullptr), swath_consumers_(), cachedir_(cachedir), basename_(basename), nr_ms1_spectra_(nr_ms1_spectra), nr_ms2_spectra_(nr_ms2_spectra) {} ~MzMLSwathFileConsumer() override { deleteSetNull_(); } protected: void deleteSetNull_() { // Properly delete the MSDataCachedConsumer -> free memory and _close_ file stream while (!swath_consumers_.empty()) { delete swath_consumers_.back(); swath_consumers_.pop_back(); } if (ms1_consumer_ != nullptr) { delete ms1_consumer_; ms1_consumer_ = nullptr; } } void addNewSwathMap_() { String mzml_file = cachedir_ + basename_ + "_" + String(swath_consumers_.size()) + ".mzML"; PlainMSDataWritingConsumer* consumer = new PlainMSDataWritingConsumer(mzml_file); consumer->getOptions().setCompression(true); consumer->setExpectedSize(nr_ms2_spectra_[swath_consumers_.size()], 0); swath_consumers_.push_back(consumer); } void consumeSwathSpectrum_(MapType::SpectrumType& s, size_t swath_nr) override { // only use swath_consumers_ to count how many we have already added while (swath_consumers_.size() <= swath_nr) { addNewSwathMap_(); } swath_consumers_[swath_nr]->consumeSpectrum(s); s.clear(false); } void addMS1Map_() { String mzml_file = cachedir_ + basename_ + "_ms1.mzML"; ms1_consumer_ = new PlainMSDataWritingConsumer(mzml_file); ms1_consumer_->setExpectedSize(nr_ms1_spectra_, 0); ms1_consumer_->getOptions().setCompression(true); } void consumeMS1Spectrum_(MapType::SpectrumType& s) override { if (ms1_consumer_ == nullptr) { addMS1Map_(); } ms1_consumer_->consumeSpectrum(s); } void ensureMapsAreFilled_() override { deleteSetNull_(); } PlainMSDataWritingConsumer* ms1_consumer_; std::vector<PlainMSDataWritingConsumer*> swath_consumers_; String cachedir_; String basename_; int nr_ms1_spectra_; std::vector<int> nr_ms2_spectra_; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/FORMAT/DATAACCESS/MSDataSqlConsumer.h
.h
3,147
102
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Hannes Roest $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/INTERFACES/IMSDataConsumer.h> #include <OpenMS/KERNEL/MSExperiment.h> namespace OpenMS { namespace Internal { class MzMLSqliteHandler; } /** @brief A data consumer that inserts MS data into a SQLite database Consumes spectra and chromatograms and inserts them into an file-based SQL database using SQLite. As SQLite is highly inefficient when inserting one spectrum/chromatogram at a time, the consumer collects the data in an internal buffer and then flushes them all together to disk. It uses MzMLSqliteHandler internally to write batches of data to disk. */ class OPENMS_DLLAPI MSDataSqlConsumer : public Interfaces::IMSDataConsumer { typedef MSExperiment MapType; typedef MapType::SpectrumType SpectrumType; typedef MapType::ChromatogramType ChromatogramType; public: /** @brief Constructor Opens the SQLite file and writes the tables. @param[in] sql_filename The filename of the SQLite database @param[in] run_id Unique identifier which links the sqMass and OSW file @param[in] buffer_size How large the internal buffer size should be (defaults to 500 spectra / chromatograms) @param[in] full_meta Whether to write the full meta-data in the SQLite header @param[in] lossy_compression Whether to use lossy compression (numpress) @param[in] linear_mass_acc Desired mass accuracy for RT or m/z space (absolute value) */ MSDataSqlConsumer(const String& sql_filename, UInt64 run_id, int buffer_size = 500, bool full_meta = true, bool lossy_compression=false, double linear_mass_acc=1e-4); /** @brief Destructor Flushes the data for good. */ ~MSDataSqlConsumer() override; /** @brief Flushes the data for good. After calling this function, no more data is held in the buffer but the class is still able to receive new data. */ void flush(); /** @brief Write a spectrum to the output file */ void consumeSpectrum(SpectrumType & s) override; /** @brief Write a chromatogram to the output file */ void consumeChromatogram(ChromatogramType & c) override; void setExpectedSize(Size /* expectedSpectra */, Size /* expectedChromatograms */) override; void setExperimentalSettings(const ExperimentalSettings& /* exp */) override; protected: String filename_; OpenMS::Internal::MzMLSqliteHandler * handler_; size_t flush_after_; bool full_meta_; std::vector<SpectrumType> spectra_; std::vector<ChromatogramType> chromatograms_; MSExperiment peak_meta_; }; } //end namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/CONCEPT/MacrosTest.h
.h
2,368
60
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Philippe M. Groarke, Hannes Roest $ // -------------------------------------------------------------------------- // See https://philippegroarke.com/posts/2018/easy_defensive_programming/ // https://github.com/p-groarke/defensive_cpp #pragma once #include <type_traits> namespace OpenMS { // no constexpr lambdas in C++11, therefore we have to use functions namespace Test { template <class T> constexpr bool fulfills_rule_of_5() { static_assert(std::is_destructible<T>::value, "T : must be destructible"); static_assert(std::is_copy_constructible<T>::value, "T : must be copy constructible"); static_assert(std::is_move_constructible<T>::value, "T : must be move constructible"); static_assert(std::is_copy_assignable<T>::value, "T : must be copy assignable"); static_assert(std::is_move_assignable<T>::value, "T : must be move assignable"); return std::is_destructible<T>::value && std::is_copy_constructible<T>::value && std::is_move_constructible<T>::value && std::is_copy_assignable<T>::value && std::is_move_assignable<T>::value; } template <class T> constexpr bool fulfills_rule_of_6() { static_assert(fulfills_rule_of_5<T>(), "T : must fulfill rule of 5"); static_assert(std::is_default_constructible<T>::value, "T : must be default constructible"); return fulfills_rule_of_5<T>() && std::is_default_constructible<T>::value; } template <class T> constexpr bool fulfills_fast_vector() { static_assert( (std::is_trivially_copy_constructible<T>::value && std::is_trivially_destructible<T>::value) || std::is_nothrow_move_constructible<T>::value, "T : doesn't fulfill fast vector (trivially copy constructible " \ "and trivially destructible, or nothrow move constructible)"); return (std::is_trivially_copy_constructible<T>::value && std::is_trivially_destructible<T>::value) || std::is_nothrow_move_constructible<T>::value; }; } }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/CONCEPT/UniqueIdGenerator.h
.h
1,512
64
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/DATASTRUCTURES/Param.h> #include <boost/random/mersenne_twister.hpp> #include <boost/random/variate_generator.hpp> #include <boost/random/uniform_int.hpp> namespace OpenMS { class DateTime; /** @brief A generator for unique ids. The unique ids are 64-bit random unsigned random integers. The class is implemented as a singleton. The random generator is implemented using boost::random. @ingroup Concept */ class OPENMS_DLLAPI UniqueIdGenerator { public: /// Returns a new unique id static UInt64 getUniqueId(); /// Initializes random generator using the given value. static void setSeed(const UInt64); /// Get the seed static UInt64 getSeed(); protected: UniqueIdGenerator(); ~UniqueIdGenerator(); private: static UInt64 seed_; static UniqueIdGenerator* instance_; static boost::mt19937_64* rng_; static boost::uniform_int<UInt64>* dist_; static UniqueIdGenerator& getInstance_(); void init_(); UniqueIdGenerator(const UniqueIdGenerator& );//protect from c++ auto-generation }; } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/CONCEPT/LogStream.h
.h
21,571
657
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow $ // $Authors: Chris Bielow, Stephan Aiche, Andreas Bertsch$ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/CONCEPT/Macros.h> #include <OpenMS/DATASTRUCTURES/String.h> #include <sstream> #include <iostream> #include <list> #include <vector> #include <ctime> #include <map> namespace OpenMS { class Colorizer; /** @brief Log streams Logging, filtering, and storing messages. Many programs emit warning messages, error messages, or simply information and remarks to their users. The LogStream class provides a convenient and straight-forward interface to classify these messages according to their importance (via the loglevel), filter and store them in files or write them to streams. \par As the LogStream class is derived from ostream, it behaves as any ostream object. Additionally you may associate streams with each LogStream object that catch only messages of certain loglevels. So the user might decide to redirect all error messages to cerr, all warning messages to cout and all information to a file. \par Along with each message its time of creation and its loglevel is stored. So the user might also decide to store all errors he got in the last two hours or alike. \par The LogStream class heavily relies on the LogStreamBuf class, which does the actual buffering and storing, but is only of interest if you want to implement a derived class, as the actual user interface is implemented in the LogStream class. @ingroup Concept */ namespace Logger { // forward declarations class LogStream; class LogStreamNotifier; /** @brief Stream buffer used by LogStream. This class implements the low level behavior of LogStream . It takes care of the buffers and stores the lines written into the LogStream object. It also contains a list of streams that are associated with the LogStream object. This list contains pointers to the streams and their minimum and maximum log level. Each line entered in the LogStream is marked with its time (in fact, the time LogStreamBuf::sync was called) and its loglevel. The loglevel is determined by either the current loglevel (as set by LogStream::setLevel or a temporary level (as set by LogStream::level for a single line only). For each line stored, the list of associated streams is checked whether the loglevel falls into the range declared by the stream's minimum and maximum level. If this condition is met, the logline (with its prefix, see LogStream::setPrefix ) is also copied to the associated stream and this stream is flushed, too. */ class OPENMS_DLLAPI LogStreamBuf : public std::streambuf { friend class LogStream; public: /// @name Constants //@{ static const time_t MAX_TIME; static const std::string UNKNOWN_LOG_LEVEL; //@} /// @name Constructors and Destructors //@{ /** Create a new LogStreamBuf object and set the level to @p log_level @param[in] log_level The log level of the LogStreamBuf (default is unknown) @param[in] col If messages should be colored, provide a colorizer here */ LogStreamBuf(const std::string& log_level = UNKNOWN_LOG_LEVEL, Colorizer* col = nullptr); /** Create a LogStreamBuf that copies the stream_list_ configuration from another LogStreamBuf. This constructor is used for thread-local logging where each thread has its own buffer and stream configuration (for thread safety), but starts with the same initial configuration as the global LogStream instances. @param[in] source_buf The LogStreamBuf whose stream_list_ should be copied @param[in] col If messages should be colored, provide a colorizer here */ LogStreamBuf(LogStreamBuf* source_buf, Colorizer* col = nullptr); /** Destruct the buffer and free all stored messages strings. */ ~LogStreamBuf() override; //@} /// @name Stream methods //@{ /** This method is called as soon as the ostream is flushed (especially this method is called by flush or endl). It transfers the contents of the streambufs putbuffer into a logline if a newline or linefeed character is found in the buffer ("\n" or "\r" resp.). The line is then removed from the putbuffer. Incomplete lines (not terminated by "\n" / "\r" are stored in incomplete_line_. */ int sync() override; /** This method calls sync and <tt>streambuf::overflow(c)</tt> to prevent a buffer overflow. */ int overflow(int c = -1) override; //@} /// @name Level methods //@{ /** Set the level of the LogStream @param[in] level The new LogLevel */ void setLevel(std::string level); /** Returns the LogLevel of this LogStream */ std::string getLevel(); //@} /** @brief Holds a stream that is connected to the LogStream. It also includes the minimum and maximum level at which the LogStream redirects messages to this stream. */ struct OPENMS_DLLAPI StreamStruct { std::ostream * stream; std::string prefix; LogStreamNotifier * target; StreamStruct() : stream(nullptr), target(nullptr) {} /// Delete the notification target. ~StreamStruct() {} }; /** Checks if some of the cached entries where sent more then once to the LogStream and (if necessary) prints a corresponding messages into all affected Logs */ void clearCache(); protected: /// Distribute a new message to connected streams. void distribute_(const std::string& outstring); /// Interpret the prefix format string and return the expanded prefix. std::string expandPrefix_(const std::string & prefix, time_t time) const; /// Returns the stream list (owned or shared) std::list<StreamStruct>& getStreamList_(); const std::list<StreamStruct>& getStreamList_() const; char * pbuf_ = nullptr; std::string level_; std::list<StreamStruct> stream_list_; ///< Stream list for this buffer std::string incomplete_line_; Colorizer* colorizer_ = nullptr; ///< optional Colorizer to color the output to stdout/stdcerr (if attached) /// @name Caching //@{ /** @brief Holds a counter of occurrences and an index for the occurrence sequence of the corresponding log message */ struct LogCacheStruct { Size timestamp; int counter; }; /** Sequential counter to remember the sequence of occurrence of the cached log messages */ Size log_cache_counter_ = 0; /// Cache of the last two log messages std::map<std::string, LogCacheStruct> log_cache_; /// Cache of the occurrence sequence of the last two log messages std::map<Size, std::string> log_time_cache_; /// Checks if the line is already in the cache bool isInCache_(std::string const & line); /** Adds the new line to the cache and removes an old one if necessary @param[in] line The Log message that should be added to the cache @return An additional massage if a re-occurring message was removed from the cache */ std::string addToCache_(std::string const & line); /// Returns the next free index for a log message Size getNextLogCounter_(); /// Non-lock acquiring sync function called in the d'tor int syncLF_(); //@} }; /// class OPENMS_DLLAPI LogStreamNotifier { public: /// Empty constructor. LogStreamNotifier(); /// Destructor virtual ~LogStreamNotifier(); /// virtual void logNotify(); /// void registerAt(LogStream & log_stream); /// void unregister(); protected: std::stringstream stream_; LogStream * registered_at_; }; /** @brief Log Stream Class. Defines a log stream which features a cache and some formatting. For the developer, however, only some macros are of interest which will push the message that follows them into the appropriate stream: Macros: - OPENMS_LOG_FATAL_ERROR - OPENMS_LOG_ERROR (non-fatal error are reported (processing continues)) - OPENMS_LOG_WARN (warning, a piece of information which should be read by the user, should be logged) - OPENMS_LOG_INFO (information, e.g. a status should be reported) - OPENMS_LOG_DEBUG (general debugging information - output be written to cout if debug_level > 0) To use a specific logger of a log level simply use it as cerr or cout: <br> <code> OPENMS_LOG_ERROR << " A bad error occurred ..." </code> <br> Which produces an error message in the log. @note The log stream macros are thread safe and can be used in a multithreaded environment, the global variables are not! The macros are protected by a OPENMS_THREAD_CRITICAL directive (which translates to an OpenMP critical pragma), however there may be a small performance penalty to this. */ class OPENMS_DLLAPI LogStream : public std::ostream { public: /// @name Constructors and Destructors //@{ /** Creates a new LogStream object that is not associated with any stream. If the argument <tt>stream</tt> is set to an output stream (e.g. <tt>cout</tt>) all output is send to that stream. @param[in] buf @param[in] delete_buf @param[in] stream */ LogStream(LogStreamBuf * buf = nullptr, bool delete_buf = true, std::ostream * stream = nullptr); /// Clears all message buffers. ~LogStream() override; //@} /// @name Stream Methods //@{ /** rdbuf method of ostream. This method is needed to access the LogStreamBuf object. @see std::ostream::rdbuf for more details. */ LogStreamBuf * rdbuf(); /// Arrow operator. LogStreamBuf * operator->(); //@} /// @name Level methods //@{ /** Set the level of the LogStream @param[in] level The new LogLevel */ void setLevel(std::string level); /** Returns the LogLevel of this LogStream */ std::string getLevel(); //@} /// @name Associating Streams //@{ /** Associate a new stream with this logstream. This method inserts a new stream into the list of associated streams and sets the corresponding minimum and maximum log levels. Any message that is subsequently logged, will be copied to this stream if its log level is between <tt>min_level</tt> and <tt>max_level</tt>. If <tt>min_level</tt> and <tt>max_level</tt> are omitted, all messages are copied to this stream. If <tt>min_level</tt> and <tt>max_level</tt> are equal, this function can be used to listen to a specified channel. @param[in] s a reference to the stream to be associated */ void insert(std::ostream & s); /** Remove an association with a stream. Remove a stream from the stream list and avoid the copying of new messages to this stream. \par If the stream was not in the list of associated streams nothing will happen. @param[in] s the stream to be removed */ void remove(std::ostream & s); /** Remove all streams associated to this LogStream, effectively silencing it. Flushes all buffers to ensure any pending log messages are written to their respective streams before they are removed. */ void removeAllStreams(); /// Add a notification target void insertNotification(std::ostream & s, LogStreamNotifier & target); /** Set prefix for output to this stream. Each line written to the stream will be prefixed by this string. The string may also contain trivial format specifiers to include loglevel and time/date of the logged message. \par The following format tags are recognized: - <b>%y</b> message type ("Error", "Warning", "Information", "-") - <b>%T</b> time (HH:MM:SS) - <b>%t</b> time in short format (HH:MM) - <b>%D</b> date (YYYY/MM/DD) - <b>%d</b> date in short format (MM/DD) - <b>%S</b> time and date (YYYY/MM/DD, HH:MM:SS) - <b>%s</b> time and date in short format (MM/DD, HH:MM) - <b>%%</b> percent sign (escape sequence) @param[in] s The stream that will be prefixed. @param[in] prefix The prefix used for the stream. */ void setPrefix(const std::ostream & s, const std::string & prefix); /// Set prefix of all output streams, details see setPrefix method with ostream void setPrefix(const std::string & prefix); /// void flush(); /** @brief Flush any incomplete line (text not terminated by newline) to all streams. This is useful for thread-local logging where the buffer needs to be flushed before streams are reconfigured globally. */ void flushIncomplete(); //@} private: typedef std::list<LogStreamBuf::StreamStruct>::iterator StreamIterator; StreamIterator findStream_(const std::ostream & stream); bool hasStream_(std::ostream & stream); bool bound_() const; /// flag needed by the destructor to decide whether the streambuf /// has to be deleted. If the default ctor is used to create /// the LogStreamBuf, delete_buffer_ is set to true and the ctor /// also deletes the buffer. bool delete_buffer_; }; //LogStream /** @brief RAII guard that temporarily removes a stream from a LogStream and re-inserts it on scope exit. This class provides exception-safe temporary removal of output streams from LogStream objects. Use this when you need to temporarily suppress logging to a specific stream (e.g., cout) during operations that may throw exceptions. Example usage: @code LogSinkGuard guard(getGlobalLogInfo(), cout); // Removes cout, will re-insert on scope exit some_operation_that_may_throw(); // cout is automatically re-inserted when guard goes out of scope @endcode @ingroup Concept */ class OPENMS_DLLAPI LogSinkGuard { public: /** @brief Construct a guard that removes the stream and re-inserts it on destruction. @param log_stream The LogStream to remove the stream from (and re-insert into on destruction) @param stream The stream to temporarily remove (e.g., std::cout) */ LogSinkGuard(LogStream& log_stream, std::ostream& stream) : log_stream_(log_stream), stream_(stream) { log_stream_.remove(stream_); } /// Destructor re-inserts the stream ~LogSinkGuard() { log_stream_.insert(stream_); } // Non-copyable and non-movable LogSinkGuard(const LogSinkGuard&) = delete; LogSinkGuard& operator=(const LogSinkGuard&) = delete; LogSinkGuard(LogSinkGuard&&) = delete; LogSinkGuard& operator=(LogSinkGuard&&) = delete; private: LogStream& log_stream_; std::ostream& stream_; }; } // namespace Logger // // Thread-Local Log Stream Accessors // // These functions return thread-local LogStream instances, eliminating data races // in the logging system. Each thread gets its own buffers and state. // See GitHub Issue #8596 for details on the race conditions this fixes. // // RESTRICTIONS (document these clearly): // - Log configuration (via LogConfigHandler) should be done ONCE at program start, // BEFORE spawning threads. Thread-local streams copy config from globals on first access. // - OpenMP thread pools reuse threads, so thread_local state persists across parallel regions. // - Do not reconfigure logging while threads are actively logging. // /// @brief Get thread-local fatal error log stream OPENMS_DLLAPI Logger::LogStream& getThreadLocalLogFatal(); /// @brief Get thread-local error log stream OPENMS_DLLAPI Logger::LogStream& getThreadLocalLogError(); /// @brief Get thread-local warning log stream OPENMS_DLLAPI Logger::LogStream& getThreadLocalLogWarn(); /// @brief Get thread-local info log stream OPENMS_DLLAPI Logger::LogStream& getThreadLocalLogInfo(); /// @brief Get thread-local debug log stream OPENMS_DLLAPI Logger::LogStream& getThreadLocalLogDebug(); // // Logging Macros (thread-safe via thread-local streams) // /// Macro for fatal errors (processing stops) - includes file and line info #define OPENMS_LOG_FATAL_ERROR \ OpenMS::getThreadLocalLogFatal() << __FILE__ << "(" << __LINE__ << "): " /// Macro for non-fatal errors (processing continues) #define OPENMS_LOG_ERROR \ OpenMS::getThreadLocalLogError() /// Macro for warnings #define OPENMS_LOG_WARN \ OpenMS::getThreadLocalLogWarn() /// Macro for information/status messages #define OPENMS_LOG_INFO \ OpenMS::getThreadLocalLogInfo() /// Macro for debug information - includes file and line info #define OPENMS_LOG_DEBUG \ OpenMS::getThreadLocalLogDebug() << past_last_slash(__FILE__) << "(" << __LINE__ << "): " /// Macro for debug information (without file info) #define OPENMS_LOG_DEBUG_NOFILE \ OpenMS::getThreadLocalLogDebug() /** @name Global LogStream accessor functions These functions provide access to global LogStream instances for configuration purposes (e.g., adding/removing output streams). For actual logging, use the OPENMS_LOG_* macros which use thread-local streams to avoid data races. @warning Direct logging to global streams is NOT thread-safe. Use OPENMS_LOG_* macros instead. */ ///@{ /** @brief Get the global fatal error log stream for configuration purposes. Returns a reference to the global fatal error LogStream instance. Use this function to configure the stream (e.g., adding/removing output destinations with insert()/remove()). @warning Do NOT use this for logging messages directly - it is not thread-safe. Use the OPENMS_LOG_FATAL_ERROR macro instead. @return Reference to the global fatal error log stream @see OPENMS_LOG_FATAL_ERROR */ OPENMS_DLLAPI Logger::LogStream& getGlobalLogFatal(); /** @brief Get the global error log stream for configuration purposes. Returns a reference to the global error LogStream instance. Use this function to configure the stream (e.g., adding/removing output destinations with insert()/remove()). @warning Do NOT use this for logging messages directly - it is not thread-safe. Use the OPENMS_LOG_ERROR macro instead. @return Reference to the global error log stream @see OPENMS_LOG_ERROR */ OPENMS_DLLAPI Logger::LogStream& getGlobalLogError(); /** @brief Get the global warning log stream for configuration purposes. Returns a reference to the global warning LogStream instance. Use this function to configure the stream (e.g., adding/removing output destinations with insert()/remove()). @warning Do NOT use this for logging messages directly - it is not thread-safe. Use the OPENMS_LOG_WARN macro instead. @return Reference to the global warning log stream @see OPENMS_LOG_WARN */ OPENMS_DLLAPI Logger::LogStream& getGlobalLogWarn(); /** @brief Get the global info log stream for configuration purposes. Returns a reference to the global info LogStream instance. Use this function to configure the stream (e.g., adding/removing output destinations with insert()/remove()). @warning Do NOT use this for logging messages directly - it is not thread-safe. Use the OPENMS_LOG_INFO macro instead. @return Reference to the global info log stream @see OPENMS_LOG_INFO */ OPENMS_DLLAPI Logger::LogStream& getGlobalLogInfo(); /** @brief Get the global debug log stream for configuration purposes. Returns a reference to the global debug LogStream instance. Use this function to configure the stream (e.g., adding/removing output destinations with insert()/remove()). @note The debug stream is disabled by default. It is enabled in TOPPBase when running with --debug flag. @warning Do NOT use this for logging messages directly - it is not thread-safe. Use the OPENMS_LOG_DEBUG macro instead. @return Reference to the global debug log stream @see OPENMS_LOG_DEBUG */ OPENMS_DLLAPI Logger::LogStream& getGlobalLogDebug(); ///@} } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/CONCEPT/CommonEnums.h
.h
1,405
42
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow $ // $Authors: Chris Bielow $ // -------------------------------------------------------------------------- #pragma once #include <string_view> namespace OpenMS { // add common enums here to avoid big includes of large classes and break circular dependencies /// Enum for different units which can be displayed on a plotting axis /// The order is arbitrary. enum class DIM_UNIT { RT = 0, ///< RT in seconds MZ, ///< m/z INT, ///< intensity IM_MS, ///< ion mobility milliseconds IM_VSSC, ///< volt-second per square centimeter (i.e. 1/K_0) FAIMS_CV, ///< FAIMS compensation voltage SIZE_OF_DIM_UNITS }; inline std::string_view DIM_NAMES[(int)DIM_UNIT::SIZE_OF_DIM_UNITS] = {"RT [s]", "m/z [Th]", "intensity", "IM [milliseconds]", "IM [vs / cm2]", "FAIMS CV"}; inline std::string_view DIM_NAMES_SHORT[(int)DIM_UNIT::SIZE_OF_DIM_UNITS] = {"RT", "m/z", "int", "IM", "IM", "FCV"}; enum class MZ_UNITS { DA = 0, ///< Dalton PPM, ///< parts-per-million SIZE_OF_MZ_UNITS }; inline std::string_view MZ_UNIT_NAMES[(int)MZ_UNITS::SIZE_OF_MZ_UNITS] = {"Da", "ppm"}; } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/CONCEPT/Exception.h
.h
21,145
725
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg$ // $Authors: Marc Sturm $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/OpenMSConfig.h> #include <iosfwd> #include <stdexcept> #include <string> namespace OpenMS { /** @defgroup Exceptions Exceptions @brief Exceptions @ingroup Concept */ /** @brief %Exception namespace @ingroup Concept */ namespace Exception { /** @brief Exception base class. This class is intended as a base class for all other exceptions. Each exception class should define a constructor taking a filename (string), line (int) and function name (string) as first arguments. This information is usually printed in case of an uncaught exception. To support this feature, each @em throw directive should look as follows: @code throw Exception::Exception(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,...); @endcode @em __FILE__ and @em __LINE__ are built-in preprocessor macros that hold the desired information. @n @em OPENMS_PRETTY_FUNCTION is replaced by the GNU G++ compiler with the demangled name of the current function. (For other compilers it is defined as "<unknown>" in config.h.) %OpenMS provides its own Exception::GlobalExceptionHandler::terminate() handler. This handler extracts as much information as possible from the exception, prints it to @em cerr , and finally calls exits the program cleanly (with exit code 1). This can be rather inconvenient for debugging, since you are told where the exception was thrown, but in general you do not know anything about the context. Therefore terminate() can also create a core dump. Using a debugger (e.g. @em dbx or @em gdb) you can then create a stack traceback. To create a core dump, you should set the environment variable @em OPENMS_DUMP_CORE to any (non empty) value. @ingroup Exceptions */ class OPENMS_DLLAPI BaseException : public std::runtime_error { public: /** @name Constructors and Destructors */ //@{ /// Default constructor BaseException() noexcept; /// Constructor BaseException(const char* file, int line, const char* function) noexcept; /// Constructor BaseException(const char* file, int line, const char* function, const std::string& name, const std::string& message) noexcept; /// Copy constructor BaseException(const BaseException& exception) noexcept; /// Destructor ~BaseException() noexcept override; //@} /** @name Accessors */ //@{ /// Returns the name of the exception const char* getName() const noexcept; /// Returns the line number where it occurred int getLine() const noexcept; /// Returns the file where it occurred const char* getFile() const noexcept; /// Returns the function where it occurred const char* getFunction() const noexcept; /// Returns the message const char* getMessage() const noexcept; //@} protected: /// The source file the exception was thrown in const char* file_; /// The line number the exception was thrown in int line_; /// The source file the exception was thrown in const char* function_; /// The name of the exception. std::string name_; }; /** @brief Precondition failed exception. A precondition (as defined by @ref OPENMS_PRECONDITION ) has failed. @ingroup Exceptions */ class OPENMS_DLLAPI Precondition : public BaseException { public: Precondition(const char* file, int line, const char* function, const std::string& condition) noexcept; }; /** @brief Postcondition failed exception. A postcondition (as defined by @ref OPENMS_POSTCONDITION ) has failed. @ingroup Exceptions */ class OPENMS_DLLAPI Postcondition : public BaseException { public: Postcondition(const char* file, int line, const char* function, const std::string& condition) noexcept; }; /** @brief Not all required information provided. Information that are required are not provided. Especially useful for missing MetaInfo values. @ingroup Exceptions */ class OPENMS_DLLAPI MissingInformation : public BaseException { public: MissingInformation(const char* file, int line, const char* function, const std::string& error_message) noexcept; }; /** @brief Int underflow exception. Throw this exception to indicate an index that was smaller than allowed. The constructor has two additional arguments, the values of which should be set to the index that caused the failure and the smallest allowed value to simplify debugging. @param[in] index the value of the index causing the problem @param[in] size smallest value allowed for index @ingroup Exceptions */ class OPENMS_DLLAPI IndexUnderflow : public BaseException { public: IndexUnderflow(const char* file, int line, const char* function, SignedSize index = 0, Size size = 0) noexcept; }; /** @brief UInt underflow exception. Throw this exception to indicate a size was smaller than allowed. The constructor has an additional argument: the value of of the requested size. This exception is thrown, if buffer sizes are insufficient. @param[in] size the size causing the problem @ingroup Exceptions */ class OPENMS_DLLAPI SizeUnderflow : public BaseException { public: SizeUnderflow(const char* file, int line, const char* function, Size size = 0) noexcept; }; /** @brief Int overflow exception. Throw this exception to indicate an index that was larger than allowed. The constructor has two additional arguments, the values of which should be set to the index that caused the failure and the largest allowed value to simplify debugging. @param[in] index the value of the index causing the problem @param[in] size largest value allowed for index @ingroup Exceptions */ class OPENMS_DLLAPI IndexOverflow : public BaseException { public: IndexOverflow(const char* file, int line, const char* function, SignedSize index = 0, Size size = 0) noexcept; }; /** @brief Array not sorted exception Throw this exception to indicate that an array/vector of elements was expected to be sorted, but was found to be unsorted. @param[in] message What was unsorted? @ingroup Exceptions */ class OPENMS_DLLAPI NotSorted : public BaseException { public: NotSorted(const char* file, int line, const char* function, const std::string& message) noexcept; }; /** @brief A call to an external library (other than OpenMS) went wrong. Throw this exception to indicate that an external library call came back unsuccessful. @param[in] size the size causing the problem @ingroup Exceptions */ class OPENMS_DLLAPI FailedAPICall : public BaseException { public: FailedAPICall(const char* file, int line, const char* function, const std::string& message) noexcept; }; /** @brief Invalid range exception. Use this exception to indicate a general range problems. @ingroup Exceptions */ class OPENMS_DLLAPI InvalidRange : public BaseException { public: InvalidRange(const char* file, int line, const char* function) noexcept; InvalidRange(const char* file, int line, const char* function, const std::string& message) noexcept; }; /** @brief Invalid UInt exception. Throw this exception to indicate that a size was unexpected. The constructor has an additional argument: the value of of the requested size. @param[in] size the size causing the problem @param[in] message context message explaining why the size is invalid @ingroup Exceptions */ class OPENMS_DLLAPI InvalidSize : public BaseException { public: InvalidSize(const char* file, int line, const char* function, Size size, const std::string& message) noexcept; }; /** @brief Out of range exception. Use this exception to indicate that a given value is out of a defined range, i. e. not within the domain of a function. @ingroup Exceptions */ class OPENMS_DLLAPI OutOfRange : public BaseException { public: OutOfRange(const char* file, int line, const char* function) noexcept; }; /** @brief Invalid value exception. Use this exception to indicate that a given value is not valid, when the value is only allowed to be out of a certain set of values. If the value has to be inside a given range, you should rather use OutOfRange. @ingroup Exceptions */ class OPENMS_DLLAPI InvalidValue : public BaseException { public: InvalidValue(const char* file, int line, const char* function, const std::string& message, const std::string& value) noexcept; }; /** @brief Exception indicating that an invalid parameter was handed over to an algorithm. @ingroup Exceptions */ class OPENMS_DLLAPI InvalidParameter : public BaseException { public: InvalidParameter(const char* file, int line, const char* function, const std::string& message) noexcept; }; /** @brief Invalid conversion exception. This exception indicates a conversion problem when converting from one type to another. @ingroup Exceptions */ class OPENMS_DLLAPI ConversionError : public BaseException { public: ConversionError(const char* file, int line, const char* function, const std::string& error) noexcept; }; /** @brief Illegal self operation exception. Throw this exception to indicate an invalid operation on the object itself. In general these operations are self assignments or related methods. @ingroup Exceptions */ class OPENMS_DLLAPI IllegalSelfOperation : public BaseException { public: IllegalSelfOperation(const char* file, int line, const char* function) noexcept; }; /** @brief Null pointer argument is invalid exception. Use this exception to indicate a failure due to an argument not containing a pointer to a valid object, but a null pointer. @ingroup Exceptions */ class OPENMS_DLLAPI NullPointer : public BaseException { public: NullPointer(const char* file, int line, const char* function) noexcept; }; /** @brief Invalid iterator exception. The iterator on which an operation should be performed was invalid. @ingroup Exceptions */ class OPENMS_DLLAPI InvalidIterator : public BaseException { public: InvalidIterator(const char* file, int line, const char* function) noexcept; }; /** @brief Incompatible iterator exception. The iterators could not be assigned because they are bound to different containers. @ingroup Exceptions */ class OPENMS_DLLAPI IncompatibleIterators : public BaseException { public: IncompatibleIterators(const char* file, int line, const char* function) noexcept; }; /** @brief Not implemented exception. This exception should be thrown to indicate not yet implemented methods. @ingroup Exceptions */ class OPENMS_DLLAPI NotImplemented : public BaseException { public: NotImplemented(const char* file, int line, const char* function) noexcept; }; /** @brief Illegal tree operation exception. This exception is thrown to indicate that an illegal tree operation was requested. @ingroup Exceptions */ class OPENMS_DLLAPI IllegalTreeOperation : public BaseException { public: IllegalTreeOperation(const char* file, int line, const char* function) noexcept; }; /** @brief Out of memory exception. Throw this exception to indicate that an allocation failed. This exception is thrown in the OPENMS new handler. @param[in] size the number of bytes that should have been allocated @see GlobalException::newHandler @ingroup Exceptions */ class OPENMS_DLLAPI OutOfMemory : public BaseException, public std::bad_alloc { public: OutOfMemory(const char* file, int line, const char* function, Size size = 0) noexcept; }; /** @brief Buffer overflow exception. @ingroup Exceptions */ class OPENMS_DLLAPI BufferOverflow : public BaseException { public: BufferOverflow(const char* file, int line, const char* function) noexcept; }; /** @brief Division by zero error exception. @ingroup Exceptions */ class OPENMS_DLLAPI DivisionByZero : public BaseException { public: DivisionByZero(const char* file, int line, const char* function) noexcept; }; /** @brief Out of grid exception. @ingroup Exceptions */ class OPENMS_DLLAPI OutOfGrid : public BaseException { public: OutOfGrid(const char* file, int line, const char* function) noexcept; }; /** @brief File not found exception. A given file could not be found. @ingroup Exceptions */ class OPENMS_DLLAPI FileNotFound : public BaseException { public: FileNotFound(const char* file, int line, const char* function, const std::string& filename) noexcept; }; /** @brief External executable (e.g. comet.exe) not found exception. A given file could not be found. Usually used in Adapters for external tools. @ingroup Exceptions */ class OPENMS_DLLAPI ExternalExecutableNotFound : public BaseException { public: ExternalExecutableNotFound(const char* file, int line, const char* function, const std::string& filename) noexcept; }; /** @brief File not readable exception. A given file is not readable for the current user. @ingroup Exceptions */ class OPENMS_DLLAPI FileNotReadable : public BaseException { public: FileNotReadable(const char* file, int line, const char* function, const std::string& filename) noexcept; }; /** @brief File not writable exception. A given file is not writable for the current user. @ingroup Exceptions */ class OPENMS_DLLAPI FileNotWritable : public BaseException { public: FileNotWritable(const char* file, int line, const char* function, const std::string& filename) noexcept; }; /** @brief Filename is too long to be writable/readable by the filesystem This exception usually occurs when output filenames are automatically generated and are found to be too long. Usually 255 characters is the limit (NTFS, Ext2/3/4,...). @ingroup Exceptions */ class OPENMS_DLLAPI FileNameTooLong : public BaseException { public: FileNameTooLong(const char* file, int line, const char* function, const std::string& filename, int max_length) noexcept; }; /** @brief General IOException. General error for IO operations, that can not be associated to the more specific exceptions (e.g. FileNotWritable) @ingroup Exceptions */ class OPENMS_DLLAPI IOException : public BaseException { public: IOException(const char* file, int line, const char* function, const std::string& filename) noexcept; }; /** @brief SqlOperation failed exception. E.g. when retrieving data from a table using the wrong column name or index. @ingroup Exceptions */ class OPENMS_DLLAPI SqlOperationFailed : public BaseException { public: SqlOperationFailed(const char* file, int line, const char* function, const std::string& description) noexcept; }; /** @brief File is empty. A given file is empty. @ingroup Exceptions */ class OPENMS_DLLAPI FileEmpty : public BaseException { public: FileEmpty(const char* file, int line, const char* function, const std::string& filename) noexcept; }; /** @brief Invalid 3-dimensional position exception. A given position in three dimensional is invalid. @ingroup Exceptions */ class OPENMS_DLLAPI IllegalPosition : public BaseException { public: IllegalPosition(const char* file, int line, const char* function, float x, float y, float z) noexcept; }; /** @brief Parse Error exception. A given expression could not be parsed. @ingroup Exceptions */ class OPENMS_DLLAPI ParseError : public BaseException { public: ParseError(const char* file, int line, const char* function, const std::string& expression, const std::string& message) noexcept; }; /** @brief Unable to create file exception. The given file could not be created. @ingroup Exceptions */ class OPENMS_DLLAPI UnableToCreateFile : public BaseException { public: UnableToCreateFile(const char* file, int line, const char* function, const std::string& filename, const std::string& message = "") noexcept; }; /** @brief Invalid file type exception. The file type specification is not valid. @ingroup Exceptions */ class OPENMS_DLLAPI InvalidFileType : public BaseException { public: InvalidFileType(const char* file, int line, const char* function, const std::string& filename, const std::string& message = "") noexcept; }; /** @brief A method or algorithm argument contains illegal values @ingroup Exceptions */ class OPENMS_DLLAPI IllegalArgument : public BaseException { public: IllegalArgument(const char* file, int line, const char* function, const std::string& error_message) noexcept; }; /** @brief A tool or algorithm which was called internally raised an exception @ingroup Exceptions */ class OPENMS_DLLAPI InternalToolError : public BaseException { public: InternalToolError(const char* file, int line, const char* function, const std::string& error_message) noexcept; }; /** @brief Element could not be found exception. The given element could not be found. @ingroup Exceptions */ class OPENMS_DLLAPI ElementNotFound : public BaseException { public: ElementNotFound(const char* file, int line, const char* function, const std::string& element) noexcept; }; /** @brief Exception used if an error occurred while fitting a model to a given dataset The given element could not be found. @ingroup Exceptions */ class OPENMS_DLLAPI UnableToFit : public BaseException { public: UnableToFit(const char* file, int line, const char* function, const std::string& name, const std::string& message) noexcept; }; /** @brief Exception used if an error occurred while calibrating a dataset. The calibration can not be performed because not enough reference masses were detected. @ingroup Exceptions */ class OPENMS_DLLAPI UnableToCalibrate : public BaseException { public: UnableToCalibrate(const char* file, int line, const char* function, const std::string& name, const std::string& message) noexcept; }; /** @brief Exception used if no more unique document ID's can be drawn from ID pool. The ID pool of OpenMS is either depleted or not existent. @ingroup Exceptions */ class OPENMS_DLLAPI DepletedIDPool : public BaseException { public: DepletedIDPool(const char* file, int line, const char* function, const std::string& name, const std::string& message) noexcept; }; } // namespace Exception /** @brief Output operator for exceptions. All %OpenMS exceptions can be printed to an arbitrary output stream. Information written contains the exception class, the error message, and the location (file, line number). The following code block can thus be used to catch any %OpenMS exceptions and convert them to human readable information: \code try { .... // some code which potentially throws an exception } catch (Exception::Exception e) { Log.error() << "caught exception: " << e << std::endl; } \endcode @ingroup Exceptions */ OPENMS_DLLAPI std::ostream& operator<<(std::ostream& os, const Exception::BaseException& e); } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/CONCEPT/FuzzyStringComparator.h
.h
10,588
352
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Clemens Groepl, Stephan Aiche $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/DATASTRUCTURES/String.h> #include <OpenMS/DATASTRUCTURES/ListUtils.h> #include <map> #include <sstream> namespace OpenMS { namespace Internal { namespace ClassTest { void OPENMS_DLLAPI testStringSimilar(const char * file, int line, const std::string & string_1, const char * string_1_stringified, const std::string & string_2, const char * string_2_stringified); bool OPENMS_DLLAPI isFileSimilar(const std::string &, const std::string &); } } /** @brief Fuzzy comparison of strings, tolerates numeric differences. */ class OPENMS_DLLAPI FuzzyStringComparator { friend void OPENMS_DLLAPI Internal::ClassTest::testStringSimilar( const char * file, int line, const std::string & string_1, const char * string_1_stringified, const std::string & string_2, const char * string_2_stringified); friend bool OPENMS_DLLAPI Internal::ClassTest::isFileSimilar(const std::string &, const std::string &); /// %Internal exception class. struct AbortComparison { }; public: ///@name the fabulous four //@{ /// Constructor FuzzyStringComparator(); /// Destructor virtual ~FuzzyStringComparator(); /// Copy constructor intentionally not implemented FuzzyStringComparator(const FuzzyStringComparator & rhs); /// Assignment operator intentionally not implemented FuzzyStringComparator & operator=(const FuzzyStringComparator & rhs); //@} /// Acceptable relative error (a number >= 1.0) const double & getAcceptableRelative() const; /// Acceptable relative error (a number >= 1.0) void setAcceptableRelative(const double rhs); /// Acceptable absolute difference (a number >= 0.0) const double & getAcceptableAbsolute() const; /// Acceptable absolute difference (a number >= 0.0) void setAcceptableAbsolute(const double rhs); /// White list. If both lines contain the same element from this list, they are skipped over. const StringList & getWhitelist() const; /// White list. If both lines contain the same element from this list, they are skipped over. StringList & getWhitelist(); /// White list. If both lines contain the same element from this list, they are skipped over. void setWhitelist(const StringList & rhs); /// Matched white list. If file 1 contains element 1 and file 2 contains element 2, they are skipped over. void setMatchedWhitelist(const std::vector< std::pair<std::string, std::string> >& rhs); /// Matched white list. If file 1 contains element 1 and file 2 contains element 2, they are skipped over. const std::vector< std::pair<std::string, std::string> >& getMatchedWhitelist() const; /** @brief verbose level - 0 = very quiet mode (absolutely no output) - 1 = quiet mode (no output unless differences detected) - 2 = default (include summary at end) - 3 = continue after errors */ const int & getVerboseLevel() const; /** @brief verbose level - 0 = very quiet mode (absolutely no output) - 1 = quiet mode (no output unless differences detected) - 2 = default (include summary at end) - 3 = continue after errors */ void setVerboseLevel(const int rhs); /** @brief get tab width (for column numbers) */ const int & getTabWidth() const; /** @brief set tab width (for column numbers) */ void setTabWidth(const int rhs); /** @brief get first column (for column numbers) */ const int & getFirstColumn() const; /** @brief set first column (for column numbers) */ void setFirstColumn(const int rhs); /** @brief Log output is written to this destination. The default is std::cout. Use std::ostringstream etc. to save the output in a string. */ std::ostream & getLogDestination() const; /** @brief Log output is written to this destination. The default is std::cout. Use std::ostringstream etc. to save the output in a string. @internal There seems to be an issue with this under Windows, see comment in FuzzyStringComparator_test.cpp */ void setLogDestination(std::ostream & rhs); /** @brief Compare two strings. This compares all lines of the input. @return true in case of no differences found */ bool compareStrings(std::string const & lhs, std::string const & rhs); /** @brief Compare two streams of input. This compares all lines of the input. Intended to be used for file streams. @return true in case of no differences found */ bool compareStreams(std::istream & input_1, std::istream & input_2); /** @brief Simple diff-like application to compare two input files. Numeric differences are tolerated up to a certain ratio or absolute difference. where @param[in] filename_1 first input file @param[in] filename_2 second input file @return true in case of no differences found @sa ratio_max_allowed_ @sa absdiff_max_allowed_ @sa verbose_level_ */ bool compareFiles(const std::string & filename_1, const std::string & filename_2); protected: /** @brief Compare two lines of input. This implements the core functionality. Intended to be used for a single line of input. @return true (non-zero) in case of success */ bool compareLines_(std::string const & line_str_1, std::string const & line_str_2); /// Report good news. void reportSuccess_() const; /// Report bad news. /// @exception AbortComparison void reportFailure_(char const * const message) const; /// Write info about hits in the whitelist void writeWhitelistCases_(const std::string & prefix) const; /// read the next line in input stream, skipping over empty lines /// and lines consisting of whitespace only void readNextLine_(std::istream & input_stream, std::string & line_string, int & line_number) const; /// opens and checks an input file stream std::ifstream bool openInputFileStream_(const std::string & filename, std::ifstream & input_stream) const; /// Log and results output goes here std::ostream * log_dest_; /// Name of first input e.g., filename std::string input_1_name_; /// Name of second input e.g., filename std::string input_2_name_; /// Stores information about the current input line (i.e., stream for the line and the current position in the stream) struct InputLine { std::stringstream line_; std::ios::pos_type line_position_; InputLine(); /// Initialize the input line to the passed string void setToString(const std::string & s); /// Save current position of the stream void updatePosition(); /// Resets the stream to the last saved position void seekGToSavedPosition(); /** @brief Convert to bool The function indicates success when none of the error flags (either failbit or badbit of the nested std::stringstream) are set. @return False on error, true otherwise. */ bool ok() const; }; InputLine input_line_1_; InputLine input_line_2_; int line_num_1_; int line_num_2_; int line_num_1_max_; int line_num_2_max_; std::string line_str_1_max_; std::string line_str_2_max_; /// Maximum ratio of numbers allowed, see @em ratio_max_. double ratio_max_allowed_; /// Maximum ratio of numbers observed so far, see @em ratio_max_allowed_. double ratio_max_; /// Maximum absolute difference of numbers allowed, see @em absdiff_max_. double absdiff_max_allowed_; /// Maximum difference of numbers observed so far, see @em absdiff_max_allowed_. double absdiff_max_; /// Stores information about characters, numbers, and white spaces loaded from the InputStream struct StreamElement_ { double number; unsigned char letter; bool is_number; bool is_space; StreamElement_(); /// reset all elements of the element to default value void reset(); /// Read the next element from an InputLine and update the InputLine accordingly /// The @p str_line contains the same data as the stream, since it saves some forth-and-back conversion internally /// TODO: avoid streams all together (slow, and no random access, required by boost::qi) at some point void fillFromInputLine(InputLine& input_line, const std::string& str_line); }; /// Stores information about characters, numbers, and white spaces loaded from the first input stream StreamElement_ element_1_; /// Stores information about characters, numbers, and white spaces loaded from the second input stream StreamElement_ element_2_; /// Wrapper for the prefix information computed for the failure report struct PrefixInfo_ { OpenMS::String prefix; OpenMS::String prefix_whitespaces; int line_column; PrefixInfo_(const InputLine & input_line, const int tab_width_, const int first_column_); }; bool is_absdiff_small_; int verbose_level_; int tab_width_; int first_column_; /** @brief Has comparison been successful so far? Note: this flag is changed in reportFailure_(); */ bool is_status_success_; /// use a prefix when reporting bool use_prefix_; /// Whitelist StringList whitelist_; /// Occurrences of whitelist entries std::map<String, UInt> whitelist_cases_; /// Alternative Whitelist std::vector< std::pair<std::string, std::string> > matched_whitelist_; }; // class FuzzyStringComparator } //namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/CONCEPT/UniqueIdIndexer.h
.h
6,636
211
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow $ // $Authors: Clemens Groepl $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/CONCEPT/UniqueIdInterface.h> #include <OpenMS/CONCEPT/Exception.h> #ifdef _MSC_VER // disable some BOOST warnings that distract from ours # pragma warning( push ) // save warning state # pragma warning( disable : 4396 ) #endif #include <unordered_map> #include <sstream> #ifdef _MSC_VER # pragma warning( pop ) // restore old warning state #endif namespace OpenMS { /**@brief A base class for containers with elements derived from UniqueIdInterface. * This adds functionality to convert a unique id into an index into the container. * * The derived class needs a data member called @p data_ which holds the actual elements derived from UniqueIdInterface. * This is classical CRTP with the additional requirement that the derived class needs to declare a .getData() member function. * * See FeatureMap and ConsensusMap for living examples. * The RandomAccessContainer returned by .getData() must support operator[], at(), and size(). */ template<typename T> class UniqueIdIndexer { public: typedef std::unordered_map<UInt64, Size> UniqueIdMap; /** @brief Returns the index of the feature with the given unique id, or Size(-1) if none exists in this random access container. The complexity is expected constant upon success, linear upon failure. The lookup actually performs the following steps: - consult the internal hash map (i.e., uniqueid_to_index_) - if an index is found and that element indeed has this unique id, then return the index - if no index is found or the unique ids do not match, then update the hash map (using updateUniqueIdToIndex()) and lookup the index again - if an index is found this time, return it, otherwise return Size(-1) . @note that subordinate elements are not considered here. */ Size uniqueIdToIndex(UInt64 unique_id) const { Size index; try { index = uniqueid_to_index_.at(unique_id); if (getBase_().at(index).getUniqueId() != unique_id) { throw std::out_of_range("unique_id_to_index_"); } } catch (std::out_of_range &) { try { this->updateUniqueIdToIndex(); index = uniqueid_to_index_.at(unique_id); } catch (std::out_of_range &) { index = -1; // which means: invalid } } return index; } /**@brief Updates the hash map from unique id to index. @sa uniqueIdToIndex() */ void updateUniqueIdToIndex() const { Size num_valid_unique_id = 0; // add or update unique id of existing features for (Size index = 0; index < getBase_().size(); ++index) { UInt64 unique_id = getBase_()[index].getUniqueId(); if (UniqueIdInterface::isValid(unique_id)) { uniqueid_to_index_[unique_id] = index; ++num_valid_unique_id; } } // remove invalid or outdated entries uniqueid_to_index_.erase(UniqueIdInterface::INVALID); for (UniqueIdMap::iterator iter = uniqueid_to_index_.begin(); iter != uniqueid_to_index_.end(); /* see loop */) { if (iter->second >= getBase_().size() || getBase_()[iter->second].getUniqueId() != iter->first) { iter = uniqueid_to_index_.erase(iter); } else { ++iter; } } if (uniqueid_to_index_.size() != num_valid_unique_id) { std::stringstream ss; ss << "Duplicate valid unique ids detected! RandomAccessContainer has size()==" << getBase_().size(); ss << ", num_valid_unique_id==" << num_valid_unique_id; ss << ", uniqueid_to_index_.size()==" << uniqueid_to_index_.size(); throw Exception::Postcondition(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, ss.str()); } return; } /** @brief Assign new UID's to doubly occurring UID's Assign new UID's to non-unique UID's. This usually occurs in merging of 'old' feature files, which have sequentially increasing UID's. Conflicting entries receive a new UID, such that all UID's are unique in the container. @note Subordinate features are not checked and may remain non-unique. However, they are associated to their parent which makes identification 'unique'. @return The number of invalid (=replaced) elements */ Size resolveUniqueIdConflicts() { Size invalid_uids(0); uniqueid_to_index_.clear(); // add unique id of existing features for (Size index = 0; index < getBase_().size(); ++index) { UInt64 unique_id = getBase_()[index].getUniqueId(); if (!UniqueIdInterface::isValid(unique_id)) { getBase_()[index].ensureUniqueId(); unique_id = getBase_()[index].getUniqueId(); } // see if UID already present while (uniqueid_to_index_.find(unique_id) != uniqueid_to_index_.end()) // double entry! { getBase_()[index].setUniqueId(); unique_id = getBase_()[index].getUniqueId(); ++invalid_uids; } uniqueid_to_index_[unique_id] = index; } return invalid_uids; } /**@brief Swap. * * @note obviously we can swap only with indices for the same type. */ void swap(UniqueIdIndexer & rhs) { std::swap(uniqueid_to_index_, rhs.uniqueid_to_index_); return; } protected: /**@brief A little helper to get access to the base (!) class RandomAccessContainer. */ const auto& getBase_() const { const T& derived = static_cast<const T&>(*this); // using CRTP return derived.getData(); } /**@brief A little helper to get access to the base (!) class RandomAccessContainer. */ auto& getBase_() { T& derived = static_cast<T&>(*this); // using CRTP return derived.getData(); } /**@brief hash map from unique id to index of features * * This is mutable because the hash map is updated on demand, even if the underlying container is const. */ mutable UniqueIdMap uniqueid_to_index_; }; } //namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/CONCEPT/ProgressLogger.h
.h
3,697
117
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg$ // $Authors: Marc Sturm, Stephan Aiche $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/CONCEPT/Types.h> namespace OpenMS { class String; /** @brief Base class for all classes that want to report their progress. Per default the progress log is disabled. Use setLogType to enable it. Use startProgress, setProgress and endProgress for the actual logging. @note All methods are const, so it can be used through a const reference or in const methods as well! */ class OPENMS_DLLAPI ProgressLogger { public: /// Constructor ProgressLogger(); /// Destructor virtual ~ProgressLogger(); /// Copy constructor ProgressLogger(const ProgressLogger& other); /// Assignment Operator ProgressLogger& operator=(const ProgressLogger& other); /// Possible log types enum LogType { CMD, ///< Command line progress GUI, ///< Progress dialog NONE ///< No progress logging }; /** @brief This class represents an actual implementation of a logger. */ class OPENMS_DLLAPI ProgressLoggerImpl { public: virtual void startProgress(const SignedSize begin, const SignedSize end, const String& label, const int current_recursion_depth) const = 0; virtual void setProgress(const SignedSize value, const int current_recursion_depth) const = 0; virtual SignedSize nextProgress() const = 0; //< does not print/show anything; returns current progress /// finalize; usually stops the clock and prints a summary; /// You may optionally pass the number of bytes read/written to get a MB/sec estimate virtual void endProgress(const int current_recursion_depth, UInt64 bytes_processed = 0) const = 0; virtual ~ProgressLoggerImpl() {} /// Factory requirements }; /// Sets the progress log that should be used. The default type is NONE! void setLogType(LogType type) const; /// Returns the type of progress log being used. LogType getLogType() const; /// @brief Sets the logger to be used for progress logging /// @param[in] logger void setLogger(ProgressLoggerImpl* logger); /** @brief Initializes the progress display Sets the progress range from @p begin to @p end. If @p begin equals @p end, setProgress only indicates that the program is still running, but without showing any absolute progress value. Sets the label to @p label. @note Make sure to call setLogType first! */ void startProgress(SignedSize begin, SignedSize end, const String& label) const; /// Sets the current progress void setProgress(SignedSize value) const; /// Ends the progress display /// You may optionally pass the number of bytes read/written to get a MB/sec estimate (if -1 or 0, it will be ignored) void endProgress(UInt64 bytes_processed = 0) const; /// increment progress by 1 (according to range begin-end) void nextProgress() const; protected: mutable LogType type_; mutable time_t last_invoke_; static int recursion_depth_; mutable ProgressLoggerImpl* current_logger_; }; // Function pointer for injecting the GUI progress logger implementation typedef ProgressLogger::ProgressLoggerImpl* (*MakeGUIProgressLoggerFunc)(); extern OPENMS_DLLAPI MakeGUIProgressLoggerFunc make_gui_progress_logger; } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/CONCEPT/ClassTest.h
.h
52,930
1,083
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Marc Sturm, Clemens Groepl, Chris Bielow, Timo Sachsenberg $ // -------------------------------------------------------------------------- #pragma once // Avoid OpenMS includes here at all costs // When the included headers are changed, *all* tests have to be recompiled! // Use the ClassTest class if you need add high-level functionality. // Includes in ClassTest.cpp are ok... #include <OpenMS/CONCEPT/PrecisionWrapper.h> #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/DATASTRUCTURES/DataValue.h> #include <OpenMS/CONCEPT/MacrosTest.h> #include <OpenMS/OpenMSConfig.h> #include <OpenMS/config.h> #include <cstring> #include <iostream> #include <string> #include <vector> #include <type_traits> using XMLCh = char16_t; // Xerces-C++ uses char16_t for UTF-16 strings that we need to output in tests // Empty declaration to avoid problems in case the namespace is not // yet defined (e.g. TEST/ClassTest_test.cpp) /// Provide a point of redirection for testing the test macros, see ClassTest_test.cpp #ifndef stdcout #define stdcout std::cout #endif namespace OpenMS { namespace Internal { /// Namespace for class tests namespace ClassTest { /** @brief Validates the given files against the XML schema (if available) @return If all files passed the validation */ bool OPENMS_DLLAPI validate(const std::vector<std::string>& file_names); /// Creates a temporary file name from the test name and the line with the specified extension std::string OPENMS_DLLAPI createTmpFileName(const std::string& file, int line, const std::string& extension = ""); /// This overload returns true; @c float is a floating point type. inline bool OPENMS_DLLAPI isRealType(float) { return true; } /// This overload returns true; @c double is a floating point type. inline bool OPENMS_DLLAPI isRealType(double) { return true; } /// This overload returns true; @c long @c double is a floating point type. inline bool OPENMS_DLLAPI isRealType(long double) { return true; } /// This overload returns true; @c ParamValue will be converted to double by #TEST_REAL_SIMILAR. inline bool OPENMS_DLLAPI isRealType(const ParamValue&) { return true; } /// This overload returns true; @c DataValue will be converted to double by #TEST_REAL_SIMILAR. inline bool OPENMS_DLLAPI isRealType(const DataValue&) { return true; } /// This catch-all template returns false; it will be instantiated for non-floating point types. template <typename T> inline bool isRealType(const T&) { return false; } /** @brief Compare floating point numbers using @em absdiff_max_allowed and @em ratio_max_allowed. Side effects: Updates #fuzzy_message. */ void OPENMS_DLLAPI testRealSimilar(const char* file, int line, long double number_1, const char* number_1_stringified, bool number_1_is_realtype, Int number_1_written_digits, long double number_2, const char* number_2_stringified, bool /* number_2_is_realtype */, Int number_2_written_digits); /// used by testRealSimilar() bool OPENMS_DLLAPI isRealSimilar(long double number_1, long double number_2); /**@brief Compare strings using @em absdiff_max_allowed and @em ratio_max_allowed. This is called by the #TEST_STRING_SIMILAR macro. Side effects: Updates #absdiff, #ratio, #fuzzy_message, #line_num_1_max and #line_num_2_max. */ void OPENMS_DLLAPI testStringSimilar(const char* file, int line, const std::string& string_1, const char* string_1_stringified, const std::string& string_2, const char* string_2_stringified); /// used by TEST_STRING_EQUAL void OPENMS_DLLAPI testStringEqual(const char* file, int line, const std::string& string_1, const char* string_1_stringified, const std::string& string_2, const char* string_2_stringified); /**@brief Compare files using @em absdiff_max_allowed and @em ratio_max_allowed. Side effects: Updates #absdiff, #ratio, #fuzzy_message, #line_num_1_max and #line_num_2_max. */ bool OPENMS_DLLAPI isFileSimilar(const std::string& filename_1, const std::string& filename_2); /// make sure we have a newline before results from first subtest void OPENMS_DLLAPI initialNewline(); /// print the text, each line gets a prefix, the marked line number gets a special prefix void OPENMS_DLLAPI printWithPrefix(const std::string& text, const int marked = -1); /** @brief Set up some classtest variables as obtained from the 'START_TEST' macro and check that no additional arguments were passed to the test executable. @param[in] version A version string, obtained from 'START_TEST(FuzzyStringComparator, "<VERSION>")' @param[in] class_name The class under test (used for error messages etc), obtained from 'START_TEST(FuzzyStringComparator, "<VERSION>")' @param[in] argc The number of arguments to the main() function of the class test (must be 1; test will quit otherwise) @param[in] argv0 Name of the executable (for debug output) */ void OPENMS_DLLAPI mainInit(const char* version, const char* class_name, int argc, const char* argv0); /** @brief Test if two files are exactly equal (used in TEST_FILE_EQUAL macro) @param[in] line The line where the macro was called (for reporting) @param[in] filename The temp file @param[in] templatename The ground truth file @param[in] filename_stringified The expression used as the first macro argument @param[in] templatename_stringified The expression used as the second macro argument */ void OPENMS_DLLAPI filesEqual(int line, const char* filename, const char* templatename, const char* filename_stringified, const char* templatename_stringified); /// removed all temporary files created with the NEW_TMP_FILE macro void OPENMS_DLLAPI removeTempFiles(); /// set the whitelist_ void OPENMS_DLLAPI setWhitelist(const char* const /* file */, const int line, const std::string& whitelist); /// Maximum ratio of numbers allowed, see #TOLERANCE_RELATIVE. extern OPENMS_DLLAPI double ratio_max_allowed; /// Maximum ratio of numbers observed so far, see #TOLERANCE_RELATIVE. extern OPENMS_DLLAPI double ratio_max; /// Recent ratio of numbers, see #TOLERANCE_RELATIVE. extern OPENMS_DLLAPI double ratio; /// Maximum absolute difference of numbers allowed, see #TOLERANCE_ABSOLUTE. extern OPENMS_DLLAPI double absdiff_max_allowed; /// Maximum difference of numbers observed so far, see #TOLERANCE_ABSOLUTE. extern OPENMS_DLLAPI double absdiff_max; /// Recent absolute difference of numbers, see #TOLERANCE_ABSOLUTE. extern OPENMS_DLLAPI double absdiff; extern OPENMS_DLLAPI int line_num_1_max; extern OPENMS_DLLAPI int line_num_2_max; /// Verbosity level ( "-v" is 1 and "-V" is 2 ) extern OPENMS_DLLAPI int verbose; /// Status of the whole test extern OPENMS_DLLAPI bool all_tests; /// Status of the current subsection extern OPENMS_DLLAPI bool test; /// Status of last elementary test extern OPENMS_DLLAPI bool this_test; /// (Used by various macros. Indicates a rough category of the exception being caught.) extern OPENMS_DLLAPI int exception; /// (Used by various macros. Stores the "name" of the exception, if applicable.) extern OPENMS_DLLAPI std::string exception_name; /// (Used by various macros. Stores the "message" of the exception, if applicable.) extern OPENMS_DLLAPI std::string exception_message; /// Name of current subsection extern OPENMS_DLLAPI std::string test_name; /// Line where current subsection started extern OPENMS_DLLAPI int start_section_line; /// Line of current elementary test extern OPENMS_DLLAPI int test_line; /// Version string supplied with #START_TEST extern OPENMS_DLLAPI const char* version_string; /// List of tmp file names (these will be cleaned up, see #NEW_TMP_FILE) extern OPENMS_DLLAPI std::vector<std::string> tmp_file_list; /// List of all failed lines for summary at the end of the test extern OPENMS_DLLAPI std::vector<UInt> failed_lines_list; /// Questionable file tested by #TEST_FILE_EQUAL extern OPENMS_DLLAPI std::ifstream infile; /// Template (correct) file used by #TEST_FILE_EQUAL extern OPENMS_DLLAPI std::ifstream templatefile; /// (A variable used by #TEST_FILE_EQUAL) extern OPENMS_DLLAPI bool equal_files; /// (A buffer for one line from a file. Used by #TEST_FILE_EQUAL.) extern OPENMS_DLLAPI char line_buffer[65536]; /// Counter for the number of elementary tests within the current subsection. extern OPENMS_DLLAPI int test_count; /// See #ADD_MESSAGE. extern OPENMS_DLLAPI std::string add_message; /**@brief Last message from a fuzzy comparison. Written by #isRealSimilar(), #testStringSimilar(), #isFileSimilar(). Read by #TEST_REAL_SIMILAR, #TEST_STRING_SIMILAR, #TEST_FILE_SIMILAR; */ extern OPENMS_DLLAPI std::string fuzzy_message; /// (Flags whether a new line is in place, depending on context and verbosity setting. Used by initialNewline() and some macros.) extern OPENMS_DLLAPI bool newline; template <typename T1, typename T2> void testEqual(const char* /*file*/, int line, const T1& expression_1, const char* expression_1_stringified, const T2& expression_2, const char* expression_2_stringified) { ++test_count; test_line = line; this_test = bool(expression_1 == T1(expression_2)) ; test &= this_test; { initialNewline(); if (!this_test || verbose > 1) { stdcout << ' ' << (this_test ? '+' : '-') << " line " << line << " : TEST_EQUAL(" << expression_1_stringified << ',' << expression_2_stringified << "): got '"; // we can't print wide chars directly using operator<< so we need to test for it if constexpr (std::is_same_v<std::remove_cv_t<T1>, XMLCh*> || std::is_same_v<std::remove_cv_t<T2>, XMLCh*>) { stdcout << (expression_1 == nullptr ? "(null)" : "(XMLCh*)") << "', expected '" << (expression_2 == nullptr ? "(null)" : "(XMLCh*)") << "'\n"; } else if constexpr (std::is_enum_v<T1> && std::is_enum_v<T2>) { stdcout << static_cast<int>(expression_1) << "', expected '" << static_cast<int>(expression_2) << "'\n"; } else { stdcout << expression_1 << "', expected '" << expression_2 << "'\n"; } } if (!this_test) { failed_lines_list.push_back(line); } } } void testTrue(const char* /*file*/, int line, const bool expression_1, const char* expression_1_stringified) { ++test_count; test_line = line; this_test = expression_1; test &= this_test; { initialNewline(); if (this_test) { if (verbose > 1) { stdcout << " + line " << line << ": TEST_TRUE(" << expression_1_stringified << "): ok\n"; } } else { stdcout << " - line " << line << ": TEST_TRUE(" << expression_1_stringified << "): failed\n"; failed_lines_list.push_back(line); } } } void testFalse(const char* /*file*/, int line, const bool expression_1, const char* expression_1_stringified) { ++test_count; test_line = line; this_test = !expression_1; test &= this_test; { initialNewline(); if (this_test) { if (verbose > 1) { stdcout << " + line " << line << ": TEST_FALSE(" << expression_1_stringified << "): ok\n"; } } else { stdcout << " - line " << line << ": TEST_FALSE(" << expression_1_stringified << "): failed\n"; failed_lines_list.push_back(line); } } } template <typename T1, typename T2> void testNotEqual(const char* /*file*/, int line, const T1& expression_1, const char* expression_1_stringified, const T2& expression_2, const char* expression_2_stringified) { ++test_count; test_line = line; this_test = !(expression_1 == T1(expression_2)); test &= this_test; { initialNewline(); if (!this_test || verbose > 1) { stdcout << ' ' << (this_test ? '+' : '-') << " line " << line << " : TEST_NOT_EQUAL(" << expression_1_stringified << ',' << expression_2_stringified << "): got '"; if constexpr (std::is_enum_v<T1> && std::is_enum_v<T2>) { stdcout << static_cast<int>(expression_1) << "', forbidden is '" << static_cast<int>(expression_2) << "'\n"; } else { stdcout << expression_1 << "', expected '" << expression_2 << "'\n"; } } if (!this_test) { failed_lines_list.push_back(line); } } } void OPENMS_DLLAPI printLastException(std::ostream& out); int OPENMS_DLLAPI endTestPostProcess(std::ostream& out); void OPENMS_DLLAPI endSectionPostProcess(std::ostream& out, const int line); } } } // A namespace alias - apparently these cannot be documented using doxygen (?) namespace TEST = OpenMS::Internal::ClassTest; /** @defgroup ClassTest Class test macros @brief These macros are used by the test programs in the subdirectory <code>OpenMS/source/TEST</code>. On successful operation the test program will print out the message "PASSED", otherwise "FAILED". If called with the @b -v option, the test program prints verbose information about subsections. If called with the @b -V option, the test program prints even more verbose information for every elementary test. The implementation is done in namespace #OpenMS::Internal::ClassTest. To create a test, follow the guidelines in @ref developer_faq (section "How to add a new class test"). Look at existing test files in src/tests/class_tests/ for examples. @ingroup Concept */ //@{ //@name test and subtest //@{ /** @brief Begin of the test program for a given class. @sa #END_TEST. The #START_TEST macro defines the start of the test program for a given classname. The classname is printed together with some information when calling the test program with any arguments (except for <code>-v</code> or <code>-V</code>). The second argument version should take the form "$Id:$" but is currently deprecated. Originally, the SVN revision was annotated by the revision control system. The #START_TEST macro should be the first one to call in a test program. It opens a global <code>try</code> block to catch any unwanted exceptions. If any of these exceptions occurs, all tests fail. Exceptions defined by %OpenMS (i.e. exception classes derived from Exception::BaseException) provide some additional information that is evaluated by the #END_TEST macro. The #END_TEST macro also closes the <code>try</code> block. This <code>try</code> block should never catch an exception! All exceptions that are thrown due to some malfunction in one of the member functions should be caught by the <code>try</code> block created by #START_SECTION and #END_SECTION . @hideinitializer */ #define START_TEST(class_name, version) \ int main(int argc, char** argv) \ { \ TEST::mainInit(version, #class_name, argc, argv[0]); \ try { /** @brief End of the test program for a class. @sa #START_TEST. The #END_TEST macro implements the correct termination of the test program and should therefore be the last macro to call. It determines the exit code based on all previously run subtests and prints out the message "PASSED" or "FAILED". This macro also closes the global <code>try</code> block opened by #START_TEST and contains the related <code>catch</code> clauses. If an exception is caught here, the test program fails. @hideinitializer */ #define END_TEST \ /* global try block */ \ } \ catch (...) \ { \ TEST::printLastException(stdcout); \ } \ return TEST::endTestPostProcess(stdcout); \ } /** @brief Begin of a subtest with a given name. @sa #END_SECTION. The #START_SECTION macro is used to declare the name of a subtest. Use this to examine a member function of the class which was specified in #START_TEST. If you want to check e.g. the memFunc() method of a class, insert a line #START_SECTION(memFunc()) in your test program. If the test program is called in verbose mode, this leads to the name of the subtest being printed on execution. If you are testing a non-public method you can use the [EXTRA] statement, e.g. #START_SECTION([EXTRA]memFunc()) to indicate this. Otherwise you will trigger a warning by %OpenMS/tools/checker.php due to this unexpected subtest. This macro also opens a <code>try</code> block to catch any unexpected exceptions thrown in the course of a subtest. To catch <em>wanted</em> exceptions (i.e. to check for exceptions that are the expected result of some command) use the #TEST_EXCEPTION macro. The <code>try</code> block opened by #START_SECTION is closed in #END_SECTION, so these two macros have to be balanced. @hideinitializer */ #define START_SECTION(name_of_test) \ TEST::test = true; \ TEST::newline = false; \ TEST::test_name = # name_of_test; \ TEST::test_count = 0; \ TEST::start_section_line = __LINE__; \ stdcout << "checking " << TEST::test_name << " ... " << std::flush; \ try \ { \ while (true) \ { /** @brief End of a subtest. @sa #START_SECTION. The #END_SECTION macro defines the end of a subtest. Each elementary test macro updates an internal variable (TEST::test) that holds the state of the current subtest. #END_SECTION prints whether the subtest has passed or failed (in verbose mode) and updates the internal variables <b>TEST::all_tests</b> that describes the state of the whole class test. <b>TEST::all_tests</b> is initialized to be <b>true</b>. If any elementary test fails, <b>TEST::test</b> becomes <b>false</b>. At the time of the next call to #END_SECTION, <b>TEST::all_tests</b> will be set to false, if <b>TEST::test</b> is false. One failed elementary test leads therefore to a failed subtest, which leads to a failed class test. This macro closes the <code>try</code> block opened by #START_SECTION, so #START_SECTION and #END_SECTION have to be balanced, or some ugly compile-time errors will occur. #END_SECTION first tries to catch all <code>OpenMS::Exception</code>s (i.e. exceptions derived from OpenMS::Exception::BaseException). If this fails, it tries to catch any exception. After the exception is caught, the execution will continue with the next subtest, but the current subtest is marked as failed (as is the whole test program). @hideinitializer */ #define END_SECTION \ break; \ } \ } \ catch (...) \ { \ TEST::printLastException(stdcout);\ } \ TEST::endSectionPostProcess(stdcout, __LINE__); //@} /** @brief Generic equality macro. This macro uses the operator == to check its two arguments for equality. Besides handling some internal stuff, it basically evaluates ((a) == (b)). Remember that operator == has to be defined somehow for the two argument types. Additionally the << operator needs to be defined. If only == is available you will get a compilation error. As workaround use TEST_EQUAL(a==b, true) thereby making bug tracing harder, as you won't see the values of a and b. @note This macro evaluates its arguments once or twice, depending on verbosity settings. @param[in] a value/object to test @param[in] b expected value @hideinitializer */ #define TEST_EQUAL(a, b) TEST::testEqual(__FILE__, __LINE__, (a), (# a), (b), (# b)); /** @brief Boolean test macro. This macro tests if its argument evaluates to 'true'. If possible use TEST_EQUAL(a, b) instead of TEST_TRUE(a==b), because the latter makes bug tracing harder. @param[in] a value/object convertible to bool @hideinitializer */ #define TEST_TRUE(a) TEST::testTrue(__FILE__, __LINE__, (a), (#a)); /** @brief Boolean test macro. This macro tests if its argument evaluates to 'false'. If possible use TEST_NOT_EQUAL(a, b) instead of TEST_FALSE(a!=b), because the latter makes bug tracing harder. @param[in] a value/object convertible to bool @hideinitializer */ #define TEST_FALSE(a) TEST::testFalse(__FILE__, __LINE__, (a), (#a)); /** @brief Generic inequality macro. This macro checks for inequality just like #TEST_EQUAL tests for equality. The only difference between the two macros is that #TEST_NOT_EQUAL evaluates !((a) == (b)). @param[in] a value/object to test @param[in] b forbidden value @hideinitializer */ #define TEST_NOT_EQUAL(a, b) TEST::testNotEqual(__FILE__, __LINE__, (a), (# a), (b), (# b)); /** @brief String equality macro. Both arguments are converted to std::string and tested for equality. (That is, we check whether <code>(std::string(a) == std::string(b))</code> holds.) @note This macro evaluates its arguments once or twice, depending on verbosity settings. @param[in] a value to test @param[in] b expected value @hideinitializer */ #define TEST_STRING_EQUAL(a, b) TEST::testStringEqual(__FILE__, __LINE__, (a), (# a), (b), (# b)); /** @brief File comparison macro. This macro is used to test file operations. It compares the file with name <code>filename</code> against a template file <code>templatename</code>. Corresponding lines of the two files have to be identical. @note line length is limited to 64k characters @note This macro evaluates its arguments once or twice, depending on verbosity settings. @hideinitializer */ #define TEST_FILE_EQUAL(filename, templatename) \ { \ TEST::filesEqual(__LINE__, filename, templatename, #filename, #templatename); \ } /** @brief Floating point similarity macro. Checks whether the two numbers are sufficiently close based upon the settings of #TOLERANCE_ABSOLUTE and #TOLERANCE_RELATIVE. @note This macro evaluates its arguments once or twice, depending on verbosity settings. @note Both arguments are converted to @c double. The actual comparison is done by isRealSimilar(). @param[in] a value to test @param[in] b expected value @hideinitializer */ #define TEST_REAL_SIMILAR(a, b) TEST::testRealSimilar(__FILE__, __LINE__, (a), (# a), TEST::isRealType(a), writtenDigits(a), (b), (# b), TEST::isRealType(b), writtenDigits(b)); /** @brief String similarity macro. Compares the two strings using @em FuzzyStringComparator with the settings of #TOLERANCE_ABSOLUTE and #TOLERANCE_RELATIVE. @note This macro evaluates its arguments once or twice, depending on verbosity settings. @note Both arguments are converted to @c std::string. The actual comparison is done by testStringSimilar(). @param[in] a value to test @param[in] b expected value @hideinitializer */ #define TEST_STRING_SIMILAR(a, b) TEST::testStringSimilar(__FILE__, __LINE__, (a), (# a), (b), (# b)); /** @brief File similarity macro. Compares the two files using @em FuzzyStringComparator with the settings of #TOLERANCE_ABSOLUTE and #TOLERANCE_RELATIVE. @note This macro evaluates its arguments once or twice, depending on verbosity settings. @note The actual comparison is done by isFileSimilar(). @param[in] a value to test @param[in] b expected value @hideinitializer */ #define TEST_FILE_SIMILAR(a, b) \ { \ ++TEST::test_count; \ TEST::test_line = __LINE__; \ TEST::this_test = TEST::isFileSimilar((a), (b)); \ TEST::test = TEST::test && TEST::this_test; \ { \ TEST::initialNewline(); \ if (TEST::this_test) \ { \ if (TEST::verbose > 1) \ { \ stdcout << " + line " << __LINE__ \ << ": TEST_FILE_SIMILAR(" # a "," # b "): absolute: " \ << precisionWrapper(TEST::absdiff) \ << " (" \ << precisionWrapper(TEST::absdiff_max_allowed) \ << "), relative: " \ << precisionWrapper(TEST::ratio) \ << " (" \ << precisionWrapper(TEST::ratio_max_allowed) \ << ")\n"; \ stdcout << "message: \n"; \ stdcout << TEST::fuzzy_message; \ } \ } \ else \ { \ stdcout << " - line " << TEST::test_line << \ ": TEST_FILE_SIMILAR(" # a "," # b ") ... -\n"; \ stdcout << "message: \n"; \ stdcout << TEST::fuzzy_message; \ TEST::failed_lines_list.push_back(TEST::test_line); \ } \ } \ } /** @brief Define the relative tolerance for floating point comparisons. @sa #TEST_REAL_SIMILAR, #TEST_STRING_SIMILAR, #TEST_FILE_SIMILAR Several macros consider two numbers sufficiently "close" if <b>the ratio of the larger and the smaller</b> is bounded by the value supplied by #TOLERANCE_RELATIVE. The default value is @f$ 1 + 10^{-5} @f$. It is possible to redefine the relative tolerance by calling #TOLERANCE_RELATIVE with the new value. @hideinitializer */ #define TOLERANCE_RELATIVE(a) \ TEST::ratio_max_allowed = (a); \ { \ TEST::initialNewline(); \ if (TEST::verbose > 1) \ { \ stdcout << " + line " << __LINE__ << \ ": TOLERANCE_RELATIVE(" << TEST::ratio_max_allowed << \ ") (\"" # a "\")\n"; \ } \ } /** @brief Define the absolute tolerance for floating point comparisons. @sa #TEST_REAL_SIMILAR, #TEST_STRING_SIMILAR, #TEST_FILE_SIMILAR Several macros consider two numbers sufficiently "close" if <b>the absolute difference</b> is bounded by the value supplied by #TOLERANCE_ABSOLUTE. The default value is @f$ 10^{-5} @f$. It is possible to redefine the absolute tolerance by calling #TOLERANCE_ABSOLUTE with the new value. @hideinitializer */ #define TOLERANCE_ABSOLUTE(a) \ TEST::absdiff_max_allowed = (a); \ { \ TEST::initialNewline(); \ if (TEST::verbose > 1) \ { \ stdcout << " + line " << __LINE__ << \ ": TOLERANCE_ABSOLUTE(" << TEST::absdiff_max_allowed << \ ") (\"" # a "\")\n"; \ } \ } /** @brief Define the whitelist_ used by #TEST_STRING_SIMILAR and #TEST_FILE_SIMILAR. If both lines contain the same element from this list, they are skipped over. (See @em FuzzyStringComparator.) */ #define WHITELIST(a) TEST::setWhitelist(__FILE__, __LINE__, (a)); /** @brief Exception test macro. This macro checks if a given type of exception occurred while executing the given command. Example: #TEST_EXCEPTION(Exception::IndexOverflow, vector[-1]). If no or a wrong exception occurred, false is returned, otherwise true. @param[in] exception_type the exception-class @param[in] command any general C++ or OpenMS-specific command @hideinitializer */ #define TEST_EXCEPTION(exception_type, command) \ { \ ++TEST::test_count; \ TEST::test_line = __LINE__; \ TEST::exception = 0; \ try \ { \ command; \ } \ catch (exception_type&) \ { \ TEST::exception = 1; \ } \ catch (::OpenMS::Exception::BaseException& e) \ { \ TEST::exception = 2; \ TEST::exception_name = e.getName(); \ } \ catch (const std::exception& e) \ { \ TEST::exception = 3; \ TEST::exception_name = e.what(); \ } \ catch (...) \ { \ TEST::exception = 4; \ } \ TEST::this_test = (TEST::exception == 1); \ TEST::test = TEST::test && TEST::this_test; \ { \ TEST::initialNewline(); \ switch (TEST::exception) \ { \ case 0: \ stdcout << " - line " << TEST::test_line << \ ": TEST_EXCEPTION(" # exception_type "," # command \ "): no exception thrown!\n"; \ TEST::failed_lines_list.push_back(TEST::test_line); \ break; \ case 1: \ if (TEST::verbose > 1) \ { \ stdcout << " + line " << TEST::test_line << \ ": TEST_EXCEPTION(" # exception_type "," # command \ "): OK\n"; \ } \ break; \ case 2: \ stdcout << " - line " << TEST::test_line << \ ": TEST_EXCEPTION(" # exception_type "," # command \ "): wrong exception thrown! \"" \ << TEST::exception_name << "\"\n"; \ TEST::failed_lines_list.push_back(TEST::test_line); \ break; \ case 3: \ stdcout << " - line " << TEST::test_line << \ ": TEST_EXCEPTION(" # exception_type "," # command \ "): wrong exception thrown! \"" \ << TEST::exception_name << "\"\n"; \ TEST::failed_lines_list.push_back(TEST::test_line); \ break; \ case 4: \ stdcout << " - line " << TEST::test_line << \ ": TEST_EXCEPTION(" # exception_type "," # command \ "): wrong exception thrown!\n"; \ TEST::failed_lines_list.push_back(TEST::test_line); \ break; \ } \ } \ } /** @brief Precondition test macro This macro checks if a precondition violation is detected while executing the command, similar to <code>TEST_EXCEPTION(Exception::Precondition,command)</code>. However the test is executed only when the #OPENMS_PRECONDITION macros are active, i.e., when compiling in Debug mode. (See Macros.h) @param[in] command any general C++ or OpenMS-specific command @hideinitializer */ #ifdef OPENMS_ASSERTIONS #define TEST_PRECONDITION_VIOLATED(command) TEST_EXCEPTION(Exception::Precondition, command); #else #define TEST_PRECONDITION_VIOLATED(command) STATUS("TEST_PRECONDITION_VIOLATED(" # command ") - skipped"); #endif /** @brief Postcondition test macro This macro checks if a postcondition violation is detected while executing the command, similar to <code>TEST_EXCEPTION(Exception::Postcondition,command)</code>. However the test is executed only when the #OPENMS_POSTCONDITION macros are active, i.e., when compiling in Debug mode. (See Macros.h) @param[in] command any general C++ or OpenMS-specific command @hideinitializer */ #ifdef OPENMS_ASSERTIONS #define TEST_POSTCONDITION_VIOLATED(command) TEST_EXCEPTION(Exception::Postcondition, command); #else #define TEST_POSTCONDITION_VIOLATED(command) STATUS("TEST_POSTCONDITION_VIOLATED(" # command ") - skipped"); #endif /** @brief Exception test macro (with test for exception message). This macro checks if a given type of exception occurred while executing the given command and additionally tests for the message of the exception. Example: #TEST_EXCEPTION_WITH_MESSAGE(Exception::IndexOverflow, vector[-1], "a null pointer was specified") If no, a wrong exception occurred or a wrong message is returned, false is returned, otherwise true. @param[in] exception_type the exception-class @param[in] command any general C++ or OpenMS-specific command @param[in] message the message the exception should give @hideinitializer */ #define TEST_EXCEPTION_WITH_MESSAGE(exception_type, command, message) \ { \ ++TEST::test_count; \ TEST::test_line = __LINE__; \ TEST::exception = 0; \ try \ { \ command; \ } \ catch (exception_type& et) \ { \ if (std::string(et.what()) != std::string(message)) \ { \ TEST::exception = 4; \ TEST::exception_message = et.what(); \ } \ else TEST::exception = 1; \ } \ catch (::OpenMS::Exception::BaseException& e) \ { \ TEST::exception = 2; \ TEST::exception_name = e.getName(); \ } \ catch (...) \ { \ TEST::exception = 3; \ } \ TEST::this_test = (TEST::exception == 1); \ TEST::test = TEST::test && TEST::this_test; \ \ { \ TEST::initialNewline(); \ switch (TEST::exception) \ { \ case 0: \ stdcout << " - line " << TEST::test_line << \ ": TEST_EXCEPTION_WITH_MESSAGE(" # exception_type "," # command ", " # message \ "): no exception thrown!\n"; \ TEST::failed_lines_list.push_back(TEST::test_line); \ break; \ case 1: \ if (TEST::verbose > 1) \ { \ /* this is actually what we want to get: */ \ stdcout << " + line " << TEST::test_line << \ ": TEST_EXCEPTION_WITH_MESSAGE(" # exception_type "," # command ", " # message \ "): OK\n"; \ } \ break; \ case 2: \ stdcout << " - line " << TEST::test_line << \ ": TEST_EXCEPTION_WITH_MESSAGE(" # exception_type "," # command ", " # message \ "): wrong exception thrown! \"" << \ TEST::exception_name << "\"\n"; \ TEST::failed_lines_list.push_back(TEST::test_line); \ break; \ case 3: \ stdcout << " - line " << TEST::test_line << \ ": TEST_EXCEPTION_WITH_MESSAGE(" # exception_type "," # command ", " # message \ "): wrong exception thrown!\n"; \ TEST::failed_lines_list.push_back(TEST::test_line); \ break; \ case 4: \ stdcout << " - line " << TEST::test_line << \ ": TEST_EXCEPTION_WITH_MESSAGE(" # exception_type "," # command ", " # message \ "): exception has wrong message: got '" << \ TEST::exception_message << \ "', expected '" << \ (message) << "'\n"; \ TEST::failed_lines_list.push_back(TEST::test_line); \ break; \ } \ } \ } /** @brief Create a temporary filename. This macro assigns a new temporary filename to the string variable given as its argument. The filename is created using the filename of the test and the line number where this macro is invoked, for example 'Matrix_test.cpp' might create a temporary file 'Matrix_test_268.tmp' if NEW_TMP_FILE is used in line 268. All temporary files are deleted if #END_TEST is called. @p filename string will contain the filename on completion of the macro. There is a version that defines the extension and one that uses tmp. @hideinitializer */ #define NEW_TMP_FILE_EXT(filename, extension) filename = TEST::createTmpFileName(__FILE__, __LINE__, extension); #define NEW_TMP_FILE(filename) filename = TEST::createTmpFileName(__FILE__, __LINE__); /** @brief Skip the remainder of the current subtest. If the condition is not fulfilled, the remainder of the current subtest is skipped over. The TEST status is set to FAIL. @hideinitializer */ #define ABORT_IF(condition) \ if (condition) \ { \ { \ TEST::test_line = __LINE__; \ TEST::this_test = false; \ TEST::test = TEST::test && TEST::this_test; \ TEST::failed_lines_list.push_back(TEST::test_line); \ TEST::initialNewline(); \ stdcout << " - line " << TEST::test_line << \ ": ABORT_IF(" # condition "): TEST ABORTED\n"; \ } \ break; \ } /** @brief Print a status message. If tests require longer preparations, #STATUS may be used to print some intermediate progress messages. #STATUS uses <code>cout</code> to print these messages (in verbose mode only). The given stream expression <code>message</code> is prefixed by the string <code>status:</code> and terminated with a newline. All valid operations on a stream may be performed in <code>message</code>. <b>Example:</b> <code> STATUS( "just calculated x = " << precisionWrapper(x) ) </code> @hideinitializer */ #define STATUS(message) \ { \ TEST::initialNewline(); \ stdcout << " line " \ << __LINE__ \ << ": status: " \ << message \ << "\n"; \ } /** @brief Sets an additional text that is displayed after final result of the test. This can be used to provide additional information about the test to the user. It is e.g. used to indicate that the DB test were skipped, when there are no credentials given. @hideinitializer */ #define ADD_MESSAGE(message) \ TEST::add_message = message; /** @brief Macro that suppresses the warning issued when no subtests are performed Please use this macro only if the method cannot be tested at all or cannot be tested properly on its own. In the later case, the method must however be tested in tests of related methods. See also @em test_count. @hideinitializer */ #define NOT_TESTABLE \ TEST::test_count = 1; //@} // end of ClassTest
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/CONCEPT/Helpers.h
.h
1,970
79
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Hannes Roest $ // -------------------------------------------------------------------------- #pragma once #include <memory> #include <vector> namespace OpenMS { namespace Helpers { /** @brief Helper function to add constness to a vector of shared pointers */ template <class T> const std::vector<std::shared_ptr<const T> >& constifyPointerVector(const std::vector<std::shared_ptr<T> >& vec) { return reinterpret_cast<const std::vector<std::shared_ptr<const T> >&>(vec); } /** * @brief Helper comparing two pointers for equality (taking NULL into account) */ template <class PtrType> inline bool cmpPtrSafe(const PtrType& a, const PtrType& b) { // We are not interested whether the pointers are equal but whether the // contents are equal if (a == nullptr && b == nullptr) { return true; } else if (a == nullptr || b == nullptr) { return false; // one is null the other is not } else { // compare the internal object return (*a == *b); } } /** * @brief Helper function to compare two pointer-containers for equality of all elements */ template <class ContainerType> inline bool cmpPtrContainer(const ContainerType& a, const ContainerType& b) { if (a.size() != b.size()) return false; // check that all elements of a and b are equal using safe comparison // (taking NULL into account) for (typename ContainerType::size_type i = 0; i < a.size(); i++) { if (!cmpPtrSafe(a[i], b[i])) { return false; } } return true; } } }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/CONCEPT/RAIICleanup.h
.h
1,008
44
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow $ // $Authors: Chris Bielow $ // -------------------------------------------------------------------------- #pragma once #include <functional> namespace OpenMS { /** @brief Exception-safe way of executing arbitrary code at the end of a scope. Just pass in a (capturing) lambda function, which will be called upon destruction of an instance of this class. */ class RAIICleanup { public: /// no default CTor; we need a lambda RAIICleanup() = delete; /// pass in any lambda you like which does the cleanup at the end RAIICleanup(std::function<void()> l) : l_(l) {} ~RAIICleanup() { l_(); } private: std::function<void()> l_; ///< called upon destruction }; } // namespace OPENMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/CONCEPT/Constants.h
.h
22,811
635
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg$ // $Authors: Marc Sturm $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/config.h> #include <string> /** @brief Main %OpenMS namespace. In this namespace all the main %OpenMS classes are located. */ namespace OpenMS { /** @brief Mathematical and physical constants namespace. This namespace contains definitions for some basic mathematical and physical constants. All constants are double precision. <BR> There are basically two ways of accessing these constants: <UL> <LI> specify all namespaces: <BR> <tt>double my_pi = OpenMS::Constants::PI</tt> <BR> <LI>shortcut via the <tt>using directive</tt>: <BR> <tt>using namespace OpenMS::Constants; <BR> double my_pi = PI;</tt> </UL> @ingroup Concept */ namespace Constants { /** @name Mathematical constants. */ //@{ /// PI inline const double PI = 3.14159265358979323846; /// Euler's number - base of the natural logarithm inline const double E = 2.718281828459045235; /** Internal threshold for equality comparisons. Default value is 1e-6. */ inline double EPSILON = 1e-6; //@} /** @name Chemical/physical constants. */ //@{ /** Elementary charge. In units of C (\f$1.60217738 \cdot 10^{-19} C\f$). */ inline const double ELEMENTARY_CHARGE = 1.60217738E-19; // C /// Elementary charge (alias) inline const double e0 = ELEMENTARY_CHARGE; /** Electron mass. In units of kg (\f$9.1093897 \cdot 10^{-31}\f$ kg). */ inline const double ELECTRON_MASS = 9.1093897E-31; // kg /** Electron mass In units (\f$1,822.88850204(77)^{-1}\f$u). */ inline const double ELECTRON_MASS_U = 1.0 / 1822.8885020477; // u /** Proton mass. In units of kg (\f$1.6726230 \cdot 10^{-27}\f$ kg). */ inline const double PROTON_MASS = 1.6726230E-27; // kg /** Proton mass. In units (\f$1.00727646677(10)\f$u) */ inline const double PROTON_MASS_U = 1.0072764667710; // u /** C13C12 mass difference. In units (\f$1.0033548\f$u) */ inline const double C13C12_MASSDIFF_U = 1.0033548378; // u /** Average mass difference between consecutive isotopes for proteins of mass 55kDa. Referred to the values used in TopPIC. In units (\f$1.002371\f$u) */ inline const double ISOTOPE_MASSDIFF_55K_U = 1.002371; // u /** Neutron mass. In units of kg (\f$1.6749286 \cdot 10^{-27}\f$ kg). */ inline const double NEUTRON_MASS = 1.6749286E-27; // kg /** Neutron mass. In units (\f$1.0086649156(6)\f$u) */ inline const double NEUTRON_MASS_U = 1.00866491566; // u /** Avogadro constant. In units of \f$mol^{-1}\f$ (\f$6.0221367 \cdot 10^{23} mol^{-1}\f$). */ inline const double AVOGADRO = 6.0221367E+23; // 1 / mol /** Avogadro constant (alias) */ inline const double NA = AVOGADRO; /** Avogadro constant (alias) */ inline const double MOL = AVOGADRO; /** Boltzmann constant. In units of J/K (\f$1.380657 \cdot 10^{-23}\f$ J/K). */ inline const double BOLTZMANN = 1.380657E-23; // J / K /** Boltzmann constant (alias) */ inline const double k = BOLTZMANN; /** Planck constant. In units of Js (\f$6.6260754 \cdot 10^{-34}\f$ Js). */ inline const double PLANCK = 6.6260754E-34; // J * sec /** Planck constant (alias) */ inline const double h = PLANCK; /** Gas constant (= NA * k) */ inline const double GAS_CONSTANT = NA * k; /** Gas constant (alias) */ inline const double R = GAS_CONSTANT; /** Faraday constant (= NA * e0) */ inline const double FARADAY = NA * e0; /** Faraday constant (alias) */ inline const double F = FARADAY; /** Bohr radius. In units m (\f$5.29177249 \cdot 10^{-11}\f$ m). */ inline const double BOHR_RADIUS = 5.29177249E-11; // m /** Bohr radius (alias) */ inline const double a0 = BOHR_RADIUS; // the following values from: // P.W.Atkins: Physical Chemistry, 5th ed., Oxford University Press, 1995 /** Vacuum permittivity. In units of \f$C^2J^{-1}m^{-1}\f$ (\f$8.85419 \cdot 10^{-12} C^2J^{-1}m^{-1}\f$). */ inline const double VACUUM_PERMITTIVITY = 8.85419E-12; // C^2 / (J * m) /** Vacuum permeability. In units of \f$Js^2C^{-2}m^{-1}\f$ (\f$4\pi \cdot 10^{-7} Js^2C^{-2}m^{-1}\f$). */ inline const double VACUUM_PERMEABILITY = (4 * PI * 1E-7); // J s^2 / (C^2 * m) /** Speed of light. In units of m/s (\f$2.99792458 \cdot 10^8 ms^{-1}\f$). */ inline const double SPEED_OF_LIGHT = 2.99792458E+8; // m / s /** Speed of Light (alias) */ inline const double c = SPEED_OF_LIGHT; /** Gravitational constant. In units of \f$Nm^2kg^{-2}\f$ (\f$6.67259 \cdot 10^{-11} Nm^2kg^{-2}\f$). */ inline const double GRAVITATIONAL_CONSTANT = 6.67259E-11; // N m^2 / kg^2 /** Fine structure constant. Without unit (\f$7.29735 \cdot 10^{-3}\f$). */ inline const double FINE_STRUCTURE_CONSTANT = 7.29735E-3; // 1 //@} /** @name Conversion factors */ //@{ /** Degree per rad. 57.2957795130823209 */ inline const double DEG_PER_RAD = 57.2957795130823209; /** Rad per degree. 0.0174532925199432957 */ inline const double RAD_PER_DEG = 0.0174532925199432957; /** mm per inch. 25.4 */ inline const double MM_PER_INCH = 25.4; /** m per foot. 3.048 */ inline const double M_PER_FOOT = 3.048; /** Joules per calorie. 4.184 */ inline const double JOULE_PER_CAL = 4.184; /** Calories per Joule. 1/JOULE_PER_CAL */ inline const double CAL_PER_JOULE = (1 / 4.184); namespace UserParam { /** User parameter name for general ion mobility values (e.g., if not further specified) String */ inline const std::string IM = "IM"; /** User parameter name for FAIMS compensation voltage values Double (in volts) */ inline const std::string FAIMS_CV = "FAIMS_CV"; /** MetaValue key for raw TimsTOF ion mobility array (from MSConvert). * Note: TODO check. I saw files with other names as well (e.g. mean inverse ion mobility). * PeakPickerIM expects to find 'Ion Mobility' array and will treat it as raw timsTOF data. */ inline const std::string ION_MOBILITY = "Ion Mobility"; /** MetaValue key for centroided ion mobility data output by PeakPickerIM and MassTraceDetection. * PeakPickerIM outputs centroided peaks with this array name. * MassTraceDetection computes intensity-weighted ion mobility average of connected centroided peaks. */ inline const std::string ION_MOBILITY_CENTROID = "Ion Mobility Centroid"; /** MetaValue key for storing PeakPickerIM ion mobility peak FWHM. */ inline const std::string FWHM_IM = "IM Peak FWHM"; /** MetaValue key for storing MassTraceDetection im FWHM peak avrage * PeakPickerIM outputs ion mobility peak FWHM 'FWHM_im' -- those will be averaged across one trace. */ inline const std::string FWHM_IM_AVG = "FWHM_im_avg"; /** MetaValue key for storing PeakPickerHiRes m/z peak FWHM */ inline const std::string FWHM_MZ_ppm = "FWHM_ppm"; /** MetaValue key for storing MassTraceDetection mz FWHM peak average * if PeakPickerHiRes outputs m/z peak FWHM 'FWHM_ppm' -- those will be averaged across one trace. */ inline const std::string FWHM_MZ_AVG = "FWHM_mz_avg"; /** MetaValue key for storing mass trace m/z standard deviation (in Dalton) */ inline const std::string SD = "SD"; /** MetaValue key for storing mass trace m/z standard deviation (in ppm) */ inline const std::string SD_ppm = "SD_ppm"; /** User parameter name for ion names (e.g., annotated by TheoreticalSpectrumGenerator) String */ inline const std::string IonNames = "IonNames"; /** User parameter name for identifier of concatenated peptides String */ inline const std::string CONCAT_PEPTIDE = "concatenated_peptides"; /** Metavalue to list unimod modifications used in site localization */ inline const std::string LOCALIZED_MODIFICATIONS_USERPARAM = "localized_modifications"; /** User parameter name for the M/Z of other chromatograms which have been merged into this one String */ inline const std::string MERGED_CHROMATOGRAM_MZS = "merged_chromatogram_mzs"; /** User parameter name for precursor mz error in ppm String */ inline const std::string PRECURSOR_ERROR_PPM_USERPARAM = "precursor_mz_error_ppm"; /** User parameter name for median of fragment mz error in ppm String */ inline const std::string FRAGMENT_ERROR_MEDIAN_PPM_USERPARAM = "fragment_mz_error_median_ppm"; /** User parameter name for fragment mz error in ppm String */ inline const std::string FRAGMENT_ERROR_PPM_USERPARAM = "fragment_mass_error_ppm"; /** User parameter name for fragment mz error in dalton String */ inline const std::string FRAGMENT_ERROR_DA_USERPARAM = "fragment_mass_error_da"; /** User parameter name for fragment annotations String */ inline const std::string FRAGMENT_ANNOTATION_USERPARAM = "fragment_annotation"; /** User parameter name for annotation of PSMExlpainedIonCurrent String */ inline const std::string PSM_EXPLAINED_ION_CURRENT_USERPARAM = "PSM_explained_ion_current"; // User parameter name for the fraction of prefix ions that have been matched inline const std::string MATCHED_PREFIX_IONS_FRACTION = "matched_prefix_ions_fraction"; // User parameter name for the fraction of suffix ions that have been matched inline const std::string MATCHED_SUFFIX_IONS_FRACTION = "matched_suffix_ions_fraction"; /** User parameter name for the spectrum reference in PeptideIdentification (it is not yet treated as a class attribute) String */ inline const std::string SPECTRUM_REFERENCE = "spectrum_reference"; /** User parameter name to store the index of the primary MS run associated with the PeptideIdentification (it is not yet treated as a class attribute). Set by IDMerger algorithm or when reading ID files with info from multiple files (e.g., PercolatorInfile) String */ inline const std::string ID_MERGE_INDEX = "id_merge_index"; /** User parameter name for target/decoy annotation of a PeptideHit, e.g. as annotated by PeptideIndexer. One of: target, decoy, target+decoy String */ inline const std::string TARGET_DECOY = "target_decoy"; /** User parameter name for a delta score: a score ratio between a rank x hit and the rank x+1 hit String */ inline const std::string DELTA_SCORE = "delta_score"; /** User parameter name to indicate a monoisotopic peak misassignment. Used for precursor correction. (usually an integer x with the correction being -x times C13C12_MASSDIFF_U) String */ inline const std::string ISOTOPE_ERROR = "isotope_error"; /** User parameter name to indicate a peptide q-value String */ inline const std::string PEPTIDE_Q_VALUE = "peptide q-value"; // Cross-Linking Mass Spectrometry user parameters /** Name of OpenPepXL main score (PSI CV term) String */ inline const std::string OPENPEPXL_SCORE = "OpenPepXL:score"; /** User parameter name for the sequence of the second peptide in a cross-link String */ inline const std::string OPENPEPXL_BETA_SEQUENCE = "sequence_beta"; /** User parameter name for the protein accessions of the second peptide in a cross-link String */ inline const std::string OPENPEPXL_BETA_ACCESSIONS = "accessions_beta"; /** User parameter name for the 1st position of cross-link (alpha peptide position in a real cross-link, 1st of two positions in a loop-link, modified position in a mono-link) String */ inline const std::string OPENPEPXL_XL_POS1 = "xl_pos1"; /** User parameter name for the 2nd position of cross-link (beta peptide position in a real cross-link, 2nd of two positions in a loop-link, "-" in a mono-link) String */ inline const std::string OPENPEPXL_XL_POS2 = "xl_pos2"; /** User parameter name for the 1st cross-link position on the protein String */ inline const std::string OPENPEPXL_XL_POS1_PROT = "xl_pos1_protein"; /** User parameter name for the 2nd cross-link position on the protein String */ inline const std::string OPENPEPXL_XL_POS2_PROT = "xl_pos2_protein"; /** User parameter name for the cross-link type, one of: cross-link, loop-link, mono-link String */ inline const std::string OPENPEPXL_XL_TYPE = "xl_type"; /** User parameter name for the cross-link rank (ranks of PeptideHits across different PeptideIdentifications) String */ inline const std::string OPENPEPXL_XL_RANK = "xl_rank"; /** User parameter name for the name of a cross-link String */ inline const std::string OPENPEPXL_XL_MOD = "xl_mod"; /** User parameter name for the mass of a cross-link String */ inline const std::string OPENPEPXL_XL_MASS = "xl_mass"; /** User parameter name for the terminal specificity of a cross-link on the alpha peptide (to distinguish a link to the first or last residue side chain from a terminal link) String */ inline const std::string OPENPEPXL_XL_TERM_SPEC_ALPHA = "xl_term_spec_alpha"; /** User parameter name for the terminal specificity of a cross-link on the beta peptide (to distinguish a link to the first or last residue side chain from a terminal link) String */ inline const std::string OPENPEPXL_XL_TERM_SPEC_BETA = "xl_term_spec_beta"; /** User parameter name for the RT of the heavy spectrum precursor in a labeled cross-linking experiment String */ inline const std::string OPENPEPXL_HEAVY_SPEC_RT = "spec_heavy_RT"; /** User parameter name for the m/z of the heavy spectrum precursor in a labeled cross-linking experiment String */ inline const std::string OPENPEPXL_HEAVY_SPEC_MZ = "spec_heavy_MZ"; /** User parameter name for the spectrum reference of the heavy spectrum in a labeled cross-linking experiment String */ inline const std::string OPENPEPXL_HEAVY_SPEC_REF = "spectrum_reference_heavy"; /** User parameter name for target/decoy annotation of alpha peptides String */ inline const std::string OPENPEPXL_TARGET_DECOY_ALPHA = "xl_target_decoy_alpha"; /** User parameter name for target/decoy annotation of beta peptides String */ inline const std::string OPENPEPXL_TARGET_DECOY_BETA = "xl_target_decoy_beta"; /** User parameter name for PeptideEvidence info for the beta/acceptor peptide: pre String */ inline const std::string OPENPEPXL_BETA_PEPEV_PRE = "BetaPepEv:pre"; /** User parameter name for PeptideEvidence info for the beta/acceptor peptide: post String */ inline const std::string OPENPEPXL_BETA_PEPEV_POST = "BetaPepEv:post"; /** User parameter name for PeptideEvidence info for the beta/acceptor peptide: start String */ inline const std::string OPENPEPXL_BETA_PEPEV_START = "BetaPepEv:start"; /** User parameter name for PeptideEvidence info for the beta/acceptor peptide: end String */ inline const std::string OPENPEPXL_BETA_PEPEV_END = "BetaPepEv:end"; /** @name User parameters in spectra which have been annotated from subdirectories in SIRIUS workspace */ ///@{ /** FloatDataArray name for observed m/z values of Sirius annotated spectra FloatDataArray */ inline const std::string SIRIUS_MZ = "mz"; /** FloatDataArray name for exact mass values of Sirius annotated spectra FloatDataArray */ inline const std::string SIRIUS_EXACTMASS = "exact_mass"; /** StringDataArray name for most likely fragment explanations of the corresponding peak in the spectrum StringDataArray */ inline const std::string SIRIUS_EXPLANATION = "explanation"; /** User parameter name for Sirius score double */ inline const std::string SIRIUS_SCORE = "score"; /** User parameter name to tell what the contents of the m/z dimension of the annotated spectra contains (mz or exact mass) String */ inline const std::string SIRIUS_PEAKMZ = "peak_mz"; /** User parameter name to tell which sum formula was considered for this annotated spectrum String */ inline const std::string SIRIUS_ANNOTATED_SUMFORMULA = "annotated_sumformula"; /** User parameter name to tell which adduct was considered for this annotated spectrum String */ inline const std::string SIRIUS_ANNOTATED_ADDUCT = "annotated_adduct"; /** User parameter name to tell if this annotated spectrum comes from a Sirius/Passatutto generated decoy or an actual target spectrum boolean */ inline const std::string SIRIUS_DECOY = "decoy"; /** User parameter name to tell if this annotated spectrum comes from a feature (then it contains the feature ID) or a single MS2 spectrum (missing) boolean */ inline const std::string SIRIUS_FEATURE_ID = "feat_id"; ///@} /** User parameter name for XL-MS FDR values String */ inline const std::string XFDR_FDR = "XFDR:FDR"; /** User parameter name for best ion annotation in a ConsensusFeature, taken from the best quality feature. (Required for IIMN) String */ inline const std::string IIMN_BEST_ION = "best ion"; /** User parameter name for a ConsensusFeature. Represents the IIMN_ROW_IDs of related ConsensusFeatures defined by MetaboliteAdductDecharger. * Partners are separated by semin colon. (Required for IIMN) List of String */ inline const std::string IIMN_ADDUCT_PARTNERS = "partners"; /** User parameter name for a unique ConsensusFeature index in a ConsensusMap. (Required for IIMN) String */ inline const std::string IIMN_ROW_ID = "row ID"; /** User parameter name for a ConsensusFeature to indicate a metabolite with different adduct states. (Required for IIMN) String */ inline const std::string IIMN_ANNOTATION_NETWORK_NUMBER = "annotation network number"; /** User parameter name for group annotation in Feature by MetaboliteAdductDecharger to indicate matching Features with different adducts. String */ inline const std::string ADDUCT_GROUP = "Group"; /** User parameter name for a list of ADDUCT_GROUP annotations in a ConsensusFeature. (Required for IIMN) vector<String> */ inline const std::string IIMN_LINKED_GROUPS = "LinkedGroups"; /** User parameter name for adduct annotation in Feature by MetaboliteAdductDecharger. String */ inline const std::string DC_CHARGE_ADDUCTS = "dc_charge_adducts"; /** User parameter name for the number of mass traces in a feature. (Required for SiriusExport) String */ inline const std::string NUM_OF_MASSTRACES = "num_of_masstraces"; /** User parameter name for the total number of data points (peaks) in a feature. (Required for MQEvidenceExporter) String */ inline const std::string NUM_OF_DATAPOINTS = "num_of_datapoints"; /** User parameter name for the name/description of a metabolite. (Required for MetaboliteSpectralMatcher) String */ inline const std::string MSM_METABOLITE_NAME = "Metabolite_Name"; /** User parameter name for the INCHI key associated with a metabolite. (Required for MetaboliteSpectralMatcher) String */ inline const std::string MSM_INCHI_STRING = "Inchi_String"; /** User parameter name for the SMILES key associated with a metabolite. (Required for MetaboliteSpectralMatcher) String */ inline const std::string MSM_SMILES_STRING = "SMILES_String"; /** User parameter name for the precursor adduct ion of a metabolite. (Required for MetaboliteSpectralMatcher) String */ inline const std::string MSM_PRECURSOR_ADDUCT = "Precursor_Ion"; /** User parameter name for the sum formula of a metabolite. (Required for MetaboliteSpectralMatcher) String */ inline const std::string MSM_SUM_FORMULA = "Sum_Formula"; /** User parameter name for the base name which links to underlying peak map String */ inline const std::string BASE_NAME = "base_name"; /** User parameter name for the significance threshold in PeptideIdentification Double */ inline const std::string SIGNIFICANCE_THRESHOLD = "significance_threshold"; /** User parameter name for the rank of a peptide hit String */ inline const std::string RANK = "rank"; /** User parameter name for the number of peaks in a spectrum String */ inline const std::string NUM_PEAKS = "num_peaks"; } //@} } }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/CONCEPT/Colorizer.h
.h
8,958
219
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow, Moritz Berger $ // $Authors: Chris Bielow, Moritz Berger $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/config.h> #include <array> #include <iosfwd> #include <sstream> namespace OpenMS { /// Text colors/styles supported by Colorizer enum class ConsoleColor { // note: the order is important here! See Colorizer::colors_ RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, UNDERLINE, BRIGHT, ///< keeps the foreground color, but makes it brighter INVERT, ///< invert foreground and background color (inverting twice stays inverted) }; /** @brief Color and style the fonts shown on cout/cerr (or other streams) Allows to color the console fonts' foreground color (making the current color brighter, or setting a new color) and/or add an underline. There are predefined Colorizer objects for your convenience, e.g. 'red' or 'underline'. They are named identically to the possible values of enum ConsoleColor. Multiple styles can be combined (with limitations for nesting colors, see below). To undo a color/style, simply call its '.undo()' function. To undo all modifications and return to a normal console color/style, call 'undoAll()'. e.g. \code std::cout << "normal text" << red() << "this is red" << underline() << "red and underlined" << red.undo() << "just underlined" << underline.undo(); \endcode You can also modify a single item and immediately return to the previous setting by passing the item to the bracket operator, e.g. \code std::cout << "normal text << red("this part is red") << " back to normal here"; \endcode Undo() has limitations and does <b>not support nesting of colors</b>, i.e. does not remember the previous color, but resets to default \code std::cout << red() << "this is red" << "blue() << "this is blue" << blue.undo() << " not red! but normal"; \endcode <b>Redirecting cout/cerr streams</b><br> If std::cout or std::cerr are redirected to a file, then Colorizer will detect this and <b>not emit</b> any color/style information. This is to avoid the ANSI color codes showing up in the file instead of being filtered out by the console's color process. Note: all OS's we know (Windows, Linux, MacOS) only have a single color configuration for the whole console/terminal, independent of streams. I.e. if you apply a permanent color to std::cout then all subsequent output to std::cerr will also be colored! (unless std::cout is redirected to a file, then coloring std::cout will have no effect, not even when printing to the console using std::cerr). */ class OPENMS_DLLAPI Colorizer { public: /// stream insertion, e.g. std::cout << red() << "this is red" << red.undo(); friend OPENMS_DLLAPI std::ostream& operator<<(std::ostream& o_stream, Colorizer& col); friend class IndentedStream; // to manipulate the internal string data before writing to a stream /// Constructor Colorizer(const ConsoleColor color); /// Constructor (deleted) Colorizer() = delete; /// Copy constructor (deleted) //. Explicitly deleted here, since stringstream member has no copy c'tor either /// If you really wanted to, you can implement a copy c'tor, but there seems little use Colorizer(const Colorizer& rhs) = delete; /// Destructor ~Colorizer() = default; /// bracket operator to prepare this colorizer object to /// color the next stream it is applied to with this object's color /// until it is reset somewhere downstream. /// e.g. 'cerr << red() << "this is red" << " this too ..." << red.undo();' Colorizer& operator()() { input_.str(""); // clear the internal buffer undo_ = false; undo_all_ = false; undos_only = false; return *this; } /// Consume @p s, convert it to a string and insert this string with color into the next /// stream this Colorizer is applied to. Reset the stream right away. /// e.g. 'cerr << red("make this red!") << " this is not red "; template<typename T> Colorizer& operator()(T s) { input_.str(""); // clear the internal buffer input_ << s; // add new data undo_ = true; undo_all_ = false; undos_only = false; return *this; } /// prepare this colorizer to undo the effect of this Colorizer object to the next stream it is applied to /// e.g. 'cerr << red.undo() << "not red anymore"' Colorizer& undo(); /// prepare this colorizer to reset the console to its default colors/style. Colorizer& undoAll(); /// A wrapper for POSIX 'isatty()' or the equivalent on Windows. /// Checks if the stream is written to the terminal/console /// or being redirected to a file/NULL/nul (i.e. not visible). /// This only works for std::cout and std::cerr. Passing any other stream /// will always return 'false'. static bool isTTY(const std::ostream& stream); protected: /// write the content of input_ to the stream void outputToStream_(std::ostream& o_stream); /// color the @p stream using the given color static void colorStream_(std::ostream& stream, const char* ANSI_command); /// color of the stream (const; set in C'tor) const ConsoleColor color_; /// clear the color/style of this Colorizer from a stream (usually cout/cerr) upon the next call of /// 'std::ostream& operator<<(std::ostream& o_stream, OpenMS::Colorizer& col)' bool undo_ = true; /// clear all color/styles from a stream (usually cout/cerr) upon the next call of /// 'std::ostream& operator<<(std::ostream& o_stream, OpenMS::Colorizer& col)' bool undo_all_ = true; /// optimization to prevent coloring a stream, print nothing and then immediately /// uncoloring is, e.g. when calling c.undo() or c.undoAll() bool undos_only = false; /// internal methods used by friends to manipulate the internal data (if present) /// This avoids exposing the stream coloring itself (which is easy to get wrong) const std::stringstream& getInternalChars_() const { return input_; } /// internal methods used by friends to manipulate the internal data (if present) /// This avoids exposing the stream coloring itself (which is easy to get wrong) void setInternalChars_(const std::string& data) { input_.str(data); } /// holds ANSI codes to switch to a certain color or undo this effect /// The undo may not be a perfect fit when nesting, /// e.g. 'cout << red() << blue() << blue.undo()' will not yield red, but the default color struct ColorWithUndo_ { const char* enable; ///< ANSI code to activate the color/style const char* disable; ///< ANSO code to undo the color/style }; /** * @brief ANSI colors/styles, corresponding to values of enum ConsoleColor */ inline static const constexpr std::array<ColorWithUndo_, 9> colors_ { ColorWithUndo_ {"\033[91m", "\033[39m"}, // red ColorWithUndo_ {"\033[92m", "\033[39m"}, // green ColorWithUndo_ {"\033[93m", "\033[39m"}, // yellow ColorWithUndo_ {"\033[94m", "\033[39m"}, // blue ColorWithUndo_ {"\033[95m", "\033[39m"}, // magenta ColorWithUndo_ {"\033[96m", "\033[39m"}, // cyan ColorWithUndo_ {"\033[4m", "\033[24m"}, // underline ColorWithUndo_ {"\033[1m", "\033[22m"}, // bright/intensified ColorWithUndo_ {"\033[7m", "\033[27m"}, // invert FG/BG }; const char* color_undo_all_ = "\033[0m"; ///< resets all attributes to default /// internal string buffer when using operator()(T data) /// This data will be colored std::stringstream input_; }; // class Colorizer // declaration of all global colorizer objects extern OPENMS_DLLAPI Colorizer red; extern OPENMS_DLLAPI Colorizer green; extern OPENMS_DLLAPI Colorizer yellow; extern OPENMS_DLLAPI Colorizer blue; extern OPENMS_DLLAPI Colorizer magenta; extern OPENMS_DLLAPI Colorizer cyan; extern OPENMS_DLLAPI Colorizer bright; extern OPENMS_DLLAPI Colorizer underline; extern OPENMS_DLLAPI Colorizer invert; /// stream operator for Colorizers, which will (depending on the state of @p col) /// add color to the @p o_stream, and print some internal string, /// e.g. 'cout << red("this is red")' or 'cout << red() << "stream stays red until dooms day";' /// or reset the color /// e.g. 'cout << red.undo() << "not red anymore"' OPENMS_DLLAPI std::ostream& operator<<(std::ostream& o_stream, OpenMS::Colorizer& col); } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/CONCEPT/GlobalExceptionHandler.h
.h
3,509
139
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg$ // $Authors: Stephan Aiche, Marc Sturm $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/CONCEPT/Exception.h> #include <string> namespace OpenMS { namespace Exception { /** @brief OpenMS global exception handler @ingroup Exceptions */ class OPENMS_DLLAPI GlobalExceptionHandler { private: /** @name Constructors */ //@{ /** @brief Default constructor. This constructor installs the OPENMS specific handlers for <tt>terminate</tt>, <tt>unexpected</tt>, and <tt>new_handler</tt>. <tt>terminate</tt> or <tt>unexpected</tt> are called to abort a program if an exception was not caught or a function exits via an exception that is not allowed by its exception specification. Both functions are replaced by a function of GlobalExceptionHandler that tries to determine the last exception thrown. This mechanism only works, if all exceptions are derived from Base. The default <tt>new_handler</tt> is replaced by #newHandler and throws an exception of type OutOfMemory instead of <tt>bad_alloc</tt> (the default behaviour defined in the ANSI C++ standard). */ GlobalExceptionHandler() throw(); //@} /// private version of c'tor to avoid initialization GlobalExceptionHandler(const GlobalExceptionHandler &) {} ~GlobalExceptionHandler() {} public: /// The accessor for the singleton. It also serves as a replacement for the constructor. static GlobalExceptionHandler & getInstance(); /** @name Accessors */ //@{ /** */ static void setName(const std::string & name) throw(); /** */ static void setMessage(const std::string & message) throw(); /** */ static void setLine(int line) throw(); /** */ static void setFile(const std::string & file) throw(); /** */ static void setFunction(const std::string & function) throw(); /** */ static void set(const std::string & file, int line, const std::string & function, const std::string & name, const std::string & message) throw(); //@} protected: /// The OPENMS replacement for terminate static void terminate() throw(); /// The OPENMS new handler static void newHandler(); /** @name Wrapper for static member. @note To avoid problems when accessing uninitialised static members we replaced them with static functions returning references to the members. */ //@{ /// wrapper for static member file_ static std::string & file_(); /// wrapper for static member line_ static int & line_(); /// wrapper for static member function_ static std::string & function_(); /// wrapper for static member name_ static std::string & name_(); /// wrapper for static member what_ static std::string & what_(); //@} }; } // namespace Exception } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/CONCEPT/StreamHandler.h
.h
5,425
147
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg$ // $Authors: Stephan Aiche$ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/DATASTRUCTURES/String.h> #include <map> #include <iosfwd> namespace OpenMS { /** * @brief Provides a central class to register globally used output streams. Currently supported streams are * * <ul> * <li>std::ofstream</li> * <li>std::ostringstream</li> * </ul> * * You can simply request a stream from StreamHandler and it will manage the process of construction and * destruction (if the stream is not needed any more). * * A normal scenario would be * * <code> * STREAM_HANDLER.registerStream(StreamHandler::FILE, "name_of_the_output_file");<br> * STREAM_HANDLER.getStream(StreamHandler::FILE, "name_of_the_output_file") << "This will be send to the file" << std::endl;<br> * // ...<br> * <br> * // you do not need the file any more<br> * STREAM_HANDLER.unregisterStream(StreamHandler::FILE, "name_of_the_output_file");<br> * // StreamHandler will close the file stream if no other part of your program requested the same stream * </code> * * @ingroup Concept */ class OPENMS_DLLAPI StreamHandler { public: /** * @brief Defines the type of the stream that should be handled */ enum StreamType { FILE, STRING }; /// Default constructor StreamHandler(); /// destructor virtual ~StreamHandler(); /** * @brief Creates a stream of type @p type and with name @p stream_name * * If the stream is already registered the reference counter is increased. * * @note The stream name must be unique. You cannot register the same stream name with two different types. * * @param[in] type Type of the stream (e.g. FILE) * @param[in] stream_name Name of the stream (e.g. the file name for a file stream). * * @return An integer indicating if the operation was completed successfully (@p value != 1 means a failure occurred). */ Int registerStream(StreamType const type, const String & stream_name); /** * @brief De-registers a stream of type @p type and with name @p stream_name from the handler. * * It also decreases the reference counter for the named stream. If the counter * reaches 0. The stream will be closed. * * @param[in] type Type of the stream (e.g. FILE) * @param[in] stream_name Name of the stream (e.g. the file name for a file stream). * */ void unregisterStream(StreamType const type, const String & stream_name); /** * @brief Returns a reference to the stream of type @p type and with name @p stream_name. * * If the stream was not registered before an ElementNotFoundException will be thrown. * * @param[in] type Type of the stream (e.g. FILE) * @param[in] stream_name Name of the stream (e.g. the file name for a file stream). * * @throw ElementNotFoundException * * @return A reference to the requested stream. */ std::ostream & getStream(StreamType const type, const String & stream_name); /** * @brief Returns true if the stream @p stream_name with type @p type is * registered. * * @param[in] type Type of the stream (e.g. FILE) * @param[in] stream_name Name of the stream (e.g. the file name for a file stream). * * @return bool indication if the stream is known. */ bool hasStream(const StreamType type, const String & stream_name); protected: std::map<String, std::ostream *> name_to_stream_map_; ///< Maps all registered stream names to the corresponding std::ostream. std::map<String, StreamType> name_to_type_map_; ///< Maps all registered stream names to the corresponding StreamHandler::StreamType std::map<String, Size> name_to_counter_map_; ///< Maps all registered stream names to the number of times it was registered. If the counter goes to zero, the stream will be closed and removed. /** * @brief Creates a stream with the given type and the given name. * * @param[in] type Type of the stream (e.g. FILE) * @param[in] stream_name Name of the stream (e.g. the file name for a file stream). * * @return A pointer to the created stream. */ std::ostream * createStream_(const StreamType type, const String & stream_name); private: // copy constructor and assignment operator are hidden to avoid // creating multiple pointers to a single filestream instance /// copy constructor StreamHandler(const StreamHandler & source); /// assignment operator virtual StreamHandler & operator=(const StreamHandler & source); friend OPENMS_DLLAPI std::ostream & operator<<(std::ostream & os, StreamHandler const & stream_handler); }; /// Overload for the \a insertion \a operator (operator<<) to have a formatted output of the StreamHandler OPENMS_DLLAPI std::ostream & operator<<(std::ostream & os, StreamHandler const & stream_handler); /// Global StreamHandler instance. OPENMS_DLLAPI extern StreamHandler STREAM_HANDLER; } // end namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/CONCEPT/Macros.h
.h
2,256
107
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg$ // $Authors: Marc Sturm $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/config.h> #include <OpenMS/CONCEPT/Exception.h> #include <string> #include <cstring> /** @brief General helper macros @{ */ #define STRINGIFY(a) #a #ifdef _OPENMP // Pragma string literals are compiler-specific: // gcc and clang use _Pragma while MSVS uses __pragma // the MSVS pragma does not need a string token somehow. #ifdef OPENMS_COMPILER_MSVC #define OPENMS_THREAD_CRITICAL(name) \ __pragma(omp critical (name)) #else #define OPENMS_THREAD_CRITICAL(name) \ _Pragma( STRINGIFY( omp critical (name) ) ) #endif #else #define OPENMS_THREAD_CRITICAL(name) #endif /** @} */ // end of helpers /** @defgroup Conditions Condition macros @brief Macros used for to enforce preconditions and postconditions. These macros are enabled if debug info is enabled and optimization is disabled in configure. Otherwise they are replaced by an empty string, so they won't cost any performance. The macros throw Exception::Precondition or Exception::Postcondition respectively if the condition fails. @ingroup Concept @{ */ #ifdef OPENMS_ASSERTIONS /** @brief Precondition macro. @hideinitializer */ #define OPENMS_PRECONDITION(condition, message) \ if (!(condition)) \ { \ throw Exception::Precondition(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, # condition " " # message); \ } \ /** @brief Postcondition macro. @hideinitializer */ #define OPENMS_POSTCONDITION(condition, message) \ if (!(condition)) \ { \ throw Exception::Postcondition(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, # condition " " # message); \ } \ #else /** @brief Precondition macro. @hideinitializer */ #define OPENMS_PRECONDITION(condition, message) /** @brief Postcondition macro. @hideinitializer */ #define OPENMS_POSTCONDITION(condition, message) #endif /** @} */ // end of Conditions
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/CONCEPT/LogConfigHandler.h
.h
7,523
181
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg$ // $Authors: Stephan Aiche$ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/CONCEPT/LogStream.h> #include <OpenMS/CONCEPT/StreamHandler.h> #include <OpenMS/DATASTRUCTURES/StringListUtils.h> #include <OpenMS/DATASTRUCTURES/Param.h> namespace OpenMS { /** @brief The LogConfigHandler provides the functionality to configure the internal logging of OpenMS algorithms that use the global instances of LogStream. @ingroup Concept */ class OPENMS_DLLAPI LogConfigHandler { public: static String PARAM_NAME; ///< Name of the parameter in which the configuration should be stored /** @brief Translates the given list of parameter settings into a LogStream configuration Translates the given list of parameter settings into a LogStream configuration. Usually this list stems from a command line call. Each element in the stringlist should follow this naming convention &lt;LOG_NAME&gt; &lt;ACTION&gt; &lt;PARAMETER&gt; with LOG_NAME: DEBUG,INFO,WARNING,ERROR,FATAL_ERROR ACTION: add,remove,clear PARAMETER: for 'add'/'remove' it is the stream name (cout, cerr or a filename), 'clear' does not require any further parameter Example: <code>DEBUG add debug.log</code><br> This function will <b>not</b> apply to settings to the log handlers. Use configure() for that. @param[in] setting StringList containing the configuration options @throw Exception::ParseError In case of an invalid configuration. @return Param object containing all settings, that can be applied using the LogConfigHandler::configure() method */ Param parse(const StringList & setting); /** @brief Applies the given parameters (@p param) to the current configuration &lt;LOG_NAME&gt; &lt;ACTION&gt; &lt;PARAMETER&gt; &lt;STREAMTYPE&gt; LOG_NAME: DEBUG,INFO,WARNING,ERROR,FATAL_ERROR ACTION: add,remove,clear PARAMETER: for 'add'/'remove' it is the stream name (cout, cerr or a filename), 'clear' does not require any further parameter STREAMTYPE: FILE, STRING (for a StringStream, which you can grab by this name using getStream() ) You cannot specify a file named "cout" or "cerr" even if you specify streamtype 'FILE' - the handler will mistake this for the internal streams, but you can use "./cout" to print to a file named cout. A classical configuration would contain a list of settings e.g. <code>DEBUG add debug.log FILE</code><br> <code>INFO remove cout FILE</code> (FILE will be ignored)<br> <code>INFO add string_stream1 STRING</code><br> @throw Exception::ElementNotFound If the LogStream (first argument) does not exist. @throw Exception::FileNotWritable If a file (or stream) should be opened as log file (or stream) that is not accessible. @throw Exception::IllegalArgument If a stream should be registered, that was already registered with a different type. */ void configure(const Param & param); /** @brief Returns a reference to the registered stream with the name @p stream_name. @throw Exception::IllegalArgument If no stream with the name @p stream_name was registered before. @return Reference to the stream. */ std::ostream & getStream(const String & stream_name); /** @brief Sets a minimum @p log_level by removing all streams from loggers lower than that level, and restoring configured streams for loggers at or above that level. This method allows dynamic adjustment of the logging level. When increasing the log level (e.g., from INFO to ERROR), streams are removed from lower priority levels. When decreasing the log level (e.g., from ERROR to INFO), previously configured streams are restored. Order of log_level: "DEBUG", "INFO", "WARNING", "ERROR", "FATAL_ERROR", "NONE" Special value "NONE" disables all logging by removing streams from all levels. @param[in] log_level The minimum log level to enable. Levels below this will have their streams removed. */ void setLogLevel(const String & log_level); /** @brief Returns the instance of LogConfigHandler. */ static LogConfigHandler * getInstance(); /// Destructor virtual ~LogConfigHandler(); protected: /** @brief Returns the named global instance of the LogStream. (OpenMS::getGlobalLogDebug(), OpenMS::getGlobalLogInfo(), OpenMS::getGlobalLogWarn(), OpenMS::getGlobalLogError(), OpenMS::getGlobalLogFatal()) @param[in] stream_name Name of the stream. Should be DEBUG,INFO,WARNING,ERROR,FATAL_ERROR. @throw ElementNotFoundException if the given @p stream_name does not correspond to one of the known LogStream instances @return A reference to the named LogStream */ Logger::LogStream & getLogStreamByName_(const String & stream_name); /** @brief Returns the correct set of registered streams for the given stream type (e.g. DEBUG, INFO, ..) @param[in] stream_type String representation of the stream type (DEBUG, INFO, ..) @throw ElementNotFoundException if the given @p stream_type does not correspond to one of the known LogStreams */ std::set<String> & getConfigSetByName_(const String & stream_type); /** @brief Translates the given @p stream_type String into a valid StreamHandler::StreamType @param[in] stream_type String representation of the StreamHandler::StreamType @throw Exception::IllegalArgument is thrown when the passed @p stream_type does not correspond to an existing StreamHandler::StreamType @return The requested StreamHandler::StreamType */ StreamHandler::StreamType getStreamTypeByName_(const String & stream_type); std::set<String> debug_streams_; ///< List of all streams that were appended to OpenMS::getGlobalLogDebug() std::set<String> info_streams_; ///< List of all streams that were appended to OpenMS::getGlobalLogInfo() std::set<String> warn_streams_; ///< List of all streams that were appended to OpenMS::getGlobalLogWarn() std::set<String> error_streams_; ///< List of all streams that were appended to OpenMS::getGlobalLogError() std::set<String> fatal_streams_; ///< List of all streams that were appended to OpenMS::getGlobalLogFatal() std::map<String, StreamHandler::StreamType> stream_type_map_; ///< Maps the registered streams to a StreamHandler::StreamType private: friend OPENMS_DLLAPI std::ostream & operator<<(std::ostream & os, LogConfigHandler const & lch); // the pointer to the single instance static LogConfigHandler * instance_; // it is a singleton so we hide all c' and d'tors /// Default constructor LogConfigHandler(); /// Copy constructor LogConfigHandler(const LogConfigHandler & source); /// Assignment operator virtual LogConfigHandler & operator=(const LogConfigHandler & source); }; /// Overload for the \a insertion \a operator (operator<<) to have a formatted output of the LogConfigHandler OPENMS_DLLAPI std::ostream & operator<<(std::ostream & os, LogConfigHandler const & lch); } // end namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/CONCEPT/UniqueIdInterface.h
.h
4,020
150
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/DATASTRUCTURES/String.h> namespace OpenMS { /** @brief A base class defining a common interface for all classes having a unique id. Have a look at RichPeak2D for an example how to extend a class to support unique ids. @sa UniqueIdGenerator, RichPeak2D @ingroup Concept */ class OPENMS_DLLAPI UniqueIdInterface { public: /**@brief This is the invalid unique id (cast it to a UInt64 if you like) It is represented as an \c enum because \c static class members lead to bugs and linker errors all the time... */ enum { INVALID = 0 }; /** @brief Returns true if the unique_id is valid, false otherwise. Currently, an invalid unique id is represented by UInt64(0), but please prefer using this method for clarity. */ inline static bool isValid(UInt64 unique_id) { return unique_id != INVALID; } /// Default constructor - the unique id will be <i>invalid</i> UniqueIdInterface() : unique_id_(UInt64(INVALID)) { //do not use clearUniqueId(), as it will be slower and creates a warranted valgrind warning; } /// Copy constructor - copies the unique id UniqueIdInterface(const UniqueIdInterface & rhs) = default; /// Move constructor UniqueIdInterface(UniqueIdInterface && rhs) = default; /// Assignment operator - copies the unique id UniqueIdInterface & operator=(UniqueIdInterface const & rhs) = default; /// Move Assignment operator - copies the unique id UniqueIdInterface& operator=(UniqueIdInterface&&) & = default; /// Destructor virtual ~UniqueIdInterface() = default; /// Equality comparison operator - the unique ids must be equal (!) bool operator==(UniqueIdInterface const & rhs) const { return unique_id_ == rhs.unique_id_; } /// Non-mutable access to unique id - returns the unique id. UInt64 getUniqueId() const { return unique_id_; } /// Clear the unique id. The new unique id will be invalid. Returns 1 if the unique id was changed, 0 otherwise. Size clearUniqueId() { if (hasValidUniqueId()) { unique_id_ = 0; return 1; } else return 0; } void swap(UniqueIdInterface & from) { std::swap(unique_id_, from.unique_id_); return; } /// Returns whether the unique id is valid. Returns 1 if the unique id is valid, 0 otherwise. Size hasValidUniqueId() const { return isValid(unique_id_); } /// Returns whether the unique id is invalid. Returns 1 if the unique id is invalid, 0 otherwise. Size hasInvalidUniqueId() const { return !isValid(unique_id_); } /// Assigns a new, valid unique id. Always returns 1. Size setUniqueId(); /// Assigns a valid unique id, but only if the present one is invalid. Returns 1 if the unique id was changed, 0 otherwise. Size ensureUniqueId(); /// Assigns the given unique id. void setUniqueId(UInt64 rhs) { unique_id_ = rhs; } /**@brief Mutable access to unique id. This is designed to work well with \c id attributes in XML, which are prefixed with letters. The portion of the String after the last underscore is extracted and parsed as a UInt64. <i>It must consist of digits only.</i> For example, <code>some_feature.setUniqueId("f_12345_00067890")</code> is equivalent to <code>some_feature.setUniqueId(67890)</code> */ void setUniqueId(const String & rhs); protected: /// the unique id UInt64 unique_id_; }; } //namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/CONCEPT/Qt5Port.h
.h
601
22
// Copyright (c) 2002-present, The OpenMS Team -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow $ // $Authors: Chris Bielow $ // -------------------------------------------------------------------------- #pragma once namespace OpenMS { /// Drop-in for QT5's QStringList::toSet template <typename T, template<typename> typename C> QSet<T> toQSet(const C<T> &container) { return QSet<T>(container.begin(), container.end()); } } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/CONCEPT/Init.h
.h
619
23
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Hannes Roest $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/config.h> #include <OpenMS/CONCEPT/Exception.h> /** @brief Initialization procedures Part of the library needs to be initialized to be used properly, these procedures need to be run at startup (and preferably only once). */
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/CONCEPT/PrecisionWrapper.h
.h
3,185
86
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Marc Sturm, Clemens Groepl $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/config.h> #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/DATASTRUCTURES/String.h> #include <iostream> namespace OpenMS { /** @brief Wrapper class to implement output with appropriate precision. See precisionWrapper(). */ template <typename FloatingPointType> struct PrecisionWrapper { /// Constructor. Note: Normally you will prefer to use the "make"-function precisionWrapper(), which see. explicit PrecisionWrapper(const FloatingPointType rhs) : ref_(rhs) {} PrecisionWrapper(const PrecisionWrapper & rhs) : ref_(rhs.ref_) {} FloatingPointType const ref_; private: PrecisionWrapper(); // intentionally not implemented }; /** @brief Wrapper function that sets the appropriate precision for output temporarily. The original precision is restored afterwards so that no side effects remain. This is a "make"-function that deduces the typename FloatingPointType from its argument and returns a PrecisionWrapper<FloatingPointType>. Example: @code std::cout << 0.1234567890123456789f << ' ' << 0.1234567890123456789 << ' ' << 0.1234567890123456789l << '\n' << precisionWrapper(0.1234567890123456789f) << '\n' // float << 0.1234567890123456789f << ' ' << 0.1234567890123456789 << ' ' << 0.1234567890123456789l << '\n' << precisionWrapper(0.1234567890123456789) << '\n' // double << 0.1234567890123456789f << ' ' << 0.1234567890123456789 << ' ' << 0.1234567890123456789l << '\n' << precisionWrapper(0.1234567890123456789l) << '\n' // long double << 0.1234567890123456789f << ' ' << 0.1234567890123456789 << ' ' << 0.1234567890123456789l << '\n'; @endcode Result: @code 0.123457 0.123457 0.123457 0.123457 0.123457 0.123457 0.123457 0.123456789012346 0.123457 0.123457 0.123457 0.123456789012345679 0.123457 0.123457 0.123457 @endcode Note: Unfortunately we cannot return a const& - this will change when rvalue references become part of the new C++ standard. In the meantime, we need a copy constructor for PrecisionWrapper. */ template <typename FloatingPointType> inline const PrecisionWrapper<FloatingPointType> precisionWrapper(const FloatingPointType rhs) { return PrecisionWrapper<FloatingPointType>(rhs); } /// Output operator for a PrecisionWrapper. Specializations are defined for float, double, long double. template <typename FloatingPointType> inline std::ostream & operator<<(std::ostream & os, const PrecisionWrapper<FloatingPointType> & rhs) { // manual conversion to String is much faster than ostreams internal conversion // (this calls the correct overload for extra precision) String s(rhs.ref_, true); os << s; return os; } } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/CONCEPT/EnumHelpers.h
.h
915
33
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow $ // $Authors: Chris Bielow $ // -------------------------------------------------------------------------- #pragma once namespace OpenMS { namespace Helpers { /// return the index of an element in a container /// useful for matching 'names_of_...' arrays to their enum value template <class ContainerType> Size indexOf(const ContainerType& cont, const typename ContainerType::value_type& val) { auto it = std::find(cont.begin(), cont.end(), val); if (it == cont.end()) { throw Exception::ElementNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, val); } return std::distance(cont.begin(), it); } } }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/CONCEPT/HashUtils.h
.h
4,999
151
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: OpenMS Team $ // $Authors: OpenMS Team $ // -------------------------------------------------------------------------- #pragma once #include <cstddef> #include <cstdint> #include <functional> #include <string> #include <type_traits> namespace OpenMS { /** * @brief Hash utilities for OpenMS classes. * * This header provides hash functions that are: * - Consistent: Equal inputs produce equal hashes * - Fast: Uses efficient FNV-1a algorithm * - Low collision: Uses proper hash combining with golden ratio mixing * * @note These hash functions satisfy the requirements for std::unordered_map/set: * if a == b, then hash(a) == hash(b). When used with stable identifiers * (strings, not pointers), hashes are reproducible across process runs * on the same platform. Not suitable for cross-platform persistent storage * due to endianness and size_t differences. * * @ingroup Concept */ /** * @brief FNV-1a hash for a byte sequence. * * FNV-1a is a non-cryptographic hash function that is: * - Fast: Only XOR and multiply per byte * - Simple: Easy to implement and verify * - Good distribution: Well-tested for hash table use * * @param data Pointer to data bytes * @param size Number of bytes * @return Hash value (size_t) */ inline std::size_t fnv1a_hash_bytes(const void* data, std::size_t size) noexcept { const auto* bytes = static_cast<const unsigned char*>(data); // FNV-1a 64-bit constants std::size_t hash = 14695981039346656037ull; // FNV offset basis for (std::size_t i = 0; i < size; ++i) { hash ^= bytes[i]; hash *= 1099511628211ull; // FNV prime } return hash; } /** * @brief FNV-1a hash for a string. * * Consistent alternative to std::hash<std::string> which may vary * between standard library implementations. * * @param s String to hash * @return Hash value */ inline std::size_t fnv1a_hash_string(const std::string& s) noexcept { return fnv1a_hash_bytes(s.data(), s.size()); } /** * @brief Combine a hash value with additional data using golden ratio mixing. * * This function combines two hash values using the well-known formula from Boost: * seed ^= hash + golden_ratio + (seed << 6) + (seed >> 2) * * The constant 0x9e3779b97f4a7c15 is derived from the 64-bit golden ratio * (2^64 / phi) and provides good bit mixing properties on 64-bit systems. * * @param seed The existing hash value (modified in place) * @param value The new hash value to combine */ inline void hash_combine(std::size_t& seed, std::size_t value) noexcept { seed ^= value + 0x9e3779b97f4a7c15 + (seed << 6) + (seed >> 2); } /** * @brief Hash for an integer type. * * Uses FNV-1a on the bytes of the integer for good distribution. * * @note This function hashes the platform's native byte representation. * Results may differ on big-endian vs little-endian systems. * This is acceptable for in-process hash containers but not for * cross-platform persistent storage. See header documentation. * * @tparam T Must be an integral type (int, long, size_t, etc.) * @param[in] value Integer value to hash * @return Hash value */ template<typename T> inline std::size_t hash_int(T value) noexcept { static_assert(std::is_integral_v<T>, "hash_int requires an integral type"); return fnv1a_hash_bytes(&value, sizeof(T)); } /** * @brief Hash for a character. * * @param c Character to hash * @return Hash value (same as fnv1a of single byte) */ inline std::size_t hash_char(char c) noexcept { // Apply FNV-1a algorithm for single character std::size_t hash = 14695981039346656037ull; hash ^= static_cast<unsigned char>(c); hash *= 1099511628211ull; return hash; } /** * @brief Hash for a floating point type (float or double). * * Hashes the raw bytes of the floating point value. This is consistent * with the default operator== for floating point types. * * @note Normalizes -0.0 to +0.0 since they compare equal but have different * bit patterns. This ensures the hash contract is satisfied. * * @tparam T Must be a floating point type (float, double) * @param value Floating point value to hash * @return Hash value */ template<typename T> inline std::size_t hash_float(T value) noexcept { static_assert(std::is_floating_point_v<T>, "hash_float requires a floating point type"); // Normalize -0.0 to +0.0 (they compare equal but have different bit patterns) if (value == T(0)) value = T(0); return fnv1a_hash_bytes(&value, sizeof(T)); } } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/CONCEPT/Types.h
.h
7,809
282
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Oliver Kohlbacher $ // $Authors: Marc Sturm, Clemens Groepl $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/config.h> #include <ctime> #include <cstddef> // for size_t & ptrdiff_t #include <limits> #include <cstdint> // since C++11 namespace OpenMS { /** @brief Signed integer type (32bit) @ingroup Concept */ typedef int32_t Int32; /** @brief Unsigned integer type (32bit) @ingroup Concept */ typedef uint32_t UInt32; /** @brief Signed integer type (64bit) @ingroup Concept */ typedef int64_t Int64; /** @brief Unsigned integer type (64bit) @ingroup Concept */ typedef uint64_t UInt64; /** @brief Time type Use this type to represent a point in time (as a synonym for time_t). @ingroup Concept */ typedef time_t Time; /** @brief Unsigned integer type @ingroup Concept */ //typedef size_t UInt; typedef unsigned int UInt; /** @brief Signed integer type @ingroup Concept */ //typedef OPENMS_SIZE_T_SIGNED Int; typedef int Int; /** @brief Byte type Use this type to represent byte data (8 bit length). A Byte is always unsigned. @ingroup Concept */ typedef uint8_t Byte; /** @brief A unique object ID (as unsigned 64bit type). @see PersistentObject @ingroup Concept */ typedef uint64_t UID; /** @brief Size type e.g. used as variable which can hold result of size() @ingroup Concept */ typedef size_t Size; /** @brief Signed Size type e.g. used as pointer difference @ingroup Concept */ typedef ptrdiff_t SignedSize; enum ASCII { ASCII__BACKSPACE = '\b', ASCII__BELL = '\a', ASCII__CARRIAGE_RETURN = '\r', ASCII__HORIZONTAL_TAB = '\t', ASCII__NEWLINE = '\n', ASCII__RETURN = ASCII__NEWLINE, ASCII__SPACE = ' ', ASCII__TAB = ASCII__HORIZONTAL_TAB, ASCII__VERTICAL_TAB = '\v', ASCII__COLON = ':', ASCII__COMMA = ',', ASCII__EXCLAMATION_MARK = '!', ASCII__POINT = '.', ASCII__QUESTION_MARK = '?', ASCII__SEMICOLON = ';' }; //@} /** @name Numbers of digits used for writing floating point numbers (a.k.a. precision). These functions are provided to unify the handling of this issue throughout %OpenMS. (So please don't use ad-hoc numbers ;-) ) If you want to avoid side effects you can use precisionWrapper() to write a floating point number with appropriate precision; in this case the original state of the stream is automatically restored afterwards. See precisionWrapper() for details. In practice, the number of decimal digits that the type can represent without loss of precision are 6 digits for single precision and 15 digits for double precision. We have \f$2^{24}/10^{6}=16.777216\f$ and \f$2^{53}/10^{15}=9.007199254740992\f$, so rounding will remove the remaining difference. Example: @code #define NUMBER 12345.67890123456789012345678901 std::cout << NUMBER << '\n'; // default precision, writes: 12345.7 double d = NUMBER; std::cout.precision(writtenDigits<double>(0.0)); // explicit template instantiation std::cout << writtenDigits<double>(0.0) << ": " << d << '\n'; // writes: 15: 12345.6789012346 float r = NUMBER; std::cout.precision(writtenDigits(r)); // type deduced from argument std::cout << writtenDigits(r) << ": " << r << '\n'; // writes: 6: 12345.7 long double l = NUMBER; std::cout.precision(writtenDigits(1L)); // argument is not used, but L suffix indicates a long double std::cout << writtenDigits(1L) << ": " << l << '\n'; // writes: 18: 12345.6789012345671 double x = 88.99; std::cout.precision(15); std::cout << "15: " << x << '\n'; // writes: 15: 88.99 std::cout.precision(16); std::cout << "16: " << x << '\n'; // writes: 16: 88.98999999999999 @endcode */ //@{ /** @brief Number of digits commonly used for writing a floating point type (a.k.a. precision). Specializations are defined for float, double, long double. */ template <typename FloatingPointType> inline constexpr Int writtenDigits(const FloatingPointType& /* unused */ = FloatingPointType()); /// Number of digits commonly used for writing a @c float (a.k.a. precision). template <> inline constexpr Int writtenDigits<float>(const float&) { return std::numeric_limits<float>::digits10; } /// Number of digits commonly used for writing a @c double (a.k.a. precision). template <> inline constexpr Int writtenDigits<double>(const double&) { return std::numeric_limits<double>::digits10; } /// We do not want to bother people who unintentionally provide an int argument to this. template <> inline constexpr Int writtenDigits<int>(const int&) { return std::numeric_limits<int>::digits10; } /// We do not want to bother people who unintentionally provide an unsigned int argument to this. template <> inline constexpr Int writtenDigits<unsigned int>(const unsigned int&) { return std::numeric_limits<unsigned int>::digits10; } /// We do not want to bother people who unintentionally provide a long int argument to this. template <> inline constexpr Int writtenDigits<long int>(const long int&) { return std::numeric_limits<int>::digits10; } /// We do not want to bother people who unintentionally provide an unsigned long int argument to this. template <> inline constexpr Int writtenDigits<unsigned long int>(const unsigned long int&) { return std::numeric_limits<unsigned int>::digits10; } class DataValue; /// DataValue will be printed like double. template <> inline constexpr Int writtenDigits<DataValue>(const DataValue&) { return std::numeric_limits<double>::digits10; } /* META-COMMENT: DO NOT INTRODUCE ANY LINEBREAKS BELOW IN "<code>std::numeric_limits<long double>::digits10 == 18</code>". The doxygen parser (version 1.5.5) will get confused! (Clemens) */ /** @brief Number of digits commonly used for writing a @c long @c double (a.k.a. precision). ... Note: On Microsoft platforms, the I/O system seems to treat @c long @c double just like @c double. We observed that <code>std::numeric_limits<long double>::digits10 == 18</code> with GCC 3.4 on MinGW, but this promise is <i>not</i> kept by the Microsoft I/O system libraries. Therefore we use the value of @c digits10 for @c double also for @c long @c double. See http://msdn.microsoft.com/ + search: "long double". */ template <> inline constexpr Int writtenDigits<long double>(const long double&) { #ifndef OPENMS_WINDOWSPLATFORM return std::numeric_limits<long double>::digits10; #else return std::numeric_limits<double>::digits10; #endif } /** @brief The general template definition will return the default precision of 6 according to 27.4.4.1 basic_iosconstructors (C++ Standard). */ template <typename FloatingPointType> inline constexpr Int writtenDigits(const FloatingPointType& /* unused */) { return 6; } namespace Internal { /** Used to set the locale to "C", to avoid problems on machines with incompatible locale settings (this overwrites the locale setting of the environment!) */ extern OPENMS_DLLAPI const char* OpenMS_locale; } } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/CONCEPT/VersionInfo.h
.h
3,441
109
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow $ // $Authors: Clemens Groepl, Chris Bielow $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/DATASTRUCTURES/String.h> namespace OpenMS { class String; /** @brief Version information class. The OpenMS release version and revision data can be retrieved as a string or as integers. Note that the term <i>"version"</i> refers to releases (such as 1.0, 1.1.1-alpha, 1.2, ...), which follows the https://semver.org/ definition of version numbers using major, minor, patch and pre-release identifiers (separated by a dash). The term <i>"revision"</i> refers to a revision control system such as git and is mainly of interest for developers. The term <i>"branch"</i> refers to the git branch that this build of OpenMS is based on. The VersionInfo class contains only static methods. @ingroup Concept */ class OPENMS_DLLAPI VersionInfo { public: struct OPENMS_DLLAPI VersionDetails { Int version_major = 0; Int version_minor = 0; Int version_patch = 0; String pre_release_identifier; VersionDetails() = default; /// Copy constructor VersionDetails(const VersionDetails & other) = default; /// Copy assignment VersionDetails& operator=(const VersionDetails& other) = default; /** @brief parse String and return as proper struct @returns VersionInfo::empty on failure */ static VersionDetails create(const String & version); bool operator<(const VersionDetails & rhs) const; bool operator==(const VersionDetails & rhs) const; bool operator!=(const VersionDetails & rhs) const; bool operator>(const VersionDetails & rhs) const; static const VersionDetails EMPTY; // 0.0.0 version for comparison }; /// Return the build time of OpenMS static String getTime(); /// Return the version number of OpenMS static String getVersion(); /// Return the version number of OpenMS static VersionDetails getVersionStruct(); /** @brief Return the revision number from revision control system, e.g. git. On released versions of OpenMS, the result is "exported". The result can be possibly be "" on some platforms, which means that revision info is unavailable. You should check for both cases in your code. @internal The current git version is queried by the build system regularly and the result is written as a header file which is included by VersionInfo.cpp. */ static String getRevision(); /** @brief Return the branch name from revision control system, e.g. git. On released versions of OpenMS the result is "exported". The result can be possibly be "" on some platforms, which means that revision info is unavailable. You should check for both cases in your code. @internal The current git branch is queried by the build system regularly and the result is written as a header file which is included by VersionInfo.cpp. */ static String getBranch(); }; }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/ANALYSIS/TOPDOWN/FLASHDeconvAlgorithm.h
.h
7,267
174
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Kyowon Jeong, Jihyung Kim $ // $Authors: Kyowon Jeong, Jihyung Kim $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/ANALYSIS/TOPDOWN/DeconvolvedSpectrum.h> #include <OpenMS/ANALYSIS/TOPDOWN/FLASHHelperClasses.h> #include <OpenMS/ANALYSIS/TOPDOWN/PeakGroup.h> #include <OpenMS/ANALYSIS/TOPDOWN/SpectralDeconvolution.h> #include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h> #include <OpenMS/DATASTRUCTURES/Matrix.h> #include <OpenMS/KERNEL/MSExperiment.h> #include <OpenMS/KERNEL/MSSpectrum.h> #include <boost/dynamic_bitset.hpp> #include <iostream> namespace OpenMS { /** @brief FLASHDeconv algorithm: ultrafast mass deconvolution algorithm for top down mass spectrometry dataset From MSSpectrum, this class outputs DeconvolvedSpectrum. Deconvolution takes three steps: i) decharging and select candidate masses - speed up via binning ii) collecting isotopes from the candidate masses and deisotoping - peak groups are defined here iii) scoring and filter out low scoring masses (i.e., peak groups) @ingroup Topdown */ class OPENMS_DLLAPI FLASHDeconvAlgorithm : public DefaultParamHandler, public ProgressLogger { public: /// default constructor FLASHDeconvAlgorithm(); /// copy constructor FLASHDeconvAlgorithm(const FLASHDeconvAlgorithm&) = default; /// move constructor FLASHDeconvAlgorithm(FLASHDeconvAlgorithm&& other) noexcept = default; /// assignment operator FLASHDeconvAlgorithm& operator=(const FLASHDeconvAlgorithm& fd) = default; /// move assignment operator FLASHDeconvAlgorithm& operator=(FLASHDeconvAlgorithm&& fd) = default; /// destructor ~FLASHDeconvAlgorithm() override = default; std::vector<double> getTolerances() const; /** * @brief Run FLASHDeconv algorithm for @p map and store @p deconvolved_spectra and @p deconvolved_feature * @param[in] map the dataset * @param[out] deconvolved_spectra the deconvolved spectra will be stored in here * @param[in] deconvolved_feature the deconvolved features wll be strored in here */ void run(MSExperiment& map, std::vector<DeconvolvedSpectrum>& deconvolved_spectra, std::vector<FLASHHelperClasses::MassFeature>& deconvolved_feature); /// get calculated averagine. Call after calculateAveragine is called. const FLASHHelperClasses::PrecalculatedAveragine& getAveragine(); /// get calculated decoy averagine. Call after calculateAveragine is called. const FLASHHelperClasses::PrecalculatedAveragine& getDecoyAveragine(); /// get noise decoy weight double getNoiseDecoyWeight() const { return noise_decoy_weight_; } /// get scan number of the spectrum in @p index -th in @p map static int getScanNumber(const MSExperiment& map, Size index); protected: void updateMembers_() override; private: /// SpectralDeconvolution instances for spectral deconvolution for target and decoys SpectralDeconvolution sd_, sd_noise_decoy_, sd_signal_decoy_; /// to merge spectra. int merge_spec_ = 0; /// forced MS level int forced_ms_level_ = 0; /// maximum MS level, which is 4. UInt max_ms_level_ = 4; /// current maximum MS level - i.e., for MS2, this is the precursor charge UInt current_max_ms_level_ = 0; /// current minimum MS level. UInt current_min_ms_level_ = 0; /// the number of preceding full scans from which MS2 precursor mass will be searched. int precursor_MS1_window_ = 0; /// FLASHIda log file name String ida_log_file_; /// mass tolerances, and minimum cosine scores per MS level DoubleList tols_, min_cos_; /// to use RNA averagine model bool use_RNA_averagine_ = false; /// should decoy deconvolution be done? bool report_decoy_ = false; /// default precursor isolation window size. double isolation_window_size_{3.0}; /// noise decoy weight determined with qvalue calcualtion. double noise_decoy_weight_ = 1; /// FLASHIda parsing information is stored here: MS1 scan - information std::map<int, std::vector<std::vector<float>>> precursor_map_for_ida_; /// a map from native ID to precursor peak group std::map<String, PeakGroup> native_id_precursor_peak_group_map_; /// read dataset to update ms level information void updateMSLevels_(MSExperiment& map); /// merge spectra void mergeSpectra_(MSExperiment& map, uint ms_level); /// run spectral deconvolution void runSpectralDeconvolution_(MSExperiment& map, std::vector<DeconvolvedSpectrum>& deconvolved_spectra); /// find precursor scan number when peak group is not found int findPrecursorScanNumber_(const MSExperiment& map, Size index, uint ms_level) const; /// append decoy peak groups to deconvolved spectrum void appendDecoyPeakGroups_(DeconvolvedSpectrum& deconvolved_spectrum, const MSSpectrum& spec, int scan_number, const PeakGroup& precursor_pg); /// run feature finding to get deconvolved features void runFeatureFinding_(std::vector<DeconvolvedSpectrum>& deconvolved_spectra, std::vector<FLASHHelperClasses::MassFeature>& deconvolved_features); /// with found deconvolved features, update QScores for masses that are contained in features. static void updatePrecursorQScores_(std::vector<DeconvolvedSpectrum>& deconvolved_spectra, int ms_level); /// find precursor peak groups from FLASHIda log file void findPrecursorPeakGroupsFormIdaLog_(const MSExperiment& map, Size index, double start_mz, double end_mz); /// register the precursor peak group (or mass) if possible for MSn (n>1) spectrum. void findPrecursorPeakGroupsForMSnSpectra_(const MSExperiment& map, const std::vector<DeconvolvedSpectrum>& deconvolved_spectra, uint ms_level); /// find scan number bounds for precursor search std::pair<int, int> findScanNumberBounds_(const MSExperiment& map, Size index, uint ms_level) const; /// collect survey scans within the given scan number bounds std::vector<DeconvolvedSpectrum> collectSurveyScans_(const std::vector<DeconvolvedSpectrum>& deconvolved_spectra, int b_scan_number, int a_scan_number, uint ms_level) const; /// get isolation window m/z range from precursors std::pair<double, double> getIsolationWindowMzRange_(const MSSpectrum& spec) const; /// find the best precursor peak group from survey scans within the isolation window PeakGroup findBestPrecursorPeakGroup_(const std::vector<DeconvolvedSpectrum>& survey_scans, double start_mz, double end_mz) const; /// determine tolerance void determineTolerance_(const MSExperiment& map, const Param& sd_param, const FLASHHelperClasses::PrecalculatedAveragine& avg, uint ms_level); /// get histogram static std::vector<int> getHistogram_(const std::vector<double>& data, double min_range, double max_range, double bin_size); /// filter low intensity peaks static void filterLowPeaks_(MSExperiment& map); }; } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/ANALYSIS/TOPDOWN/FLASHHelperClasses.h
.h
11,308
274
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Kyowon Jeong, Jihyung Kim $ // $Authors: Kyowon Jeong, Jihyung Kim $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/APPLICATIONS/TOPPBase.h> #include <OpenMS/CHEMISTRY/ISOTOPEDISTRIBUTION/CoarseIsotopePatternGenerator.h> #include <OpenMS/CHEMISTRY/ISOTOPEDISTRIBUTION/IsotopeDistribution.h> #include <OpenMS/CONCEPT/Constants.h> #include <OpenMS/CONCEPT/HashUtils.h> #include <OpenMS/FEATUREFINDER/MassTraceDetection.h> #include <boost/dynamic_bitset.hpp> #include <functional> namespace OpenMS { /** * @brief Wrapper struct for all the structs needed by the FLASHDeconv * The following structures/classes are defined: PrecalculatedAveragine, MassFeature, IsobaricQuantities, LogMzPeak, * Tag, and DAG for tagging. * i) PrecalculatedAveragine - to match observed isotopic envelope against theoretical one, theoretical envelope from * averagine model should be quickly calculated. To do so, precalculate averagines for different masses at the beginning of FLASHDeconv runs * ii) MassFeature - the feature of the deconvolved masses (instead of m/zs for MS features). * iii) IsobaricQuantities - the quantities from isobaric quantification (implemented within FLASHDeconv) * iv) LogMzPeak - Log transformed peak from original peak. Contains information such as charge, isotope index, and * uncharged mass. * v) Tag - the sequence tag generated on deconvolved spectra in FLASHTaggerAlgorithm * vi) DAG - the graph for sequence tagging in FLASHTaggerAlgorithm and for proteoform characterization in FLASHExtenderAlgorithm * @see SpectralDeconvolution */ struct OPENMS_DLLAPI FLASHHelperClasses { /// @brief Averagine patterns pre-calculated for speed up. Other variables are also calculated for fast cosine calculation class OPENMS_DLLAPI PrecalculatedAveragine { private: /// isotope distributions for different (binned) masses std::vector<IsotopeDistribution> isotopes_; /// L2 norms_ for masses - for quick isotope cosine calculation std::vector<double> norms_; /// mass differences between average mass and monoisotopic mass std::vector<double> average_mono_mass_difference_; /// mass differences between most abundant mass and monoisotopic mass std::vector<double> abundant_mono_mass_difference_; std::vector<double> snr_mul_factor_; /// Isotope start indices: isotopes of the indices less than them have very low intensities std::vector<int> left_count_from_apex_; /// Isotope end indices: isotopes of the indices larger than them have very low intensities std::vector<int> right_count_from_apex_; /// most abundant isotope index std::vector<Size> apex_index_; /// max isotope index Size max_isotope_index_; /// mass interval for calculation double mass_interval_; /// min mass for calculation double min_mass_; /// calculate the mass bin index from mass Size massToIndex_(double mass) const; public: /// default constructor PrecalculatedAveragine() = default; /** @brief constructor with parameters such as mass ranges and bin size. @param[in] min_mass the averagine distributions will be calculated from this min_mass @param[in] max_mass to the max_mass @param[in] delta with the bin size delta @param[in] generator this generates (calculates) the distributions @param[in] use_RNA_averagine if set, nucleotide-based isotope patters are calculated @param[in] decoy_iso_distance if set to a positive value, nonsensical isotope patterns are generated - the distance between isotope = decoy_iso_distance * normal distance. */ PrecalculatedAveragine(double min_mass, double max_mass, double delta, CoarseIsotopePatternGenerator& generator, bool use_RNA_averagine, double decoy_iso_distance = -1); /// copy constructor PrecalculatedAveragine(const PrecalculatedAveragine&) = default; /// move constructor PrecalculatedAveragine(PrecalculatedAveragine&& other) noexcept = default; /// copy assignment operator PrecalculatedAveragine& operator=(const PrecalculatedAveragine& pc) = default; /// move assignment operator PrecalculatedAveragine& operator=(PrecalculatedAveragine&& pc) noexcept = default; /// destructor ~PrecalculatedAveragine() = default; /// get distribution for input mass. If input mass exceeds the maximum mass (specified in constructor), output for the maximum mass IsotopeDistribution get(double mass) const; /// get max isotope index size_t getMaxIsotopeIndex() const; /// set max isotope index void setMaxIsotopeIndex(int index); /// get isotope distance (from apex to the left direction) to consider. This is specified in the constructor. index. If input mass exceeds the /// maximum mass (specified in constructor), output for the maximum mass Size getLeftCountFromApex(double mass) const; /// get isotope distance (from apex to the right direction) to consider. This is specified in the constructor. index. If input mass exceeds the /// maximum mass (specified in constructor), output for the maximum mass Size getRightCountFromApex(double mass) const; /// get index of most abundant isotope. If input mass exceeds the maximum mass (specified in constructor), output for the maximum mass Size getApexIndex(double mass) const; /// get index of last isotope. If input mass exceeds the maximum mass (specified in constructor), output for the maximum mass Size getLastIndex(double mass) const; /// get mass difference between avg and mono masses. If input mass exceeds the maximum mass (specified in constructor), output for the maximum /// mass double getAverageMassDelta(double mass) const; /// get mass difference between most abundant mass and mono masses. If input mass exceeds the maximum mass (specified in constructor), output for /// the maximum mass double getMostAbundantMassDelta(double mass) const; /// get the SNR multiplication factor - used for quick SNR calculation double getSNRMultiplicationFactor(double mass) const; }; /// Mass feature (Deconvolved masses in spectra are traced by Mass tracing to generate mass features - like LC-MS features). struct OPENMS_DLLAPI MassFeature { public: /// feature index; uint index; /// the trace calculated from the masses MassTrace mt; /// per charge and isotope intensities std::vector<float> per_charge_intensity; std::vector<float> per_isotope_intensity; /// isotope offset between deconvolved masses and mass feature int iso_offset; /// representative scan number, min and max scan numbers, and representative charge int scan_number, min_scan_number, max_scan_number, rep_charge; /// average mass double avg_mass; /// minimum maximum charges, and number of charges int min_charge, max_charge, charge_count; double isotope_score, qscore; double rep_mz; bool is_decoy; uint ms_level; /// features are compared bool operator<(const MassFeature& a) const { return avg_mass < a.avg_mass; } bool operator>(const MassFeature& a) const { return avg_mass > a.avg_mass; } bool operator==(const MassFeature& other) const { return avg_mass == other.avg_mass; } }; /// Isobaric quantities. struct OPENMS_DLLAPI IsobaricQuantities { public: int scan; double rt; double precursor_mz; double precursor_mass; std::vector<double> quantities; std::vector<double> merged_quantities; /// return true if no isobaric quantities have been stored bool empty() const; }; /// log transformed peak. After deconvolution, all necessary information from deconvolution such as charge and isotope index is stored. class OPENMS_DLLAPI LogMzPeak { public: /// original peak mz double mz = 0; /// original peak intensity float intensity = 0; /// log transformed mz double logMz = -1000; /// determined mass after deconvolution. NOT monoisotopic but only decharged double mass = .0; /// absolute charge (in case negative, is_positive is set to false) int abs_charge = 0; /// is positive mode bool is_positive = true; /// isotope index int isotopeIndex = -1; /// default constructor LogMzPeak() = default; /** @brief constructor from Peak1D. @param[in] peak the original spectral peak @param[in] positive determines the charge carrier mass. Can be obtained by getChargeMass(true) for positive mode (Constants::PROTON_MASS_U) and getChargeMass(false) for negative mode (-Constants::PROTON_MASS_U) */ explicit LogMzPeak(const Peak1D& peak, bool positive); /// copy constructor LogMzPeak(const LogMzPeak&) = default; /// destructor ~LogMzPeak() = default; /// get uncharged mass of this peak. It is NOT a monoisotopic mass of a PeakGroup, rather the mass of each LogMzPeak. Returns 0 if no /// charge is set double getUnchargedMass() const; /// log mz values are compared bool operator<(const LogMzPeak& a) const; bool operator>(const LogMzPeak& a) const; bool operator==(const LogMzPeak& other) const; }; /** @brief calculate log mzs from mzs @param[in] mz mz @param[in] positive determines the charge carrier mass */ static double getLogMz(double mz, bool positive); /** @brief get charge carrier mass : positive mode mass of (Constants\::PROTON_MASS_U) and negative mode mass of (-Constants\::PROTON_MASS_U) @param[in] positive_ioniziation_mode Determines the charge carrier mass (true = positive or false = negative) */ static float getChargeMass(bool positive_ioniziation_mode); }; } // namespace OpenMS namespace std { /// @brief Hash specialization for FLASHHelperClasses::MassFeature template<> struct hash<OpenMS::FLASHHelperClasses::MassFeature> { std::size_t operator()(const OpenMS::FLASHHelperClasses::MassFeature& mf) const noexcept { // Hash based on avg_mass (the field used in operator==) return OpenMS::hash_float(mf.avg_mass); } }; /// @brief Hash specialization for FLASHHelperClasses::LogMzPeak template<> struct hash<OpenMS::FLASHHelperClasses::LogMzPeak> { std::size_t operator()(const OpenMS::FLASHHelperClasses::LogMzPeak& peak) const noexcept { // Hash based on logMz and intensity (the fields used in operator==) std::size_t seed = OpenMS::hash_float(peak.logMz); OpenMS::hash_combine(seed, OpenMS::hash_float(peak.intensity)); return seed; } }; } // namespace std
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/ANALYSIS/TOPDOWN/PeakGroup.h
.h
17,227
441
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Kyowon Jeong, Jihyung Kim $ // $Authors: Kyowon Jeong, Jihyung Kim $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/ANALYSIS/TOPDOWN/FLASHHelperClasses.h> #include <OpenMS/CONCEPT/HashUtils.h> #include <OpenMS/DATASTRUCTURES/Matrix.h> #include <functional> namespace OpenMS { /** @brief Class describing a deconvolved mass. A mass contains multiple (LogMz) peaks of different charges and isotope indices. PeakGroup is the set of such peaks representing a single monoisotopic mass. PeakGroup also contains features that define the quality of it. It is used for PeakGroupScoring calculation. DeconvolvedSpectrum consists of PeakGroups. @ingroup Topdown */ class OPENMS_DLLAPI PeakGroup { typedef FLASHHelperClasses::LogMzPeak LogMzPeak; typedef FLASHHelperClasses::PrecalculatedAveragine PrecalculatedAveragine; public: /// target decoy type of PeakGroup. /// This specifies if a PeakGroup is a target (0), noise decoy (1),or signal decoy (2) enum TargetDecoyType { target = 0, noise_decoy, signal_decoy, }; /// default constructor PeakGroup() = default; /** @brief Constructor specifying charge range @param[in] min_abs_charge min Charge @param[in] max_abs_charge max Charge @param[in] is_positive whether MS is positive mode */ explicit PeakGroup(int min_abs_charge, int max_abs_charge, bool is_positive); /// default destructor ~PeakGroup() = default; /// copy constructor PeakGroup(const PeakGroup&) = default; /// move constructor PeakGroup(PeakGroup&& other) = default; /// comparison operators bool operator<(const PeakGroup& a) const; bool operator>(const PeakGroup& a) const; bool operator==(const PeakGroup& a) const; /// assignment operator PeakGroup& operator=(const PeakGroup& t) = default; /** @brief add monoisotopic indices of peaks by offset and discard negative isotope peaks. Total intensity is also updated */ void updateMonoMassAndIsotopeIntensities(double tol); /** @brief Update setQscore. Cosine and SNRs are also updated. @param[in] noisy_peaks noisy peaks to calculate setQscore @param[in] avg precalculated averagine @param[in] min_cos the peak groups with cosine score less than this will have setQscore 0. @param[in] tol ppm tolerance @param[in] is_low_charge if set, charge fit score calculation becomes less stroct @param[in] excluded_masses masses to exclude @param[in] is_last if this is set, it means that PeakGroupScoring calculation is at its last iteration. More detailed noise power calculation is activated and mono mass is not recalibrated. @return returns isotope offset after isotope cosine calculation */ int updateQscore(const std::vector<LogMzPeak>& noisy_peaks, const FLASHHelperClasses::PrecalculatedAveragine& avg, double min_cos, double tol, bool is_low_charge, const std::vector<double>& excluded_masses, bool is_last = false); /** * @brief given a monoisotopic mass, recruit raw peaks from the raw input spectrum and add to this peakGroup. This is a bit time-consuming and is done for only a small number of selected * high-quality peakgroups. * @param[in] spec raw spectrum * @param[in] tol ppm tolerance * @param[in] avg precalculated averagine * @param[in] mono_mass monoisotopic mass * @param[in] renew_signal_peaks Whether or not the signal peaks should be renewed during recruitment * @return returns the noisy peaks for this peakgroup - i.e., the raw peaks within the range of this peakGroup that are not matched to any istope of this peakGroup mass. */ std::vector<LogMzPeak> recruitAllPeaksInSpectrum(const MSSpectrum& spec, double tol, const FLASHHelperClasses::PrecalculatedAveragine& avg, double mono_mass, bool renew_signal_peaks = true); /** * @brief Get noisy peaks for this PeakGroup without modifying any state (const-safe). * This is a const alternative to recruitAllPeaksInSpectrum(..., false) for use in output/write functions. * @param[in] spec raw spectrum * @param[in] tol ppm tolerance * @param[in] avg precalculated averagine * @return returns the noisy peaks - raw peaks within range that don't match the isotope pattern */ std::vector<LogMzPeak> getNoisyPeaks(const MSSpectrum& spec, double tol, const FLASHHelperClasses::PrecalculatedAveragine& avg) const; /// set scan number void setScanNumber(int scan_number); /// set per abs_charge isotope cosine void setChargeIsotopeCosine(int abs_charge, float cos); /// set min_abs_charge and max_abs_charge charge range void setAbsChargeRange(int min_abs_charge, int max_abs_charge); /// set isotope cosine score void setIsotopeCosine(float cos); /// set representative max_snr_abs_charge void setRepAbsCharge(int max_snr_abs_charge); /// set monoisotopic mass void setMonoisotopicMass(double mono_mass); /// set Qscore - for FLASHIda log file parsing void setQscore(double qscore); /// set charge score - for FLASHIda log file parsing void setChargeScore(float charge_score); /// set average mass ppm error void setAvgPPMError(float error); /// set SNR manually - for FLASHIda log file parsing void setSNR(float snr); /// set charge SNR manually - for FLASHIda log file parsing void setChargeSNR(int abs_charge, float c_snr); /// set if it is targeted void setTargeted(); /// get scan number int getScanNumber() const; /// get monoisotopic mass double getMonoMass() const; /// get intensity float getIntensity() const; /// get per abs_charge SNR float getChargeSNR(int abs_charge) const; /// get per abs_charge isotope cosine float getChargeIsotopeCosine(int abs_charge) const; /// get per abs_charge intenstiy float getChargeIntensity(int abs_charge) const; /// get mz range that results in max setQscore std::tuple<double, double> getRepMzRange() const; /// get mz range of the charge std::tuple<double, double> getMzRange(int abs_charge) const; /// get charge range - the actual charge values std::tuple<int, int> getAbsChargeRange() const; /// get per isotope intensities const std::vector<float>& getIsotopeIntensities() const; /// get isotopic cosine score float getIsotopeCosine() const; /// get the density of the peaks within charge and isotope range /** * @brief Get the density of peaks within charge and isotope range. * @return Peak occupancy value (0-1) representing the fraction of expected peaks that are present */ float getPeakOccupancy() const; /// get representative charge int getRepAbsCharge() const; /** * @brief Get the one-dimensional quality score for this peak group. * * The Q-score represents the confidence/quality of the peak group based on * isotope pattern matching, charge state consistency, and signal-to-noise ratio. * * @return Quality score in range [0, 1], where higher values indicate better quality. * Returns 0.0 if the score has not been calculated (default initialization). */ double getQscore() const; /** * @brief Get the two-dimensional quality score incorporating feature-level information. * * The 2D Q-score extends the 1D score by incorporating additional dimensions such as * retention time consistency, ion mobility correlation, or MS1-MS2 relationship. * This score is typically set after feature tracing/grouping across scans. * * @return The maximum of the 1D Q-score and the 2D Q-score, in range [0, 1]. * If the 2D score has not been set (initialized to -1.0), effectively returns * the 1D Q-score. */ double getQscore2D() const; /// get total SNR float getSNR() const; /// get charge score float getChargeScore() const; /// get average mass ppm error; float getAvgPPMError() const; /// get average mass ppm error; float getAvgDaError() const; /// get if it is positive mode bool isPositive() const; /// get if it is targeted bool isTargeted() const; /// get the target decoy type of this PeakGroup::TargetDecoyType getTargetDecoyType() const; /// for this PeakGroup, specify the target decoy type. void setTargetDecoyType(PeakGroup::TargetDecoyType index); /** * Get q value */ float getQvalue() const; /** * set peakGroup q value */ void setQvalue(double q); /// set distance between consecutive isotopes void setIsotopeDaDistance(double d); /// get distance between consecutive isotopes double getIsotopeDaDistance() const; /// get minimum neagative isotope index int getMinNegativeIsotopeIndex() const; /// set index of this peak group void setIndex(uint i); /** * @brief Set the two-dimensional quality score for this peak group. * * The 2D Q-score incorporates feature-level information such as retention time * consistency or ion mobility correlation across multiple scans. * * @param[in] fqscore The 2D quality score to set, typically in range [0, 1]. */ void setQscore2D(double fqscore); /** * @brief Set the feature index for this peak group. * * Associates this peak group with a feature (traced isotope pattern across scans). * * @param[in] findex The feature index to assign to this peak group. */ void setFeatureIndex(uint findex); /// get index of this peak group uint getIndex() const; /** * @brief Get the feature index associated with this peak group. * * The feature index identifies which traced feature (isotope pattern across * multiple scans) this peak group belongs to. * * @return The feature index. Returns 0 if no feature has been assigned * (default initialization). */ uint getFeatureIndex() const; /// iterators for the signal LogMz peaks in this PeakGroup std::vector<FLASHHelperClasses::LogMzPeak>::const_iterator begin() const noexcept; std::vector<FLASHHelperClasses::LogMzPeak>::const_iterator end() const noexcept; std::vector<FLASHHelperClasses::LogMzPeak>::iterator begin() noexcept; std::vector<FLASHHelperClasses::LogMzPeak>::iterator end() noexcept; const FLASHHelperClasses::LogMzPeak& operator[](Size i) const; /** * @brief Get mass errors for each isotope index in this peak group. * * Calculates the average mass error for peaks at each isotope index, * comparing observed masses to theoretical masses from the averagine model. * * @param[in] ppm If true (default), returns errors in parts-per-million (ppm). * If false, returns errors in Daltons (Da). * @return Vector of average mass errors, one per unique isotope index present * in the peak group. Returns an empty vector if no peaks are present. */ std::vector<float> getMassErrors(bool ppm = true) const; /// vector operators for the LogMzPeaks in this PeakGroup void push_back(const FLASHHelperClasses::LogMzPeak& pg); FLASHHelperClasses::LogMzPeak& back(); Size size() const noexcept; void reserve(Size n); bool empty() const; void swap(std::vector<FLASHHelperClasses::LogMzPeak>& x); void sort(); /** * @brief Get deep learning feature vectors (signal and noise). * * @param[in] spec Raw spectrum to extract features from. * @param[in] charge_count Number of charges to include in the feature vector. * @param[in] isotope_count Number of isotopes to include in the feature vector. * @param[in] avg Precalculated averagine model for theoretical isotope patterns. * @param[in] tol Tolerance in ppm for peak matching. * @return Tuple of (signal_vector, noise_vector) for ML model input. */ std::tuple<std::vector<double>, std::vector<double>> getDLVector(const MSSpectrum& spec, const Size charge_count, const Size isotope_count, const FLASHHelperClasses::PrecalculatedAveragine& avg, double tol); private: /// update chargefit score and also update per charge intensities here. void updateChargeFitScoreAndChargeIntensities_(bool is_low_charge); /// update avg ppm error void updateAvgMassError_(); /// update avg Da error float getPPMError_(const LogMzPeak& p) const; /// get Da error of a logMzPeak from the closest isotope float getDaError_(const LogMzPeak& p) const; /// using signal and total (signal + noise) power, update SNR value void updateSNR_(float mul_factor); /// clear peaks void clear_(); /// calculate per isotope intensities. When abs_charge == 0, all peaks are considered void getPerIsotopeIntensities_(std::vector<float>& intensities, int& min_isotope_index, int& max_isotope_index, int abs_charge, int min_negative_isotope_index, double tol); /// update per charge intensities, noise power, and squared intensities. used for SNR estimation void updatePerChargeInformation_(const std::vector<LogMzPeak>& noisy_peaks, double tol, bool is_last); /// update the charge range using the calculated per charge information void updateChargeRange_(); /// update per charge cosine values void updatePerChargeCos_(const FLASHHelperClasses::PrecalculatedAveragine& avg, double tol); /** * calculate noisy peak power. The goal of this function is to group noisy peaks that are possibly from the same molecule and sum their intensities before calculate power * @param[in] noisy_peaks noisy peaks to calculate power * @param[in] z charge * @param[in] tol ppm tolerance * @return calculated noise power */ float getNoisePeakPower_(const std::vector<LogMzPeak>& noisy_peaks, int z, double tol) const; /// log Mz peaks std::vector<FLASHHelperClasses::LogMzPeak> logMzpeaks_; /// negative isotope index peaks std::vector<FLASHHelperClasses::LogMzPeak> negative_iso_peaks_; /// per charge summed signal squared, noise pwr, SNR, isotope cosine, and intensity vectors std::vector<float> per_charge_sum_signal_squared_; std::vector<float> per_charge_noise_pwr_; std::vector<float> per_charge_cos_; std::vector<float> per_charge_int_; std::vector<float> per_charge_snr_; /// per isotope intensity. std::vector<float> per_isotope_int_; /// charge range int min_abs_charge_ = 0, max_abs_charge_ = -1; /// peak group index uint index_ = 0; /// feature index in which this peak group is included. 0 if not included in any feature uint findex_ = 0; /// scan number int scan_number_ = 0; /// is positive or not bool is_positive_ = false; /// if this peak group has been targeted bool is_targeted_ = false; /// monoisotopic mass double monoisotopic_mass_ = -1.0; /// summed intensity float intensity_ = 0.f; /// index to specify if this peak_group is a target, a noise, or a signal decoy. PeakGroup::TargetDecoyType target_decoy_type_ = target; /// up to which negative isotope index should be considered for isotope pattern matching. /// By considering negative isotopes, one can reduce isotope index error. int min_negative_isotope_index_ = -1; /// distance between consecutive isotopes. Can be different for decoys double iso_da_distance_ = Constants::ISOTOPE_MASSDIFF_55K_U; /// scoring variables /// the charge for which the charge SNR is maximized int max_snr_abs_charge_ = -1; /// cosine score between averagine and the observed isotope pattern float isotope_cosine_score_ = 0.f; /// charge fit score float charge_score_ = 0.f; /// quality score double qscore_ = .0; /// quality score when considering correlation between masses within the same feature. double qscore2D_ = -1.0f; float avg_ppm_error_ = 0.f; float avg_da_error_ = 0.f; /// total SNR float snr_ = 0.f; /// q value, only active when FDR report is activated. float qvalue_ = 1.f; }; } // namespace OpenMS namespace std { /// std::hash specialization for OpenMS::PeakGroup /// Hashes all fields used in operator== (monoisotopic mass and intensity) template<> struct hash<OpenMS::PeakGroup> { std::size_t operator()(const OpenMS::PeakGroup& pg) const noexcept { std::size_t seed = OpenMS::hash_float(pg.getMonoMass()); OpenMS::hash_combine(seed, OpenMS::hash_float(pg.getIntensity())); return seed; } }; } // namespace std
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/ANALYSIS/TOPDOWN/TopDownIsobaricQuantification.h
.h
2,585
69
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Kyowon Jeon $ // $Authors: Kyowon Jeong $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/ANALYSIS/QUANTITATION/IsobaricQuantitationMethod.h> #include <OpenMS/ANALYSIS/TOPDOWN/DeconvolvedSpectrum.h> #include <OpenMS/ANALYSIS/TOPDOWN/FLASHHelperClasses.h> #include <OpenMS/ANALYSIS/TOPDOWN/PeakGroup.h> #include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h> #include <iomanip> #include <iostream> namespace OpenMS { /** @brief Isobaric quantification for Top down proteomics. The report ion ratios from multiple MS2 are merged when their precursor masses belong to the same deconvolved features (MassFeature instances). @ingroup Topdown */ class OPENMS_DLLAPI TopDownIsobaricQuantification : public DefaultParamHandler { public: /// constructor TopDownIsobaricQuantification(); /// destructor ~TopDownIsobaricQuantification() override = default; /// copy constructor TopDownIsobaricQuantification(const TopDownIsobaricQuantification&); /// move constructor TopDownIsobaricQuantification(TopDownIsobaricQuantification&& other) = default; /// assignment operator TopDownIsobaricQuantification& operator=(const TopDownIsobaricQuantification& other); /** * Run quantification * @param[in] exp the MS experiment * @param[in] deconvolved_spectra deconvolved spectra for which the quantification will be carried out * @param[out] mass_features mass features that are used to merge quantification results for the MS2 spectra from the same precursor mass */ void quantify(const MSExperiment& exp, std::vector<DeconvolvedSpectrum>& deconvolved_spectra, const std::vector<FLASHHelperClasses::MassFeature>& mass_features); protected: void updateMembers_() override; /// implemented for DefaultParamHandler void setDefaultParams_(); private: /// The quantification method used for the dataset to be analyzed. std::map<String, std::unique_ptr<IsobaricQuantitationMethod>> quant_methods_; /// retain only fully quantified ratios bool only_fully_quantified_ = false; void addMethod_(std::unique_ptr<IsobaricQuantitationMethod> ptr) { std::string internal_name = ptr->getMethodName(); quant_methods_[internal_name] = std::move(ptr); } }; } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/ANALYSIS/TOPDOWN/PeakGroupScoring.h
.h
1,981
56
// Copyright (c) 2002-present, The OpenMS Team -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Kyowon Jeong $ // $Authors: Kyowon Jeong $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/ANALYSIS/TOPDOWN/DeconvolvedSpectrum.h> #include <OpenMS/ANALYSIS/TOPDOWN/FLASHHelperClasses.h> #include <OpenMS/KERNEL/Peak1D.h> #include <OpenMS/METADATA/Precursor.h> namespace OpenMS { class PeakGroup; /** @brief scoring functions for PeakGroup. For now, only Qscore has been implemented. For Qscore, the weight vector has been determined by logistic regression. In the future, other technique such as deep learning would be used. @ingroup Topdown */ class OPENMS_DLLAPI PeakGroupScoring { public: typedef FLASHHelperClasses::LogMzPeak LogMzPeak; /// get QScore for a peak group of specific abs_charge static double getQscore(const PeakGroup* pg); /// Write Csv file for Qscore training. static void writeAttCsvForQscoreTraining(const DeconvolvedSpectrum& deconvolved_spectrum, std::fstream& f); /// Write Csv file for Qscore training header. static void writeAttCsvForQscoreTrainingHeader(std::fstream& f); /// get Deep learning based peak group score. Not implemented yet. static double getDLscore(PeakGroup* pg, const MSSpectrum& spec, const FLASHHelperClasses::PrecalculatedAveragine& avg, double tol); private: /// convert a peak group to a feature vector for setQscore calculation static std::vector<double> toFeatureVector_(const PeakGroup* pg); /// the weights for Qscore calculation static std::vector<double> weight_; /// charge and isotope counts for DL scoring. static const int charge_count_for_DL_scoring_ = 11; static const int iso_count_for_DL_scoring_ = 13; }; } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/ANALYSIS/TOPDOWN/DeconvolvedSpectrum.h
.h
6,656
170
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Kyowon Jeong, Jihyung Kim $ // $Authors: Kyowon Jeong, Jihyung Kim $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/ANALYSIS/TOPDOWN/FLASHHelperClasses.h> #include <OpenMS/ANALYSIS/TOPDOWN/PeakGroup.h> #include <OpenMS/KERNEL/MSSpectrum.h> #include <iomanip> namespace OpenMS { class PeakGroup; /** @brief A class representing a deconvolved spectrum. DeconvolvedSpectrum consists of PeakGroup instances representing masses. For MSn n>1, a PeakGroup representing the precursor mass is also added in this class. Properly assigning a precursor mass from the original precursor peak and its deconvolution result is very important in top down proteomics. This assignment is performed here for conventional acquired datasets. But for FLASHIda acquired datasets, the assignment is already done by FLASHIda. So this class simply use the results from FLASHIda log file for assignment. The parsing of FLASHIda log file is done in FLASHDeconv tool class. */ class OPENMS_DLLAPI DeconvolvedSpectrum { public: typedef FLASHHelperClasses::LogMzPeak LogMzPeak; /// default constructor DeconvolvedSpectrum() = default; /** @brief Constructor for DeconvolvedSpectrum. Takes the spectrum and scan number calculated from outside @param[in] scan_number scan number of the spectrum */ explicit DeconvolvedSpectrum(int scan_number); /// default destructor ~DeconvolvedSpectrum() = default; /// copy constructor DeconvolvedSpectrum(const DeconvolvedSpectrum&) = default; /// move constructor DeconvolvedSpectrum(DeconvolvedSpectrum&& other) noexcept = default; /// assignment operator DeconvolvedSpectrum& operator=(const DeconvolvedSpectrum& deconvolved_spectrum) = default; /// Convert DeconvolvedSpectrum to MSSpectrum (e.g., used to store in mzML format). /// @param[in] to_charge the charge of each peak in mzml output. /// @param[in] tol the ppm tolerance /// @param[in] retain_undeconvolved if set, undeconvolved peaks in the original peaks are output (assuming their abs charge == 1 and m/zs are adjusted with the to_charge parameter) MSSpectrum toSpectrum(int to_charge, double tol = 10.0, bool retain_undeconvolved = false); /// original spectrum getter const MSSpectrum& getOriginalSpectrum() const; /// get precursor peak group for MSn (n>1) spectrum. It returns an empty peak group if no peak group is registered (by registerPrecursor) const PeakGroup& getPrecursorPeakGroup() const; /// precursor charge getter (set in registerPrecursor) int getPrecursorCharge() const; /// get precursor peak const Precursor& getPrecursor() const; /// get possible max mass of the deconvolved masses - for MS1, max mass specified by user /// for MSn, min value between max mass specified by the user and precursor mass /// @param[in] max_mass the max mass specified by the user double getCurrentMaxMass(double max_mass) const; /// get possible min mass of the deconvolved masses - for MS1, min mass specified by user /// for MSn, 50.0 /// @param[in] min_mass the min mass specified by the user double getCurrentMinMass(double min_mass) const; /// get possible max charge of the deconvolved masses - for MS1, max charge specified by user /// for MSn, min value between max charge specified by the user and precursor charge /// @param[in] max_abs_charge the max absolute value of the charge specified by the user int getCurrentMaxAbsCharge(int max_abs_charge) const; /// get scan number of the original spectrum int getScanNumber() const; /// get precursor scan number - only if it is registered. Otherwise return 0 int getPrecursorScanNumber() const; /// get activation method const Precursor::ActivationMethod& getActivationMethod() const; /// return isobaric quantities FLASHHelperClasses::IsobaricQuantities getQuantities() const; /// set isobaric quantities void setQuantities(const FLASHHelperClasses::IsobaricQuantities& quantities); /// set precursor for MSn for n>1 void setPrecursor(const Precursor& precursor); /// set precursor scan number void setPrecursorScanNumber(int scan_number); /// set activation method void setActivationMethod(const Precursor::ActivationMethod& method); /// set precursor peakGroup void setPrecursorPeakGroup(const PeakGroup& pg); /// original spectrum setter void setOriginalSpectrum(const MSSpectrum& spec); /// set peak groups in this spectrum void setPeakGroups(std::vector<PeakGroup>& x); /// iterators and vector operators for std::vector<PeakGroup> peak_groups_ in this spectrum std::vector<PeakGroup>::const_iterator begin() const noexcept; std::vector<PeakGroup>::const_iterator end() const noexcept; std::vector<PeakGroup>::iterator begin() noexcept; std::vector<PeakGroup>::iterator end() noexcept; /// PeakGroup vector functions and operators const PeakGroup& operator[](Size i) const; PeakGroup& operator[](Size i); void push_back(const PeakGroup& pg); void emplace_back(const PeakGroup& pg); void pop_back(); PeakGroup& back(); Size size() const noexcept; void clear(); void reserve(Size n); bool empty() const; bool isDecoy() const; /// sort by deconvolved monoisotopic masses void sort(); /// sort by Qscore of peakGroups void sortByQscore(); /// comparison operators bool operator<(const DeconvolvedSpectrum& a) const; bool operator>(const DeconvolvedSpectrum& a) const; bool operator==(const DeconvolvedSpectrum& a) const; private: /// peak groups (deconvolved masses) std::vector<PeakGroup> peak_groups_; /// the original raw spectrum (not deconvolved) MSSpectrum spec_; /// precursor peakGroup (or mass) PeakGroup precursor_peak_group_; /// precursor raw peak (not deconvolved one) Precursor precursor_peak_; /// activation method for file output Precursor::ActivationMethod activation_method_ = Precursor::ActivationMethod::CID; /// scan number and precursor scan number int scan_number_ = 0, precursor_scan_number_ = 0; /// isobaric quantities FLASHHelperClasses::IsobaricQuantities quantities_; }; } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/ANALYSIS/TOPDOWN/SpectralDeconvolution.h
.h
14,116
307
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Kyowon Jeong, Jihyung Kim $ // $Authors: Kyowon Jeong, Jihyung Kim $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/ANALYSIS/TOPDOWN/DeconvolvedSpectrum.h> #include <OpenMS/ANALYSIS/TOPDOWN/FLASHHelperClasses.h> #include <OpenMS/ANALYSIS/TOPDOWN/PeakGroup.h> #include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h> #include <OpenMS/DATASTRUCTURES/Matrix.h> #include <OpenMS/KERNEL/MSExperiment.h> #include <OpenMS/KERNEL/MSSpectrum.h> #include <boost/dynamic_bitset.hpp> #include <iostream> namespace OpenMS { /** @brief FLASHDeconv algorithm: ultrafast mass deconvolution algorithm for top down mass spectrometry dataset From MSSpectrum, this class outputs DeconvolvedSpectrum. Deconvolution takes three steps: i) decharging and select candidate masses - speed up via binning ii) collecting isotopes from the candidate masses and deisotope - peak groups are defined here iii) scoring and filter out low scoring masses (i.e., peak groups) @ingroup Topdown */ class OPENMS_DLLAPI SpectralDeconvolution : public DefaultParamHandler { public: typedef FLASHHelperClasses::PrecalculatedAveragine PrecalculatedAveragine; typedef FLASHHelperClasses::LogMzPeak LogMzPeak; /// default constructor SpectralDeconvolution(); /// copy constructor SpectralDeconvolution(const SpectralDeconvolution&) = default; /// move constructor SpectralDeconvolution(SpectralDeconvolution&& other) = default; /// assignment operator SpectralDeconvolution& operator=(const SpectralDeconvolution& fd) = default; /// move assignment operator SpectralDeconvolution& operator=(SpectralDeconvolution&& fd) = default; /// destructor ~SpectralDeconvolution() = default; /** @brief main deconvolution function that generates the deconvolved target and dummy spectrum based on the original spectrum. @param[in] spec the original spectrum @param[in] scan_number scan number from input spectrum. @param[in] precursor_peak_group precursor peak group */ void performSpectrumDeconvolution(const MSSpectrum& spec, int scan_number, const PeakGroup& precursor_peak_group); /// return deconvolved spectrum DeconvolvedSpectrum& getDeconvolvedSpectrum(); /// get calculated averagine. Call after calculateAveragine is called. const PrecalculatedAveragine& getAveragine(); /// set calculated averagine void setAveragine(const PrecalculatedAveragine& avg); /** @brief set targeted or excluded masses for targeted deconvolution. Masses are targeted or excluded in all ms levels. * @param[out] masses target masses to set @param[in] exclude if set, masses are excluded. */ void setTargetMasses(const std::vector<double>& masses, bool exclude = false); /** @brief precalculate averagine (for predefined mass bins) to speed up averagine generation @param[in] use_RNA_averagine if set, averagine for RNA (nucleotides) is calculated */ void calculateAveragine(bool use_RNA_averagine); /// when estimating tolerance, max_mass_dalton_tolerance_ should be large void setToleranceEstimation() { max_mass_dalton_tolerance_ = 100; } /// convert double to nominal mass static int getNominalMass(double mass); /** calculate cosine between two vectors a and b with additional parameters for fast calculation * @param[in] a vector a * @param[in] a_start non zero start index of a * @param[in] a_end non zero end index of a (exclusive) * @param[in] b vector b * @param[out] offset element index offset between a and b * @param[in] min_iso_len minimum isotope size. If isotope size is less than this, return 0 */ static float getCosine(const std::vector<float>& a, int a_start, int a_end, const IsotopeDistribution& b, int offset, int min_iso_len); /** @brief Examine intensity distribution over isotope indices. Also determines the most plausible isotope index or, monoisotopic mono_mass @param[in] mono_mass monoisotopic mass @param[in] per_isotope_intensities vector of intensities associated with each isotope - aggregated through charges @param[in] offset output offset between input monoisotopic mono_mass and determined monoisotopic mono_mass @param[in] avg precalculated averagine @param[in] iso_int_shift isotope shift in per_isotope_intensities. @param[in] window_width isotope offset value range. If -1, set automatically. @param[in] excluded_masses masses not considered in the calculation. @return calculated cosine similarity score */ static float getIsotopeCosineAndIsoOffset(double mono_mass, const std::vector<float>& per_isotope_intensities, int& offset, const PrecalculatedAveragine& avg, int iso_int_shift, int window_width, const std::vector<double>& excluded_masses); /** * set target dummy type for the SpectralDeconvolution run. All masses from the target SpectralDeconvolution run will have the target_decoy_type_. * @param[out] target_decoy_type This target_decoy_type_ specifies if a PeakGroup is a target (0), charge dummy (1), noise dummy (2), or isotope dummy (3) * @param[out] target_dspec_for_decoy_calcualtion target masses from normal deconvolution */ void setTargetDecoyType(PeakGroup::TargetDecoyType target_decoy_type, const DeconvolvedSpectrum& target_dspec_for_decoy_calcualtion); /// minimum isotopologue count in a peak group const static int min_iso_size = 2; protected: void updateMembers_() override; private: /// FLASHDeconv parameters /// allowed isotope error in deconvolved mass to calculate qvalue int allowed_iso_error_ = -1; /// min charge and max charge subject to analysis, set by users int min_abs_charge_, max_abs_charge_; /// is positive mode bool is_positive_; /// mass ranges of deconvolution, set by users double min_mass_, max_mass_; /// current_max_charge_: controlled by precursor charge for MSn n>1; otherwise just max_abs_charge_ int current_max_charge_; /// max mass is controlled by precursor mass for MSn n>1; otherwise just max_mass double current_max_mass_; /// max mass is max_mass for MS1 and 50 for MS2 double current_min_mass_; /// isotope distance for noise decoy. This distance has been determined so i) it is close to the mass of 13C - 12C yet is not close to any correct isotope distances of different charges (from 1 to 10). double noise_iso_delta_ = .9444; /// minimum number of peaks supporting a mass const static int min_support_peak_count_ = 2; /// tolerance in ppm for each MS level DoubleList tolerance_; /// bin multiplication factor (log mz * bin_mul_factors_ = bin number) - for fast convolution, binning is used DoubleList bin_mul_factors_; /// Isotope cosine threshold for each MS level DoubleList min_isotope_cosine_; /// snr threshold for each MS level DoubleList min_snr_; /// minimum Qscore of a deconvolved mass double min_qscore_ = .2; /// the peak group vector from normal run. This is used when dummy masses are generated. const DeconvolvedSpectrum* target_dspec_for_decoy_calculation_; /// PeakGroup::TargetDecoyType values PeakGroup::TargetDecoyType target_decoy_type_ = PeakGroup::TargetDecoyType::target; /// precalculated averagine distributions for fast averagine generation FLASHHelperClasses::PrecalculatedAveragine avg_; /// mass bins that are targeted for FLASHIda global targeting mode boost::dynamic_bitset<> target_mass_bins_; std::vector<double> target_mono_masses_; /// mass bins that are excluded for FLASHIda global targeting mode std::vector<double> excluded_masses_; /// mass bins that are previously deconvolved and excluded for decoy mass generation boost::dynamic_bitset<> excluded_mass_bins_for_decoy_runs_; std::vector<double> excluded_peak_masses_for_decoy_runs_; std::vector<double> excluded_masses_for_decoy_runs_; /// Stores log mz peaks std::vector<LogMzPeak> log_mz_peaks_; /// selected_peak_groups_ stores the deconvolved mass peak groups DeconvolvedSpectrum deconvolved_spectrum_; /// binned_log_masses_ stores the selected bins for this spectrum + overlapped spectrum (previous a few spectra). boost::dynamic_bitset<> binned_log_masses_; /// binned_log_mz_peaks_ stores the binned log mz peaks boost::dynamic_bitset<> binned_log_mz_peaks_; /// This stores the "universal pattern" std::vector<double> universal_pattern_; /// This stores the patterns for harmonic reduction Matrix<double> harmonic_pattern_matrix_; /// This stores the "universal pattern" in binned dimension std::vector<int> binned_universal_pattern_; /// This stores the patterns for harmonic reduction in binned dimension Matrix<int> binned_harmonic_patterns; /// minimum mass and mz values representing the first bin of massBin and mzBin, respectively: to save memory space double mass_bin_min_value_; double mz_bin_min_value_; /// current ms Level uint ms_level_; /// isotope dalton distance double iso_da_distance_; /// for precursor targetting. int target_precursor_charge_ = 0; double target_precursor_mz_ = 0; /// this is additional mass tolerance in Da to get more high signal-to-ratio peaks in this candidate peakgroup finding double max_mass_dalton_tolerance_ = .16; /** @brief static function that converts bin to value @param[in] bin bin number @param[in] min_value minimum value (corresponding to bin number = 0) @param[in] bin_mul_factor bin multiplication factor: bin_value = (min_value + bin_number/ bin_mul_factors_) @return value corresponding to bin */ static double getBinValue_(Size bin, double min_value, double bin_mul_factor); /** @brief static function that converts value to bin @param[in] value value @param[in] min_value minimum value (corresponding to bin number = 0) @param[in] bin_mul_factor bin multiplication factor: bin_number = (bin_value * bin_mul_factors_ - min_value) @return bin corresponding to value */ static Size getBinNumber_(double value, double min_value, double bin_mul_factor); /// generate log mz peaks from the input spectrum void updateLogMzPeaks_(); /** @brief generate mz bins and intensity per mz bin from log mz peaks @param[in] bin_number number of mz bins @param[in] binned_log_mz_peak_intensities intensity per mz bin */ void binLogMzPeaks_(Size bin_number, std::vector<float>& binned_log_mz_peak_intensities); /// get mass value for input mass bin: used for debugging double getMassFromMassBin_(Size mass_bin, double bin_mul_factor) const; /// get mz value for input mz bin: used for debugging double getMzFromMzBin_(Size mass_bin, double bin_mul_factor) const; /// Generate peak groups from the input spectrum void generatePeakGroupsFromSpectrum_(); /// filter out overlapping masses static void removeOverlappingPeakGroups_(DeconvolvedSpectrum& dspec, double tol, PeakGroup::TargetDecoyType target_decoy_type = PeakGroup::TargetDecoyType::target); /** @brief Update binned_log_masses_. It select candidate mass bins using the universal pattern, eliminate possible harmonic masses. This function does not perform deisotoping @param[in] mz_intensities per mz bin intensity @return a matrix containing charge ranges for all found masses */ Matrix<int> updateMassBins_(const std::vector<float>& mz_intensities); /** @brief Subfunction of updateMassBins_. @param[in,out] mass_intensities per mass bin intensity @return a matrix containing charge ranges for all found masses */ Matrix<int> filterMassBins_(const std::vector<float>& mass_intensities); /** @brief Subfunction of updateMassBins_. It select candidate masses and update binned_log_masses_ using the universal pattern, eliminate possible harmonic masses @param[in] mass_intensities mass bin intensities which are updated in this function @param[in] mz_intensities mz bin intensities */ void updateCandidateMassBins_(std::vector<float>& mass_intensities, const std::vector<float>& mz_intensities); /** @brief For selected masses in binned_log_masses_, select the peaks from the original spectrum. Also isotopic peaks are clustered in this function. @param[in] per_mass_abs_charge_ranges charge range per mass */ void getCandidatePeakGroups_(const Matrix<int>& per_mass_abs_charge_ranges); /// Make the universal pattern. void setFilters_(); /// function for peak group scoring and filtering void scoreAndFilterPeakGroups_(); /// filter out charge error masses void removeChargeErrorPeakGroups_(DeconvolvedSpectrum& dspec, const PeakGroup::TargetDecoyType& target_decoy_type) const; /// filter out excluded masses void removeExcludedMasses_(DeconvolvedSpectrum& dspec, std::vector<double> excluded_masses, double tol) const; void setTargetPrecursorCharge_(); /// prepare signal decoy exclusions for decoy runs void prepareSignalDecoyExclusions_(); /// prepare noise decoy spectrum by filtering signal peaks void prepareNoiseDecoySpectrum_(const MSSpectrum& spec); /// register precursor information for MSn spectra (n > 1) void registerPrecursorForMSn_(const PeakGroup& precursor_peak_group); bool isPeakGroupInExcludedMassForDecoyRuns_(const PeakGroup& peak_group, double tol, int offset = 0) const; }; } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/ANALYSIS/TOPDOWN/Qvalue.h
.h
1,235
36
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Kyowon Jeong $ // $Authors: Kyowon Jeong $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/ANALYSIS/TOPDOWN/DeconvolvedSpectrum.h> #include <OpenMS/ANALYSIS/TOPDOWN/FLASHHelperClasses.h> #include <OpenMS/KERNEL/Peak1D.h> namespace OpenMS { class PeakGroup; /** @brief Qvalue : contains functions to calculate Qvalues from deconvolution quality score (Qscore) defined in PeakGroupScoring @ingroup Topdown */ class OPENMS_DLLAPI Qvalue { public: typedef FLASHHelperClasses::LogMzPeak LogMzPeak; /// Calculate and perform a batch update of peak group qvalues using Qscores of target and dummy peak groups in deconvolved spectra, when FDR report is necessary. /// @param[out] deconvolved_spectra target and decoy deconvolved spectra /// @return the noise decoy weight for decoy output static double updatePeakGroupQvalues(std::vector<DeconvolvedSpectrum>& deconvolved_spectra); private: }; } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/ANALYSIS/TOPDOWN/MassFeatureTrace.h
.h
2,762
70
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Kyowon Jeong, Jihyung Kim $ // $Authors: Kyowon Jeong, Jihyung Kim $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/ANALYSIS/TOPDOWN/DeconvolvedSpectrum.h> #include <OpenMS/ANALYSIS/TOPDOWN/FLASHHelperClasses.h> #include <OpenMS/ANALYSIS/TOPDOWN/PeakGroup.h> #include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h> #include <OpenMS/FEATUREFINDER/MassTraceDetection.h> #include <iomanip> #include <iostream> namespace OpenMS { /** @brief Feature trace in mass dimension for FLASHDeconv This class performs mass tracing on the deconvolved masses by SpectralDeconvolution In other words, per spectrum deconvolved masses are converted into deconvolved features Currently only works for MS1 spectra. (Top-down DIA is not yet used much). Every time an MS1 spectrum is deconvolved, the relevant information is stored in this class. This class also comes with tsv, TopFD feature file formats. @ingroup Topdown */ class OPENMS_DLLAPI MassFeatureTrace : public DefaultParamHandler { public: typedef FLASHHelperClasses::PrecalculatedAveragine PrecalculatedAveragine; typedef FLASHHelperClasses::LogMzPeak LogMzPeak; /// constructor MassFeatureTrace(); /// destructor ~MassFeatureTrace() override = default; /// copy constructor MassFeatureTrace(const MassFeatureTrace&) = default; /// move constructor MassFeatureTrace(MassFeatureTrace&& other) = default; /// assignment operator MassFeatureTrace& operator=(const MassFeatureTrace& fd) = default; MassFeatureTrace& operator=(MassFeatureTrace&& fd) = default; /** @brief Find mass features. @param[in] averagine precalculated averagine for cosine calculation @param[in] deconvolved_spectra the spectra on which features are found @param[in] ms_level ms level to process @param[out] is_decoy if set, only process decoy spectra. otherwise only target spectra */ std::vector<FLASHHelperClasses::MassFeature> findFeaturesAndUpdateQscore2D(const PrecalculatedAveragine& averagine, std::vector<DeconvolvedSpectrum>& deconvolved_spectra, int ms_level = 1, bool is_decoy = false); protected: void updateMembers_() override; private: /// peak group information is stored in here for tracing std::map<double, std::map<double, PeakGroup>> peak_group_map_; // rt , mono mass, peakgroup }; } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/ANALYSIS/TARGETED/IncludeExcludeTarget.h
.h
6,106
217
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Andreas Bertsch $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/KERNEL/StandardTypes.h> #include <OpenMS/METADATA/CVTermList.h> #include <OpenMS/ANALYSIS/TARGETED/TargetedExperimentHelper.h> #include <OpenMS/CONCEPT/HashUtils.h> #include <functional> #include <vector> namespace OpenMS { /** @brief This class stores a SRM/MRM transition The default values for precursor and product m/z values are set to numeric_limits<double>::max(). Default values for precursor an product charge is set to numeric_limits<Int>::max(). */ class OPENMS_DLLAPI IncludeExcludeTarget : public CVTermList { public: typedef TargetedExperimentHelper::Configuration Configuration; typedef TargetedExperimentHelper::RetentionTime RetentionTime; /** @name Constructors and destructors */ //@{ /// default constructor IncludeExcludeTarget(); /// copy constructor IncludeExcludeTarget(const IncludeExcludeTarget & rhs); /// destructor ~IncludeExcludeTarget() override; //@} /// assignment operator IncludeExcludeTarget & operator=(const IncludeExcludeTarget & rhs); /** @name Accessors */ //@{ void setName(const String & name); const String & getName() const; void setPeptideRef(const String & peptide_ref); const String & getPeptideRef() const; void setCompoundRef(const String & compound_ref); const String & getCompoundRef() const; /// sets the precursor mz (Q1 value) void setPrecursorMZ(double mz); double getPrecursorMZ() const; void setPrecursorCVTermList(const CVTermList & list); void addPrecursorCVTerm(const CVTerm & cv_term); const CVTermList & getPrecursorCVTermList() const; void setProductMZ(double mz); double getProductMZ() const; void setProductCVTermList(const CVTermList & list); void addProductCVTerm(const CVTerm & cv_term); const CVTermList & getProductCVTermList() const; void setInterpretations(const std::vector<CVTermList> & interpretations); const std::vector<CVTermList> & getInterpretations() const; void addInterpretation(const CVTermList & interpretation); void setConfigurations(const std::vector<Configuration> & configuration); const std::vector<Configuration> & getConfigurations() const; void addConfiguration(const Configuration & configuration); void setPrediction(const CVTermList & prediction); void addPredictionTerm(const CVTerm & prediction); const CVTermList & getPrediction() const; void setRetentionTime(RetentionTime rt); const RetentionTime & getRetentionTime() const; //@} /** @name Predicates */ //@{ /// equality operator bool operator==(const IncludeExcludeTarget & rhs) const; /// inequality operator bool operator!=(const IncludeExcludeTarget & rhs) const; //@} protected: void updateMembers_(); String name_; double precursor_mz_; CVTermList precursor_cv_terms_; double product_mz_; CVTermList product_cv_terms_; std::vector<CVTermList> interpretation_list_; String peptide_ref_; String compound_ref_; std::vector<Configuration> configurations_; CVTermList prediction_; RetentionTime rts_; }; } // namespace OpenMS namespace std { /// std::hash specialization for OpenMS::IncludeExcludeTarget template <> struct hash<OpenMS::IncludeExcludeTarget> { std::size_t operator()(const OpenMS::IncludeExcludeTarget& t) const noexcept { std::size_t seed = 0; // Hash CVTermList base class OpenMS::hash_combine(seed, OpenMS::hashCVTermList(t)); // Hash name_ OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(t.getName())); // Hash precursor_mz_ and precursor_cv_terms_ OpenMS::hash_combine(seed, OpenMS::hash_float(t.getPrecursorMZ())); OpenMS::hash_combine(seed, OpenMS::hashCVTermList(t.getPrecursorCVTermList())); // Hash product_mz_ and product_cv_terms_ OpenMS::hash_combine(seed, OpenMS::hash_float(t.getProductMZ())); OpenMS::hash_combine(seed, OpenMS::hashCVTermList(t.getProductCVTermList())); // Hash interpretation_list_ for (const auto& interp : t.getInterpretations()) { OpenMS::hash_combine(seed, OpenMS::hashCVTermList(interp)); } // Hash peptide_ref_ and compound_ref_ OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(t.getPeptideRef())); OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(t.getCompoundRef())); // Hash configurations_ for (const auto& config : t.getConfigurations()) { OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(config.contact_ref)); OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(config.instrument_ref)); OpenMS::hash_combine(seed, OpenMS::hashCVTermList(config)); for (const auto& validation : config.validations) { OpenMS::hash_combine(seed, OpenMS::hashCVTermList(validation)); } } // Hash prediction_ OpenMS::hash_combine(seed, OpenMS::hashCVTermList(t.getPrediction())); // Hash rts_ (RetentionTime) const auto& rt = t.getRetentionTime(); OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(rt.software_ref)); OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(rt.retention_time_unit))); OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(rt.retention_time_type))); OpenMS::hash_combine(seed, OpenMS::hash_int(rt.isRTset() ? 1 : 0)); if (rt.isRTset()) { OpenMS::hash_combine(seed, OpenMS::hash_float(rt.getRT())); } OpenMS::hash_combine(seed, OpenMS::hashCVTermListInterface(rt)); return seed; } }; } // namespace std
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/ANALYSIS/TARGETED/TargetedExperiment.h
.h
9,660
323
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Andreas Bertsch $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/KERNEL/StandardTypes.h> #include <OpenMS/ANALYSIS/MRM/ReactionMonitoringTransition.h> #include <OpenMS/ANALYSIS/TARGETED/IncludeExcludeTarget.h> #include <OpenMS/METADATA/CVTerm.h> #include <OpenMS/METADATA/CVTermList.h> #include <OpenMS/METADATA/Software.h> #include <OpenMS/METADATA/SourceFile.h> #include <OpenMS/ANALYSIS/TARGETED/TargetedExperimentHelper.h> #include <vector> namespace OpenMS { /** @brief A description of a targeted experiment containing precursor and production ions. A targeted experiment contains transitions used in SRM/MRM as well as SWATH-MS/DIA analysis using a targeted approach. This container holds descriptions of the precursors and product ions analyzed in such a targeted experiment. Generally, the precursor ions can be peptides or small molecules (for metabolomics) and each precursor has a set of product ions associated with it. The TargetedExperiment can be stored to disk either in .traml format using the @ref TraMLFile "TraMLFile" or in .tsv format using the TransitionTSVFile. */ class OPENMS_DLLAPI TargetedExperiment { public: struct OPENMS_DLLAPI SummaryStatistics { Size protein_count; Size peptide_count; Size compound_count; Size transition_count; std::map<ReactionMonitoringTransition::DecoyTransitionType, size_t> decoy_counts; ///< # target/decoy transitions bool contains_invalid_references; }; typedef TargetedExperimentHelper::CV CV; typedef TargetedExperimentHelper::Protein Protein; typedef TargetedExperimentHelper::RetentionTime RetentionTime; typedef TargetedExperimentHelper::Compound Compound; typedef TargetedExperimentHelper::Peptide Peptide; typedef TargetedExperimentHelper::Contact Contact; typedef TargetedExperimentHelper::Publication Publication; typedef TargetedExperimentHelper::Instrument Instrument; typedef TargetedExperimentHelper::Prediction Prediction; typedef TargetedExperimentHelper::Interpretation Interpretation; typedef ReactionMonitoringTransition Transition; typedef Residue IonType; // IonType enum of Interpretation class typedef std::map<String, const Protein *> ProteinReferenceMapType; typedef std::map<String, const Peptide *> PeptideReferenceMapType; typedef std::map<String, const Compound *> CompoundReferenceMapType; /** @name Constructors and destructors */ //@{ /// default constructor TargetedExperiment(); /// copy constructor TargetedExperiment(const TargetedExperiment & rhs); /// move constructor TargetedExperiment(TargetedExperiment && rhs) noexcept; /// destructor virtual ~TargetedExperiment(); //@} /// assignment operator TargetedExperiment & operator=(const TargetedExperiment & rhs); /// move assignment operator TargetedExperiment & operator=(TargetedExperiment && rhs) noexcept; /** @name Predicates */ //@{ bool operator==(const TargetedExperiment & rhs) const; bool operator!=(const TargetedExperiment & rhs) const; //@} /** @brief Joins two targeted experiments. Proteins, peptides and transitions are merged (see operator+= for details). */ TargetedExperiment operator+(const TargetedExperiment & rhs) const; /** @brief Add one targeted experiment to another. @param[in] rhs The targeted experiment to add to this one. */ TargetedExperiment& operator+=(const TargetedExperiment & rhs); TargetedExperiment& operator+=(TargetedExperiment && rhs); /** @brief Clears all data and meta data @param[in] clear_meta_data If @em true, all meta data is cleared in addition to the data. */ void clear(bool clear_meta_data); /// return summary stats about this TE. SummaryStatistics getSummary() const; /** @name Accessors */ //@{ // cv list void setCVs(const std::vector<CV> & cvs); const std::vector<CV> & getCVs() const; void addCV(const CV & cv); // contact list void setContacts(const std::vector<Contact> & contacts); const std::vector<Contact> & getContacts() const; void addContact(const Contact & contact); // publication list void setPublications(const std::vector<Publication> & publications); const std::vector<Publication> & getPublications() const; void addPublication(const Publication & publication); // target list void setTargetCVTerms(const CVTermList & cv_terms); const CVTermList & getTargetCVTerms() const; void addTargetCVTerm(const CVTerm & cv_term); void setTargetMetaValue(const String & name, const DataValue & value); // instrument list void setInstruments(const std::vector<Instrument> & instruments); const std::vector<Instrument> & getInstruments() const; void addInstrument(const Instrument & instrument); // software list void setSoftware(const std::vector<Software> & software); const std::vector<Software> & getSoftware() const; void addSoftware(const Software & software); // protein list void setProteins(const std::vector<Protein> & proteins); void setProteins(std::vector<Protein> && proteins); const std::vector<Protein> & getProteins() const; const Protein & getProteinByRef(const String & ref) const; bool hasProtein(const String & ref) const; void addProtein(const Protein & protein); // compound list void setCompounds(const std::vector<Compound> & rhs); const std::vector<Compound> & getCompounds() const; void addCompound(const Compound & rhs); void setPeptides(const std::vector<Peptide> & rhs); void setPeptides(std::vector<Peptide> && rhs); const std::vector<Peptide> & getPeptides() const; bool hasPeptide(const String & ref) const; const Peptide & getPeptideByRef(const String & ref) const; bool hasCompound(const String & ref) const; const Compound & getCompoundByRef(const String & ref) const; void addPeptide(const Peptide & rhs); /// set transition list void setTransitions(const std::vector<ReactionMonitoringTransition> & transitions); void setTransitions(std::vector<ReactionMonitoringTransition> && transitions); /// returns the transition list const std::vector<ReactionMonitoringTransition> & getTransitions() const; /// adds a transition to the list void addTransition(const ReactionMonitoringTransition & transition); void setIncludeTargets(const std::vector<IncludeExcludeTarget> & targets); const std::vector<IncludeExcludeTarget> & getIncludeTargets() const; void addIncludeTarget(const IncludeExcludeTarget & target); void setExcludeTargets(const std::vector<IncludeExcludeTarget> & targets); const std::vector<IncludeExcludeTarget> & getExcludeTargets() const; void addExcludeTarget(const IncludeExcludeTarget & target); /// sets the source files void setSourceFiles(const std::vector<SourceFile> & source_files); /// returns the source file list const std::vector<SourceFile> & getSourceFiles() const; /// adds a source file to the list void addSourceFile(const SourceFile & source_file); //@} ///@name Sorting peaks //@{ /** @brief Lexicographically sorts the transitions by their product m/z. */ void sortTransitionsByProductMZ(); //@} ///@name Sorting peaks //@{ /** @brief Lexicographically sorts the transitions by their name. */ void sortTransitionsByName(); //@} /** @brief Checks whether the data structure (and the underlying TraML file) contains invalid references First checks whether all of the references are unique (protein, peptide, compound). Secondly, checks that each reference is valid and points either to a protein, peptide or compound. Returns false if the file is valid. */ bool containsInvalidReferences() const; protected: void createProteinReferenceMap_() const; void createPeptideReferenceMap_() const; void createCompoundReferenceMap_() const; std::vector<CV> cvs_; std::vector<Contact> contacts_; std::vector<Publication> publications_; std::vector<Instrument> instruments_; CVTermList targets_; std::vector<Software> software_; std::vector<Protein> proteins_; std::vector<Compound> compounds_; std::vector<Peptide> peptides_; std::vector<ReactionMonitoringTransition> transitions_; std::vector<IncludeExcludeTarget> include_targets_; std::vector<IncludeExcludeTarget> exclude_targets_; std::vector<SourceFile> source_files_; mutable ProteinReferenceMapType protein_reference_map_; mutable bool protein_reference_map_dirty_; mutable PeptideReferenceMapType peptide_reference_map_; mutable bool peptide_reference_map_dirty_; mutable CompoundReferenceMapType compound_reference_map_; mutable bool compound_reference_map_dirty_; }; namespace TargetedExperimentHelper { } // namespace TargetedExperimentHelper /// prints out the summary statistics OPENMS_DLLAPI std::ostream& operator<<(std::ostream& os, const TargetedExperiment::SummaryStatistics& s); } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/ANALYSIS/TARGETED/MRMMapping.h
.h
2,537
82
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Hannes Roest $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h> #include <OpenMS/ANALYSIS/TARGETED/TargetedExperiment.h> #include <OpenMS/KERNEL/MSExperiment.h> namespace OpenMS { /** @brief A class to map targeted assays to chromatograms. */ class OPENMS_DLLAPI MRMMapping : public DefaultParamHandler { public: /** @name Constructors and destructors */ //@{ /// default constructor MRMMapping(); /// destructor ~MRMMapping() override {} //@} /** @brief Maps input chromatograms to assays in a targeted experiment The output chromatograms are an annotated copy of the input chromatograms with native id, precursor information and peptide sequence (if available) annotated in the chromatogram files. The algorithm tries to match a given set of chromatograms and targeted assays. It iterates through all the chromatograms retrieves one or more matching targeted assay for the chromatogram. By default, the algorithm assumes that a 1:1 mapping exists. If a chromatogram cannot be mapped (does not have a corresponding assay) the algorithm issues a warning, the user can specify that the program should abort in such a case (see error_on_unmapped). @note If multiple mapping is enabled (see map_multiple_assays parameter) then each mapped assay will get its own chromatogram that contains the same raw data but different meta-annotation. This *can* be useful if the same transition is used to monitor multiple analytes but may also indicate a problem with too wide mapping tolerances. */ void mapExperiment(const OpenMS::PeakMap& input_chromatograms, const OpenMS::TargetedExperiment& targeted_exp, OpenMS::PeakMap& output) const; protected: /// copy constructor MRMMapping(const MRMMapping & rhs); /// assignment operator MRMMapping & operator=(const MRMMapping & rhs); /// Synchronize members with param class void updateMembers_() override; double precursor_tol_; double product_tol_; bool map_multiple_assays_; bool error_on_unmapped_; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/ANALYSIS/TARGETED/MetaboTargetedTargetDecoy.h
.h
3,482
80
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Oliver Alka $ // $Authors: Oliver Alka $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/KERNEL/StandardTypes.h> #include <OpenMS/ANALYSIS/TARGETED/TargetedExperiment.h> namespace OpenMS { /** @brief Resolve overlapping fragments and missing decoys for experimental specific decoy generation in targeted/pseudo targeted metabolomics. */ class OPENMS_DLLAPI MetaboTargetedTargetDecoy { public: /** @brief MetaboTargetDecoyMassMapping introduces a mapping of target and decoy masses and their respective compound reference using an identifier */ class MetaboTargetDecoyMassMapping { public: String identifier; ///> unique identifier (e.g. m_id) String target_compound_ref; ///> identifier which allows to reference back to the target (e.g. target_transitions_id) String decoy_compound_ref; ///> identifier which allows to reference back to the decoy (e.g. decoy_transitions_id) std::vector<double> target_product_masses; ///> masses of target transitions std::vector<double> decoy_product_masses; ///> masses of decoy transitions }; /** @brief Constructs a mass mapping of targets and decoys using the unique m_id identifier. @param[in] t_exp TransitionExperiment holds compound and transition information used for the mapping. */ static std::vector<MetaboTargetDecoyMassMapping> constructTargetDecoyMassMapping(const TargetedExperiment& t_exp); /** @brief Resolves overlapping target and decoy transition masses by adding a specifiable mass (e.g. CH2) to the overlapping decoy fragment. @param[in,out] t_exp TransitionExperiment holds compound and transition information @param[in,out] mappings map of identifier to target and decoy masses @param[in] mass_to_add (e.g. CH2) @param[in] mz_tol m/z tolerarance for target and decoy transition masses to be considered overlapping @param[in] mz_tol_unit m/z tolerance unit ("ppm" or "Da") */ static void resolveOverlappingTargetDecoyMassesByDecoyMassShift(TargetedExperiment& t_exp, std::vector<MetaboTargetedTargetDecoy::MetaboTargetDecoyMassMapping>& mappings, const double& mass_to_add, const double& mz_tol, const String& mz_tol_unit); /** @brief Generate a decoy for targets where fragmentation tree re-rooting was not possible, by adding a specifiable mass to the target fragments. @param[in,out] t_exp TransitionExperiment holds compound and transition information @param[in,out] mappings map of identifier to target and decoy masses @param[in] mass_to_add the maximum number of transitions required per assay */ static void generateMissingDecoysByMassShift(TargetedExperiment& t_exp, std::vector<MetaboTargetedTargetDecoy::MetaboTargetDecoyMassMapping>& mappings, const double& mass_to_add); protected: /** @brief Generate a TransitionMap based on Compound_Ref and ReactionMonitoringTransitions @param[in] t_exp TransitionExperiment holds compound and transition information */ static std::map<String, std::vector<OpenMS::ReactionMonitoringTransition> > constructTransitionsMap_(const TargetedExperiment& t_exp); }; } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/ANALYSIS/TARGETED/TargetedExperimentHelper.h
.h
26,910
871
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Andreas Bertsch $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/KERNEL/StandardTypes.h> #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/CONCEPT/Exception.h> #include <OpenMS/CONCEPT/Macros.h> #include <OpenMS/CHEMISTRY/AASequence.h> #include <OpenMS/METADATA/CVTerm.h> #include <OpenMS/METADATA/CVTermList.h> #include <OpenMS/METADATA/CVTermListInterface.h> #include <OpenMS/CHEMISTRY/Residue.h> #include <OpenMS/CONCEPT/HashUtils.h> #include <boost/numeric/conversion/cast.hpp> #include <functional> namespace OpenMS { /** @brief This class stores helper structures that are used in multiple classes of the TargetedExperiment (e.g. ReactionMonitoringTransition and IncludeExcludeTarget). */ namespace TargetedExperimentHelper { struct Configuration : public CVTermList { String contact_ref; String instrument_ref; std::vector<CVTermList> validations; }; struct CV { CV(const String & new_id, const String & new_fullname, const String & new_version, const String & new_URI) : id(new_id), fullname(new_fullname), version(new_version), URI(new_URI) { } String id; String fullname; String version; String URI; bool operator==(const CV & cv) const { return id == cv.id && fullname == cv.fullname && version == cv.version && URI == cv.URI; } }; struct Protein : public CVTermList { Protein() = default; bool operator==(const Protein& rhs) const { return CVTermList::operator==(rhs) && id == rhs.id && sequence == rhs.sequence; } String id; String sequence; }; /** @brief This class stores a retention time structure that is used in TargetedExperiment (representing a TraML file) According to the standard, each retention time tag can have one or more CV terms describing the retention time in question. The unit and type of retention time are stored using the RTUnit and RTType structure while the actual value is stored in retention_time_ and can be accessed by getRT / setRT. Currently support for RT windows or lower/upper limits is not implemented but is available via CV terms. */ class OPENMS_DLLAPI RetentionTime : public CVTermListInterface { public: enum class RTUnit : std::int8_t { SECOND = 0, ///< RT stored in seconds MINUTE, ///< RT stored in minutes UNKNOWN, ///< no stored annotation SIZE_OF_RTUNIT }; enum class RTType : std::int8_t { LOCAL = 0, ///< undefined local chromatography NORMALIZED, ///< standardized reference chromatography PREDICTED, ///< predicted by referenced software HPINS, ///< H-PINS "The de facto standard providing the retention times" IRT, ///< iRT retention time standard UNKNOWN, ///< no stored annotation SIZE_OF_RTTYPE }; RetentionTime() : CVTermListInterface(), software_ref(""), retention_time_unit(RTUnit::SIZE_OF_RTUNIT), retention_time_type(RTType::SIZE_OF_RTTYPE), retention_time_set_(false), retention_time_(0.0) // retention_time_width(0.0), // retention_time_lower(0.0), // retention_time_upper(0.0) { } RetentionTime(const RetentionTime &) = default; RetentionTime(RetentionTime &&) noexcept = default; virtual ~RetentionTime() = default; RetentionTime & operator=(const RetentionTime &) & = default; RetentionTime & operator=(RetentionTime &&) & = default; bool operator==(const RetentionTime & rhs) const { return CVTermListInterface::operator==(rhs) && software_ref == rhs.software_ref && retention_time_unit == rhs.retention_time_unit && retention_time_type == rhs.retention_time_type && retention_time_set_ == rhs.retention_time_set_ && retention_time_ == rhs.retention_time_; } bool isRTset() const { return retention_time_set_; } void setRT(double rt) { retention_time_ = rt; retention_time_set_ = true; } double getRT() const { OPENMS_PRECONDITION(isRTset(), "RT needs to be set") return retention_time_; } String software_ref; RTUnit retention_time_unit; RTType retention_time_type; private: bool retention_time_set_; double retention_time_; // double retention_time_width; // double retention_time_lower; // double retention_time_upper; }; /** @brief Base class to represent either a peptide or a compound Stores retention time, identifiers, charge and precursor ion mobility drift time. */ class OPENMS_DLLAPI PeptideCompound : public CVTermList { public: PeptideCompound() = default; PeptideCompound(const PeptideCompound &) = default; PeptideCompound(PeptideCompound &&) noexcept = default; PeptideCompound & operator=(const PeptideCompound &) & = default; PeptideCompound & operator=(PeptideCompound &&) & = default; bool operator==(const PeptideCompound & rhs) const { return CVTermList::operator==(rhs) && rts == rhs.rts && id == rhs.id && charge_ == rhs.charge_ && charge_set_ == rhs.charge_set_; } /// Set the peptide or compound charge state void setChargeState(int charge) { charge_ = charge; charge_set_ = true; } /// Whether peptide or compound has set charge state bool hasCharge() const { return charge_set_; } /// Return the peptide or compound charge state int getChargeState() const { OPENMS_PRECONDITION(charge_set_, "Cannot return charge which was never set") return charge_; } /// Set the peptide or compound ion mobility drift time void setDriftTime(double dt) { drift_time_ = dt; } /// Return the peptide or compound ion mobility drift time double getDriftTime() const { return drift_time_; } //@{ /// Check whether compound or peptide has an annotated retention time bool hasRetentionTime() const { return (!rts.empty() && rts[0].isRTset()); } /** @brief Gets compound or peptide retention time * * @note Ensure that retention time is present by calling hasRetentionTime() */ double getRetentionTime() const { if (!hasRetentionTime()) { throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "No retention time information available"); } return rts[0].getRT(); } /// Get compound or peptide retentiontime type RetentionTime::RTType getRetentionTimeType() const { if (!hasRetentionTime()) { throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "No retention time information available"); } return rts[0].retention_time_type; } /// Get compound or peptide retentiontime unit (minute/seconds) RetentionTime::RTUnit getRetentionTimeUnit() const { if (!hasRetentionTime()) { throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "No retention time information available"); } return rts[0].retention_time_unit; } //@} String id; std::vector<RetentionTime> rts; protected: int charge_{0}; bool charge_set_{false}; double drift_time_{-1}; }; /** @brief Represents a compound (small molecule) Also stores its theoretical mass, SMILES string and molecular formula */ class OPENMS_DLLAPI Compound : public PeptideCompound { public: Compound() : theoretical_mass(0.0) { } Compound(const Compound &) = default; Compound(Compound &&) noexcept = default; Compound & operator=(const Compound &) & = default; Compound & operator=(Compound &&) & = default; bool operator==(const Compound & rhs) const { return PeptideCompound::operator==(rhs) && molecular_formula == rhs.molecular_formula && smiles_string == rhs.smiles_string && theoretical_mass == rhs.theoretical_mass; } String molecular_formula; String smiles_string; double theoretical_mass; protected: }; /** @brief Represents a peptide (amino acid sequence) Also stores information about the sequence, a linked protein and modified amino acids. */ class OPENMS_DLLAPI Peptide : public PeptideCompound { public: struct Modification : public CVTermListInterface { double avg_mass_delta; double mono_mass_delta; Int32 location; Int32 unimod_id; Modification() : CVTermListInterface(), location(-1), unimod_id(-1) { } }; Peptide() = default; Peptide(const Peptide &) = default; Peptide(Peptide &&) noexcept = default; Peptide & operator=(const Peptide &) & = default; Peptide & operator=(Peptide &&) & = default; bool operator==(const Peptide & rhs) const { return PeptideCompound::operator==(rhs) && protein_refs == rhs.protein_refs && evidence == rhs.evidence && sequence == rhs.sequence && mods == rhs.mods && peptide_group_label_ == rhs.peptide_group_label_; } /** @name The peptide group label specifies to non-labeled peptide group to which the peptide belongs * * MS:1000893: "An arbitrary string label used to mark a set of peptides * that belong together in a set, whereby the members are differentiated * by different isotopic labels. For example, the heavy and light forms * of the same peptide will both be assigned the same peptide group * label." [PSI:MS] * */ //@{ /// Set the peptide group label void setPeptideGroupLabel(const String & label) { peptide_group_label_ = label; } /// Get the peptide group label String getPeptideGroupLabel() const { return peptide_group_label_; } //@} std::vector<String> protein_refs; CVTermList evidence; String sequence; std::vector<Modification> mods; protected: String peptide_group_label_; }; struct OPENMS_DLLAPI Contact : public CVTermList { Contact() : CVTermList() { } bool operator==(const Contact & rhs) const { return CVTermList::operator==(rhs) && id == rhs.id; } String id; }; struct OPENMS_DLLAPI Publication : public CVTermList { Publication() : CVTermList() { } bool operator==(const Publication & rhs) const { return CVTermList::operator==(rhs) && id == rhs.id; } String id; }; struct OPENMS_DLLAPI Instrument : public CVTermList { Instrument() : CVTermList() { } bool operator==(const Instrument & rhs) const { return CVTermList::operator==(rhs) && id == rhs.id; } String id; }; struct OPENMS_DLLAPI Prediction : public CVTermList { Prediction() : CVTermList() { } bool operator==(const Prediction & rhs) const { return CVTermList::operator==(rhs) && contact_ref == rhs.contact_ref && software_ref == rhs.software_ref; } String software_ref; String contact_ref; }; /** @brief Product ion interpretation The interpretation of a MS product ion (mostly has functions for peptides at the moment). Can store information about the ion type, */ struct OPENMS_DLLAPI Interpretation : public CVTermListInterface { /* enum ResidueType { Full = 0, // with N-terminus and C-terminus Internal, // internal, without any termini NTerminal, // only N-terminus CTerminal, // only C-terminus AIon, // MS:1001229 N-terminus up to the C-alpha/carbonyl carbon bond BIon, // MS:1001224 N-terminus up to the peptide bond CIon, // MS:1001231 N-terminus up to the amide/C-alpha bond XIon, // MS:1001228 amide/C-alpha bond up to the C-terminus YIon, // MS:1001220 peptide bond up to the C-terminus ZIon, // MS:1001230 C-alpha/carbonyl carbon bond Precursor, // MS:1001523 Precursor ion BIonMinusH20, // MS:1001222 b ion without water YIonMinusH20, // MS:1001223 y ion without water BIonMinusNH3, // MS:1001232 b ion without ammonia YIonMinusNH3, // MS:1001233 y ion without ammonia NonIdentified, // MS:1001240 Non-identified ion Unannotated, // no stored annotation SizeOfResidueType }; */ typedef Residue::ResidueType IonType; ///< Interpretation IonType unsigned char ordinal; ///< MS:1000903 : product ion series ordinal (e.g. 8 for a y8 ion) unsigned char rank; ///< MS:1000926 : product interpretation rank (e.g. 1 for the most likely rank) IonType iontype; ///< which type of ion (b/y/z/ ...), see Residue::ResidueType // Constructor Interpretation() : CVTermListInterface(), ordinal(0), rank(0), iontype(Residue::Unannotated) // Unannotated does not imply any MS OBO term { } /** @name Operators assignment, equality, inequality */ //@{ bool operator==(const Interpretation & rhs) const { return CVTermListInterface::operator==(rhs) && ordinal == rhs.ordinal && rank == rhs.rank && iontype == rhs.iontype; } bool operator!=(const Interpretation & rhs) const { return !(operator==(rhs)); } //@} }; /** @brief Represents a product ion A product ion entry in the TraML file format */ struct OPENMS_DLLAPI TraMLProduct : public CVTermListInterface { TraMLProduct() = default; bool operator==(const TraMLProduct & rhs) const { return CVTermListInterface::operator==(rhs) && charge_ == rhs.charge_ && charge_set_ == rhs.charge_set_ && mz_ == rhs.mz_ && configuration_list_ == rhs.configuration_list_ && interpretation_list_ == rhs.interpretation_list_; } void setChargeState(int charge) { charge_ = charge; charge_set_ = true; } /// Whether product has set charge state bool hasCharge() const { return charge_set_; } int getChargeState() const { OPENMS_PRECONDITION(charge_set_, "Cannot return charge which was never set") return charge_; } double getMZ() const { return mz_; } void setMZ(double mz) { mz_ = mz; } const std::vector<Configuration> & getConfigurationList() const { return configuration_list_; } void addConfiguration(const Configuration& configuration) { configuration_list_.push_back(configuration); } const std::vector<Interpretation> & getInterpretationList() const { return interpretation_list_; } void addInterpretation(const Interpretation& interpretation) { interpretation_list_.push_back(interpretation); } void resetInterpretations() { return interpretation_list_.clear(); } private: int charge_{0}; ///< Product ion charge bool charge_set_{false}; ///< Whether product ion charge is set or not double mz_{0}; ///< Product ion m/z std::vector<Configuration> configuration_list_; ///< Product ion configurations used std::vector<Interpretation> interpretation_list_; ///< Product ion interpretation }; /// helper function that converts a Peptide object to a AASequence object OPENMS_DLLAPI OpenMS::AASequence getAASequence(const Peptide& peptide); /// helper function that sets a modification on a AASequence object OPENMS_DLLAPI void setModification(int location, int max_size, const String& modification, OpenMS::AASequence & aas); } /// Helper template to hash any type with getCVTerms() method (CVTermList, CVTermListInterface) template<typename T> inline std::size_t hashCVTerms(const T& obj) noexcept { std::size_t seed = 0; const auto& cv_terms = obj.getCVTerms(); for (const auto& [accession, terms] : cv_terms) { hash_combine(seed, fnv1a_hash_string(accession)); for (const auto& term : terms) { hash_combine(seed, fnv1a_hash_string(term.getAccession())); hash_combine(seed, fnv1a_hash_string(term.getName())); hash_combine(seed, fnv1a_hash_string(term.getCVIdentifierRef())); if (term.hasValue()) { hash_combine(seed, fnv1a_hash_string(term.getValue().toString())); } if (term.hasUnit()) { hash_combine(seed, fnv1a_hash_string(term.getUnit().accession)); } } } return seed; } // Convenience wrappers for backward compatibility inline std::size_t hashCVTermList(const CVTermList& cvtl) noexcept { return hashCVTerms(cvtl); } inline std::size_t hashCVTermListInterface(const CVTermListInterface& cvtli) noexcept { return hashCVTerms(cvtli); } } // namespace OpenMS // Hash function specializations for TargetedExperimentHelper classes // Placed in std namespace to allow use with std::unordered_map/set namespace std { /// Hash function for TargetedExperimentHelper::CV template<> struct hash<OpenMS::TargetedExperimentHelper::CV> { std::size_t operator()(const OpenMS::TargetedExperimentHelper::CV& cv) const noexcept { std::size_t seed = 0; OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(cv.id)); OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(cv.fullname)); OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(cv.version)); OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(cv.URI)); return seed; } }; /// Hash function for TargetedExperimentHelper::Protein template<> struct hash<OpenMS::TargetedExperimentHelper::Protein> { std::size_t operator()(const OpenMS::TargetedExperimentHelper::Protein& protein) const noexcept { std::size_t seed = OpenMS::hashCVTermList(protein); OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(protein.id)); OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(protein.sequence)); return seed; } }; /// Hash function for TargetedExperimentHelper::RetentionTime template<> struct hash<OpenMS::TargetedExperimentHelper::RetentionTime> { std::size_t operator()(const OpenMS::TargetedExperimentHelper::RetentionTime& rt) const noexcept { std::size_t seed = OpenMS::hashCVTermListInterface(rt); OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(rt.software_ref)); OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<std::int8_t>(rt.retention_time_unit))); OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<std::int8_t>(rt.retention_time_type))); OpenMS::hash_combine(seed, OpenMS::hash_int(rt.isRTset() ? 1 : 0)); if (rt.isRTset()) { OpenMS::hash_combine(seed, OpenMS::hash_float(rt.getRT())); } return seed; } }; /// Hash function for TargetedExperimentHelper::PeptideCompound template<> struct hash<OpenMS::TargetedExperimentHelper::PeptideCompound> { std::size_t operator()(const OpenMS::TargetedExperimentHelper::PeptideCompound& pc) const noexcept { std::size_t seed = OpenMS::hashCVTermList(pc); for (const auto& rt : pc.rts) { OpenMS::hash_combine(seed, std::hash<OpenMS::TargetedExperimentHelper::RetentionTime>{}(rt)); } OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(pc.id)); OpenMS::hash_combine(seed, OpenMS::hash_int(pc.hasCharge() ? 1 : 0)); if (pc.hasCharge()) { OpenMS::hash_combine(seed, OpenMS::hash_int(pc.getChargeState())); } return seed; } }; /// Hash function for TargetedExperimentHelper::Compound template<> struct hash<OpenMS::TargetedExperimentHelper::Compound> { std::size_t operator()(const OpenMS::TargetedExperimentHelper::Compound& compound) const noexcept { std::size_t seed = std::hash<OpenMS::TargetedExperimentHelper::PeptideCompound>{}(compound); OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(compound.molecular_formula)); OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(compound.smiles_string)); OpenMS::hash_combine(seed, OpenMS::hash_float(compound.theoretical_mass)); return seed; } }; /// Hash function for TargetedExperimentHelper::Peptide template<> struct hash<OpenMS::TargetedExperimentHelper::Peptide> { std::size_t operator()(const OpenMS::TargetedExperimentHelper::Peptide& peptide) const noexcept { std::size_t seed = std::hash<OpenMS::TargetedExperimentHelper::PeptideCompound>{}(peptide); for (const auto& ref : peptide.protein_refs) { OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(ref)); } OpenMS::hash_combine(seed, OpenMS::hashCVTermList(peptide.evidence)); OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(peptide.sequence)); for (const auto& mod : peptide.mods) { OpenMS::hash_combine(seed, OpenMS::hashCVTermListInterface(mod)); OpenMS::hash_combine(seed, OpenMS::hash_float(mod.avg_mass_delta)); OpenMS::hash_combine(seed, OpenMS::hash_float(mod.mono_mass_delta)); OpenMS::hash_combine(seed, OpenMS::hash_int(mod.location)); OpenMS::hash_combine(seed, OpenMS::hash_int(mod.unimod_id)); } OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(peptide.getPeptideGroupLabel())); return seed; } }; /// Hash function for TargetedExperimentHelper::Contact template<> struct hash<OpenMS::TargetedExperimentHelper::Contact> { std::size_t operator()(const OpenMS::TargetedExperimentHelper::Contact& contact) const noexcept { std::size_t seed = OpenMS::hashCVTermList(contact); OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(contact.id)); return seed; } }; /// Hash function for TargetedExperimentHelper::Publication template<> struct hash<OpenMS::TargetedExperimentHelper::Publication> { std::size_t operator()(const OpenMS::TargetedExperimentHelper::Publication& pub) const noexcept { std::size_t seed = OpenMS::hashCVTermList(pub); OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(pub.id)); return seed; } }; /// Hash function for TargetedExperimentHelper::Instrument template<> struct hash<OpenMS::TargetedExperimentHelper::Instrument> { std::size_t operator()(const OpenMS::TargetedExperimentHelper::Instrument& inst) const noexcept { std::size_t seed = OpenMS::hashCVTermList(inst); OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(inst.id)); return seed; } }; /// Hash function for TargetedExperimentHelper::Prediction template<> struct hash<OpenMS::TargetedExperimentHelper::Prediction> { std::size_t operator()(const OpenMS::TargetedExperimentHelper::Prediction& pred) const noexcept { std::size_t seed = OpenMS::hashCVTermList(pred); OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(pred.software_ref)); OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(pred.contact_ref)); return seed; } }; /// Hash function for TargetedExperimentHelper::Interpretation template<> struct hash<OpenMS::TargetedExperimentHelper::Interpretation> { std::size_t operator()(const OpenMS::TargetedExperimentHelper::Interpretation& interp) const noexcept { std::size_t seed = OpenMS::hashCVTermListInterface(interp); OpenMS::hash_combine(seed, OpenMS::hash_int(interp.ordinal)); OpenMS::hash_combine(seed, OpenMS::hash_int(interp.rank)); OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(interp.iontype))); return seed; } }; /// Hash function for TargetedExperimentHelper::TraMLProduct template<> struct hash<OpenMS::TargetedExperimentHelper::TraMLProduct> { std::size_t operator()(const OpenMS::TargetedExperimentHelper::TraMLProduct& product) const noexcept { std::size_t seed = OpenMS::hashCVTermListInterface(product); OpenMS::hash_combine(seed, OpenMS::hash_int(product.hasCharge() ? 1 : 0)); if (product.hasCharge()) { OpenMS::hash_combine(seed, OpenMS::hash_int(product.getChargeState())); } OpenMS::hash_combine(seed, OpenMS::hash_float(product.getMZ())); // Hash configuration_list_ (required for consistency with operator==) for (const auto& config : product.getConfigurationList()) { OpenMS::hash_combine(seed, OpenMS::hashCVTermList(config)); OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(config.contact_ref)); OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(config.instrument_ref)); for (const auto& validation : config.validations) { OpenMS::hash_combine(seed, OpenMS::hashCVTermList(validation)); } } for (const auto& interp : product.getInterpretationList()) { OpenMS::hash_combine(seed, std::hash<OpenMS::TargetedExperimentHelper::Interpretation>{}(interp)); } return seed; } }; } // namespace std
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/ANALYSIS/TARGETED/MetaboTargetedAssay.h
.h
11,617
216
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Oliver Alka $ // $Authors: Oliver Alka $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/KERNEL/StandardTypes.h> #include <map> //insert #include <OpenMS/ANALYSIS/MRM/ReactionMonitoringTransition.h> #include <OpenMS/ANALYSIS/TARGETED/TargetedExperiment.h> #include <OpenMS/ANALYSIS/ID/SiriusMSConverter.h> //SiriusMSFile #include <OpenMS/FORMAT/DATAACCESS/SiriusFragmentAnnotation.h> //SiriusTargetDecoySpectra #include <OpenMS/CONCEPT/Exception.h> namespace OpenMS { /** @brief This class provides methods for the extraction of targeted assays for metabolomics. */ class OPENMS_DLLAPI MetaboTargetedAssay { public: /** @brief MetaboTargetedAssay is able to store a precursor, metadata as well as compound information. */ double precursor_int; ///< precursor intensity double transition_quality_score; ///< transitions quality score (not yet used) double precursor_mz; ///< precursor mass-to-charge double compound_rt; ///< compound retention time String molecular_formula; ///<< (putative) molecular formula int compound_file; ///< integer of file it belongs to in a list of files String compound_name; ///< compound name String compound_adduct; ///< compound adduct TargetedExperiment::Compound potential_cmp; ///< compound information stored in a TargetedExperiment std::vector<ReactionMonitoringTransition> potential_rmts; ///< vector of transitions belonging to the compound /** @brief CompoundTargetDecoyPair stores a pair of CompoundInfo and MSSpectrum (target, decoy) */ class CompoundTargetDecoyPair { public: SiriusMSFile::CompoundInfo compound_info; SiriusFragmentAnnotation::SiriusTargetDecoySpectra target_decoy_spectra; CompoundTargetDecoyPair() = default; CompoundTargetDecoyPair(SiriusMSFile::CompoundInfo info, SiriusFragmentAnnotation::SiriusTargetDecoySpectra td_spectra) : compound_info(std::move(info)), target_decoy_spectra(std::move(td_spectra)) {} }; /** @brief CompoundTargetDecoyPair stores a pair of CompoundInfo and MSSpectrum */ class CompoundSpectrumPair { public: SiriusMSFile::CompoundInfo compound_info; MSSpectrum spectrum; CompoundSpectrumPair() = default; CompoundSpectrumPair(SiriusMSFile::CompoundInfo info, MSSpectrum spectrum) : compound_info(std::move(info)), spectrum(std::move(spectrum)) {} }; /** @brief TargetDecoyGroup stores the mz, rt and file number in correspondence to the index of a MetaboTargetedAssay vector */ struct TargetDecoyGroup { int target_index = -1; int decoy_index = -1; double target_mz = 0.0; double target_rt = 0.0; double decoy_mz = 0.0; double decoy_rt = 0.0; int target_file_number = 0; int decoy_file_number = 0; }; /** @brief Extract a vector of MetaboTargetedAssays without using fragment annotation @return Vector of MetaboTargetedAssay @param[in] spectra Input of MSExperiment with spectra information @param[in] feature_ms2_index FeatureMapping class to associated MS2 spectra @param[in] precursor_rt_tol Retention time tolerance of the precursor @param[in] precursor_mz_distance Max m/z distance of the precursor entries of two spectra to be merged @param[in] cosine_sim_threshold Cosine similarity threshold for the usage of SpectraMerger @param[in] transition_threshold Intensity threshold for MS2 peak used in MetaboTargetedAssay @param[in] min_fragment_mz Minimum m/z a fragment ion has to have to be considered as a transition @param[in] max_fragment_mz Maximum m/z a fragment ion has to have to be considered as a transition @param[in] method_consensus_spectrum Boolean to use consensus spectrum method @param[in] exclude_ms2_precursor Boolean to exclude MS2 precursor from MetaboTargetedAssay @param[in] file_counter Count if multiple files are used. */ static std::vector<MetaboTargetedAssay> extractMetaboTargetedAssay(const MSExperiment& spectra, const FeatureMapping::FeatureToMs2Indices& feature_ms2_index, const double& precursor_rt_tol, const double& precursor_mz_distance, const double& cosine_sim_threshold, const double& transition_threshold, const double& min_fragment_mz, const double& max_fragment_mz, const bool& method_consensus_spectrum, const bool& exclude_ms2_precursor, const unsigned int& file_counter); /** @brief Extract a vector of MetaboTargetedAssays using fragment annotation @return Vector of MetaboTargetedAssay @param[in] v_cmp_spec Vector of CompoundInfo with associated fragment annotated MSspectrum @param[in] transition_threshold Intensity threshold for MS2 peak used in MetaboTargetedAssay @param[in] min_fragment_mz Minimum m/z a fragment ion has to have to be considered as a transition @param[in] max_fragment_mz Maximum m/z a fragment ion has to have to be considered as a transition @param[in] use_exact_mass Boolean if exact mass should be used as peak mass for annotated fragments @param[in] exclude_ms2_precursor Boolean to exclude MS2 precursor from MetaboTargetedAssay */ static std::vector<MetaboTargetedAssay> extractMetaboTargetedAssayFragmentAnnotation(const std::vector< CompoundTargetDecoyPair >& v_cmp_spec, const double& transition_threshold, const double& min_fragment_mz, const double& max_fragment_mz, const bool& use_exact_mass, const bool& exclude_ms2_precursor); /** @brief Pair compound information (SiriusMSFile) with the annotated target and decoy spectrum from SIRIUS/Passatutto based on the m_id (unique identifier composed of description_filepath_native_id_k introduced in the SiriusMSConverter) @return Vector of MetaboTargetedAssay::CompoundTargetDecoyPair @param[in] v_cmpinfo Vector of SiriusMSFile::CompoundInfo @param[in] annotated_spectra Vector of SiriusTargetDecoySpectra */ static std::vector< MetaboTargetedAssay::CompoundTargetDecoyPair > pairCompoundWithAnnotatedTDSpectraPairs(const std::vector<SiriusMSFile::CompoundInfo>& v_cmpinfo, const std::vector<SiriusFragmentAnnotation::SiriusTargetDecoySpectra>& annotated_spectra); /** @brief Perform feature linking to build ambiguity groups based on the target and decoy position in the vector of MetaboTargetedAssays @return Map of pair (mz, rt) and vector of ambiguities for this mz,rt combination (MetaboTargetedAssay) @param[in] v_mta Vector of MetaboTargetedAssay @param[in] ar_mz_tol FeatureGroupingAlgorithmQT parameter distance_MZ:max_difference @param[in] ar_rt_tol FeatureGroupingAlgorithmQT parameter distance_RT:max_difference @param[in] ar_mz_tol_unit_res FeatureGroupingAlgorithmQT parameter distance_MZ_unit (ppm, Da) @param[in] in_files_size Number of files which were processed in the vector of MetaboTargetedAssay (e.g. initially 5 different files in the vector<MetaboTargetedAssay>) */ static std::unordered_map< UInt64, std::vector<MetaboTargetedAssay> > buildAmbiguityGroup(const std::vector<MetaboTargetedAssay>& v_mta, const double& ar_mz_tol, const double& ar_rt_tol, const String& ar_mz_tol_unit_res, size_t in_files_size); /** @brief Resolve ambiguity groups based on occurrence in samples (e.g. at least in 20% of the samples) and if multiple possible identifications are reported within one ambiguity group use the one with the highest occurrence @param[in,out] map_mta_filter Map of pair (mz, rt) and vector of ambiguities for this mz,rt combination (MetaboTargetedAssay) @param[in] total_occurrence_filter Value which has to be reached for the ambiguity group to be reported (e.g. in 20 % of the samples) @param[in] in_files_size Number of files which were processed in the vector of MetaboTargetedAssay (e.g. initially 5 different files in the vector<MetaboTargetedAssay>) */ static void resolveAmbiguityGroup(std::unordered_map< UInt64, std::vector<MetaboTargetedAssay> >& map_mta_filter, const double& total_occurrence_filter, size_t in_files_size); protected: /// Used to calculate the hard noise intensity threshold hard minimal threshold of min_int * noise_threshold_constant_ static constexpr float noise_threshold_constant_ = 1.1; /** @brief Compare two peaks based on their intensity */ static bool intensityLess_(const Peak1D& a, const Peak1D& b); /** @brief Gets charge from a singly charged adduct ([M+H]+/[M-H]-) */ static int getChargeFromAdduct_(const String& adduct); /** @brief Filter one ambiguity group based on occurrence in samples (e.g. at least in 20% of the samples) @param[in,out] mta Either cleared or left untouched @param[in] total_occurrence_filter Value which has to be reached for the ambiguity group to be reported (e.g. in 20 % of the samples) @param[in] in_files_size Number of files which were processed in the vector of MetaboTargetedAssay (e.g. initially 5 different files in the vector<MetaboTargetedAssay>) */ static void filterBasedOnTotalOccurrence_(std::vector<MetaboTargetedAssay>& mta, double total_occurrence_filter, size_t in_files_size); /** @brief Filter one ambiguity group with multiple possible identifications to use the one with the highest occurrence @param[in,out] mta Vector of MetaboTargetedAssay */ static void filterBasedOnMolFormAdductOccurrence_(std::vector<MetaboTargetedAssay>& mta); /** @brief Sort vector of MetaboTargetedAssay by precursor ion intensity */ static void sortByPrecursorInt(std::vector<MetaboTargetedAssay>& vec_mta); }; } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/ANALYSIS/QUANTITATION/ItraqFourPlexQuantitationMethod.h
.h
1,915
70
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Stephan Aiche $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/ANALYSIS/QUANTITATION/IsobaricQuantitationMethod.h> namespace OpenMS { /** @brief iTRAQ 4 plex quantitation to be used with the IsobaricQuantitation. @htmlinclude OpenMS_ItraqFourPlexQuantitationMethod.parameters */ class OPENMS_DLLAPI ItraqFourPlexQuantitationMethod : public IsobaricQuantitationMethod { public: /// Default c'tor ItraqFourPlexQuantitationMethod(); /// d'tor ~ItraqFourPlexQuantitationMethod() override; /// Copy c'tor ItraqFourPlexQuantitationMethod(const ItraqFourPlexQuantitationMethod& other); /// Assignment operator ItraqFourPlexQuantitationMethod& operator=(const ItraqFourPlexQuantitationMethod& rhs); /// @brief Methods to implement from IsobaricQuantitationMethod /// @{ const String& getMethodName() const override; const IsobaricChannelList& getChannelInformation() const override; Size getNumberOfChannels() const override; Matrix<double> getIsotopeCorrectionMatrix() const override; Size getReferenceChannel() const override; /// @} private: /// the actual information on the different itraq4plex channels. IsobaricChannelList channels_; /// The name of the quantitation method. static const String name_; /// The reference channel for this experiment. Size reference_channel_; protected: /// implemented for DefaultParamHandler void setDefaultParams_(); /// implemented for DefaultParamHandler void updateMembers_() override; }; } // namespace
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/ANALYSIS/QUANTITATION/AbsoluteQuantitation.h
.h
14,470
350
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Douglas McCloskey, Pasquale Domenico Colaianni $ // $Authors: Douglas McCloskey, Pasquale Domenico Colaianni $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/config.h> //Kernal classes #include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h> #include <OpenMS/KERNEL/StandardTypes.h> #include <OpenMS/KERNEL/MSExperiment.h> #include <OpenMS/KERNEL/MSChromatogram.h> #include <OpenMS/KERNEL/FeatureMap.h> #include <OpenMS/KERNEL/MRMTransitionGroup.h> #include <OpenMS/KERNEL/MRMFeature.h> //Analysis classes #include <OpenMS/ANALYSIS/MAPMATCHING/TransformationDescription.h> #include <OpenMS/ANALYSIS/MAPMATCHING/TransformationModel.h> #include <OpenMS/ANALYSIS/TARGETED/TargetedExperiment.h> //Quantitation classes #include <OpenMS/METADATA/AbsoluteQuantitationStandards.h> #include <OpenMS/ANALYSIS/QUANTITATION/AbsoluteQuantitationMethod.h> //Standard library #include <cstddef> // for size_t & ptrdiff_t #include <vector> #include <string> namespace OpenMS { /** @brief AbsoluteQuantitation is a class to support absolute or relative quantitation for targeted or untargeted quantitation workflows (e.g., Isotope Dilution Mass Spectrometry). @section AbsoluteQuantitation_method Method A transformation model where y = ratio (analyte/IS) corresponding to peak height or peak area and x = ratio (analyte/IS) corresponding to concentration is used to fit a series of runs with standards of known concentrations that span the detection range of the instrument. The fitted transformation model can then be used to quantify the concentration of an analyte in an unknown sample given the analyte peak height or area, IS peak height or area, and IS concentration. @section AbsoluteQuantitation_terms Terms - **Component**: A protein, peptide, or compound fragment, transition, or whole species measured by LC-MS, LC-MS/MS, GC-MS, GC-MS/MS, LC-MS-TOF, HPLC-UV, HPLC-IR, etc. - **Calibration curve**: A series of standards used to correlate instrument measurements to actual concentrations - **LLOQ/ULOQ**: Lower/Upper Limit of Quantitation - the concentration range where quantitation is reliable - **LLOD/ULOD**: Lower/Upper Limit of Detection - the concentration range where detection is possible @section AbsoluteQuantitation_workflow Workflow 1. Prepare standards with known concentrations spanning the expected range 2. Measure standards and extract features (peaks) 3. Call fitCalibration() or optimizeCalibrationCurves() to fit the calibration model 4. Call quantifyComponents() to calculate concentrations for unknown samples @section AbsoluteQuantitation_example Example @code AbsoluteQuantitation aq; // Set quantitation methods for each component std::vector<AbsoluteQuantitationMethod> methods; // ... populate methods ... aq.setQuantMethods(methods); // Optimize calibration curves from standards std::map<String, std::vector<AbsoluteQuantitationStandards::featureConcentration>> standards; // ... populate standards ... aq.optimizeCalibrationCurves(standards); // Quantify unknowns FeatureMap unknowns; // ... load unknown samples ... aq.quantifyComponents(unknowns); // Results are stored as "calculated_concentration" metavalue @endcode @see AbsoluteQuantitationMethod for method parameters @see AbsoluteQuantitationStandards for standard concentration data @see MRMFeatureFilter for upstream QC filtering @ingroup TargetedQuantitation */ class OPENMS_DLLAPI AbsoluteQuantitation : public DefaultParamHandler { public: //@{ /// Constructor AbsoluteQuantitation(); /// Destructor ~AbsoluteQuantitation() override; //@} /** @brief quant_method setter. A list of AbsoluteQuantitationMethod classes are given as input and a map is constructed based on their component_name member. @param[in] quant_methods A list of AbsoluteQuantitationMethod classes */ void setQuantMethods(std::vector<AbsoluteQuantitationMethod>& quant_methods); /** @brief quant_method getter. A list of AbsoluteQuantitationMethod classes are returned. */ std::vector<AbsoluteQuantitationMethod> getQuantMethods(); std::map<String, AbsoluteQuantitationMethod> getQuantMethodsAsMap(); /** @brief This function calculates the ratio between features. @param[in] component_1 component of the numerator @param[in] component_2 component of the denominator @param[in] feature_name name of the feature to calculate the ratio on e.g., peak_apex, peak_area @return The ratio. @exception Exception::UnableToFit */ double calculateRatio(const Feature & component_1, const Feature & component_2, const String & feature_name); /** @brief This function calculates the bias of the calibration. The bias is defined as the following: |actual_concentration - calculated_concentration|/actual_concentration * 100% This is in contrast to accuracy, which is defined as the following: calculated_concentration/actual_concentration * 100% @param[in] actual_concentration the actual concentration of the component @param[in] calculated_concentration the calibration curve back calculated concentration of the component @return The bias. @exception Exception::UnableToFit */ double calculateBias(const double & actual_concentration, const double & calculated_concentration); /** @brief This function fits the calibration points to the model. @param[in] component_concentrations list of structures with features and concentrations @param[in] feature_name name of the feature to calculate the absolute concentration. @param[in] transformation_model model used to fit the calibration points @param[in] transformation_model_params parameters used by the transformation_model @returns updated Param object @exception Exception::UnableToFit */ Param fitCalibration(const std::vector<AbsoluteQuantitationStandards::featureConcentration> & component_concentrations, const String & feature_name, const String & transformation_model, const Param & transformation_model_params); /** @brief This function calculates the biases and the correlation coefficient of the calibration points. @param[in] component_concentrations list of structures with features and concentrations @param[in] feature_name name of the feature to calculate the absolute concentration. @param[in] transformation_model model used to fit the calibration points @param[in] transformation_model_params parameters used by the transformation_model @param[out] biases Vector of point biases @param[out] correlation_coefficient Pearson's R @exception None */ void calculateBiasAndR( const std::vector<AbsoluteQuantitationStandards::featureConcentration> & component_concentrations, const String & feature_name, const String & transformation_model, const Param & transformation_model_params, std::vector<double> & biases, double & correlation_coefficient); /** @brief This function optimizes the parameters of the calibration for a given component iteratively. @param[in,out] component_concentrations list of structures with features and concentrations. The optimal points will be returned. @param[in] feature_name name of the feature to calculate the absolute concentration. @param[in] transformation_model model used to fit the calibration points @param[in] transformation_model_params parameters used by the transformation_model @param[out] optimized_params optimized parameters @returns true if a a fit was found, false otherwise @exception Exception::UnableToFit */ bool optimizeCalibrationCurveIterative( std::vector<AbsoluteQuantitationStandards::featureConcentration> & component_concentrations, const String & feature_name, const String & transformation_model, const Param & transformation_model_params, Param & optimized_params); /** @brief This function optimizes the parameters of the calibration for a all components. @param[in,out] components_concentrations An AbsoluteQuantitationStandards::components_to_concentrations type. Note that the method will update the list of featureConcentrations in place. The resulting components_concentrations will reflect the optimal set of points for downstream QC/QA. */ void optimizeCalibrationCurves(std::map<String,std::vector<AbsoluteQuantitationStandards::featureConcentration>> & components_concentrations); /** @brief This function optimizes the parameters of the calibration for a single component. @note This method is provided primarily to ease Python bindings. C++ users are encouraged to use `optimizeCalibrationCurves()`. @param[in] component_name @param[in,out] component_concentrations The method will update the argument in place. The resulting value will reflect the optimal set of points for downstream QC/QA. */ void optimizeSingleCalibrationCurve( const String& component_name, std::vector<AbsoluteQuantitationStandards::featureConcentration>& component_concentrations ); /** @brief This function applies the calibration curve to the component. @param[in] component the component to be quantified @param[in] IS_component the internal standard (IS) of the component to be quantified. This can be an empty feature if there is no IS for the component. @param[in] feature_name name of the feature to calculate the absolute concentration. @param[in] transformation_model model used to fit the calibration points @param[in] transformation_model_params parameters used by the transformation_model @return The absolute concentration. @exception Exception::UnableToFit */ double applyCalibration(const Feature & component, const Feature & IS_component, const String & feature_name, const String & transformation_model, const Param & transformation_model_params); /** @brief This function applies the calibration curve to all components. An additional annotation for metaValue of "calculated_concentration" and "concentration_units" corresponding to the absolute concentration as back-calculated from the fitted calibration curve model and parameters will be added to each sub-feature. It is assumed that all duplicate components have been removed. If not, the function will quantify all components, but the first internal standard found will be used to calculate the ratio for the calculation. @param[in,out] unknowns A FeatureMap to quantify. */ void quantifyComponents(FeatureMap& unknowns); protected: /** @brief This function extracts out the components. @param[in] component_concentrations list of structures with features and concentrations @param[in] component_concentrations_indices indices to extract out @returns component_concentrations_sub sublist of structures with features and concentrations. @exception None */ std::vector<AbsoluteQuantitationStandards::featureConcentration> extractComponents_( const std::vector<AbsoluteQuantitationStandards::featureConcentration> & component_concentrations, const std::vector<size_t>& component_concentrations_indices); /** @brief This function computes a candidate outlier point by iteratively leaving one point out to find the one which results in the maximum R^2 of a first order linear regression of the remaining ones. @param[in] component_concentrations list of structures with features and concentrations @param[in] feature_name name of the feature to calculate the absolute concentration. @param[in] transformation_model model used to fit the calibration points @param[in] transformation_model_params parameters used by the transformation_model @return The position of the candidate outlier point in component_concentrations. @exception Exception::UnableToFit is thrown if fitting cannot be performed */ int jackknifeOutlierCandidate_( const std::vector<AbsoluteQuantitationStandards::featureConcentration>& component_concentrations, const String & feature_name, const String & transformation_model, const Param & transformation_model_params); /** @brief This function computes a candidate outlier point by computing the residuals of all points to the linear fit and selecting the one with the largest deviation. @param[in] component_concentrations list of structures with features and concentrations @param[in] feature_name name of the feature to calculate the absolute concentration. @param[in] transformation_model model used to fit the calibration points @param[in] transformation_model_params parameters used by the transformation_model @return The position of the candidate outlier point in component_concentrations. @exception Exception::UnableToFit is thrown if fitting cannot be performed */ int residualOutlierCandidate_( const std::vector<AbsoluteQuantitationStandards::featureConcentration>& component_concentrations, const String & feature_name, const String & transformation_model, const Param & transformation_model_params); private: /// Synchronize members with param class void updateMembers_() override; size_t min_points_; double max_bias_; double min_correlation_coefficient_; size_t max_iters_; String outlier_detection_method_; bool use_chauvenet_; String optimization_method_; // members /// map between components and quantitation methods std::map<String, AbsoluteQuantitationMethod> quant_methods_; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/ANALYSIS/QUANTITATION/AbsoluteQuantitationMethod.h
.h
4,975
101
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Douglas McCloskey, Pasquale Domenico Colaianni $ // $Authors: Douglas McCloskey, Pasquale Domenico Colaianni $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/config.h> // OPENMS_DLLAPI #include <OpenMS/DATASTRUCTURES/String.h> #include <OpenMS/DATASTRUCTURES/Param.h> namespace OpenMS { /** @brief AbsoluteQuantitationMethod is a class to hold information about the quantitation method and for applying and/or generating the quantitation method. The quantitation method describes all parameters required to define the calibration curve used for absolute quantitation by Isotope Dilution Mass Spectrometry (IDMS). The quantitation method also defines the statistics of the fitted calibration curve as well as the lower and upper bounds of the calibration for later Quality Control. @section AbsoluteQuantitationMethod_params Key Parameters | Parameter | Description | |-----------|-------------| | component_name | Unique identifier for the analyte | | feature_name | Which feature to use (e.g., "peak_apex_int", "peak_area") | | IS_name | Internal standard name for ratio calculation | | LLOD/ULOD | Lower/Upper Limit of Detection | | LLOQ/ULOQ | Lower/Upper Limit of Quantitation | | transformation_model | Calibration model (e.g., "linear", "b_spline") | | correlation_coefficient | Pearson R of the calibration fit | @see AbsoluteQuantitation for the main quantitation workflow @see AbsoluteQuantitationMethodFile for file I/O @ingroup TargetedQuantitation */ class OPENMS_DLLAPI AbsoluteQuantitationMethod { public: bool operator==(const AbsoluteQuantitationMethod& other) const; bool operator!=(const AbsoluteQuantitationMethod& other) const; void setComponentName(const String& component_name); ///< Component name setter String getComponentName() const; ///< Component name getter void setFeatureName(const String& feature_name); ///< Feature name setter String getFeatureName() const; ///< Feature name getter void setISName(const String& IS_name); ///< IS name setter String getISName() const; ///< IS_name getter void setLLOD(const double llod); ///< LLOD setter double getLLOD() const; ///< LLOD getter void setULOD(const double ulod); ///< ULOD setter double getULOD() const; ///< ULOD getter bool checkLOD(const double value) const; ///< This function checks if the value is within the limits of detection (LOD) void setLLOQ(const double lloq); ///< LLOQ setter double getLLOQ() const; ///< LLOQ getter void setULOQ(const double uloq); ///< ULOQ setter double getULOQ() const; ///< ULOQ getter bool checkLOQ(const double value) const; ///< This function checks if the value is within the limits of quantitation (LOQ) void setNPoints(const Int n_points); ///< Set the number of points Int getNPoints() const; ///< Get the number of points void setCorrelationCoefficient(const double correlation_coefficient); ///< Set the correlation coefficient double getCorrelationCoefficient() const; ///< Get the correlation coefficient void setConcentrationUnits(const String& concentration_units); ///< Concentration units setter String getConcentrationUnits() const; ///< Concentration units getter void setTransformationModel(const String& transformation_model); ///< Transformation model setter String getTransformationModel() const; ///< Transformation model getter void setTransformationModelParams(const Param& transformation_model_params); ///< Transformation model parameters setter Param getTransformationModelParams() const; ///< Transformation model parameters getter private: Param transformation_model_params_; ///< transformation model parameters String component_name_; ///< id of the component String feature_name_; ///< name of the feature (i.e., peak_apex_int or peak_area) String IS_name_; ///< the internal standard (IS) name for the transition String concentration_units_; ///< concentration units of the component's concentration String transformation_model_; ///< transformation model double llod_ { 0.0 }; ///< lower limit of detection (LLOD) of the transition double ulod_ { 0.0 }; ///< upper limit of detection (ULOD) of the transition double lloq_ { 0.0 }; ///< lower limit of quantitation (LLOQ) of the transition double uloq_ { 0.0 }; ///< upper limit of quantitation (ULOQ) of the transition double correlation_coefficient_ { 0.0 }; ///< the Pearson R value for the correlation coefficient of the calibration curve Int n_points_ { 0 }; ///< number of points used in a calibration curve }; }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/ANALYSIS/QUANTITATION/IsobaricChannelExtractor.h
.h
11,009
264
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow $ // $Authors: Stephan Aiche, Chris Bielow $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h> #include <OpenMS/KERNEL/Peak2D.h> #include <OpenMS/KERNEL/MSExperiment.h> #include <OpenMS/KERNEL/StandardTypes.h> namespace OpenMS { class IsobaricQuantitationMethod; class ConsensusMap; class ConsensusFeature; /// small quality control class, holding temporary data for reporting struct ChannelQC { std::vector<double> mz_deltas; ///< m/z distance between expected and observed reporter ion closest to expected position int signal_not_unique{0}; ///< counts if more than one peak was found within the search window of each reporter position }; typedef std::map<String, ChannelQC> ChannelQCSet; /** @brief Extracts individual channels from MS/MS spectra for isobaric labeling experiments. In addition to extracting the channel information this class can also filter the extracted channel information according to several parameters, i.e., discard channel information if certain criteria are not met. @li %Precursor activation method (e.g., select only HCD scans). @li Minimum precursor intensity. @li Minimum reporter intensity (i.e., remove reporter channels below a certain intensity) @li %Precursor purity (i.e., fraction of TIC in the precursor window that can be assigned to the precursor) The precursor purity computation uses the interpolation approach described in: Savitski MM, Sweetman G, Askenazi M, et al. (2011). Delayed fragmentation and optimized isolation width settings for improvement of protein identification and accuracy of isobaric mass tag quantification on Orbitrap-type mass spectrometers. Analytical chemistry 83: 8959-67. http://www.ncbi.nlm.nih.gov/pubmed/22017476 @note Centroided MS and MS/MS data is required. @htmlinclude OpenMS_IsobaricChannelExtractor.parameters */ class OPENMS_DLLAPI IsobaricChannelExtractor : public DefaultParamHandler { public: /** @brief C'tor to create a new channel extractor for the given quantitation method. @param[in] quant_method IsobaricQuantitationMethod providing the necessary information which channels should be extracted. */ explicit IsobaricChannelExtractor(const IsobaricQuantitationMethod* const quant_method); /// Copy c'tor IsobaricChannelExtractor(const IsobaricChannelExtractor& other); /// Assignment operator IsobaricChannelExtractor& operator=(const IsobaricChannelExtractor& rhs); /** @brief Extracts the isobaric channels from the tandem MS data and stores intensity values in a consensus map. @param[in] ms_exp_data Raw data to search for isobaric quantitation channels. @param[in] consensus_map Output map containing the identified channels and the corresponding intensities. */ void extractChannels(const PeakMap& ms_exp_data, ConsensusMap& consensus_map); /** * @brief Extracts intensities for channels of reporter ions from isobaric tags (according to the quantitation method given when creating this object) * * Stores statistics about extraction in @p channel_qc. * * @param[in] spec_idx index in the MSExperiment @p exp * @param[in] exp reference to the MSExperiment for finding precursors etc. * @param[out] channel_qc vector of pairs of m/z and channel index for storing channel QC information * @return std::vector<double> extracted intensities for each channel (0 if no peak was found) */ std::vector<double> extractSingleSpec(Size spec_idx, const MSExperiment& exp, std::vector<std::pair<double, unsigned>>& channel_qc); /** * @brief Registers channel information in a ConsensusMap. * * Adds column headers with channel metadata to the consensus map. * Only needed when using extractSingleSpec() instead of extractChannels(). * * @param[out] consensus_map ConsensusMap to register channels in * @param[in] filename Optional filename to associate with channels */ void registerChannelsInOutputMap(ConsensusMap& consensus_map, const String& filename = ""); /** * @brief Prints statistics about the channel errors with OPENMS_LOG_INFO. */ void printStats(); void printStats(ChannelQCSet& stats) const; /** * @brief Prints the stats collected during quantification. ChannelQC mzdeltas may contain missing values encoded as quiet_NaN. * * @param[in] stats the stats to print (NOT const, since we need to sort it for median calculation) * */ void printStatsWithMissing(std::vector<ChannelQC>& stats) const; /** * @brief Clears channel statistics, e.g. after a new experiment has been loaded. */ void clearStats(); /** * @brief Returns a reference to the channel statistics. * * @return Reference to the internal ChannelQCSet containing accumulated QC metrics */ ChannelQCSet& getStats(); private: /** @brief Small struct to capture the current state of the purity computation. It basically contains two iterators pointing to the current potential MS1 precursor scan of an MS2 scan and the MS1 scan immediately following the current MS2 scan. */ struct PurityState_ { /// Iterator pointing to the potential MS1 precursor scan PeakMap::ConstIterator precursorScan; /// Iterator pointing to the potential follow up MS1 scan PeakMap::ConstIterator followUpScan; /// Indicates if a follow up scan was found bool hasFollowUpScan; /// reference to the experiment to analyze const PeakMap& baseExperiment; /** @brief C'tor taking the experiment that will be analyzed. @param[in] targetExp The experiment that will be analyzed. */ PurityState_(const PeakMap& targetExp); /** @brief Searches the experiment for the next MS1 spectrum with a retention time bigger then @p rt. @param[in] rt The next follow up scan should have a retention bigger then this value. */ void advanceFollowUp(const double rt); /** @brief Check if the currently selected follow up scan has a retention time bigger then the given value. @param[in] rt The retention time to check. */ bool followUpValid(const double rt) const; }; /// The used quantitation method (itraq4plex, tmt6plex,..). const IsobaricQuantitationMethod* quant_method_; /// Used to select only specific types of spectra for the channel extraction. String selected_activation_; /// Allowed deviation between the expected and observed reporter ion m/z. Peak2D::CoordinateType reporter_mass_shift_; /// Minimum intensity of the precursor to be considered for quantitation. Peak2D::IntensityType min_precursor_intensity_; /// Flag if precursor with missing intensity value or missing precursor spectrum should be included or not. bool keep_unannotated_precursor_; /// Minimum reporter ion intensity to be considered for quantitation. Peak2D::IntensityType min_reporter_intensity_; /// Flag if complete quantification should be discarded if a single reporter ion has an intensity below the threshold given in IsobaricChannelExtractor::min_reporter_intensity_ . bool remove_low_intensity_quantifications_; /// Minimum precursor purity to accept the spectrum for quantitation. double min_precursor_purity_; /// Max. allowed deviation between theoretical and observed isotopic peaks of the precursor peak in the isolation window to be counted as part of the precursor. double max_precursor_isotope_deviation_; /// Flag if precursor purity will solely be computed based on the precursor scan (false), or interpolated between the precursor- and the following MS1 scan. bool interpolate_precursor_purity_; /// Constant for distance used in qc calculations static constexpr double qc_dist_mz = 0.5; // fixed! Do not change! /// Accumulates QC metrics for the different channels ChannelQCSet channel_mz_delta; /** @brief Checks if the given precursor fulfills all constraints for extractions. @param[in] precursor The precursor to test. @return $true$ if the precursor can be used for extraction, $false$ otherwise. */ bool isValidPrecursor_(const Precursor& precursor) const; /** @brief Checks whether the given ConsensusFeature contains a channel that is below the given intensity threshold. @param[in] cf The ConsensusFeature to check. @return $true$ if a low intensity reporter is contained, $false$ otherwise. */ bool hasLowIntensityReporter_(const ConsensusFeature& cf) const; /** @brief Computes the purity of the precursor given an iterator pointing to the MS/MS spectrum and one to the precursor spectrum. @param[in] ms2_spec Iterator pointing to the MS2 spectrum. @param[in] precursor Iterator pointing to the precursor spectrum of ms2_spec. @return Fraction of the total intensity in the isolation window of the precursor spectrum that was assigned to the precursor. */ double computePrecursorPurity_(const PeakMap::ConstIterator& ms2_spec, const PurityState_& precursor) const; /** @brief Computes the purity of the precursor given an iterator pointing to the MS/MS spectrum and a reference to the potential precursor spectrum. @param[in] ms2_spec Iterator pointing to the MS2 spectrum. @param[in] precursor_spec Precursor spectrum of ms2_spec. @return Fraction of the total intensity in the isolation window of the precursor spectrum that was assigned to the precursor. */ double computeSingleScanPrecursorPurity_(const PeakMap::ConstIterator& ms2_spec, const PeakMap::SpectrumType& precursor_spec) const; /** @brief Get the first (of potentially many) activation methods (HCD,CID,...) of this spectrum. @param[in] s The spectrum @return Entry from Precursor::NamesOfActivationMethod or empty string. */ String getActivationMethod_(const PeakMap::SpectrumType& s) const { for (std::vector<Precursor>::const_iterator it = s.getPrecursors().begin(); it != s.getPrecursors().end(); ++it) { if (!it->getActivationMethods().empty()) return Precursor::NamesOfActivationMethod[static_cast<size_t>(*(it->getActivationMethods().begin()))]; } return ""; } protected: /// implemented for DefaultParamHandler void setDefaultParams_(); /// implemented for DefaultParamHandler void updateMembers_() override; }; } // namespace
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/ANALYSIS/QUANTITATION/TMTEighteenPlexQuantitationMethod.h
.h
2,118
75
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Stephan Aiche, Samuel Wein, Radu Suciu $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/config.h> #include <OpenMS/ANALYSIS/QUANTITATION/IsobaricQuantitationMethod.h> namespace OpenMS { /** @brief TMT 18plex quantitation to be used with the IsobaricQuantitation. @htmlinclude OpenMS_TMTEighteenPlexQuantitationMethod.parameters */ class OPENMS_DLLAPI TMTEighteenPlexQuantitationMethod : public IsobaricQuantitationMethod { public: /// Default c'tor TMTEighteenPlexQuantitationMethod(); /// d'tor ~TMTEighteenPlexQuantitationMethod() override = default; /// Copy c'tor TMTEighteenPlexQuantitationMethod(const TMTEighteenPlexQuantitationMethod& other); /// Assignment operator TMTEighteenPlexQuantitationMethod & operator=(const TMTEighteenPlexQuantitationMethod& rhs); /// @brief Methods to implement from IsobaricQuantitationMethod /// @{ const String& getMethodName() const override; const IsobaricChannelList& getChannelInformation() const override; Size getNumberOfChannels() const override; Matrix<double> getIsotopeCorrectionMatrix() const override; Size getReferenceChannel() const override; /// @} private: /// the actual information on the different tmt18plex channels. IsobaricChannelList channels_; /// The name of the quantitation method. static const String name_; /// The reference channel for this experiment. Size reference_channel_; /// List of available channel names as they are presented to the user static const std::vector<std::string> channel_names_; protected: /// implemented for DefaultParamHandler void setDefaultParams_(); /// implemented for DefaultParamHandler void updateMembers_() override; }; } // namespace
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/ANALYSIS/QUANTITATION/TMTSixPlexQuantitationMethod.h
.h
1,920
73
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Stephan Aiche $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/config.h> #include <OpenMS/ANALYSIS/QUANTITATION/IsobaricQuantitationMethod.h> namespace OpenMS { /** @brief TMT 6plex quantitation to be used with the IsobaricQuantitation. @htmlinclude OpenMS_TMTSixPlexQuantitationMethod.parameters */ class OPENMS_DLLAPI TMTSixPlexQuantitationMethod : public IsobaricQuantitationMethod { public: /// Default c'tor TMTSixPlexQuantitationMethod(); /// d'tor ~TMTSixPlexQuantitationMethod() override = default; /// Copy c'tor TMTSixPlexQuantitationMethod(const TMTSixPlexQuantitationMethod& other); /// Assignment operator TMTSixPlexQuantitationMethod & operator=(const TMTSixPlexQuantitationMethod& rhs); /// @brief Methods to implement from IsobaricQuantitationMethod /// @{ const String& getMethodName() const override; const IsobaricChannelList& getChannelInformation() const override; Size getNumberOfChannels() const override; Matrix<double> getIsotopeCorrectionMatrix() const override; Size getReferenceChannel() const override; /// @} private: /// the actual information on the different tmt 6plex channels. IsobaricChannelList channels_; /// The name of the quantitation method. static const String name_; /// The reference channel for this experiment. Size reference_channel_; protected: /// implemented for DefaultParamHandler void setDefaultParams_(); /// implemented for DefaultParamHandler void updateMembers_() override; }; } // namespace
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/ANALYSIS/QUANTITATION/ProteinInference.h
.h
2,132
72
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow $ // $Authors: $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/KERNEL/Peak2D.h> #include <vector> namespace OpenMS { class PeptideHit; class ConsensusMap; /** @brief [experimental class] given a peptide quantitation, infer corresponding protein quantities Infers protein ratios from peptide ratios (currently using unique peptides only). Use the IDMapper class to add protein and peptide information to a quantitative ConsensusMap prior to this step. */ class OPENMS_DLLAPI ProteinInference { public: typedef Peak2D::IntensityType IntensityType; /// Constructor ProteinInference(); /// copy constructor ProteinInference(const ProteinInference& cp); /// assignment operator ProteinInference& operator=(const ProteinInference& rhs); /** @brief given a peptide quantitation, infer corresponding protein quantities Infers protein ratios from peptide ratios (currently using unique peptides only). Use the IDMapper class to add protein and peptide information to a quantitative ConsensusMap prior to this step. @param[in] consensus_map Peptide quantitation with ProteinIdentifications attached, where Protein quantitation will be attached @param[in] reference_map Index of (iTRAQ) reference channel within the consensus map @throws Exception::MissingInformation if Protein/PeptideIdentifications are missing */ void infer(ConsensusMap& consensus_map, const UInt reference_map); protected: void infer_(ConsensusMap& consensus_map, const size_t protein_idenfication_index, const UInt reference_map); bool sortByUnique_(std::vector<PeptideHit>& peptide_hits_local, const bool is_higher_score_better); }; // !class } // !namespace
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/ANALYSIS/QUANTITATION/IsobaricQuantifier.h
.h
2,653
78
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Stephan Aiche, Chris Bielow $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h> #include <OpenMS/ANALYSIS/QUANTITATION/IsobaricQuantifierStatistics.h> namespace OpenMS { class IsobaricQuantitationMethod; class ConsensusMap; /** @brief Given the extracted channel intensities the IsobaricQuantifier corrects and normalizes the intensities for further processing. @htmlinclude OpenMS_IsobaricQuantifier.parameters */ class OPENMS_DLLAPI IsobaricQuantifier : public DefaultParamHandler { public: /** @brief Constructor given an IsobaricQuantitationMethod (e.g., iTRAQ 4 plex). @param[in] quant_method The quantification method used for the data set to analyze. */ explicit IsobaricQuantifier(const IsobaricQuantitationMethod* const quant_method); /// Copy c'tor IsobaricQuantifier(const IsobaricQuantifier& other); /// Assignment operator IsobaricQuantifier& operator=(const IsobaricQuantifier& rhs); /** @brief Using the raw isobaric intensities we apply isotope correction, normalization (using median). @param[in] consensus_map_in Raw isobaric channel intensities from channel extraction. @param[in] consensus_map_out Corrected and normalized isobaric channel ratios for peptides. @throws Exception::FailedAPICall is least-squares fit fails @throws Exception::InvalidParameter if parameter is invalid (e.g. reference_channel) */ void quantify(const ConsensusMap& consensus_map_in, ConsensusMap& consensus_map_out); protected: /// implemented for DefaultParamHandler void setDefaultParams_(); /// implemented for DefaultParamHandler void updateMembers_() override; private: /// Stats of current quantitation run. IsobaricQuantifierStatistics stats_; /// The quantification method used for the dataset to be analyzed. const IsobaricQuantitationMethod* quant_method_; /// Is true if isotope correction is enabled, false otherwise. bool isotope_correction_enabled_; /// Is true if normalization is enabled, false otherwise. bool normalization_enabled_; /// Computes labeling statistics (efficiency, number of empty scans,...) void computeLabelingStatistics_(ConsensusMap& consensus_map_out); }; } // namespace
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/ANALYSIS/QUANTITATION/TMTSixteenPlexQuantitationMethod.h
.h
2,098
75
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Stephan Aiche, Samuel Wein $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/config.h> #include <OpenMS/ANALYSIS/QUANTITATION/IsobaricQuantitationMethod.h> namespace OpenMS { /** @brief TMT 16plex quantitation to be used with the IsobaricQuantitation. @htmlinclude OpenMS_TMTSixteenPlexQuantitationMethod.parameters */ class OPENMS_DLLAPI TMTSixteenPlexQuantitationMethod : public IsobaricQuantitationMethod { public: /// Default c'tor TMTSixteenPlexQuantitationMethod(); /// d'tor ~TMTSixteenPlexQuantitationMethod() override = default; /// Copy c'tor TMTSixteenPlexQuantitationMethod(const TMTSixteenPlexQuantitationMethod& other); /// Assignment operator TMTSixteenPlexQuantitationMethod & operator=(const TMTSixteenPlexQuantitationMethod& rhs); /// @brief Methods to implement from IsobaricQuantitationMethod /// @{ const String& getMethodName() const override; const IsobaricChannelList& getChannelInformation() const override; Size getNumberOfChannels() const override; Matrix<double> getIsotopeCorrectionMatrix() const override; Size getReferenceChannel() const override; /// @} private: /// the actual information on the different tmt16plex channels. IsobaricChannelList channels_; /// The name of the quantitation method. static const String name_; /// The reference channel for this experiment. Size reference_channel_; /// List of available channel names as they are presented to the user static const std::vector<std::string> channel_names_; protected: /// implemented for DefaultParamHandler void setDefaultParams_(); /// implemented for DefaultParamHandler void updateMembers_() override; }; } // namespace
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/ANALYSIS/QUANTITATION/TMTElevenPlexQuantitationMethod.h
.h
2,075
76
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Stephan Aiche $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/config.h> #include <OpenMS/ANALYSIS/QUANTITATION/IsobaricQuantitationMethod.h> namespace OpenMS { /** @brief TMT 11plex quantitation to be used with the IsobaricQuantitation. @htmlinclude OpenMS_TMTSixPlexQuantitationMethod.parameters */ class OPENMS_DLLAPI TMTElevenPlexQuantitationMethod : public IsobaricQuantitationMethod { public: /// Default c'tor TMTElevenPlexQuantitationMethod(); /// d'tor ~TMTElevenPlexQuantitationMethod() override = default; /// Copy c'tor TMTElevenPlexQuantitationMethod(const TMTElevenPlexQuantitationMethod& other); /// Assignment operator TMTElevenPlexQuantitationMethod & operator=(const TMTElevenPlexQuantitationMethod& rhs); /// @brief Methods to implement from IsobaricQuantitationMethod /// @{ const String& getMethodName() const override; const IsobaricChannelList& getChannelInformation() const override; Size getNumberOfChannels() const override; Matrix<double> getIsotopeCorrectionMatrix() const override; Size getReferenceChannel() const override; /// @} private: /// the actual information on the different tmt11plex channels. IsobaricChannelList channels_; /// The name of the quantitation method. static const String name_; /// The reference channel for this experiment. Size reference_channel_; /// List of available channel names as they are presented to the user static const std::vector<std::string> channel_names_; protected: /// implemented for DefaultParamHandler void setDefaultParams_(); /// implemented for DefaultParamHandler void updateMembers_() override; }; } // namespace
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/ANALYSIS/QUANTITATION/TMTTenPlexQuantitationMethod.h
.h
2,054
76
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Stephan Aiche $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/config.h> #include <OpenMS/ANALYSIS/QUANTITATION/IsobaricQuantitationMethod.h> namespace OpenMS { /** @brief TMT 10plex quantitation to be used with the IsobaricQuantitation. @htmlinclude OpenMS_TMTTenPlexQuantitationMethod.parameters */ class OPENMS_DLLAPI TMTTenPlexQuantitationMethod : public IsobaricQuantitationMethod { public: /// Default c'tor TMTTenPlexQuantitationMethod(); /// d'tor ~TMTTenPlexQuantitationMethod() override = default; /// Copy c'tor TMTTenPlexQuantitationMethod(const TMTTenPlexQuantitationMethod& other); /// Assignment operator TMTTenPlexQuantitationMethod & operator=(const TMTTenPlexQuantitationMethod& rhs); /// @brief Methods to implement from IsobaricQuantitationMethod /// @{ const String& getMethodName() const override; const IsobaricChannelList& getChannelInformation() const override; Size getNumberOfChannels() const override; Matrix<double> getIsotopeCorrectionMatrix() const override; Size getReferenceChannel() const override; /// @} private: /// the actual information on the different tmt10plex channels. IsobaricChannelList channels_; /// The name of the quantitation method. static const String name_; /// The reference channel for this experiment. Size reference_channel_; /// List of available channel names as they are presented to the user static const std::vector<std::string> channel_names_; protected: /// implemented for DefaultParamHandler void setDefaultParams_(); /// implemented for DefaultParamHandler void updateMembers_() override; }; } // namespace
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/ANALYSIS/QUANTITATION/IsobaricIsotopeCorrector.h
.h
10,665
219
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Stephan Aiche, Chris Bielow $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/DATASTRUCTURES/Matrix.h> #include <memory> #include <vector> namespace OpenMS { class IsobaricQuantitationMethod; class IsobaricQuantifierStatistics; class ConsensusMap; class ConsensusFeature; /** @brief Performs isotope impurity correction on intensities extracted from isobaric labeling experiments. This class implements algorithms for correcting isotope impurities in quantitative proteomics data obtained from isobaric labeling experiments such as iTRAQ or TMT. Isotope impurities arise from the fact that the reagents used for labeling are not 100% pure and contain isotopic variants that can contribute to the signal in neighboring channels. The correction is performed using a non-negative least squares (NNLS) approach, which solves the linear system Ax = b, where: - A is the correction matrix derived from the isotope impurity information provided by the reagent manufacturer - b is the vector of observed intensities in each channel - x is the vector of corrected intensities The NNLS approach ensures that the corrected intensities remain non-negative, which is physically meaningful for mass spectrometry data. @see IsobaricQuantitationMethod @see IsobaricQuantifierStatistics */ class OPENMS_DLLAPI IsobaricIsotopeCorrector { public: /** @brief Apply isotope correction to the given input map and store the corrected values in the output map. @param[in] consensus_map_in The map containing the values that should be corrected. @param[in,out] consensus_map_out The map where the corrected values should be stored. @param[in] quant_method IsobaricQuantitationMethod (e.g., iTRAQ 4 plex) @throws Exception::FailedAPICall If the least-squares fit fails. @throws Exception::InvalidParameter If the given correction matrix is invalid. */ static IsobaricQuantifierStatistics correctIsotopicImpurities(const ConsensusMap& consensus_map_in, ConsensusMap& consensus_map_out, const IsobaricQuantitationMethod* quant_method); /** @brief Apply isotope correction to a vector of channel intensities. This method applies the isotope correction directly to a vector of intensities representing the different isobaric channels. The vector is modified in-place to contain the corrected values. @param[in,out] intensities Vector of channel intensities to be corrected (modified in-place) @param[in] quant_method IsobaricQuantitationMethod providing the correction matrix (e.g., iTRAQ 4 plex) @throws Exception::FailedAPICall If the least-squares fit fails. @throws Exception::InvalidParameter If the given correction matrix is invalid. @note The size of the intensities vector must match the number of channels in the quantitation method. */ static void correctIsotopicImpurities(std::vector<double>& intensities, const IsobaricQuantitationMethod* quant_method); // No instance methods as this is a purely static class private: /** * @brief Fills the input vector for the NNLS step given the ConsensusFeature. * * Warning, assumes that the consensusMap and its ConsensusFeatures have exactly the same cardinality as the * number of channels as in the quantitation method and are in the same order as the channels. * * I.e. for a TMT16plex, although the whole ConsensusMap has 160 potential map_index values because we had 10 files, * every ConsensusFeature is only allowed to have exactly 16 map_index values (one for each channel) and they are * in the same order as the channels in the quantitation method. * * @param[out] b Vector to be filled with intensities * @param[out] m_b OpenMS matrix to be filled with intensities (alternative representation) * @param[in] cf ConsensusFeature containing the channel intensities * @param[in] cm ConsensusMap containing the feature * * @pre The ConsensusFeature must contain exactly the same number of elements as there are * channels in the quantitation method */ static void fillInputVector_(std::vector<double>& b, Matrix<double>& m_b, const ConsensusFeature& cf, const ConsensusMap& cm); /** * @brief Extract channel intensities from a ConsensusFeature. * * Extracts the intensities for each channel from the given ConsensusFeature. * * @param[in] quant_method The isobaric quantitation method defining the channels * @param[in] cf ConsensusFeature containing the channel intensities * @param[in] cm ConsensusMap containing the feature * @return Vector of intensities, one for each channel */ static std::vector<double> getIntensities_(const IsobaricQuantitationMethod* quant_method, const ConsensusFeature& cf, const ConsensusMap& cm); /** @brief Solve the non-negative least squares problem using OpenMS matrices. Solves the NNLS problem Ax = b, where A is the correction matrix and b is the vector of observed intensities. This version uses OpenMS Matrix objects for the computation. @param[in] correction_matrix The isotope correction matrix (A) @param[in] m_b The vector of observed intensities (b) @param[in] m_x The output vector of corrected intensities (x) @throws Exception::FailedAPICall If the NNLS solver fails */ static void solveNNLS_(const Matrix<double>& correction_matrix, const Matrix<double>& m_b, Matrix<double>& m_x); /** @brief Solve the non-negative least squares problem using Matrix and vectors. Solves the NNLS problem Ax = b, where A is the correction matrix and b is the vector of observed intensities. @note This overload mutates the correction matrix in-place for efficiency. Use the const-preserving overload (taking const Matrix<double>&) if the original matrix must remain unchanged. @param[in,out] correction_matrix The isotope correction matrix (A). Modified in-place by the NNLS solver. @param[in] b The vector of observed intensities (b) @param[out] x The output vector of corrected intensities (x) */ static void solveNNLS_(Matrix<double>& correction_matrix, std::vector<double>& b, std::vector<double>& x); /** @brief Compute statistics for the correction process. Calculates various statistics about the correction process by comparing the NNLS solution (guaranteed non-negative) with the naive LU-decomposition solution (which may have negative values). @param[in] m_x The NNLS-corrected intensities (non-negative) @param[in] x_naive The naive LU-decomposition solution (may contain negative values) @param[in] cf_intensity The original intensity of the consensus feature @param[in] quant_method The isobaric quantitation method @param[in,out] stats The statistics object to update */ static void computeStats_(const std::vector<double>& m_x, const std::vector<double>& x_naive, const float cf_intensity, const IsobaricQuantitationMethod* quant_method, IsobaricQuantifierStatistics& stats); /** @brief Compute statistics for the correction process using OpenMS matrices. Calculates various statistics about the correction process by comparing the NNLS solution (guaranteed non-negative) with the naive LU-decomposition solution (which may have negative values). @param[in] m_x The NNLS-corrected intensities as OpenMS matrix (non-negative) @param[in] x_naive The naive LU-decomposition solution (may contain negative values) @param[in] cf_intensity The original intensity of the consensus feature @param[in] quant_method The isobaric quantitation method @param[in,out] stats The statistics object to update */ static void computeStats_(const Matrix<double>& m_x, const std::vector<double>& x_naive, const float cf_intensity, const IsobaricQuantitationMethod* quant_method, IsobaricQuantifierStatistics& stats); /** @brief Update the output consensus map with corrected intensities using std::vector. Copies the consensus feature from the input map to the output map and updates its intensities with the corrected values. @param[in] consensus_map_in The input consensus map @param[in,out] consensus_map_out The output consensus map to be updated @param[in] current_cf Index of the current consensus feature @param[in] m_x Vector of corrected intensities @return The sum of corrected intensities */ static float updateOutputMap_(const ConsensusMap& consensus_map_in, ConsensusMap& consensus_map_out, Size current_cf, const std::vector<double>& m_x); /** @brief Update the output consensus map with corrected intensities using OpenMS Matrix. Copies the consensus feature from the input map to the output map and updates its intensities with the corrected values. @param[in] consensus_map_in The input consensus map @param[out] consensus_map_out The output consensus map to be updated @param[in] current_cf Index of the current consensus feature @param[out] m_x Matrix of corrected intensities @return The sum of corrected intensities */ static float updateOutputMap_(const ConsensusMap& consensus_map_in, ConsensusMap& consensus_map_out, Size current_cf, const Matrix<double>& m_x); }; } // namespace
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/ANALYSIS/QUANTITATION/KDTreeFeatureNode.h
.h
1,513
66
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Johannes Veit $ // $Authors: Johannes Veit $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/config.h> #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/CONCEPT/Exception.h> #include <OpenMS/CONCEPT/Macros.h> namespace OpenMS { class KDTreeFeatureMaps; /// A node of the kD-tree with pointer to corresponding data and index class OPENMS_DLLAPI KDTreeFeatureNode { public: /// Constructor KDTreeFeatureNode(KDTreeFeatureMaps* data, Size idx); /// Copy constructor - copy the pointer, use same data object KDTreeFeatureNode(const KDTreeFeatureNode& rhs); /// Assignment operator - copy the pointer, use same data object KDTreeFeatureNode& operator=(KDTreeFeatureNode const& rhs); /// Destructor virtual ~KDTreeFeatureNode(); /// libkdtree++ needs this typedef typedef double value_type; /// Needed for 2D range queries using libkdtree++. [0] returns RT, [1] m/z. value_type operator[](Size i) const; /// Return index of corresponding feature in data_ Size getIndex() const; protected: /// Pointer to the actual data KDTreeFeatureMaps* data_; /// Index of this feature Size idx_; private: /// Default constructor is not supposed to be called KDTreeFeatureNode(); }; }
Unknown