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/ANALYSIS/QUANTITATION/KDTreeFeatureMaps.h | .h | 3,468 | 137 | // 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/KERNEL/StandardTypes.h>
#include <OpenMS/KERNEL/Feature.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/ANALYSIS/MAPMATCHING/TransformationModelLowess.h>
#include <OpenMS/DATASTRUCTURES/KDTree.h>
#include <OpenMS/ANALYSIS/QUANTITATION/KDTreeFeatureNode.h>
namespace OpenMS
{
/// Stores a set of features, together with a 2D tree for fast search
class OPENMS_DLLAPI KDTreeFeatureMaps : public DefaultParamHandler
{
public:
/// 2D tree on features
typedef KDTree::KDTree<2,KDTreeFeatureNode> FeatureKDTree;
/// Default constructor
KDTreeFeatureMaps() :
DefaultParamHandler("KDTreeFeatureMaps")
{
check_defaults_ = false;
}
/// Constructor
template <typename MapType>
KDTreeFeatureMaps(const std::vector<MapType>& maps, const Param& param) :
DefaultParamHandler("KDTreeFeatureMaps")
{
check_defaults_ = false;
setParameters(param);
addMaps(maps);
}
/// Destructor
~KDTreeFeatureMaps() override
{
}
/// Add @p maps and balance kd-tree
template <typename MapType>
void addMaps(const std::vector<MapType>& maps)
{
num_maps_ = maps.size();
for (Size i = 0; i < num_maps_; ++i)
{
const MapType& m = maps[i];
for (typename MapType::const_iterator it = m.begin(); it != m.end(); ++it)
{
addFeature(i, &(*it));
}
}
optimizeTree();
}
/// Add feature
void addFeature(Size mt_map_index, const BaseFeature* feature);
/// Return pointer to feature i
const BaseFeature* feature(Size i) const;
/// RT
double rt(Size i) const;
/// m/z
double mz(Size i) const;
/// Intensity
float intensity(Size i) const;
/// Charge
Int charge(Size i) const;
/// Map index
Size mapIndex(Size i) const;
/// Number of features stored
Size size() const;
/// Number of points in the tree
Size treeSize() const;
/// Number of maps
Size numMaps() const;
/// Clear all data
void clear();
/// Optimize the kD tree
void optimizeTree();
/// Fill @p result with indices of all features compatible (wrt. RT, m/z, map index) to the feature with @p index
void getNeighborhood(Size index, std::vector<Size>& result_indices, double rt_tol, double mz_tol, bool mz_ppm, bool include_features_from_same_map = false, double max_pairwise_log_fc = -1.0) const;
/// Fill @p result with indices of all features within the specified boundaries
void queryRegion(double rt_low, double rt_high, double mz_low, double mz_high, std::vector<Size>& result_indices, Size ignored_map_index = std::numeric_limits<Size>::max()) const;
/// Apply RT transformations
void applyTransformations(const std::vector<TransformationModelLowess*>& trafos);
protected:
void updateMembers_() override;
/// Feature data
std::vector<const BaseFeature*> features_;
/// Map indices
std::vector<Size> map_index_;
/// (Potentially transformed) retention times
std::vector<double> rt_;
/// Number of maps
Size num_maps_;
/// 2D tree on features from all input maps.
FeatureKDTree kd_tree_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/QUANTITATION/ItraqConstants.h | .h | 5,332 | 130 | // 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/CONCEPT/Types.h>
#include <OpenMS/KERNEL/Peak2D.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/DATASTRUCTURES/StringListUtils.h>
#include <OpenMS/DATASTRUCTURES/Matrix.h>
#include <map>
namespace OpenMS
{
/**
@brief Some constants used throughout iTRAQ classes.
Constants for iTRAQ experiments and a ChannelInfo structure to store information about a single channel.
*/
class OPENMS_DLLAPI ItraqConstants
{
public:
static const Int CHANNEL_COUNT[];
enum ITRAQ_TYPES {FOURPLEX = 0, EIGHTPLEX, TMT_SIXPLEX, SIZE_OF_ITRAQ_TYPES};
/// stores information on an iTRAQ channel
struct ChannelInfo
{
String description; ///< description given by experimentalist (e.g. lung tissue)
Int name; ///< 114-117 or 113 to 121
Int id; ///< 0-4 or 0-8
Peak2D::CoordinateType center; ///< expected centroid of peak in MZ
bool active; ///< channel actually added to the experiment?
};
/// maps iTRAQ channel (e.g. 117) to more information
typedef std::map<Int, ChannelInfo> ChannelMapType;
/// (user defined?) isotope correction matrix in (-2, -1, +1, +2) row style
typedef std::vector<Matrix<double>> IsotopeMatrices;
/// channel names for 4plex( 114, 115, 116, 117)
static const Int CHANNELS_FOURPLEX[4][1];
/// channel names for 8plex( 113, 114, 115, 116, 117, 118, 119, 121)
static const Int CHANNELS_EIGHTPLEX[8][1];
/// channel names for 6plex TMT with CID fragmentation( 126, 127, 128, 129, 130, 131)
static const Int CHANNELS_TMT_SIXPLEX[6][1];
// channel names for 6plex TMT with ETD fragmentation( 114, 115, 116, 117, 118, 119)
//static const Int CHANNELS_SIXPLEX_ETD[6][1];
/// default isotope correction matrix (4 plex)
static const double ISOTOPECORRECTIONS_FOURPLEX[4][4];
/// default isotope correction matrix (8 plex)
static const double ISOTOPECORRECTIONS_EIGHTPLEX[8][4];
/// default isotope correction matrix (6 plex TMT)
static const double ISOTOPECORRECTIONS_TMT_SIXPLEX[6][4];
// default isotope correction matrix (6 plex TMT)
//static const double ISOTOPECORRECTIONS_SIXPLEX_ETD[6][4];
/**
@brief convert isotope correction matrix to stringlist
Each line is converted into a string of the format <channel>:<-2Da>/<-1Da>/<+1Da>/<+2Da> ; e.g. '114:0/0.3/4/0'
Useful for creating parameters or debug output.
@param[in] itraq_type Which matrix to stringify. Should be of values from enum ITRAQ_TYPES
@param[in] isotope_corrections Vector of the two matrices (4plex, 8plex).
*/
static StringList getIsotopeMatrixAsStringList(const int itraq_type, const IsotopeMatrices & isotope_corrections);
/**
@brief convert strings to isotope correction matrix rows
Each string of format <channel>:<-2Da>/<-1Da>/<+1Da>/<+2Da> ; e.g. '114:0/0.3/4/0'
is parsed and the corresponding channel(row) in the matrix is updated.
Not all channels need to be present, missing channels will be left untouched.
Useful to update the matrix with user isotope correction values.
@param[in] itraq_type Which matrix to stringify. Should be of values from enum ITRAQ_TYPES
@param[in] channels New channel isotope values as strings
@param[in] isotope_corrections Vector of the two matrices (4plex, 8plex).
*/
static void updateIsotopeMatrixFromStringList(const int itraq_type, const StringList & channels, IsotopeMatrices & isotope_corrections);
/**
@brief information about an iTRAQ channel
State, name and expected mz-position of iTRAQ channels are initialized.
@param[in] itraq_type Should be of values from enum ITRAQ_TYPES
@param[in] map Storage to initialize
*/
static void initChannelMap(const int itraq_type, ChannelMapType & map);
/**
@brief activate & annotate channels
State and description of iTRAQ channels are updated.
Each input string must have the format <channel>:<description>, e.g. "114:myref","115:liver"
@param[in] active_channels StringList with channel and description
@param[in] map Storage to update
*/
static void updateChannelMap(const StringList & active_channels, ChannelMapType & map);
/**
@brief translate isotope correction matrix in -2,-1,+1,+2 form into 114,115,116,117 format
Translates e.g. ItraqConstants::ISOTOPECORRECTIONS_EIGHTPLEX matrix into a 8x8 matrix which
maps how channel (row) distributes its tags onto other channels (columns).
@param[in] itraq_type Should be of values from enum ITRAQ_TYPES
@param[in] isotope_corrections isotope correction matrix in -2...+2 form
*/
static Matrix<double> translateIsotopeMatrix(const int & itraq_type, const IsotopeMatrices & isotope_corrections);
}; // !class
} // !namespace
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/QUANTITATION/IsotopeLabelingMDVs.h | .h | 9,777 | 187 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Ahmed Khalil $
// $Authors: Ahmed Khalil $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/DATASTRUCTURES/Matrix.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/KERNEL/Feature.h>
namespace OpenMS
{
/**
@brief IsotopeLabelingMDVs is a class to support and analyze isotopic labeling experiments
(i.e. MDVs : Mass Distribution Vectors, also known as Mass Isotopomer Distribution (MID))
*/
class OPENMS_DLLAPI IsotopeLabelingMDVs :
public DefaultParamHandler
{
public:
//@{
/// Constructor
IsotopeLabelingMDVs();
/// Destructor
~IsotopeLabelingMDVs() override;
//@}
enum class DerivatizationAgent
{
NOT_SELECTED,
TBDMS,
SIZE_OF_DERIVATIZATIONAGENT
};
enum class MassIntensityType
{
NORM_MAX,
NORM_SUM,
SIZE_OF_MASSINTENSITYTYPE
};
static const std::string NamesOfDerivatizationAgent[static_cast<int>(DerivatizationAgent::SIZE_OF_DERIVATIZATIONAGENT)];
static const std::string NamesOfMassIntensityType[static_cast<int>(MassIntensityType::SIZE_OF_MASSINTENSITYTYPE)];
/**
@brief This function performs an isotopic correction to account for unlabeled abundances coming from
the derivatization agent (e.g., tBDMS) using correction matrix method and is calculated as follows:
MDV_corrected = CM^-1 * MDV_normalized_feature
The formula is obtained from "The importance of accurately correcting for the natural abundance of stable isotopes",
Midani et al, doi:10.1016/j.ab.2016.12.011
@param[in] normalized_feature Feature with normalized values for each component and unlabeled chemical formula for each component group.
@param[out] corrected_feature Feature with corrected values for each component.
@param[in] correction_matrix Square matrix holding correction factors derived either experimentally or theoretically which describe how spectral peaks of
naturally abundant 13C contribute to spectral peaks that overlap (or convolve) the spectral peaks of the corrected MDV of the derivatization agent.
@param[out] correction_matrix_agent name of the derivatization agent, the internally stored correction matrix if the name of the agent is supplied,
only "TBDMS" is supported for now.
*/
void isotopicCorrection(
const Feature& normalized_feature,
Feature& corrected_feature,
const Matrix<double>& correction_matrix,
const DerivatizationAgent& correction_matrix_agent);
/**
@brief This function performs an isotopic correction to account for unlabeled abundances coming from
the derivatization agent (e.g., tBDMS) using correction matrix method and is calculated as follows:
MDV_corrected = CM^-1 * MDV_normalized_feature
The formula is obtained from "The importance of accurately correcting for the natural abundance of stable isotopes",
Midani et al, doi:10.1016/j.ab.2016.12.011
@param[in] measured_fm FeatureMap with normalized values for each component and unlabeled chemical formula for each component group.
@param[out] corrected_fm FeatureMap with corrected values for each component.
@param[in] correction_matrix Square matrix holding correction factors derived either experimentally or theoretically which describe how spectral peaks of
naturally abundant 13C contribute to spectral peaks that overlap (or convolve) the spectral peaks of the corrected MDV of the derivatization agent.
@param[out] correction_matrix_agent name of the derivatization agent, the internally stored correction matrix if the name of the agent is supplied,
only "TBDMS" is supported for now.
*/
void isotopicCorrections(
const FeatureMap& measured_fm,
FeatureMap& corrected_fm,
const Matrix<double>& correction_matrix,
const DerivatizationAgent& correction_matrix_agent);
/**
@brief This function calculates the isotopic purity of the MDV using the following formula:
isotopic purity of tracer (atom % 13C) = n / [n + (M + n-1)/(M + n)],
where n in M+n is represented as the index of the result.
The formula is extracted from "High-resolution 13C metabolic flux analysis",
Long et al, doi:10.1038/s41596-019-0204-0
@param[in,out] normalized_feature Feature with normalized values for each component and the number of heavy labeled e.g., carbons. Out is a Feature with the calculated isotopic purity for the component group.
@param[in] experiment_data Vector of experiment data in percent.
@param[in] isotopic_purity_name Name of the isotopic purity tracer to be saved as a meta value.
*/
void calculateIsotopicPurity(
Feature& normalized_feature,
const std::vector<double>& experiment_data,
const std::string& isotopic_purity_name);
/**
@brief This function calculates the isotopic purity of the MDVs using the following formula:
isotopic purity of tracer (atom % 13C) = n / [n + (M + n-1)/(M + n)],
where n in M+n is represented as the index of the result.
The formula is extracted from "High-resolution 13C metabolic flux analysis",
Long et al, doi:10.1038/s41596-019-0204-0
@param[in,out] measured_fm FeatureMap with normalized values for each component and the number of heavy labeled e.g., carbons. Out is a FeatureMap with the calculated isotopic purity for the component group.
@param[in] experiment_data Vector of vectors of Experiment data in percent.
@param[in] isotopic_purity_name Vector of names of the isotopic purity tracer to be saved as a meta value.
*/
void calculateIsotopicPurities(
FeatureMap& measured_fm,
const std::vector<std::vector<double>>& experiment_data,
const std::vector<std::string>& isotopic_purity_name);
/**
@brief This function calculates the accuracy of the MDV as compared to the theoretical MDV (only for 12C quality control experiments)
using average deviation to the mean. The result is mapped to the meta value "average_accuracy" in the updated Feature.
@param[in,out] normalized_feature Feature with normalized values for each component and the chemical formula of the component group. Out is a Feature with the component group accuracy and accuracy for the error for each component.
@param[in] feature_name Feature name to determine which features are needed to apply calculations on.
@param[in] fragment_isotopomer_theoretical_formula Empirical formula from which the theoretical values will be generated.
*/
void calculateMDVAccuracy(
Feature& normalized_feature,
const std::string& feature_name,
const std::string& fragment_isotopomer_theoretical_formula);
/**
@brief This function calculates the accuracy of the MDVs as compared to the theoretical MDVs (only for 12C quality control experiments)
using average deviation to the mean.
@param[in] normalized_fm FeatureMap with normalized values for each component and the chemical formula of the component group. Out is a FeatureMap with the component group accuracy and accuracy for the error for each component.
@param[in] feature_name Feature name to determine which features are needed to apply calculations on.
@param[in] fragment_isotopomer_theoretical_formulas A map of ProteinName/peptideRef to Empirical formula from which the theoretical values will be generated.
*/
void calculateMDVAccuracies(
FeatureMap& normalized_fm,
const std::string& feature_name,
const std::map<std::string, std::string>& fragment_isotopomer_theoretical_formulas);
/**
@brief This function calculates the mass distribution vector (MDV)
either normalized to the highest mass intensity (norm_max) or normalized
to the sum of all mass intensities (norm_sum)
@param[in] measured_feature Feature with measured intensity for each component.
@param[out] normalized_feature Feature with normalized values for each component.
@param[in] mass_intensity_type Mass intensity type (either norm_max or norm_sum).
@param[in] feature_name Feature name to determine which features are needed to apply calculations on.
*/
void calculateMDV(
const Feature& measured_feature,
Feature& normalized_feature,
const MassIntensityType& mass_intensity_type,
const std::string& feature_name);
/**
@brief This function calculates the mass distribution vector (MDV)
either normalized to the highest mass intensity (norm_max) or normalized
to the sum of all mass intensities (norm_sum)
@param[in] measured_fm FeatureMap with measured intensity for each component.
@param[out] normalized_fm FeatureMap with normalized values for each component.
@param[in] mass_intensity_type Mass intensity type (either norm_max or norm_sum).
@param[in] feature_name Feature name to determine which features are needed to apply calculations on.
*/
void calculateMDVs(
const FeatureMap& measured_fm,
FeatureMap& normalized_fm,
const MassIntensityType& mass_intensity_type,
const std::string& feature_name);
protected:
/// Synchronize members with param class
void updateMembers_() override;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/QUANTITATION/ItraqEightPlexQuantitationMethod.h | .h | 1,945 | 72 | // 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 iTRAQ 8 plex quantitation to be used with the IsobaricQuantitation.
@htmlinclude OpenMS_ItraqEightPlexQuantitationMethod.parameters
*/
class OPENMS_DLLAPI ItraqEightPlexQuantitationMethod :
public IsobaricQuantitationMethod
{
public:
/// Default c'tor
ItraqEightPlexQuantitationMethod();
/// d'tor
~ItraqEightPlexQuantitationMethod() override;
/// Copy c'tor
ItraqEightPlexQuantitationMethod(const ItraqEightPlexQuantitationMethod& other);
/// Assignment operator
ItraqEightPlexQuantitationMethod & operator=(const ItraqEightPlexQuantitationMethod& 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 itraq8plex 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/PeptideAndProteinQuant.h | .h | 16,021 | 394 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hendrik Weisser $
// $Authors: Hendrik Weisser $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/KERNEL/ConsensusMap.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <OpenMS/METADATA/ProteinIdentification.h>
#include <OpenMS/METADATA/ExperimentalDesign.h>
namespace OpenMS
{
/**
@brief Helper class for peptide and protein quantification based on feature data annotated with IDs.
This class is used by @ref TOPP_ProteinQuantifier. See there for further documentation.
@htmlinclude OpenMS_PeptideAndProteinQuant.parameters
*/
class OPENMS_DLLAPI PeptideAndProteinQuant :
public DefaultParamHandler
{
public:
/// Mapping: sample ID -> abundance
typedef std::map<UInt64, double> SampleAbundances;
/// Quantitative and associated data for a peptide
struct PeptideData
{
/// mapping: fraction -> filename -> charge -> channel/label -> abundance
std::map<Int, std::map<String, std::map<Int, std::map<UInt, double>>>> abundances;
/// mapping: fraction -> filename -> charge -> abundance
std::map<Int, std::map<String, std::map<Int, UInt64>>> psm_counts;
/// mapping: sample -> total abundance
SampleAbundances total_abundances;
/// spectral counting-based abundances
SampleAbundances total_psm_counts;
/// protein accessions for this peptide
std::set<String> accessions;
/// total number of identifications
Size psm_count = 0;
/// constructor
PeptideData() = default;
};
/// Mapping: peptide sequence (modified) -> peptide data
typedef std::map<AASequence, PeptideData> PeptideQuant;
/// Quantitative and associated data for a protein
struct ProteinData
{
/// mapping: peptide (unmodified) -> sample -> abundance
std::map<String, SampleAbundances> peptide_abundances;
std::map<String, SampleAbundances> peptide_psm_counts;
/// mapping: filename -> channel/label -> abundance
std::map<String, std::map<UInt, double>> channel_level_abundances;
/// mapping: filename -> PSM counts
std::map<String, UInt64> file_level_psm_counts;
/// mapping: sample -> total abundance
SampleAbundances total_abundances;
/// spectral counting-based abundances
SampleAbundances total_psm_counts;
/// number of distinct peptide sequences
SampleAbundances total_distinct_peptides;
/// total number of PSMs mapping to this protein
Size psm_count = 0;
/// constructor
ProteinData() = default;
};
/// Mapping: protein accession -> protein data
typedef std::map<String, ProteinData> ProteinQuant;
/// Statistics for processing summary
struct Statistics
{
/// number of samples (or assays in mzTab terms)
Size n_samples;
/// number of fractions
Size n_fractions;
/// number of MS files
Size n_ms_files;
/// protein statistics
Size quant_proteins, too_few_peptides;
/// peptide statistics
Size quant_peptides, total_peptides;
/// feature statistics
Size quant_features, total_features, blank_features, ambig_features;
/// constructor
Statistics() :
n_samples(0), quant_proteins(0), too_few_peptides(0),
quant_peptides(0), total_peptides(0), quant_features(0),
total_features(0), blank_features(0), ambig_features(0) {}
};
/// Constructor
PeptideAndProteinQuant();
/// Destructor
~PeptideAndProteinQuant() override {}
/**
@brief Read quantitative data from a feature map.
Parameters should be set before using this method, as setting parameters will clear all results.
*/
void readQuantData(FeatureMap& features, const ExperimentalDesign& ed);
/**
@brief Read quantitative data from a consensus map.
Parameters should be set before using this method, as setting parameters will clear all results.
*/
void readQuantData(ConsensusMap& consensus, const ExperimentalDesign& ed);
/**
@brief Read quantitative data from identification results (for quantification via spectral counting).
Parameters should be set before using this method, as setting parameters will clear all results.
*/
void readQuantData(std::vector<ProteinIdentification>& proteins,
PeptideIdentificationList& peptides,
const ExperimentalDesign& ed);
/**
@brief Compute peptide abundances.
Based on quantitative data for individual charge states (in member @p pep_quant_), overall abundances for peptides are computed (and stored again in @p pep_quant_).
Quantitative data must first be read via readQuantData().
Optional (peptide-level) protein inference information (e.g. from Fido or ProteinProphet) can be supplied via @p peptides. In that case, peptide-to-protein associations - the basis for protein-level quantification - will also be read from @p peptides!
*/
void quantifyPeptides(const PeptideIdentificationList& peptides =
PeptideIdentificationList());
/**
@brief Compute protein abundances.
Peptide abundances must be computed first with quantifyPeptides(). Optional protein inference information (e.g. BasicProteinInference or Epifany) can be supplied via @p proteins.
@param[in] proteins Optional protein inference information
*/
void quantifyProteins(const ProteinIdentification& proteins = ProteinIdentification());
std::map<OpenMS::String, OpenMS::String> mapAccessionToLeader(const OpenMS::ProteinIdentification& proteins) const;
/// Get summary statistics
const Statistics& getStatistics();
/// Get peptide abundance data
const PeptideQuant& getPeptideResults();
/// Get protein abundance data
const ProteinQuant& getProteinResults();
/// Annotate protein quant results as meta data to protein ids
void annotateQuantificationsToProteins(
const ProteinQuant& protein_quants,
ProteinIdentification& proteins,
bool remove_unquantified = true);
private:
/// Processing statistics for output in the end
Statistics stats_;
/// Peptide quantification data
PeptideQuant pep_quant_;
/// Protein quantification data
ProteinQuant prot_quant_;
/// Experimental design for filename/channel to sample mapping
ExperimentalDesign experimental_design_;
/**
@brief Get the "canonical" annotation (a single peptide hit) of a feature/consensus feature from the associated list of peptide identifications.
Only the best-scoring peptide hit of each ID in @p peptides is taken into account. The hits of each ID must already be sorted! If there's more than one ID and the best hits are not identical by sequence, or if there's no peptide ID, an empty peptide hit (for "ambiguous/no annotation") is returned.
Protein accessions from identical peptide hits are accumulated.
*/
PeptideHit getAnnotation_(PeptideIdentificationList& peptides);
/**
@brief Gather quantitative information from a feature.
Store quantitative information from @p feature in member @p pep_quant_, based on the peptide annotation in @p hit.
@p fraction, use 0 for first fraction (or if no fractionation was performed)
@p filename, the base filename (without path/extension) from which the feature originates
@p channel_or_label, the channel/label identifier (e.g., TMT channel, typically 1 for LFQ)
Channel identifiers originate from consensus map headers/experimental designs and are therefore non-negative.
If @p hit is empty ("ambiguous/no annotation"), nothing is stored.
*/
void quantifyFeature_(const FeatureHandle& feature,
size_t fraction,
const String& filename,
const PeptideHit& hit,
UInt channel_or_label);
/**
* @brief Determine fraction, filename, charge state, and channel of a peptide with the highest
* number of abundances.
* @param[in] peptide_abundances Const input map fraction -> filename -> charge -> channel -> abundance
* @param[in] best Will additionally return the best fraction, filename, charge state, and channel
* @return true if at least one abundance was found, false otherwise
*/
bool getBest_(
const std::map<Int, std::map<String, std::map<Int, std::map<UInt, double>>>> & peptide_abundances,
std::tuple<size_t, String, size_t, UInt> & best);
/**
@brief Order keys (charges/peptides for peptide/protein quantification) according to how many samples they allow to quantify, breaking ties by total abundance.
The keys of @p abundances are stored ordered in @p result, best first.
*/
template <typename T>
void orderBest_(const std::map<T, SampleAbundances> & abundances,
std::vector<T>& result)
{
typedef std::pair<Size, double> PairType;
std::multimap<PairType, T, std::greater<PairType> > order;
for (typename std::map<T, SampleAbundances>::const_iterator ab_it =
abundances.begin(); ab_it != abundances.end(); ++ab_it)
{
double total = 0.0;
for (SampleAbundances::const_iterator samp_it = ab_it->second.begin();
samp_it != ab_it->second.end(); ++samp_it)
{
total += samp_it->second;
}
if (total <= 0.0) continue; // not quantified
PairType key = std::make_pair(ab_it->second.size(), total);
order.insert(std::make_pair(key, ab_it->first));
}
result.clear();
for (typename std::multimap<PairType, T, std::greater<PairType> >::
iterator ord_it = order.begin(); ord_it != order.end(); ++ord_it)
{
result.push_back(ord_it->second);
}
}
/**
@brief Normalize peptide abundances across samples by (multiplicative) scaling to equal medians.
*/
void normalizePeptides_();
/**
@brief Transfer peptide-level quantitative data to protein-level data structures.
This method populates prot_quant_ with peptide abundance and PSM count data.
@param[in] proteins Protein identification information
*/
void transferPeptideDataToProteins_(const ProteinIdentification& proteins);
/**
@brief Select peptides for protein quantification based on filtering criteria.
@param[in] protein_accession The protein accession to select peptides for
@param[in] top_n Maximum number of peptides to select (0 = no limit)
@param[in] fix_peptides Whether to use consistent peptides across samples
@return Vector of selected peptide sequences
*/
std::vector<String> selectPeptidesForQuantification_(const String& protein_accession,
Size top_n,
bool fix_peptides);
/**
@brief Aggregate abundances using the specified mathematical method.
@param[in] abundances Vector of abundance values to aggregate
@param[in] method Aggregation method ("median", "mean", "weighted_mean", "sum")
@return Aggregated abundance value
*/
double aggregateAbundances_(const std::vector<double>& abundances,
const String& method) const;
/**
@brief Calculate protein abundances for a single protein using selected peptides.
@param[in] protein_accession The protein accession
@param[in] selected_peptides Vector of peptide sequences to use for quantification
@param[in] aggregate_method Method to aggregate peptide abundances
@param[in] top_n Maximum number of peptides to use per sample
@param[in] include_all Whether to include proteins with insufficient peptides
*/
void calculateProteinAbundances_(const String& protein_accession,
const std::vector<String>& selected_peptides,
const String& aggregate_method,
Size top_n,
bool include_all);
/**
@brief Calculate detailed protein abundances at channel level using selected peptides.
@param[in] protein_accession The protein accession
@param[in] selected_peptides Vector of peptide sequences to use for quantification
@param[in] aggregate_method Method to aggregate peptide abundances
@param[in] top_n Maximum number of peptides to use per sample
@param[in] include_all Whether to include proteins with insufficient peptides
@param[in] accession_to_leader Map for resolving protein group leaders
*/
void calculateFileAndChannelLevelProteinAbundances_(const String& protein_accession,
const std::vector<String>& selected_peptides,
const String& aggregate_method,
Size top_n,
bool include_all,
const std::map<String, String>& accession_to_leader);
/**
@brief Perform iBAQ normalization on protein abundances.
@param[in] proteins Protein identification information containing sequences
*/
void performIbaqNormalization_(const ProteinIdentification& proteins);
/**
@brief Get the "canonical" protein accession from the list of protein accessions of a peptide.
@param[in] pep_accessions Protein accessions of a peptide
@param[in] accession_to_leader Captures information about indistinguishable proteins (maps accession to accession of group leader)
If there is no information about indistinguishable proteins (from protXML) available, a canonical accession exists only for proteotypic peptides - it's the single accession for the respective peptide.
Otherwise, a peptide has a canonical accession if it maps only to proteins of one indistinguishable group. In this case, the canonical accession is that of the group leader.
If there is no canonical accession, the empty string is returned.
*/
String getAccession_(const std::set<String>& pep_accessions,
const std::map<String, String>& accession_to_leader) const;
/**
@brief Count the number of identifications (best hits only) of each peptide sequence.
The peptide hits in @p peptides are sorted by score in the process.
*/
void countPeptides_(PeptideIdentificationList& peptides);
/**
@brief Map (filename, channel) to sample using ExperimentalDesign.
@param[in] filename The base filename (without path/extension)
@param[in] channel_or_label The channel/label identifier
@param[in] ed The experimental design containing the mapping information
@return The sample ID corresponding to the filename and channel
*/
size_t getSampleIDFromFilenameAndChannel_(const String& filename,
UInt channel_or_label,
const ExperimentalDesign& ed) const;
/// Clear all data when parameters are set
void updateMembers_() override;
}; // class
} // namespace
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/QUANTITATION/IsobaricQuantifierStatistics.h | .h | 2,018 | 52 | // 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/CONCEPT/Types.h>
#include <map>
namespace OpenMS
{
class String;
/**
@brief Statistics for quantitation performance and comparison of NNLS vs. naive method (aka matrix inversion)
*/
class OPENMS_DLLAPI IsobaricQuantifierStatistics
{
public:
/**
@brief Create stats object.
*/
IsobaricQuantifierStatistics();
/**
@brief Reset statistics object.
*/
void reset();
Size channel_count; ///< 4plex, 6plex, or 8 plex?!
Size iso_number_ms2_negative; ///< number of MS2 spectra where one or more channels had negative solution
Size iso_number_reporter_negative; ///< number of channels where naive solution was negative
Size iso_number_reporter_different; ///< number of channels >0 where naive solution was different; happens when naive solution is negative in other channels
double iso_solution_different_intensity; ///< absolute intensity difference between both solutions (for channels > 0)
double iso_total_intensity_negative; ///< only for spectra where naive solution is negative
Size number_ms2_total; ///< total number of MS2 spectra
Size number_ms2_empty; ///< number of empty MS2 (no reporters at all)
std::map<String, Size> empty_channels; ///< Channel_ID -> Missing; indicating the number of empty channels from all MS2 scans, i.e., numbers are between number_ms2_empty and number_ms2_total
/// Copy c'tor
IsobaricQuantifierStatistics(const IsobaricQuantifierStatistics& other);
/// Assignment operator
IsobaricQuantifierStatistics& operator=(const IsobaricQuantifierStatistics& rhs);
};
} // namespace
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/QUANTITATION/IsobaricNormalizer.h | .h | 3,747 | 100 | // 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/CONCEPT/Types.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/KERNEL/Peak2D.h>
#include <OpenMS/KERNEL/ConsensusFeature.h>
#include <OpenMS/ANALYSIS/QUANTITATION/IsobaricQuantifierStatistics.h>
#include <map>
namespace OpenMS
{
class IsobaricQuantitationMethod;
class ConsensusMap;
/**
@brief Performs median normalization on the extracted ratios of isobaric labeling experiment.
*/
class OPENMS_DLLAPI IsobaricNormalizer
{
public:
/// Default c'tor
explicit IsobaricNormalizer(const IsobaricQuantitationMethod* const quant_method);
/// Copy c'tor
IsobaricNormalizer(const IsobaricNormalizer& other);
/// Assignment operator
IsobaricNormalizer& operator=(const IsobaricNormalizer& rhs);
/**
@brief Normalizes the intensity ratios in the given input map (using median).
@param[in] consensus_map The map to normalize.
*/
void normalize(ConsensusMap& consensus_map);
private:
/// The selected quantitation method that will be used for the normalization.
const IsobaricQuantitationMethod* quant_meth_;
/// The name of the reference channel as given in the IsobaricChannelInformation.
String reference_channel_name_;
/**
@brief Given a ConsensusFeature the method will return an iterator pointing to the consensus element representing the reference channel.
@param[in] cf The ConsensusFeature for which the reference element should be found.
@param[in] consensus_map The ConsensusMap in which the reference element should be found.
@return An iterator pointing to the consensus element of the reference channel. ConsensusFeature::end() if the reference channel is not contained.
*/
ConsensusFeature::HandleSetType::iterator findReferenceChannel_(ConsensusFeature& cf, const ConsensusMap& consensus_map) const;
/**
@brief Constructs a mapping from file description to the index in the corresponding ratio/intensity vectors.
@param[in] consensus_map The consensus map for which the mapping should be build.
*/
void buildVectorIndex_(const ConsensusMap& consensus_map);
/**
@brief Collects ratios and intensities for a given ConsensusFeature.
@param[in] cf The consensus feature to evaluate.
@param[in] ref_intensity The intensity of the reference channel.
*/
void collectRatios_(const ConsensusFeature& cf,
const Peak2D::IntensityType& ref_intensity);
/**
@brief Computes the normalization factors from the given peptide ratios.
@param[in] normalization_factors The normalization factors to compute.
*/
void computeNormalizationFactors_(std::vector<Peak2D::IntensityType>& normalization_factors);
/// The mapping between map indices and the corresponding indices in the peptide ratio/intensity vectors.
std::map<Size, Size> map_to_vec_index_;
/// The index of the reference channel in the peptide ratio/intensity vectors.
Size ref_map_id_;
/// Collection containing the collected peptide ratios for the individual channels.
std::vector<std::vector<Peak2D::IntensityType> > peptide_ratios_;
/// Collection containing the collected peptide intensities for the individual channels.
std::vector<std::vector<Peak2D::IntensityType> > peptide_intensities_;
};
} // namespace
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/QUANTITATION/IsobaricQuantitationMethod.h | .h | 3,861 | 116 | // 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/DefaultParamHandler.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
#include <OpenMS/KERNEL/Peak2D.h>
#include <utility>
#include <vector>
namespace OpenMS
{
// Forward declarations
template <typename Value>
class Matrix;
/**
@brief Abstract base class describing an isobaric quantitation method in terms of the used channels and an isotope correction matrix.
*/
class OPENMS_DLLAPI IsobaricQuantitationMethod :
public DefaultParamHandler
{
public:
/**
@brief Summary of an isobaric quantitation channel.
*/
struct IsobaricChannelInformation
{
/// The name of the channel.
String name;
/// The id of the channel.
Int id;
/// Optional description of the channel.
String description;
/// The expected centroid position of the channel peak in m/z.
Peak2D::CoordinateType center;
/// Ids of the affected channels. Must contain 4 or 8 entries, depending on the number of columns in the Thermo data sheet (with or without subchannels). Order has to match the ones from the correction matrix parameter.
std::vector<Int> affected_channels;
/// C'tor
IsobaricChannelInformation(String local_name,
const Int local_id,
String local_description,
const Peak2D::CoordinateType& local_center,
const std::vector<Int>& affected_channels) :
name(std::move(local_name)),
id(local_id),
description(std::move(local_description)),
center(local_center),
affected_channels(affected_channels)
{
}
};
/// @brief c'tor setting the name for the underlying param handler
IsobaricQuantitationMethod();
/// @brief d'tor
~IsobaricQuantitationMethod() override;
typedef std::vector<IsobaricChannelInformation> IsobaricChannelList;
/**
@brief Returns a unique name for the quantitation method.
@return The unique name or identifier of the quantitation method.
*/
virtual const String& getMethodName() const = 0;
/**
@brief Returns information on the different channels used by the quantitation method.
@return A std::vector containing the channel information for this quantitation method.
*/
virtual const IsobaricChannelList& getChannelInformation() const = 0;
/**
@brief Gives the number of channels available for this quantitation method.
@return The number of channels available for this quantitation method.
*/
virtual Size getNumberOfChannels() const = 0;
/**
@brief Returns an isotope correction matrix suitable for the given quantitation method.
*/
virtual Matrix<double> getIsotopeCorrectionMatrix() const = 0;
/**
@brief Returns the index of the reference channel in the IsobaricChannelList (see IsobaricQuantitationMethod::getChannelInformation()).
*/
virtual Size getReferenceChannel() const = 0;
protected:
/**
@brief Helper function to convert a string list containing an isotope correction matrix into a Matrix<double>.
@param[in] stringlist The StringList to convert.
@return An isotope correction matrix as Matrix<double>.
*/
Matrix<double> stringListToIsotopeCorrectionMatrix_(const std::vector<String>& stringlist) const;
};
} // namespace
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/QUANTITATION/DDAWorkflowCommons.h | .h | 6,533 | 123 | // Copyright (c) 2002-present, The OpenMS Team -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Timo Sachsenberg $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/DATASTRUCTURES/StringListUtils.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/FEATUREFINDER/MassTraceDetection.h>
#include <OpenMS/PROCESSING/FILTERING/ThresholdMower.h>
#include <OpenMS/PROCESSING/CALIBRATION/InternalCalibration.h>
#include <OpenMS/PROCESSING/CALIBRATION/MZTrafoModel.h>
#include <OpenMS/MATH/StatisticFunctions.h>
#include <OpenMS/FEATUREFINDER/FeatureFinderMultiplexAlgorithm.h>
#include <map>
#include <vector>
namespace OpenMS
{
/**
@brief Common functions for DDA workflows
@ingroup Analysis_ID
*/
class OPENMS_DLLAPI DDAWorkflowCommons
{
public:
/* @brief create Map between mzML file and corresponding id file
* Checks implemented:
* - Check if the number of spectra and id files match.
* - If spectra and id files share common base names (without extension)
* but appear in different order, throw an error.
*
* @param[in] in <StringList> List of mzML file paths.
* @param[in] in_ids <StringList> List of identification file paths.
* @return <std::map<String, String>> A map where keys are mzML file paths and values are corresponding id file paths.
* @throws Exception::InvalidParameter if the number of mzML files and identification files don't match
* @throws Exception::MissingInformation if files share common base names but appear in different order
* @note This mapping is crucial for linking raw data with identification results in DDA workflows.
*/
static std::map<String, String> mapMzML2Ids(StringList & in, StringList & in_ids);
/**
* @brief Small helper to get the mapping from id files to mzML files
*
* Basically just reverses the mapMzML2Ids function.
* Potential improvement: Could be combined into a single function exposed to the user.
*
* @param[in] m2i <const std::map<String, String>&> The mzML to id file mapping generated by mapMzML2Ids.
* @return <std::map<String, String>> A map where keys are id file paths and values are corresponding mzML file paths.
*/
static std::map<String, String> mapId2MzMLs(const std::map<String, String>& m2i);
/**
* Estimates the median chromatographic full width at half maximum (FWHM) for a given MSExperiment.
*
* @param[in] ms_centroided The centroided MSExperiment for which to estimate the FWHM.
* @return The estimated median chromatographic FWHM in retention time units.
* @note FWHM is a measure of peak width and is crucial for chromatographic peak detection and feature finding.
* The estimation is based on the top 1000 intensity mass traces to focus on prominent chromatographic peaks.
*/
static double estimateMedianChromatographicFWHM(MSExperiment & ms_centroided);
/**
* @brief Recalibrates the masses of the MSExperiment using peptide identifications.
*
* This function recalibrates the masses of the MSExperiment by applying a mass recalibration
* based on the theoretical masses from identification data.
*
* @param[in,out] ms_centroided <MSExperiment&> The MSExperiment object containing the centroided spectra, which will be recalibrated in place.
* @param[in] peptide_ids <PeptideIdentificationList&> The vector of PeptideIdentification objects containing the peptide identifications.
* @param[in] id_file_abs_path The absolute path of the identification file.
*
* @note Mass recalibration is essential to improve mass accuracy, which is critical for correct peptide identification and quantification.
*/
static void recalibrateMS1(MSExperiment & ms_centroided,
PeptideIdentificationList& peptide_ids,
const String & id_file_abs_path = ""
);
/**
* @brief Extracts seeding features from centroided MS data (e.g., for untarged extraction).
*
* MS1 spectra are subjected to a threshold filter to removelow-intensity peaks,
* and then uses the FeatureFinderMultiplex algorithm to identify potential seeding features.
* The function also takes into account the median full width at half maximum (FWHM) of the peaks
* to adjust the FeatureFinderMultiplex parameters for better seed detection.
*
* @param[in] ms_centroided <const MSExperiment&> The centroided MSExperiment object. Only MS1 level
* spectra are considered for seed feature calculation.
* @param[in] intensity_threshold Intensity threshold below which peaks are discarded.
* @param[out] seeds The FeatureMap object where the identified seeding features will be stored.
* @param[in] median_fwhm The median FWHM of the peaks, used to adjust the FeatureFinderMultiplex parameters for
* seed detection.
* @param[in] charge_min Minimum charge state to consider for feature seeds (default: 2).
* @param[in] charge_max Maximum charge state to consider for feature seeds (default: 5).
*
* @note The function employs a ThresholdMower filter with hardcoded parameters (m/z tolerance: 20 ppm, intensity cutoff: intensity_threshold, below cutoff: remove)
* and the FeatureFinderMultiplex algorithm with parameters optimized for seed feature detection in DDA workflows.
* These parameters may be refined or exposed as function arguments in future implementations for more flexibility.
*/
static void calculateSeeds(
const MSExperiment & ms_centroided,
const double intensity_threshold,
FeatureMap & seeds,
double median_fwhm,
Size charge_min = 2,
Size charge_max = 5
);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/MRM/ReactionMonitoringTransition.h | .h | 15,308 | 462 | // 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/ANALYSIS/TARGETED/TargetedExperimentHelper.h>
#include <OpenMS/CONCEPT/HashUtils.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/METADATA/CVTermList.h>
#include <functional>
#include <vector>
#include <bitset>
namespace OpenMS
{
/**
@brief This class stores a SRM/MRM transition
This class is capable of representing a \<Transition\> tag in a TraML
document completely and contains all associated information.
The default values for precursor m/z is 0.0 which indicates that it is
uninitialized.
*/
class OPENMS_DLLAPI ReactionMonitoringTransition :
public CVTermList
{
public:
typedef TargetedExperimentHelper::Configuration Configuration;
typedef TargetedExperimentHelper::RetentionTime RetentionTime;
typedef TargetedExperimentHelper::TraMLProduct Product;
typedef TargetedExperimentHelper::Prediction Prediction;
enum DecoyTransitionType
{
UNKNOWN, ///< Unknown type
TARGET, ///< Target transition
DECOY ///< Decoy transition
};
/** @name Constructors and destructors
*/
//@{
/// default constructor
ReactionMonitoringTransition();
/// copy constructor
ReactionMonitoringTransition(const ReactionMonitoringTransition & rhs);
/// Move constructor
ReactionMonitoringTransition(ReactionMonitoringTransition&&) noexcept;
/// destructor
~ReactionMonitoringTransition() override;
//@}
/// assignment operator
ReactionMonitoringTransition & operator=(const ReactionMonitoringTransition & rhs);
/// move assignment operator
ReactionMonitoringTransition & operator=(ReactionMonitoringTransition && rhs) noexcept ;
/** @name Accessors
*/
//@{
void setName(const String & name);
const String & getName() const;
void setNativeID(const String & name);
const String & getNativeID() 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);
/// get the precursor mz (Q1 value)
double getPrecursorMZ() const;
/// Returns true if precursor CV Terms exist (means it is safe to call getPrecursorCVTermList)
bool hasPrecursorCVTerms() const;
void setPrecursorCVTermList(const CVTermList & list);
void addPrecursorCVTerm(const CVTerm & cv_term);
/** @brief Obtain the list of CV Terms for the precursor
*
* @note You first need to check whether they exist using hasPrecursorCVTerms()
*/
const CVTermList & getPrecursorCVTermList() const;
void setProductMZ(double mz);
double getProductMZ() const;
int getProductChargeState() const;
bool isProductChargeStateSet() const;
void addProductCVTerm(const CVTerm & cv_term);
const std::vector<Product> & getIntermediateProducts() const;
void addIntermediateProduct(const Product& product);
void setIntermediateProducts(const std::vector<Product> & products);
void setProduct(Product product);
const Product & getProduct() const;
/// Returns true if a Prediction object exists (means it is safe to call getPrediction)
bool hasPrediction() const;
void setPrediction(const Prediction & prediction);
void addPredictionTerm(const CVTerm & prediction);
/** @brief Obtain the Prediction object
*
* @note You first need to check whether the object is accessible using hasPrediction()
*/
const Prediction & getPrediction() const;
/// Returns the type of transition (target or decoy)
DecoyTransitionType getDecoyTransitionType() const;
/// Sets the type of transition (target or decoy)
void setDecoyTransitionType(const DecoyTransitionType & d);
/// Returns the library intensity (ion count or normalized ion count from a spectral library)
double getLibraryIntensity() const;
/// Sets the library intensity (ion count or normalized ion count from a spectral library)
void setLibraryIntensity(double intensity);
/** @name Retention time
*
* @brief Retention time set on transition level
*
* @note Retention time can be set on analyte level (peptide / compound
* level) or transition level -- usually the retention time set here on
* transition level is ignored, therefore only use this if you have a good
* reason.
*
*/
//@{
/** @brief Sets the retention time on transition level
*
* Stores a retention time on the level of an individual transition
*
* @note This is very likely not what you want, to set the retention time
* of an analyte use TargetedExperimentHelper::PeptideCompound::getRetentionTime()
*/
void setRetentionTime(RetentionTime rt);
/** @brief Gets the retention time on transition level
*
* Stores a retention time on the level of an individual transition
*
* @note This is very likely not what you want, to set the retention time
* of an analyte use TargetedExperimentHelper::PeptideCompound::getRetentionTime()
*/
const RetentionTime & getRetentionTime() const;
//@}
/** @name Detecting transitions
*
* @brief Transitions used for detection of analyte
*
* Detecting transitions represent the set of transitions of an assay that
* should be used to enable candidate peak group detection. Ideally they
* were observed and validated in previous experiments and have an
* associated library intensity.
*
* For an overview, see Schubert OT et al., Building high-quality assay libraries for
* targeted analysis of SWATH MS data., Nat Protoc. 2015 Mar;10(3):426-41.
* doi: 10.1038/nprot.2015.015. Epub 2015 Feb 12. PMID: 25675208
*
*/
//@{
bool isDetectingTransition() const;
void setDetectingTransition(bool val);
//@}
/** @name Identifying transitions
*
* @brief Transitions used for differentiation between different analyte isomers (peptidoforms).
*
* Identifying transitions represent the set of transitions of an assay
* that should be used for the independent identification of a candidate
* peak group (often in relation to another analyte isomer or peptidoform).
* These transitions could for example be site-determining transitions in a
* phospho-proteomic DIA experiment. These transitions will be scored independently
* of the detecting transitions.
*
*/
//@{
bool isIdentifyingTransition() const;
void setIdentifyingTransition(bool val);
//@}
/** @name Quantifying transitions
*
* @brief Transitions used for quantification
*
* Quantifying transitions represent the set of transitions of an assay
* that should be used for the quantification of the peptide. This includes
* exclusion of e.g. interfered transitions (example: light/heavy peptide
* pairs isolated in the same swath window), that should not be used for
* quantification of the peptide.
*
*/
//@{
bool isQuantifyingTransition() const;
void setQuantifyingTransition(bool val);
//@}
//@}
/** @name Predicates
*/
//@{
/// equality operator
bool operator==(const ReactionMonitoringTransition & rhs) const;
/// inequality operator
bool operator!=(const ReactionMonitoringTransition & rhs) const;
//@}
/** @name Comparator classes.
These classes implement binary predicates that can be used
to compare two transitions with respect to their product ions.
*/
//@{
/// Comparator by Product ion MZ
struct ProductMZLess
{
bool operator()(ReactionMonitoringTransition const & left, ReactionMonitoringTransition const & right) const;
};
//@}
/** @name Comparator classes.
These classes implement binary predicates that can be used
to compare two transitions with respect to their name.
*/
//@{
/// Comparator by name
struct NameLess
{
bool operator()(ReactionMonitoringTransition const & left, ReactionMonitoringTransition const & right) const;
};
//@}
protected:
void updateMembers_();
/** @name Attributes
*/
//@{
String name_; ///< id, required attribute
// attributes to a peptide / compound (optional)
String peptide_ref_; ///< Reference to a specific peptide
String compound_ref_; ///< Reference to a specific compound
/// Intensity of the product (q3) ion (stored in CV Term 1001226 inside the \<Transition\> tag)
double library_intensity_;
/// specific properties of a transition (e.g. specific CV terms)
DecoyTransitionType decoy_type_;
//@}
/** @name Subelements
*/
//@{
// Precursor
// Product
// IntermediateProduct
// RetentionTime
// Prediction
// cvparam / userParam
/// A transition has exactly one precursor and it must supply the CV Term 1000827 (isolation window target m/z)
double precursor_mz_;
/// (Other) CV Terms of the Precursor (Q1) of the transition or target
CVTermList* precursor_cv_terms_;
/// Product (Q3) of the transition
Product product_;
/// Intermediate product ion information of the transition when using MS3 or above (optional)
std::vector<Product> intermediate_products_;
/// Information about predicted or calibrated retention time (optional)
RetentionTime rts;
/// Information about a prediction for a suitable transition using some software (optional)
Prediction* prediction_;
/// A set of flags to store information about the transition at hand
/// (currently: detecting, identifying and quantifying)
std::bitset<3> transition_flags_;
//@}
};
} // namespace OpenMS
namespace std
{
/// Hash function for ReactionMonitoringTransition
template<>
struct hash<OpenMS::ReactionMonitoringTransition>
{
std::size_t operator()(const OpenMS::ReactionMonitoringTransition& rmt) const noexcept
{
std::size_t seed = 0;
// Hash base class CVTermList - use the CV terms map
for (const auto& [accession, terms] : rmt.getCVTerms())
{
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(accession));
OpenMS::hash_combine(seed, OpenMS::hash_int(terms.size()));
for (const auto& term : terms)
{
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(term.getAccession()));
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(term.getName()));
}
}
// Hash name_
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(rmt.getName()));
// Hash peptide_ref_
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(rmt.getPeptideRef()));
// Hash compound_ref_
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(rmt.getCompoundRef()));
// Hash precursor_mz_
OpenMS::hash_combine(seed, OpenMS::hash_float(rmt.getPrecursorMZ()));
// Hash precursor_cv_terms_ (pointer - check if present)
if (rmt.hasPrecursorCVTerms())
{
const auto& precursorTerms = rmt.getPrecursorCVTermList();
for (const auto& [accession, terms] : precursorTerms.getCVTerms())
{
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(accession));
OpenMS::hash_combine(seed, OpenMS::hash_int(terms.size()));
}
}
else
{
OpenMS::hash_combine(seed, OpenMS::hash_int(0));
}
// Hash product_ - use getMZ and charge state
const auto& product = rmt.getProduct();
OpenMS::hash_combine(seed, OpenMS::hash_float(product.getMZ()));
if (product.hasCharge())
{
OpenMS::hash_combine(seed, OpenMS::hash_int(product.getChargeState()));
}
// Hash product CV terms
for (const auto& [accession, terms] : product.getCVTerms())
{
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(accession));
OpenMS::hash_combine(seed, OpenMS::hash_int(terms.size()));
}
// Hash configuration list size and interpretation list size
OpenMS::hash_combine(seed, OpenMS::hash_int(product.getConfigurationList().size()));
OpenMS::hash_combine(seed, OpenMS::hash_int(product.getInterpretationList().size()));
// Hash intermediate_products_ - use size and individual product m/z values
const auto& intermediates = rmt.getIntermediateProducts();
OpenMS::hash_combine(seed, OpenMS::hash_int(intermediates.size()));
for (const auto& ip : intermediates)
{
OpenMS::hash_combine(seed, OpenMS::hash_float(ip.getMZ()));
if (ip.hasCharge())
{
OpenMS::hash_combine(seed, OpenMS::hash_int(ip.getChargeState()));
}
}
// Hash rts (RetentionTime)
const auto& rt = rmt.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()));
}
// Hash RetentionTime CV terms
for (const auto& [accession, terms] : rt.getCVTerms())
{
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(accession));
OpenMS::hash_combine(seed, OpenMS::hash_int(terms.size()));
}
// Hash prediction_ (pointer - check if present)
if (rmt.hasPrediction())
{
const auto& pred = rmt.getPrediction();
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(pred.software_ref));
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(pred.contact_ref));
for (const auto& [accession, terms] : pred.getCVTerms())
{
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(accession));
OpenMS::hash_combine(seed, OpenMS::hash_int(terms.size()));
}
}
else
{
OpenMS::hash_combine(seed, OpenMS::hash_int(0));
}
// Hash library_intensity_
OpenMS::hash_combine(seed, OpenMS::hash_float(rmt.getLibraryIntensity()));
// Hash decoy_type_
OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(rmt.getDecoyTransitionType())));
// Hash transition_flags_ (bitset<3>) - use the boolean accessors
OpenMS::hash_combine(seed, OpenMS::hash_int(rmt.isDetectingTransition() ? 1 : 0));
OpenMS::hash_combine(seed, OpenMS::hash_int(rmt.isIdentifyingTransition() ? 1 : 0));
OpenMS::hash_combine(seed, OpenMS::hash_int(rmt.isQuantifyingTransition() ? 1 : 0));
return seed;
}
};
} // namespace std
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/SEQUENCE/NeedlemanWunsch.h | .h | 2,339 | 74 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Nora Wild $
// $Authors: Nora Wild $
// --------------------------------------------------------------------------
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/OpenMSConfig.h>
#include <vector>
namespace OpenMS
{
/**
@brief This class contains functions that are used to calculate the global alignment score of two amino acid sequences.
This class uses the Needleman-Wunsch algorithm. For match and mismatch it uses a similarity scoring matrix.
*/
class OPENMS_DLLAPI NeedlemanWunsch
{
public:
/// contains the valid matrices and the number of them
enum class ScoringMatrix
{
identity,
PAM30MS,
SIZE_OF_SCORINGMATRIX
};
/// Constructor that sets the scoring matrix and the gap penalty
NeedlemanWunsch(ScoringMatrix matrix, int penalty);
/// Default constructor (scoring matrix PAM30MS and penalty 5)
NeedlemanWunsch() = default;
/// Default destructor
~NeedlemanWunsch()=default;
/// Names of valid matrices
static const std::vector<std::string> NamesOfScoringMatrices;
/**
@brief Calculates the similarity score of the global alignment of two amino acid sequences using Needleman-Wunsch-
Algorithm.
*/
int align(const String& seq1, const String& seq2);
/**
@brief sets the scoring matrix. Takes either a string or the enum ScoringMatrix.
@exception Exception: illegal argument is thrown if the input is not a member of the valid matrices.
*/
void setMatrix(const ScoringMatrix& matrix);
void setMatrix(const std::string& matrix);
/// sets the cost of gaps
void setPenalty(const int penalty);
/// returns the scoring matrix
ScoringMatrix getMatrix() const;
/// returns the gap penalty
int getPenalty() const;
private:
int gap_penalty_ = 5; ///< penalty for alignment score calculation
ScoringMatrix my_matrix_ = ScoringMatrix::PAM30MS; ///< scoring matrix for the alignment score calculation
std::vector<int> first_row_{}; ///< alignment score calculation with two rows
std::vector<int> second_row_{};
};
} | Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/XLMS/XQuestScores.h | .h | 8,268 | 130 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Eugen Netz $
// $Authors: Eugen Netz $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/MSSpectrum.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/CONCEPT/Types.h>
#include <OpenMS/CHEMISTRY/SimpleTSGXLMS.h>
#include <vector>
namespace OpenMS
{
/**
* @brief An implementation of the scores for cross-link identification from the xQuest algorithm (O. Rinner et al., 2008, "Identification of cross-linked peptides from large sequence databases")
*/
class OPENMS_DLLAPI XQuestScores
{
public:
/**
@brief compute a simple and fast to compute pre-score for a cross-link spectrum match
@param[in] matched_alpha number of experimental peaks matched to theoretical linear ions from the alpha peptide
@param[in] ions_alpha number of theoretical ions from the alpha peptide
@param[in] matched_beta number of experimental peaks matched to theoretical linear ions from the beta peptide
@param[in] ions_beta number of theoretical ions from the beta peptide
*/
static float preScore(Size matched_alpha, Size ions_alpha, Size matched_beta, Size ions_beta);
/**
@brief compute a simple and fast to compute pre-score for a mono-link spectrum match
@param[in] matched_alpha number of experimental peaks matched to theoretical linear ions from the alpha peptide
@param[in] ions_alpha number of theoretical ions from the alpha peptide
*/
static float preScore(Size matched_alpha, Size ions_alpha);
/**
@brief compute the match-odds score, a score based on the probability of getting the given number of matched peaks by chance
@param[in] theoretical_spec theoretical spectrum, sorted by position
@param[in] matched_size alignment between the theoretical and the experimental spectra
@param[in] fragment_mass_tolerance fragment mass tolerance of the alignment
@param[in] fragment_mass_tolerance_unit_ppm fragment mass tolerance unit of the alignment, true = ppm, false = Da
@param[in] is_xlink_spectrum type of cross-link, true = cross-link, false = mono-link
@param[in] n_charges number of considered charges in the theoretical spectrum
*/
static double matchOddsScore(const PeakSpectrum& theoretical_spec, const Size matched_size, double fragment_mass_tolerance, bool fragment_mass_tolerance_unit_ppm, bool is_xlink_spectrum = false, Size n_charges = 1);
static double matchOddsScoreSimpleSpec(const std::vector< SimpleTSGXLMS::SimplePeak >& theoretical_spec, const Size matched_size, double fragment_mass_tolerance, bool fragment_mass_tolerance_unit_ppm, bool is_xlink_spectrum = false, Size n_charges = 1);
/**
@brief compute the logOccupancyProb score, similar to the match_odds, a score based on the probability of getting the given number of matched peaks by chance
@param[in] theoretical_spec theoretical spectrum, sorted by position
@param[in] matched_size number of matched peaks between experimental and theoretical spectra
@param[in] fragment_mass_tolerance the tolerance of the alignment
@param[in] fragment_mass_tolerance_unit_ppm the tolerance unit of the alignment, true = ppm, false = Da
*/
static double logOccupancyProb(const PeakSpectrum& theoretical_spec, const Size matched_size, double fragment_mass_tolerance, bool fragment_mass_tolerance_unit_ppm);
/**
* @brief compute the weighted total ion current score for a cross-link. Reimplementation from xQuest.
* @param[in] alpha_size sequence length of alpha peptide
* @param[in] beta_size sequence length of beta peptide
* @param[in] intsum_alpha intensity sum of matched peaks from alpha peptide
* @param[in] intsum_beta intensity sum of matched peaks from beta peptide
* @param[in] total_current sum of peak intensities of the experimental spectrum
* @param[in] type_is_cross_link type of cross-link, true = cross-link, false = mono-link
* @return true = cross-link, false = mono-link. in case of a mono-link, beta_size and intsum_beta should be 0
*/
static double weightedTICScoreXQuest(Size alpha_size, Size beta_size, double intsum_alpha, double intsum_beta, double total_current, bool type_is_cross_link);
/**
* @brief compute the weighted total ion current score for a cross-link. Scaling changed from original xQuest.
* @param[in] alpha_size sequence length of alpha peptide
* @param[in] beta_size sequence length of beta peptide
* @param[in] intsum_alpha intensity sum of matched peaks from alpha peptide
* @param[in] intsum_beta intensity sum of matched peaks from beta peptide
* @param[in] total_current Sum of peak intensities of the experimental spectrum
* @param[in] type_is_cross_link Type of cross-link, true = cross-link, false = mono-link
* @return true = cross-link, false = mono-link. in case of a mono-link, beta_size and intsum_beta should be 0
*/
static double weightedTICScore(Size alpha_size, Size beta_size, double intsum_alpha, double intsum_beta, double total_current, bool type_is_cross_link);
/**
* @brief computes sum of peak intensities of matched peaks for either the alpha or the beta peptide
* @param[in] matched_spec_linear alignment between linear alpha or beta ions and linear experimental peaks
* @param[in] matched_spec_xlinks alignment between xlink alpha or beta ions and xlink experimental peaks
* @param[in] spectrum_linear_peaks experimental linear ion spectrum
* @param[in] spectrum_xlink_peaks experimental xlink spectrum
*/
static double matchedCurrentChain(const std::vector< std::pair< Size, Size > >& matched_spec_linear, const std::vector< std::pair< Size, Size > >& matched_spec_xlinks, const PeakSpectrum& spectrum_linear_peaks, const PeakSpectrum& spectrum_xlink_peaks);
/**
* @brief computes sum of peak intensities of all matched peaks
* @param[in] matched_spec_linear_alpha alignment between linear alpha ions and linear experimental peaks
* @param[in] matched_spec_linear_beta alignment between linear beta ions and linear experimental peaks
* @param[in] matched_spec_xlinks_alpha alignment between xlink alpha ions and xlink experimental peaks
* @param[in] matched_spec_xlinks_beta alignment between xlink beta ions and xlink experimental peaks
* @param[in] spectrum_linear_peaks experimental linear ion spectrum
* @param[in] spectrum_xlink_peaks experimental xlink spectrum
*/
static double totalMatchedCurrent(const std::vector< std::pair< Size, Size > >& matched_spec_linear_alpha, const std::vector< std::pair< Size, Size > >& matched_spec_linear_beta, const std::vector< std::pair< Size, Size > >& matched_spec_xlinks_alpha, const std::vector< std::pair< Size, Size > >& matched_spec_xlinks_beta, const PeakSpectrum& spectrum_linear_peaks, const PeakSpectrum& spectrum_xlink_peaks);
/**
* @brief computes a crude cross-correlation between two spectra. Crude, because it uses a static binsize based on a tolerance in Da and it uses equal intensities for all peaks
* @param[in] spec1 first spectrum
* @param[in] spec2 second spectrum
* @param[in] maxshift Number of bins, that should be considered for shifting the second spectrum. the second spectrum is shifted from -maxshift to +maxshift of tolerance bins and a correlation is computed for each position.
* @param[in] tolerance or binsize in Da
*/
static std::vector< double > xCorrelation(const PeakSpectrum & spec1, const PeakSpectrum & spec2, Int maxshift, double tolerance);
/**
* @brief computes a crude dot product between two spectra. Crude, because it uses a static binsize based on a tolerance in Da and it uses equal intensities for all peaks
* @param[in] spec1 first spectrum
* @param[in] spec2 second spectrum
* @param[in] tolerance tolerance or binsize in Da
*/
static double xCorrelationPrescore(const PeakSpectrum & spec1, const PeakSpectrum & spec2, double tolerance);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/XLMS/OPXLSpectrumProcessingAlgorithms.h | .h | 5,614 | 94 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Eugen Netz $
// $Authors: Eugen Netz $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CONCEPT/Types.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/KERNEL/Peak1D.h>
#include <OpenMS/METADATA/DataArrays.h>
#include <OpenMS/CHEMISTRY/SimpleTSGXLMS.h>
#include <numeric>
#include <vector>
namespace OpenMS
{
class OPENMS_DLLAPI OPXLSpectrumProcessingAlgorithms
{
public:
/**
* @brief Merges two spectra into one while correctly considering metainfo in DataArrays
* @param[in,out] first_spectrum
* @param[in,out] second_spectrum
* @return A PeakSpectrum containing all peaks from both input spectra
*/
static PeakSpectrum mergeAnnotatedSpectra(PeakSpectrum & first_spectrum, PeakSpectrum & second_spectrum);
/**
* @brief Preprocesses spectra
*
* Filters out spectra with too few peaks (based on @p peptide_min_size) and those that do not fit into the precursor charge range.
* Removes zero intensity peaks and normalizes intensities from all spectra in @p exp.
* MS2 spectra are reduced in peak count using a WindowMower, if @p labeled is false.
* The number of returned spectra (MS2 only) is equal to the number of input MS2 spectra for labeled data (otherwise not necessarily).
*
* @param[in,out] exp Input data, which contains MS1 and MS2 spectra. Will be modified.
* @param[in] fragment_mass_tolerance For deisotoping (used only if @p deisotope is true)
* @param[in] fragment_mass_tolerance_unit_ppm For deisotoping (used only if @p deisotope is true)
* @param[in] peptide_min_size Minimum length of a peptide (used to filter spectra with few peaks)
* @param[in] min_precursor_charge MS2 spectra's minimal PC charge (ignored if @p labeled is true)
* @param[in] max_precursor_charge MS2 spectra's maximal PC charge (ignored if @p labeled is true)
* @param[in] deisotope Deisotope MS2 spectra?
* @param[in] labeled Is the data labeled? (i.e. keep all MS2 spectra irrespective of precursor)
* @return A PeakMap of preprocessed spectra (MS2 spectra only)
*/
static PeakMap preprocessSpectra(PeakMap& exp, double fragment_mass_tolerance, bool fragment_mass_tolerance_unit_ppm, Size peptide_min_size, Int min_precursor_charge, Int max_precursor_charge, bool deisotope, bool labeled);
/**
* @brief Computes a spectrum alignment while considering fragment charges stored in a IntegerDataArray and a cut-off for the intensity difference ratio
* @param[out] alignment The empty alignment, that will be filled by the algorithm
* @param[in] fragment_mass_tolerance The peak mass tolerance
* @param[in] fragment_mass_tolerance_unit_ppm True if the given tolerance is a ppm tolerance, false if tolerance is in Da
* @param[in] theo_spectrum The first spectrum to be aligned (preferably the theoretical one)
* @param[in] exp_spectrum the second spectrum to be aligned (preferably the experimental one)
* @param[in] theo_charges IntegerDataArray with charges for the theo_spectrum
* @param[in] exp_charges IntegerDataArray with charges for the exp_spectrum
* @param[out] ppm_error_array empty FloatDataArray to be filled with per peak ppm errors
* @param[in] intensity_cutoff Peaks will only be aligned if intensity1 / intensity2 > intensity_cutoff, with intensity1 being the lower of the two compared peaks and intensity2 the higher one. Set to 0 to ignore intensity differences.
*/
static void getSpectrumAlignmentFastCharge(
std::vector<std::pair<Size, Size> > & alignment, double fragment_mass_tolerance,
bool fragment_mass_tolerance_unit_ppm,
const PeakSpectrum& theo_spectrum,
const PeakSpectrum& exp_spectrum,
const DataArrays::IntegerDataArray& theo_charges,
const DataArrays::IntegerDataArray& exp_charges,
DataArrays::FloatDataArray& ppm_error_array,
double intensity_cutoff = 0.0);
/**
* @brief Computes a spectrum alignment while considering fragment charges. Uses TSGXLMS::SimplePeak for the theoretical spectrum and its charges. Does not consider intensities.
* @param[out] alignment The empty alignment, that will be filled by the algorithm
* @param[in] fragment_mass_tolerance The peak mass tolerance
* @param[in] fragment_mass_tolerance_unit_ppm True if the given tolerance is a ppm tolerance, false if tolerance is in Da
* @param[in] theo_spectrum The first spectrum to be aligned (preferably the theoretical one)
* @param[in] exp_spectrum the second spectrum to be aligned (preferably the experimental one)
* @param[in] exp_charges IntegerDataArray with charges for the exp_spectrum
*/
static void getSpectrumAlignmentSimple(
std::vector<std::pair<Size, Size> > & alignment,
double fragment_mass_tolerance,
bool fragment_mass_tolerance_unit_ppm,
const std::vector< SimpleTSGXLMS::SimplePeak >& theo_spectrum,
const PeakSpectrum& exp_spectrum,
const DataArrays::IntegerDataArray& exp_charges);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/XLMS/OPXLHelper.h | .h | 19,430 | 291 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Eugen Netz $
// $Authors: Eugen Netz $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/ANALYSIS/XLMS/OPXLDataStructs.h>
#include <OpenMS/CHEMISTRY/ResidueModification.h>
#include <OpenMS/FORMAT/FASTAFile.h>
#include <OpenMS/CHEMISTRY/EnzymaticDigestion.h>
#include <OpenMS/CHEMISTRY/ModifiedPeptideGenerator.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <numeric>
namespace OpenMS
{
/**
* @brief The OPXLHelper class contains functions needed by OpenPepXL to reduce duplicated code
*/
class OPENMS_DLLAPI OPXLHelper
{
public:
/**
* @brief A comparator for PeptideIdentifications that compares the scores in the first PeptideHit
*
*/
struct PeptideIDScoreComparator
{
bool operator() (const PeptideIdentification& a, const PeptideIdentification& b) const
{
if (!a.getHits().empty() && !b.getHits().empty())
{
return a.getHits()[0].getScore() < b.getHits()[0].getScore();
}
else
{
return false;
}
}
bool operator() (const PeptideIdentification& a, const double& b) const
{
if (!a.getHits().empty())
{
return a.getHits()[0].getScore() < b;
}
else
{
return false;
}
}
bool operator() (const double& a, const PeptideIdentification& b) const
{
if (!b.getHits().empty())
{
return a < b.getHits()[0].getScore();
}
else
{
return false;
}
}
};
/**
* @brief Enumerates precursor masses for all candidates in an XL-MS search
Assumes the list of peptides and the list of spectrum precursor masses are sorted by mass in ascending order,
and the list of mono-link masses is sorted in descending order.
* @param[in] peptides The peptides with precomputed masses from the digestDatabase function
* @param[in] cross_link_mass_light Mass of the cross-linker, only the light one if a labeled linker is used
* @param[in] cross_link_mass_mono_link A list of possible masses for the cross-link, if it is attached to a peptide on one side
* @param[in] cross_link_residue1 A list of residues, to which the first side of the linker can react
* @param[in] cross_link_residue2 A list of residues, to which the second side of the linker can react
* @param[in] spectrum_precursors A vector of all MS2 precursor masses of the searched spectra. Used to filter out candidates.
* @param[in,out] precursor_correction_positions A vector of the position of the used precursor correction
* @param[in] precursor_mass_tolerance The precursor mass tolerance
* @param[in] precursor_mass_tolerance_unit_ppm The unit of the precursor mass tolerance ("Da" or "ppm")
* @return A vector of XLPrecursors containing all possible candidate cross-links
*/
static std::vector<OPXLDataStructs::XLPrecursor> enumerateCrossLinksAndMasses(const std::vector<OPXLDataStructs::AASeqWithMass>& peptides, double cross_link_mass_light, const DoubleList& cross_link_mass_mono_link, const StringList& cross_link_residue1, const StringList& cross_link_residue2, const std::vector< double >& spectrum_precursors, std::vector< int >& precursor_correction_positions, double precursor_mass_tolerance, bool precursor_mass_tolerance_unit_ppm);
/**
* @brief Digests a database with the given EnzymaticDigestion settings and precomputes masses for all peptides
Also keeps track of the peptides at protein terminals and builds peptide candidates with all possible modification patterns
according to the parameters.
* @param[in] fasta_db The protein database
* @param[in] digestor The object containing the digestion settings, e.g. the enzyme
* @param[in] min_peptide_length The minimal peptide length for the digestion
* @param[in] cross_link_residue1 A list of residues, to which the first side of the linker can react
* @param[in] cross_link_residue2 A list of residues, to which the second side of the linker can react
* @param[in] fixed_modifications The list of fixed modifications
* @param[in] variable_modifications The list of variable modifications
* @param[in] max_variable_mods_per_peptide The maximal number of variable modifications per peptide
* @return A vector of AASeqWithMass containing the peptides, their masses and information about terminal peptides
*/
static std::vector<OPXLDataStructs::AASeqWithMass> digestDatabase(std::vector<FASTAFile::FASTAEntry> fasta_db,
const EnzymaticDigestion& digestor, Size min_peptide_length, const StringList& cross_link_residue1, const StringList& cross_link_residue2,
const ModifiedPeptideGenerator::MapToResidueType& fixed_modifications,
const ModifiedPeptideGenerator::MapToResidueType& variable_modifications,
Size max_variable_mods_per_peptide);
/**
* @brief Builds specific cross-link candidates with all possible combinations of linked positions from peptide pairs. Used to build candidates for the precursor mass window of a single MS2 spectrum.
* @param[in] candidates The XLPrecursors containing indices of two peptides
* @param[in] precursor_corrections Same size as @p candidates
* @param[in] precursor_correction_positions Same size as @p candidates; A vector of the position of the used precursor correction
* @param[in] peptide_masses The digested peptide database, that the indices in the XLPrecursors refer to
* @param[in] cross_link_residue1 A list of residues, to which the first side of the linker can react
* @param[in] cross_link_residue2 A list of residues, to which the second side of the linker can react
* @param[in] cross_link_mass mass of the cross-linker, only the light one if a labeled linker is used
* @param[in] cross_link_mass_mono_link A list of possible masses for the cross-link, if it is attached to a peptide on one side
* @param[in] spectrum_precursor_vector The precursor masses of the experimental spectrum (used to filter out certain candidates, e.g. mono- and loop-links have a different mass)
* @param[in] allowed_error_vector Allowed mass error in Da for the respective precursor in @p spectrum_precursor_vector.
* @param[in] cross_link_name The name of the cross-linker
* @return A vector of ProteinProteinCrossLink candidates containing all necessary information to generate theoretical spectra
*/
static std::vector <OPXLDataStructs::ProteinProteinCrossLink> buildCandidates(const std::vector< OPXLDataStructs::XLPrecursor > & candidates,
const std::vector< int > & precursor_corrections,
const std::vector< int > & precursor_correction_positions,
const std::vector<OPXLDataStructs::AASeqWithMass> & peptide_masses,
const StringList & cross_link_residue1,
const StringList & cross_link_residue2,
double cross_link_mass,
const DoubleList & cross_link_mass_mono_link,
const std::vector< double >& spectrum_precursor_vector,
const std::vector< double >& allowed_error_vector,
const String& cross_link_name);
/**
* @brief Fills up the given FragmentAnnotation vector with annotations from a theoretical spectrum
This function takes an alignment of a theoretical spectrum with meta information and an experimental spectrum
and builds annotations taking the MZ and intensity values from the experimental spectrum and the ion names and charges from the theoretical spectrum
to annotate matched experimental peaks.
* @param[in,out] frag_annotations The vector to fill. Does not have to be empty, as annotations from several alignments can just be added on to the same vector.
* @param[in] matching The alignment between the two spectra
* @param[in] theoretical_spectrum The theoretical spectrum with meta information
* @param[in] experiment_spectrum The experimental spectrum
*/
static void buildFragmentAnnotations(std::vector<PeptideHit::PeakAnnotation> & frag_annotations, const std::vector< std::pair< Size, Size > > & matching, const PeakSpectrum & theoretical_spectrum, const PeakSpectrum & experiment_spectrum);
/**
* @brief Builds PeptideIdentifications and PeptideHits
* @param[in,out] peptide_ids The vector of PeptideIdentifications for the whole experiment. The created PepIds will be pushed on this one.
* @param[in] top_csms_spectrum All CrossLinkSpectrumMatches from the current spectrum to be written out
* @param[in,out] all_top_csms A vector of all CrossLinkSpectrumMatches of the experiment, that is also extended in this function
* @param[in] all_top_csms_current_index The index of the current spectrum in all_top_csms (some spectra have no matches, so this is not equal to the spectrum index)
* @param[in] spectra The searched spectra as a PeakMap
* @param[in] scan_index The index of the current spectrum
* @param[in] scan_index_heavy The index of the heavy spectrum in a spectrum pair with labeled linkers
*/
static void buildPeptideIDs(PeptideIdentificationList & peptide_ids, const std::vector< OPXLDataStructs::CrossLinkSpectrumMatch > & top_csms_spectrum, std::vector< std::vector< OPXLDataStructs::CrossLinkSpectrumMatch > > & all_top_csms, Size all_top_csms_current_index, const PeakMap & spectra, Size scan_index, Size scan_index_heavy);
/**
* @brief adds MetaValues for cross-link positions to PeptideHits
* @param[in,out] peptide_ids The vector of peptide_ids containing XL-MS search results with alpha and beta PeptideHits, after mapping of peptides to proteins
*/
static void addProteinPositionMetaValues(std::vector< PeptideIdentification > & peptide_ids);
/// @overload
static void addProteinPositionMetaValues(PeptideIdentificationList & peptide_ids);
/**
* @brief adds xl_target_decoy MetaValue that combines alpha and beta target_decoy info
* @param[in,out] peptide_ids The vector of peptide_ids containing XL-MS search results with alpha and beta PeptideHits, after mapping of peptides to proteins
*/
static void addXLTargetDecoyMV(std::vector< PeptideIdentification > & peptide_ids);
/// @overload
static void addXLTargetDecoyMV(PeptideIdentificationList & peptide_ids);
/**
* @brief adds accessions_beta MetaValue to alpha peptides for TOPPView visualization and CSV table output
* @param[in,out] peptide_ids The vector of peptide_ids containing XL-MS search results with alpha and beta PeptideHits, after mapping of peptides to proteins
*/
static void addBetaAccessions(std::vector< PeptideIdentification > & peptide_ids);
/// @overload
static void addBetaAccessions(PeptideIdentificationList & peptide_ids);
/**
* @brief removes beta peptides from cross-link IDs, since all info is already contained in the alpha peptide hits
* @param[in,out] peptide_ids The vector of peptide_ids containing XL-MS search results with alpha and beta PeptideHits
*/
static void removeBetaPeptideHits(std::vector< PeptideIdentification > & peptide_ids);
/// @overload
static void removeBetaPeptideHits(PeptideIdentificationList & peptide_ids);
/**
* @brief Adds the list of features that percolator should use for OpenPepXL
* @param[in,out] prot_id Receives updated search parameters ('feature_extractor' and 'extra_features') as meta value for OpenPepXL
*/
static void addPercolatorFeatureList(ProteinIdentification& prot_id);
/**
* @brief sorts PeptideHits for each PeptideIdentification by score and adds the delta score as a MetaValue
* @param[in,out] peptide_ids The vector of peptide_ids containing XL-MS search results without beta PeptideHits
*/
static void computeDeltaScores(std::vector< PeptideIdentification >& peptide_ids);
/// @overload
static void computeDeltaScores(PeptideIdentificationList & peptide_ids);
/**
* @brief combines all hits to spectrum pairs with the same light spectrum into one ranked list
*
* This function is a post-processing step for OpenPepXL with labeled linkers.
* This function collects PeptideIdentifications from all spectrum pairs with the same light spectrum,
* then resorts them by the score, makes them unique in case of equal candidates and reduces their number down to the chosen number of reported top hits.
*
* @param[in,out] peptide_ids PeptideIdentifications from a Cross-Linking MS search with labeled linkers
* @param[in] number_top_hits The chosen number of reported top hits
*/
static std::vector< PeptideIdentification > combineTopRanksFromPairs(std::vector< PeptideIdentification > & peptide_ids, Size number_top_hits);
/// @overload
static std::vector< PeptideIdentification > combineTopRanksFromPairs(PeptideIdentificationList & peptide_ids, Size number_top_hits);
/**
* @brief Searches for cross-link candidates for a MS/MS spectrum
This function uses enumerateCrossLinksAndMasses and buildCandidates to search for peptide pairs fitting to the given precursor mass_light
and all considered precursor corrections.
* @param[in] precursor_correction_steps An IntList of integers as indices of isotopic peaks around the experimental precursor
* @param[in] precursor_mass The decharged precursor mass
* @param[in] precursor_mass_tolerance The precursor tolerance
* @param[in] precursor_mass_tolerance_unit_ppm The unit of the precursor tolerance. "ppm" if true, "Da" if false
* @param[in] filtered_peptide_masses A vector of AASeqWithMass containing the sorted (ascending) peptide database with precomputed peptide masses
* @param[in] cross_link_mass The mass of the cross-linker (light mass, if labeled)
* @param[in] cross_link_mass_mono_link A list of possible mono-link masses
* @param[in] cross_link_residue1 A list of one-letter-code residues, that the first side of the cross-linker can attach to
* @param[in] cross_link_residue2 A list of one-letter-code residues, that the second side of the cross-linker can attach to
* @param[in] cross_link_name The name of the cross-linker, e.g. "DSS" or "BS3"
* @param[in] use_sequence_tags Whether to use sequence tags to filter out candidates
* @param[in] tags The list of sequence tags that are used to filter candidate sequences. Only applied if use_sequence_tags = true
*/
static std::vector <OPXLDataStructs::ProteinProteinCrossLink> collectPrecursorCandidates(const IntList& precursor_correction_steps,
double precursor_mass,
double precursor_mass_tolerance,
bool precursor_mass_tolerance_unit_ppm,
const std::vector<OPXLDataStructs::AASeqWithMass>& filtered_peptide_masses,
double cross_link_mass,
const DoubleList& cross_link_mass_mono_link,
const StringList& cross_link_residue1,
const StringList& cross_link_residue2,
String cross_link_name,
bool use_sequence_tags = false,
const std::vector<std::string>& tags = std::vector<std::string>());
/**
* @brief Computes the mass error of a precursor mass to a hit
* @param[in] csm The cross-link spectrum match containing the hit
* @param[in] precursor_mz The precursor mz of the MS/MS spectrum
* @param[in] precursor_charge The charge of the precursor
*/
static double computePrecursorError(const OPXLDataStructs::CrossLinkSpectrumMatch& csm, double precursor_mz, int precursor_charge);
/**
* @brief Computes the mean of alpha, beta, xlinks-alpha and xlinks-beta respectively and store means in @p csm
*/
static void isoPeakMeans(OPXLDataStructs::CrossLinkSpectrumMatch& csm,
const DataArrays::IntegerDataArray& num_iso_peaks_array,
const std::vector< std::pair< Size, Size > >& matched_spec_linear_alpha,
const std::vector< std::pair< Size, Size > >& matched_spec_linear_beta,
const std::vector< std::pair< Size, Size > >& matched_spec_xlinks_alpha,
const std::vector< std::pair< Size, Size > >& matched_spec_xlinks_beta);
/**
* @brief Filters the list of candidates for cases that include at least one of the tags in at least one of the two sequences
* @param[in,out] candidates The list of XLPrecursors as enumerated by e.g. enumerateCrossLinksAndMasses
* @param[in,out] precursor_correction_positions
* @param[in] tags The list of tags for the current spectrum produced by the Tagger
*/
static void filterPrecursorsByTags(std::vector <OPXLDataStructs::XLPrecursor>& candidates, std::vector< int >& precursor_correction_positions, const std::vector<std::string>& tags);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/XLMS/OpenPepXLAlgorithm.h | .h | 8,200 | 167 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Eugen Netz $
// $Authors: Timo Sachsenberg, Eugen Netz $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/KERNEL/ConsensusMap.h>
#include <OpenMS/FORMAT/FASTAFile.h>
#include <OpenMS/ANALYSIS/XLMS/OPXLDataStructs.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
namespace OpenMS
{
//-------------------------------------------------------------
//Doxygen docu
//-------------------------------------------------------------
/**
@brief Search for peptide pairs linked with a labeled cross-linker
This tool performs a search for cross-links in the given mass spectra.
It uses linked MS1 features to pair up MS2 spectra and uses these pairs to find the fragment peaks that contain the linker and those that do not.
It executes the following steps in order:
<ul>
<li>Processing of spectra: deisotoping and filtering</li>
<li>Digesting and preprocessing the protein database, building a peptide pair index dependent on the precursor masses of the MS2 spectra</li>
<li>Generating theoretical spectra of cross-linked peptides and aligning the experimental spectra against those</li>
<li>Scoring of cross-link spectrum matches</li>
<li>Using PeptideIndexer to map the peptides to all possible source proteins</li>
</ul>
See below for available parameters and more functionality.
<h3>Input: MS2 spectra, linked features from FeatureFinderMultiplex and fasta database of proteins expected to be cross-linked in the sample</h3>
The spectra should be provided as one PeakMap. If you have multiple files, e.g. for multiple fractions, you should run this tool on each
file separately.
The database should be provided as a vector of FASTAEntries containing the target and decoy proteins.
A ConsensusMap, that links the MS1 feature pairs from heavy and light cross-linkers is also required.
This can be generated by the tool FeatureFinderMultiplex.
Setting up FeatureFinderMultiplex:
In the FeatureFinderMultiplex parameters you have to change the mass of one of the labels to the difference between the light and heavy
(e.g. change the mass of Arg6 to 12.075321 for labeled DSS) in the advanced options.
The parameter -labels should have one empty label ( [] ) and the label you adapted (e.g. [][Arg6]).
For the other settings refer to the documentation of FeatureFinderMultiplex.
<h3>Parameters</h3>
The parameters for fixed and variable modifications refer to additional modifications beside the cross-linker.
The linker used in the experiment has to be described using the cross-linker specific parameters.
Only one mass is allowed for a cross-linker, that links two peptides (cross_linker:mass_light), while multiple masses are possible for mono-links of the same cross-linking reagent.
Mono-links are cross-linkers, that are linked to one peptide by one of their two reactive groups.
The masses refer to the light version of the linker. The parameter cross_linker:mass_iso_shift defines the difference
between the light and heavy versions of the cross-linker and the mono-links.
The parameters cross_linker:residue1 and cross_linker:residue2 are used to enumerate the amino acids,
that each end of the linker can react with. This way any heterobifunctional cross-linker can be defined.
To define a homobifunctional cross-linker, these two parameters should have the same value.
The parameter cross_linker:name is used to solve ambiguities arising from different cross-linkers having the same mass
after the linking reaction (see section on output for clarification).
<h3>Output: XL-MS Identifications with scores and linked positions in the proteins</h3>
The input parameters protein_ids and peptide_ids are filled with XL-MS search parameters and IDs
<CENTER>
<table>
<tr>
<th ALIGN = "center"> pot. predecessor tools </td>
<td VALIGN="middle" ROWSPAN=2> → OpenPepXL →</td>
<th ALIGN = "center"> pot. successor tools </td>
</tr>
<tr>
<td VALIGN="middle" ALIGN = "center" ROWSPAN=1> - </td>
<td VALIGN="middle" ALIGN = "center" ROWSPAN=1> - </td>
</tr>
</table>
</CENTER>
*/
class OPENMS_DLLAPI OpenPepXLAlgorithm :
public DefaultParamHandler, public ProgressLogger
{
public:
/// Exit codes
enum class ExitCodes
{
EXECUTION_OK,
ILLEGAL_PARAMETERS,
UNEXPECTED_RESULT,
INCOMPATIBLE_INPUT_DATA
};
/// Default constructor
OpenPepXLAlgorithm();
/// Default destructor
~OpenPepXLAlgorithm() override;
/**
* @brief Performs the main function of this class, the search for cross-linked peptides
@param[in,out] unprocessed_spectra The input PeakMap of experimental spectra
@param[in] cfeatures Consensus features linking light and heavy mass pairs; e.g. created by FeatureFinderMultiplex
@param[in] fasta_db The protein database containing targets and decoys
@param[in,out] protein_ids A result vector containing search settings. Should contain one PeptideIdentification.
@param[out] peptide_ids A result vector containing cross-link spectrum matches as PeptideIdentifications and PeptideHits. Should be empty.
@param[out] preprocessed_pair_spectra A result structure containing linear and cross-linked ion spectra. Will be overwritten. This is only necessary for writing out xQuest type spectrum files.
@param[out] spectrum_pairs A result vector containing paired spectra indices. Should be empty. This is only necessary for writing out xQuest type spectrum files.
@param[out] all_top_csms A result vector containing cross-link spectrum matches as CrossLinkSpectrumMatches. Should be empty. This is only necessary for writing out xQuest type spectrum files.
@param[out] spectra A result vector containing the input spectra after preprocessing and filtering. Should be empty. This is only necessary for writing out xQuest type spectrum files.
*/
ExitCodes run(PeakMap& unprocessed_spectra, ConsensusMap& cfeatures, std::vector<FASTAFile::FASTAEntry>& fasta_db, std::vector<ProteinIdentification>& protein_ids, PeptideIdentificationList& peptide_ids, OPXLDataStructs::PreprocessedPairSpectra& preprocessed_pair_spectra, std::vector< std::pair<Size, Size> >& spectrum_pairs, std::vector< std::vector< OPXLDataStructs::CrossLinkSpectrumMatch > >& all_top_csms, PeakMap& spectra);
private:
void updateMembers_() override;
static OPXLDataStructs::PreprocessedPairSpectra preprocessPairs_(const PeakMap& spectra, const std::vector< std::pair<Size, Size> >& spectrum_pairs, const double cross_link_mass_iso_shift, double fragment_mass_tolerance, double fragment_mass_tolerance_xlinks, bool fragment_mass_tolerance_unit_ppm, bool deisotope);
String decoy_string_;
bool decoy_prefix_;
Int min_precursor_charge_;
Int max_precursor_charge_;
double precursor_mass_tolerance_;
bool precursor_mass_tolerance_unit_ppm_;
IntList precursor_correction_steps_;
double fragment_mass_tolerance_;
double fragment_mass_tolerance_xlinks_;
bool fragment_mass_tolerance_unit_ppm_;
StringList cross_link_residue1_;
StringList cross_link_residue2_;
double cross_link_mass_light_;
double cross_link_mass_iso_shift_;
DoubleList cross_link_mass_mono_link_;
String cross_link_name_;
StringList fixedModNames_;
StringList varModNames_;
Size max_variable_mods_per_peptide_;
Size peptide_min_size_;
Size missed_cleavages_;
String enzyme_name_;
Int number_top_hits_;
String deisotope_mode_;
String add_y_ions_;
String add_b_ions_;
String add_x_ions_;
String add_a_ions_;
String add_c_ions_;
String add_z_ions_;
String add_losses_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/XLMS/OPXLDataStructs.h | .h | 13,991 | 336 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Eugen Netz $
// $Authors: Eugen Netz $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/METADATA/PeptideHit.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/CHEMISTRY/ResidueModification.h>
#include <OpenMS/FORMAT/FASTAFile.h>
#include <OpenMS/CHEMISTRY/EnzymaticDigestion.h>
#include <OpenMS/CONCEPT/HashUtils.h>
#include <functional>
//#include <numeric>
namespace OpenMS
{
class OPENMS_DLLAPI OPXLDataStructs
{
public:
/**
* @brief The ProteinProteinCrossLinkType enum enumerates possible types of Protein-Protein cross-linking reaction results. Cross-link, Mono-link or Loop-link.
*/
enum ProteinProteinCrossLinkType
{
CROSS = 0,
MONO = 1,
LOOP = 2,
NUMBER_OF_CROSS_LINK_TYPES
};
/**
* @brief The ProteinProteinCrossLink struct represents a cross-link between two peptides in OpenPepXL.
This struct completely defines a cross-link linking two peptides. It contains the two peptides alpha and beta as AASequences,
the positions that are linked in each peptide, the mass and name of the linker and terminal specificities to distinguish linkers attached to side chains
of the terminal residues from linkers attached to the termini themselves.
The beta peptide can be an empty AASequence object in case of a mono- or loop-link.
Used to represent a theoretical candidate for generation of theoretical spectra and matching to experimental spectra.
*/
struct ProteinProteinCrossLink
{
const AASequence *alpha = nullptr; ///< longer peptide
const AASequence *beta = nullptr; ///< shorter peptide (empty for mono-link), tie breaker: mass then lexicographical
std::pair<SignedSize, SignedSize> cross_link_position; ///< index in alpha, beta or between alpha, alpha in loop-links
double cross_linker_mass = 0;
String cross_linker_name;
ResidueModification::TermSpecificity term_spec_alpha = ResidueModification::TermSpecificity::ANYWHERE;
ResidueModification::TermSpecificity term_spec_beta = ResidueModification::TermSpecificity::ANYWHERE;
int precursor_correction = 0;
ProteinProteinCrossLinkType getType() const
{
if (beta && !beta->empty()) return CROSS;
if (cross_link_position.second == -1) return MONO;
return LOOP;
}
bool operator==(const ProteinProteinCrossLink & other) const
{
return alpha == other.alpha &&
beta == other.beta &&
cross_link_position == other.cross_link_position &&
cross_linker_mass == other.cross_linker_mass &&
cross_linker_name == other.cross_linker_name &&
term_spec_alpha == other.term_spec_alpha &&
term_spec_beta == other.term_spec_beta &&
precursor_correction == other.precursor_correction;
}
};
/**
* @brief The CrossLinkSpectrumMatch struct represents a PSM between a ProteinProteinCrossLink and a spectrum in OpenPepXL.
This struct contains a ProteinProteinCrossLink and indices to one or two spectra.
It also contains the results of a match between the ProteinProteinCrossLink and these spectra as scores and peak annotations.
Used as a temporary container to collect results efficiently, since only a few top matches will be kept for each experimental spectrum for output.
*/
struct CrossLinkSpectrumMatch
{
/// structure of the cross-link
ProteinProteinCrossLink cross_link;
/// reference to pair of spectra
Size scan_index_light = 0;
Size scan_index_heavy = 0;
/// final score
double score = 0;
/// rank among the matches to the same spectrum
Size rank = 0;
/// counts, scores and other data for xQuest-like output
double xquest_score = 0;
double pre_score = 0;
double percTIC = 0;
double wTIC = 0;
double wTICold = 0;
double int_sum = 0;
double intsum_alpha = 0;
double intsum_beta = 0;
double total_current = 0;
double precursor_error_ppm = 0;
double match_odds = 0;
double match_odds_alpha = 0;
double match_odds_beta = 0;
double log_occupancy = 0;
double log_occupancy_alpha = 0;
double log_occupancy_beta = 0;
double xcorrx_max = 0;
double xcorrc_max = 0;
Size matched_linear_alpha = 0;
Size matched_linear_beta = 0;
Size matched_xlink_alpha = 0;
Size matched_xlink_beta = 0;
double num_iso_peaks_mean = 0;
double num_iso_peaks_mean_linear_alpha = 0;
double num_iso_peaks_mean_linear_beta = 0;
double num_iso_peaks_mean_xlinks_alpha = 0;
double num_iso_peaks_mean_xlinks_beta = 0;
double ppm_error_abs_sum_linear_alpha = 0;
double ppm_error_abs_sum_linear_beta = 0;
double ppm_error_abs_sum_xlinks_alpha = 0;
double ppm_error_abs_sum_xlinks_beta = 0;
double ppm_error_abs_sum_linear = 0;
double ppm_error_abs_sum_xlinks = 0;
double ppm_error_abs_sum_alpha = 0;
double ppm_error_abs_sum_beta = 0;
double ppm_error_abs_sum = 0;
int precursor_correction = 0;
double precursor_total_intensity = 0;
double precursor_target_intensity = 0;
double precursor_signal_proportion = 0;
Size precursor_target_peak_count = 0;
Size precursor_residual_peak_count = 0;
std::vector<PeptideHit::PeakAnnotation> frag_annotations;
Size peptide_id_index = 0;
};
/**
* @brief Comparator to sort CrossLinkSpectrumMatches by the main score
*/
struct CLSMScoreComparator
{
bool operator() (const CrossLinkSpectrumMatch& a, const CrossLinkSpectrumMatch& b)
{
if (a.score == b.score)
{
// in rare cases when the sequences are the same, multiple candidates with different cross-linked positions can have the same score
// that leads to ambiguous sorting and may cause differences between compilers
// in those cases we prefer higher positions (just like the score),
// because the lower position might be an N-term link, which is usually less likely and all other positions are equal (because the score is equal)
if (a.cross_link.cross_link_position.first == b.cross_link.cross_link_position.first)
{
return a.cross_link.cross_link_position.second < b.cross_link.cross_link_position.second;
}
return a.cross_link.cross_link_position.first < b.cross_link.cross_link_position.first;
}
return a.score < b.score;
}
};
/**
* @brief The XLPrecursor struct represents a cross-link candidate in the process of filtering candidates by precursor masses in OpenPepXL.
Since the precursor mass does not change depending on the exact linked residues, one XLPrecursor can represent several ProteinProteinCrossLinks
in the process of filtering by precursor mass. The precursor mass is the sum of the masses of the two peptides and the cross-linker.
This struct also contains the indices of the two peptides in a vector, so that the two peptides can be identified again.
This precursor mass is enumerated for all peptide pairs in the protein database given as input to OpenPepXL
and is one of the major contributors to the memory usage of the tool because of the squared complexity of this enumeration.
Therefore this should be kept as compact as possible.
*/
struct XLPrecursor
{
float precursor_mass{};
unsigned int alpha_index = 0;
unsigned int beta_index = 0;
String alpha_seq;
String beta_seq;
};
// comparator for sorting XLPrecursor vectors and using upper_bound and lower_bound using only a precursor mass
/**
* @brief The XLPrecursorComparator is a comparator for XLPrecursors, that allows direct comparison of the XLPrecursor precursor mass with double numbers.
This comparator can be used to sort a vector of XLPrecursors by precursor mass and to search for XLPrecursors with precursor masses within a double type mass range.
*/
struct XLPrecursorComparator
{
bool operator() (const XLPrecursor& a, const XLPrecursor& b) const
{
return a.precursor_mass < b.precursor_mass;
}
bool operator() (const XLPrecursor& a, const double& b) const
{
return a.precursor_mass < b;
}
bool operator() (const double& a, const XLPrecursor& b) const
{
return a < b.precursor_mass;
}
};
/**
* @brief The PeptidePosition enum
Used to record the positions of peptides in proteins after in silico digestion determine whether protein terminal modifications are possible on a peptide.
*/
enum PeptidePosition
{
INTERNAL = 0,
C_TERM = 1,
N_TERM = 2
};
/**
* @brief The AASeqWithMass struct represents a normal peptide with its precomputed mass.
This struct stores information about a peptide as an AASequence and a PeptidePosition.
It is used to enumerate pairs of peptides in OpenPepXL.
Since the mass of every peptide is used many times, it is precomputed once and also stored in this struct.
A vector of these structs is used to represent the digested protein database in OpenPepXL.
An instance of this struct is created only once for each peptide in the digested database, so it does not contribute to memory usage
as much as XLPrecursor does.
*/
struct AASeqWithMass
{
double peptide_mass = 0;
AASequence peptide_seq;
PeptidePosition position = PeptidePosition::INTERNAL;
String unmodified_seq;
};
/**
* @brief The AASeqWithMassComparator is a comparator for AASeqWithMass objects.
This comparator allows to sort AASeqWithMass objects by the precomputed peptide mass and search for AASeqWithMass objects within a double type mass range.
*/
struct AASeqWithMassComparator
{
bool operator() (const AASeqWithMass& a, const AASeqWithMass& b) const
{
return a.peptide_mass < b.peptide_mass;
}
bool operator() (const AASeqWithMass& a, const double& b) const
{
return a.peptide_mass < b;
}
bool operator() (const double& a, const AASeqWithMass& b) const
{
return a < b.peptide_mass;
}
};
/**
* @brief The PreprocessedPairSpectra struct represents the result of comparing a light and a heavy labeled spectra to each other.
OpenPepXL can use labeled cross-linkers to denoise MS2 spectra. The PeakMaps contained in this struct represent the result of this
denoising process for a whole mzML input file.
*/
struct PreprocessedPairSpectra
{
MSExperiment spectra_linear_peaks; ///< merge spectrum of linear peaks (present in both spectra)
MSExperiment spectra_xlink_peaks; ///< Xlink peaks in the light spectrum (linear peaks between spectra_light_different and spectra heavy_to_light)
MSExperiment spectra_all_peaks;
// pre-initialize so we can simply std::swap the spectra (no synchronization in multi-threading context needed as we get no reallocation of the PeakMaps).
PreprocessedPairSpectra(Size size)
{
for (Size i = 0; i != size; ++i)
{
spectra_linear_peaks.addSpectrum(PeakSpectrum());
spectra_xlink_peaks.addSpectrum(PeakSpectrum());
spectra_all_peaks.addSpectrum(PeakSpectrum());
}
}
};
}; // class
} // namespace OpenMS
namespace std
{
/// @brief std::hash specialization for ProteinProteinCrossLink
template<>
struct hash<OpenMS::OPXLDataStructs::ProteinProteinCrossLink>
{
std::size_t operator()(const OpenMS::OPXLDataStructs::ProteinProteinCrossLink& link) const noexcept
{
std::size_t seed = 0;
// Hash pointers (alpha and beta) - these are compared by pointer value in operator==
OpenMS::hash_combine(seed, OpenMS::hash_int(reinterpret_cast<std::uintptr_t>(link.alpha)));
OpenMS::hash_combine(seed, OpenMS::hash_int(reinterpret_cast<std::uintptr_t>(link.beta)));
// Hash cross_link_position (pair of SignedSize)
OpenMS::hash_combine(seed, OpenMS::hash_int(link.cross_link_position.first));
OpenMS::hash_combine(seed, OpenMS::hash_int(link.cross_link_position.second));
// Hash cross_linker_mass (double)
OpenMS::hash_combine(seed, OpenMS::hash_float(link.cross_linker_mass));
// Hash cross_linker_name (String, which is std::string)
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(link.cross_linker_name));
// Hash term_spec_alpha and term_spec_beta (enums)
OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(link.term_spec_alpha)));
OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(link.term_spec_beta)));
// Hash precursor_correction (int)
OpenMS::hash_combine(seed, OpenMS::hash_int(link.precursor_correction));
return seed;
}
};
} // namespace std
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/XLMS/XFDRAlgorithm.h | .h | 7,618 | 202 | // 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, Eugen Netz $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <OpenMS/METADATA/PeptideHit.h>
#include <OpenMS/METADATA/ProteinIdentification.h>
#include <OpenMS/MATH/STATISTICS/Histogram.h>
namespace OpenMS
{
//-------------------------------------------------------------
// Doxygen docu
//-------------------------------------------------------------
/**
@brief Calculates false discovery rate estimates on crosslink identifications.
This tool calculates and FDR estimate for crosslink identifications, which are produced by OpenPepXL.
The method employed currently is identical to the target-decoy approach used by xProphet (Walzthoeni et al., 2012).
Consequently, this tool can also consume xquest.xml files (produced either by OpenPepXL or xQuest). The tool supports
output in the idXML and mzIdentML formats.
@experimental This tool is work in progress and usage and input requirements might change.
*/
class OPENMS_DLLAPI XFDRAlgorithm :
public DefaultParamHandler, public ProgressLogger
{
public:
/// Exit codes
enum class ExitCodes
{
EXECUTION_OK,
ILLEGAL_PARAMETERS,
UNEXPECTED_RESULT
};
/// Default constructor
XFDRAlgorithm();
/// Default destructor
~XFDRAlgorithm() override;
/**
@brief Performs the main function of this class, the FDR estimation for cross-linked peptide experiments
@param[in,out] peptide_ids The PeptideIdentifications from an XL-MS experiment
@param[in,out] protein_id The ProteinIdentification from an XL-MS experiment
*/
ExitCodes run(PeptideIdentificationList& peptide_ids, ProteinIdentification& protein_id);
/**
* @brief Checks whether the parameters of the object are valid
* @return ExitCode EXECUTION_OK if they are valid, ILLEGAL_PARAMETERS otherwise
*/
ExitCodes validateClassArguments() const;
private:
void updateMembers_() override;
/**
* @brief Prepares vector of PeptideIdentification such that it can be processed downstream.
* The encompassed steps are:
* * Set min_score_ and max_score_ encountered in the data
* * Ensure that crosslink_type and crosslink_rank are available in the PeptideIdentification
* * Define the crosslink as either inter/or intraprotein
* * Set the identifier of the Peptide Identification if there is only one protein identification
*
*/
void initDataStructures_(PeptideIdentificationList& peptide_ids, ProteinIdentification& protein_id);
/**
* @brief Inspects a PeptideIdentification and assigns all cross-link types that this identification belongs to
* @param[in,out] pep_id Peptide ID to be assigned.
* @param[out] types Result vector containing the names of the crosslink classes
*/
static void assignTypes_(PeptideHit& pep_id, StringList& types);
/** Target counting as performed by the xProphet software package
@brief xprophet method for target hits counting as implemented in xProphet
@param[in,out] cum_histograms Cumulative score distributions
@param[in] targetclass Name of key for targets in @p cum_histograms
@param[in] decoyclass Name of key for decoys in @p cum_histograms
@param[in] fulldecoyclass Name of key for full decoys in @p cum_histograms
@param[out] fdr Output FDR values
@param[in] mono
*/
void fdr_xprophet_(std::map< String, Math::Histogram<> >& cum_histograms,
const String& targetclass, const String& decoyclass, const String& fulldecoyclass,
std::vector< double >& fdr, bool mono) const;
/**
* @brief Calculates the qFDR values for the provided FDR values, assuming that the FDRs are sorted by score in the input vector
* @param[in] fdr Vector with FDR values which should be used for qFDR calculation
* @param[out] qfdr Result qFDR values
*/
static void calc_qfdr_(const std::vector< double >& fdr, std::vector< double >& qfdr);
void findTopUniqueHits_(PeptideIdentificationList& peptide_ids);
void writeArgumentsLog_() const;
String getId_(const PeptideHit& ph) const;
static Size getMinIonsMatched_(const PeptideHit& ph)
{
Size alpha_ions = Size(ph.getMetaValue("matched_linear_alpha")) + Size(ph.getMetaValue("matched_xlink_alpha"));
Size beta_ions = Size(ph.getMetaValue("matched_linear_beta")) + Size(ph.getMetaValue("matched_xlink_beta"));
return std::min(alpha_ions, beta_ions);
}
inline static void setIntraProtein_(PeptideHit& ph, const bool value)
{
ph.setMetaValue("XFDR:is_intraprotein", DataValue(value ? "true" : "false"));
}
inline static void setInterProtein_(PeptideHit& ph, const bool value)
{
ph.setMetaValue("XFDR:is_interprotein", DataValue(value ? "true" : "false"));
}
/**
* @brief Determines whether the Peptide Evidences belong to the same protein, modulo decoy
*/
static bool isSameProtein_(
String prot1,
String prot2,
const String &decoy_string)
{
prot1.substitute(decoy_string, "");
prot2.substitute(decoy_string, "");
assert( ! prot1.hasSubstring(decoy_string));
assert( ! prot2.hasSubstring(decoy_string));
return prot1 == prot2;
}
// Score range for this of the tool
Int min_score_;
Int max_score_;
// unique top hits
std::vector<String> unique_ids_;
std::vector<double> unique_id_scores_;
// maps index of peptide id all_pep_ids_ to vector of cross link class
std::map<String, std::vector<String>> cross_link_classes_;
// Program arguments
String decoy_string_;
double arg_mindeltas_;
double arg_minborder_;
double arg_maxborder_;
Int arg_minionsmatched_;
double arg_minscore_;
bool arg_uniquex_;
bool arg_no_qvalues_;
double arg_binsize_;
// Names of the class parameters
static const String param_decoy_string_;
static const String param_minborder_;
static const String param_maxborder_;
static const String param_mindeltas_;
static const String param_minionsmatched_;
static const String param_uniquexl_;
static const String param_no_qvalues_;
static const String param_minscore_;
static const String param_binsize_;
// Constants related to particular crosslink classes
static const String crosslink_class_intradecoys_;
static const String crosslink_class_fulldecoysintralinks_;
static const String crosslink_class_interdecoys_;
static const String crosslink_class_fulldecoysinterlinks_;
static const String crosslink_class_monodecoys_;
static const String crosslink_class_intralinks_;
static const String crosslink_class_interlinks_;
static const String crosslink_class_monolinks_;
static const String crosslink_class_decoys_;
static const String crosslink_class_targets_;
static const String crosslink_class_hybriddecoysintralinks_;
static const String crosslink_class_hybriddecoysinterlinks_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/MapAlignmentEvaluationAlgorithm.h | .h | 1,811 | 52 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Katharina Albers $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/ConsensusMap.h>
namespace OpenMS
{
/**
@brief Base class for all Caap evaluation algorithms
These algorithms evaluates alignment results against a ground truth.
*/
class OPENMS_DLLAPI MapAlignmentEvaluationAlgorithm
{
protected:
typedef ConsensusFeature::HandleSetType::const_iterator HandleIterator;
public:
/// Default constructor
MapAlignmentEvaluationAlgorithm();
/// Destructor
virtual ~MapAlignmentEvaluationAlgorithm();
///Applies the algorithm. The input consensus map is compared to the ground truth.
virtual void evaluate(const ConsensusMap & conensus_map_in, const ConsensusMap & consensus_map_gt, const double & rt_dev, const double & mz_dev, const Peak2D::IntensityType & int_dev, const bool use_charge, double & out) = 0;
///Decides if two features are the same, based on maximum allowed deviations for retention time, m/z and intensity.
bool isSameHandle(const FeatureHandle & lhs, const FeatureHandle & rhs, const double & rt_dev, const double & mz_dev, const Peak2D::IntensityType & int_dev, const bool use_charge);
private:
///Copy constructor is not implemented -> private
MapAlignmentEvaluationAlgorithm(const MapAlignmentEvaluationAlgorithm &);
///Assignment operator is not implemented -> private
MapAlignmentEvaluationAlgorithm & operator=(const MapAlignmentEvaluationAlgorithm &);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/FeatureDistance.h | .h | 6,453 | 160 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hendrik Weisser $
// $Authors: Clemens Groepl, Hendrik Weisser, Chris Bielow $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/KERNEL/BaseFeature.h>
#include <limits>
namespace OpenMS
{
/**
@brief A functor class for the calculation of distances between features or consensus features.
It implements a customizable distance function of the following form:
@f[
w_{RT} \cdot \left( \frac{\left| RT_1 - RT_2 \right|}{\Delta RT_{max}} \right)^{p_{RT}} +
w_{MZ} \cdot \left( \frac{\left| MZ_1 - MZ_2 \right|}{\Delta MZ_{max}} \right)^{p_{MZ}} +
w_{int} \cdot \left( \frac{\left| int_1 - int_2 \right|}{int_{max}} \right)^{p_{int}}
@f]
This function returns a normalized distance between zero and one (unless constraints are violated, see below).
@f$ RT_i @f$, @f$ MZ_i @f$, and @f$ int_i @f$ are the RT, m/z, and intensity values of the respective feature.
Constraints are: @f$ {\Delta RT_{max}}, {\Delta MZ_{max}} @f$ and @f$ int_{max} @f$.
If an absolute difference exceeds the specified maximum, the behavior depends on the value used for @p check_constraints in the constructor:
If "false" (i.e., no constraints), the distance in that dimension may become greater than 1; if "true", @ref infinity is returned as overall distance.
@f$ {\Delta RT_{max}} @f$ and @f$ {\Delta MZ_{max}} @f$ are the maximum allowed differences in RT and m/z, respectively.
They are specified by the parameters @p distance_RT:max_difference and @p distance_MZ:max_difference, and are used for normalization,
i.e., the observed RT or m/z differences of the feature pair are scaled relative to this value.
@f$ int_{max} @f$ is the intensity which yields a normalized intensity of 1. This parameter is not settable via user params,
but is set in the constructor (via parameter @p max_intensity), since it depends on the data at hand.
@f$ p_X @f$ is the exponent for the distance in dimension X, specified by the parameter @p distance_X:exponent.
Normalized differences (between (0, 1) unless unconstrained) are taken to this power. This makes it possible to compare values using linear, quadratic, etc. distance.
@f$ w_X @f$ is the weight of final distance in dimension X, specified by the parameter @p distance_X:weight. The weights can be used to increase or decrease
the contribution of RT, m/z, or intensity in the distance function.
(The default weight for the intensity dimension is zero, i.e. intensity is not considered by default. However, @f$ int_{max} @f$ is still a constraint and
should be set sensibly in the c'tor.)
By default, two features are paired only if they have the same charge state (or at least one unknown charge '0') - otherwise, @ref infinity is returned.
This behavior can be changed by the @p ignore_charge parameter.
@note Peptide identifications annotated to features are not taken into account here,
because they are stored in a format that is not suitable for rapid comparison.
@htmlinclude OpenMS_FeatureDistance.parameters
@ingroup FeatureGrouping
*/
class OPENMS_DLLAPI FeatureDistance :
public DefaultParamHandler
{
public:
/// Value to return if max. difference is exceeded or if charge states don't match
static const double infinity;
/**
@brief Constructor
@param[in] max_intensity Maximum intensity of features (for normalization)
@param[in] force_constraints Check "max. difference" constraints given in the parameters and return @ref infinity if violated?
*/
FeatureDistance(double max_intensity = 1.0,
bool force_constraints = false);
/// Destructor
~FeatureDistance() override;
/// Assignment operator
FeatureDistance & operator=(const FeatureDistance & other);
/**
@brief Evaluation operator - checks constraints and computes the distance between two features
@returns In the first element, whether constraints were satisfied; in
the second element, the distance (@ref infinity if constraints were
violated and @ref force_constraints_ is true).
*/
std::pair<bool, double> operator()(const BaseFeature & left,
const BaseFeature & right);
protected:
/// Structure for storing distance parameters
struct DistanceParams_
{
DistanceParams_() {}
DistanceParams_(const String & what, const Param & global)
{
Param param = global.copy("distance_" + what + ":", true);
if (what == "MZ")
{
max_diff_ppm = (param.getValue("unit") == "ppm");
}
else
{
max_diff_ppm = false;
}
max_difference = param.getValue("max_difference");
exponent = param.getValue("exponent");
weight = param.getValue("weight");
norm_factor = 1 / max_difference;
relevant = (weight != 0.0) && (exponent != 0.0);
if (!relevant)
{
weight = 0.0;
}
}
double max_difference, exponent, weight, norm_factor;
bool max_diff_ppm, relevant;
};
/// Docu in base class
void updateMembers_() override;
/// Computes a distance component given absolute difference and parameters
inline double distance_(double diff, const DistanceParams_ & params) const;
/// Storage of parameters for the individual distance components
DistanceParams_ params_rt_, params_mz_, params_intensity_;
/// Reciprocal value of the total weight in the distance function
double total_weight_reciprocal_;
/// Maximum intensity of features (for normalization)
double max_intensity_;
/// Compute a distance even if charge states don't match?
bool ignore_charge_;
/// Compute a distance even if adducts don't match?
bool ignore_adduct_;
/// Always return @ref infinity if "max. difference" constraints are not met?
bool force_constraints_;
/// Log-transform intensities when computing intensity distance?
bool log_transform_;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/MapAlignmentEvaluationAlgorithmRecall.h | .h | 1,556 | 48 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Katharina Albers $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/ANALYSIS/MAPMATCHING/MapAlignmentEvaluationAlgorithm.h>
namespace OpenMS
{
/**
@brief Caap evaluation algorithm to obtain a recall value.
It evaluates an input consensus map with respect to a ground truth.
@ingroup MapAlignment
*/
class OPENMS_DLLAPI MapAlignmentEvaluationAlgorithmRecall :
public MapAlignmentEvaluationAlgorithm
{
public:
/// Default constructor
MapAlignmentEvaluationAlgorithmRecall();
/// Destructor
~MapAlignmentEvaluationAlgorithmRecall() override;
/**
@brief Applies the algorithm
*/
void evaluate(const ConsensusMap & consensus_map_in, const ConsensusMap & consensus_map_gt, const double & rt_dev, const double & mz_dev, const Peak2D::IntensityType & int_dev, const bool use_charge, double & out) override;
private:
/// Copy constructor intentionally not implemented -> private
MapAlignmentEvaluationAlgorithmRecall(const MapAlignmentEvaluationAlgorithmRecall &);
/// Assignment operator intentionally not implemented -> private
MapAlignmentEvaluationAlgorithmRecall & operator=(const MapAlignmentEvaluationAlgorithmRecall &);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/ConsensusMapNormalizerAlgorithmThreshold.h | .h | 1,991 | 55 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Lars Nilse $
// $Authors: Hendrik Brauer, Oliver Kohlbacher, Johannes Junker $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/ConsensusMap.h>
namespace OpenMS
{
/**
* @brief Algorithms of ConsensusMapNormalizer
*
*/
class OPENMS_DLLAPI ConsensusMapNormalizerAlgorithmThreshold
{
private:
/// copy constructor is not implemented -> private
ConsensusMapNormalizerAlgorithmThreshold(const ConsensusMapNormalizerAlgorithmThreshold & copyin);
/// assignment operator is not implemented -> private
ConsensusMapNormalizerAlgorithmThreshold & operator=(const ConsensusMapNormalizerAlgorithmThreshold & rhs);
public:
/// default constructor is not implemented -> private
ConsensusMapNormalizerAlgorithmThreshold();
/// destructor is not implemented -> private
virtual ~ConsensusMapNormalizerAlgorithmThreshold();
/**
* @brief determines the ratio of all maps to the map with the most features
* @param[in] map ConsensusMap
* @param[in] ratio_threshold threshold for the ratio
* @param[in] acc_filter string describing the regular expression for filtering accessions
* @param[in] desc_filter string describing the regular expression for filtering descriptions
*/
static std::vector<double> computeCorrelation(const ConsensusMap & map, const double & ratio_threshold, const String & acc_filter, const String & desc_filter);
/**
* @brief applies the given ratio to the maps of the consensusMap
* @param[in] map ConsensusMap
* @param[in] ratios ratios for the normalization
*/
static void normalizeMaps(ConsensusMap & map, const std::vector<double> & ratios);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/MapAlignmentAlgorithmKD.h | .h | 3,115 | 95 | // 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/ANALYSIS/QUANTITATION/KDTreeFeatureMaps.h>
#include <OpenMS/ANALYSIS/MAPMATCHING/TransformationModelLowess.h>
namespace OpenMS
{
/**
@brief An efficient reference-free feature map alignment algorithm for unlabeled data
This algorithm uses a kd-tree to efficiently compute conflict-free connected components (CCC)
in a compatibility graph on feature data. This graph is comprised of nodes corresponding
to features and edges connecting features f and f' iff both are within each other's tolerance
windows (wrt. RT and m/z difference). CCCs are those CCs that do not contain multiple features
from the same input map, and whose features all have the same charge state.
All CCCs above a user-specified minimum size are considered true sets of corresponding features
and based on these, LOWESS transformations are computed for each input map such that the average
deviation from the mean retention time within all CCCs is minimized.
@ingroup MapAlignment
*/
class OPENMS_DLLAPI MapAlignmentAlgorithmKD
{
public:
/// Constructor
MapAlignmentAlgorithmKD(Size num_maps, const Param& param);
/// Default destructor
virtual ~MapAlignmentAlgorithmKD();
/// Compute data points needed for RT transformation in the current @p kd_data, add to fit_data_
void addRTFitData(const KDTreeFeatureMaps& kd_data);
/// Fit LOWESS to fit_data_, store final models in transformations_
void fitLOWESS();
/// Transform RTs for @p kd_data
void transform(KDTreeFeatureMaps& kd_data) const;
protected:
virtual void updateMembers_();
/// Compute connected components, store CC indices in member cc_index. Return number of CCs.
Size computeCCs_(const KDTreeFeatureMaps& kd_data, std::vector<Size>& cc_index) const;
/// Return connected components
void getCCs_(const KDTreeFeatureMaps& kd_data, std::map<Size, std::vector<Size> >& result) const;
/// Filter connected components (return conflict-free CCs of sufficiently large size and small diameter)
void filterCCs_(const KDTreeFeatureMaps& kd_data, const std::map<Size, std::vector<Size> >& ccs, std::map<Size, std::vector<Size> >& filtered_ccs) const;
private:
/// Default constructor is not supposed to be used.
MapAlignmentAlgorithmKD();
/// RT data for fitting the LOWESS
std::vector<TransformationModel::DataPoints> fit_data_;
/// LOWESS transformations
std::vector<TransformationModelLowess*> transformations_;
/// Parameters
Param param_;
/// Maximum absolute log10 fold change threshold between compatible features
double max_pairwise_log_fc_;
/// RT tolerance
double rt_tol_secs_;
/// m/z tolerance
double mz_tol_;
/// m/z unit ppm?
bool mz_ppm_;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/TransformationModel.h | .h | 4,645 | 159 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Hendrik Weisser $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/Param.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <tuple>
namespace OpenMS
{
/**
@brief Base class for transformation models
Implements the identity (no transformation). Parameters and data are ignored.
Note that this class and its derived classes do not allow copying/assignment, due to the need for internal memory management associated with some of the transformation models.
@ingroup MapAlignment
*/
class OPENMS_DLLAPI TransformationModel
{
public:
/// Coordinate pair (with optional annotation)
struct DataPoint
{
double first, second;
String note;
DataPoint(double first_ = 0.0,
double second_ = 0.0,
const String& note_ = "") :
first(first_),
second(second_),
note(note_)
{}
DataPoint(const std::pair<double, double>& pair) :
first(pair.first),
second(pair.second),
note("")
{}
bool operator<(const DataPoint& other) const
{
return (std::tie(first, second, note) <
std::tie(other.first, other.second, other.note));
}
bool operator==(const DataPoint& other) const
{
return (std::tie(first, second, note) ==
std::tie(other.first, other.second, other.note));
}
};
/// Vector of coordinate pairs
typedef std::vector<DataPoint> DataPoints;
/// Constructor
TransformationModel() {}
/// Alternative constructor (derived classes should implement this one!)
/// Both data and params must be provided, since some derived classes require both to create a model!
TransformationModel(const TransformationModel::DataPoints&, const Param&);
/// Destructor
virtual ~TransformationModel();
/// Evaluates the model at the given value
virtual double evaluate(double value) const;
/**
@brief Weight the data by the given weight function
Currently supported valid weighting functions include the following:
- 1 / x.
- 1 / x2.
- 1 / y.
- 1 / y2.
- ln x.
- ln y.
Note that the user needs to ensure valid bounds for the data by setting
the x_datum_min/x_datum_max and y_datum_min/y_datum_max params.
*/
virtual void weightData(DataPoints& data);
/**
@brief Unweight the data by the given weight function
*/
virtual void unWeightData(DataPoints& data);
/**
@brief Check for a valid weighting function string
*/
bool checkValidWeight(const String& weight, const std::vector<String>& valid_weights) const;
/**
@brief Check that the datum is within the valid min and max bounds.
The method checks if the datum is within the user specified min and max bounds.
If the datum is below the min bounds, the min bound is returned.
If the datum is above the max bounds, the max bound is returned.
*/
double checkDatumRange(const double& datum, const double& datum_min, const double& datum_max);
/**
@brief Weight the data according to the weighting function
*/
double weightDatum(const double& datum, const String& weight) const;
/**
@brief Apply the reverse of the weighting function to the data
*/
double unWeightDatum(const double& datum, const String& weight) const;
/// Gets the (actual) parameters
const Param& getParameters() const;
/// Returns a list of valid x weight function strings
std::vector<String> getValidXWeights() const;
/// Returns a list of valid y weight function strings
std::vector<String> getValidYWeights() const;
/// Gets the default parameters
static void getDefaultParameters(Param& params);
protected:
/// Parameters
Param params_;
/// x weighting
String x_weight_;
double x_datum_min_;
double x_datum_max_;
/// y weighting
String y_weight_;
double y_datum_min_;
double y_datum_max_;
bool weighting_;
private:
/// do not allow copy
TransformationModel(const TransformationModel&);
/// do not allow assignment
const TransformationModel& operator=(const TransformationModel&);
};
} // end of namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/FeatureMapping.h | .h | 2,058 | 59 | // 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/BaseFeature.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/ANALYSIS/QUANTITATION/KDTreeFeatureMaps.h>
#include <OpenMS/KERNEL/MSExperiment.h>
namespace OpenMS
{
class OPENMS_DLLAPI FeatureMapping
{
public:
/// Stores information required for preprocessing
class FeatureMappingInfo
{
public:
std::vector<FeatureMap> feature_maps; ///< feature data
KDTreeFeatureMaps kd_tree; ///< KDTree references into feature_maps to provides fast spatial queries
};
/// Stores preprocessed feature mapping information
class FeatureToMs2Indices
{
public:
std::map<const BaseFeature*, std::vector<size_t>> assignedMS2;
std::vector<size_t> unassignedMS2;
};
/**
@brief Allocate ms2 spectra to feature within the minimal distance
@return FeatureToMs2Indices
@param[in] spectra: Input of PeakMap/MSExperiment with spectra information
@param[in] fm_info: KDTree used for query and match spectra with features
@param[in] precursor_mz_tolerance: mz_tolerance used for query
@param[in] precursor_rt_tolerance: rt tolerance used for query
@param[in] ppm: mz tolerance window calculation in ppm or Da
*/
static FeatureToMs2Indices assignMS2IndexToFeature(const MSExperiment& spectra,
const FeatureMappingInfo& fm_info,
const double& precursor_mz_tolerance,
const double& precursor_rt_tolerance,
bool ppm);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/TransformationModelInterpolated.h | .h | 4,499 | 133 | // 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, Hendrik Weisser $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/config.h>
#include <OpenMS/ANALYSIS/MAPMATCHING/TransformationModel.h>
#include <OpenMS/ANALYSIS/MAPMATCHING/TransformationModelLinear.h>
namespace OpenMS
{
/**
@brief Interpolation model for transformations
Between the data points, the interpolation uses the neighboring points to
interpolate. The following interpolation methods are available:
- linear: Linearly interpolate between neighboring points
- cspline: Use a cubic spline to interpolate between neighboring points
- akima: Use an akima spline to interpolate between neighboring points (less affected by outliers)
Outside the range spanned by the points, we extrapolate using one of the following methods:
- two-point-linear: Uses a line through the first and last point to extrapolate
- four-point-linear: Uses a line through the first and second point to
extrapolate in front and and a line through the last
and second-to-last point in the end. If the data is
non-linear, this may yield better approximations for
extrapolation.
- global-linear: Uses a linear regression to fit a line through all data
points and use it for extrapolation. Note that
global-linear extrapolation may \b not be continuous with
the interpolation at the border.
@ingroup MapAlignment
*/
class OPENMS_DLLAPI TransformationModelInterpolated :
public TransformationModel
{
public:
/**
@brief Constructor
@param[in] data The known data points.
@param[in] params Param object holding information on which model to choose.
@exception IllegalArgument is thrown if there are not enough data points or if an unknown interpolation type is given.
*/
TransformationModelInterpolated(const DataPoints& data, const Param& params);
TransformationModelInterpolated(const std::vector<std::pair<double,double>>& data, const Param& params, bool preprocess);
/// Destructor
~TransformationModelInterpolated() override;
/**
* @brief Evaluate the interpolation model at the given value
*
* @param[in] value The position where the interpolation should be evaluated.
*
* @return The interpolated value.
*/
double evaluate(double value) const override;
/// Gets the default parameters
static void getDefaultParameters(Param& params);
/**
* @brief The class defines a generic interpolation technique used in the
* TransformationModelInterpolated.
*
* @note This class is nested in cpp file as we don't want this to be part
* of the public interface nor to be exposed to derived or other classes.
*/
class Interpolator
{
public:
/**
* @brief Initialize the Interpolator.
*
* @param[in] x The x data.
* @param[in] y The y data.
*/
virtual void init(std::vector<double>& x, std::vector<double>& y) = 0;
/**
* @brief Evaluate the underlying interpolation at a specific position x.
*
* @param[in] x The position where the interpolation should be evaluated.
*
* @return The interpolated value.
*/
virtual double eval(const double& x) const = 0;
/**
* @brief d'tor.
*/
virtual ~Interpolator() {}
};
private:
/// Data coordinates x
std::vector<double> x_;
/// Data coordinates y
std::vector<double> y_;
/// Interpolation function
Interpolator* interp_;
/// Linear model for extrapolation (front)
TransformationModelLinear* lm_front_;
/// Linear model for extrapolation (back)
TransformationModelLinear* lm_back_;
/// Preprocesses the incoming data and fills the (private) vectors x_ and y_
void preprocessDataPoints_(const DataPoints& data);
/// Preprocesses the incoming data and fills the (private) vectors x_ and y_
void preprocessDataPoints_(const std::vector<std::pair<double,double>>& data);
};
} // namespace
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithm.h | .h | 4,077 | 100 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/KERNEL/ConsensusMap.h>
namespace OpenMS
{
/**
@brief Base class for all feature grouping algorithms
These algorithms group corresponding features in one map or across maps.
*/
class OPENMS_DLLAPI FeatureGroupingAlgorithm :
public DefaultParamHandler
{
public:
/// Default constructor
FeatureGroupingAlgorithm();
/// Destructor
~FeatureGroupingAlgorithm() override;
///Applies the algorithm. The features in the input @p maps are grouped and the output is written to the consensus map @p out
virtual void group(const std::vector<FeatureMap > & maps, ConsensusMap & out) = 0;
///Applies the algorithm. The consensus features in the input @p maps are grouped and the output is written to the consensus map @p out
/// Algorithms not supporting ConsensusMap input should simply not override this method,
/// as the base implementation will forward the data to the FeatureMap version of group()
virtual void group(const std::vector<ConsensusMap> & maps, ConsensusMap & out);
/// Transfers subelements (grouped features) from input consensus maps to the result consensus map
void transferSubelements(const std::vector<ConsensusMap> & maps, ConsensusMap & out) const;
protected:
/// after grouping by the subclasses, postprocess unassigned IDs, protein IDs and sort results in a
/// consistent way
template<class MapType>
void postprocess_(const std::vector<MapType>& maps, ConsensusMap& out)
{
// add protein IDs and unassigned peptide IDs to the result map here,
// to keep the same order as the input maps (useful for output later):
auto& newIDs = out.getUnassignedPeptideIdentifications();
Size map_idx = 0;
for (typename std::vector<MapType>::const_iterator map_it = maps.begin();
map_it != maps.end(); ++map_it)
{
// add protein identifications to result map:
out.getProteinIdentifications().insert(
out.getProteinIdentifications().end(),
map_it->getProteinIdentifications().begin(),
map_it->getProteinIdentifications().end());
// assign the map_index to unassigned PepIDs as well.
// for the assigned ones, this has to be done in the subclass.
for (const PeptideIdentification& pepID : map_it->getUnassignedPeptideIdentifications())
{
auto newPepID = pepID;
// Note: during linking of _consensus_Maps we have the problem that old identifications
// should already have a map_index associated. Since we group the consensusFeatures only anyway
// (without keeping the subfeatures) the method for now is to "re"-index based on the input file/map index.
// Subfeatures have to be transferred in postprocessing if required
// (see FeatureGroupingAlgorithm::transferSubelements as used in the TOPP tools, i.e. FeatureLinkerBase),
// which also takes care of a re-re-indexing if the old map_index of the IDs was saved.
newPepID.setMetaValue("map_index", map_idx);
newIDs.push_back(newPepID);
}
map_idx++;
}
// canonical ordering for checking the results:
out.sortByQuality();
out.sortByMaps();
out.sortBySize();
}
private:
///Copy constructor is not implemented -> private
FeatureGroupingAlgorithm(const FeatureGroupingAlgorithm &);
///Assignment operator is not implemented -> private
FeatureGroupingAlgorithm & operator=(const FeatureGroupingAlgorithm &);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithmLabeled.h | .h | 1,767 | 56 | // 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/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithm.h>
namespace OpenMS
{
/**
@brief A map feature grouping algorithm for labeling techniques with two labels.
It takes one maps and searches for corresponding features with a defined distance in RT and m/z.
@htmlinclude OpenMS_FeatureGroupingAlgorithmLabeled.parameters
@ingroup FeatureGrouping
*/
class OPENMS_DLLAPI FeatureGroupingAlgorithmLabeled :
public FeatureGroupingAlgorithm
{
public:
/// Default constructor
FeatureGroupingAlgorithmLabeled();
/// Destructor
~FeatureGroupingAlgorithmLabeled() override;
/**
@brief Applies the algorithm
@note Exactly one @em input map has to be provided.
@note The @em output map has to have two file descriptions, containing
the same file name. The file descriptions have to be labeled 'heavy' and 'light'.
@exception Exception::IllegalArgument is thrown if the input data is not valid.
*/
void group(const std::vector<FeatureMap > & maps, ConsensusMap & out) override;
private:
///Copy constructor is not implemented -> private
FeatureGroupingAlgorithmLabeled(const FeatureGroupingAlgorithmLabeled &);
///Assignment operator is not implemented -> private
FeatureGroupingAlgorithmLabeled & operator=(const FeatureGroupingAlgorithmLabeled &);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/StablePairFinder.h | .h | 6,134 | 162 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: $
// --------------------------------------------------------------------------
#ifndef OPENMS_ANALYSIS_MAPMATCHING_STABLEPAIRFINDER_H
#define OPENMS_ANALYSIS_MAPMATCHING_STABLEPAIRFINDER_H
#include <OpenMS/ANALYSIS/MAPMATCHING/BaseGroupFinder.h>
namespace OpenMS
{
class AASequence;
/**
@brief This class implements a pair finding algorithm for consensus features.
It offers a method to determine pairs across two consensus maps. The corresponding consensus
features must be aligned, but may have small position deviations.
The distance measure is implemented in class @ref FeatureDistance - see there for details.
<B> Additional criteria for pairing </B>
Depending on parameter @p use_identifications, peptide identifications annotated to the
features may have to be compatible (i.e. no annotation or the same annotation) for a pairing
to occur.
Stability criterion: The distance to the nearest neighbor must be smaller than the distance
to the second-nearest neighbor by a certain factor, see parameter @p second_nearest_gap.
There is a non-trivial relation between this parameter and the maximum allowed difference
(in RT or m/z) of the distance measure: If @p second_nearest_gap is greater than one,
lowering @p max_difference may in fact lead to more - rather than fewer - pairings, because
it increases the distance difference between the nearest and the second-nearest neighbor, so
that the constraint imposed by @p second_nearest_gap may be fulfilled more often.
<B> Quality calculation </B>
The quality of a pairing is computed from the distance between the paired elements (nearest
neighbors) and the distances to the second-nearest neighbors of both elements, according to
the formula:
@f[
q_{i,j} = \big( 1 - d_{i,j} \big) \cdot
\big( 1 - \frac{g \cdot d_{i,j}}{d_{2,i}} \big) \cdot
\big( 1 - \frac{g \cdot d_{i,j}}{d_{2,j}} \big) \cdot
@f]
@f$ q_{i,j} @f$ is the quality of the pairing of elements @em i and @em j, @f$ d_{i,j} @f$ is
the distance between the two, @f$ d_{2,i} @f$ and @f$d_{2,j} @f$ are the distances to the
second-nearest neighbors of @em i and @em j, respectively, and @em g is the factor defined by
parameter @p second_nearest_gap.
Note that by the definition of the distance measure, @f$ 0 \leq d_{i,j} \leq 1 @f$ if @em i and
@em j are to form a pair. The criteria for pairing further require that
@f$ g \cdot d_{i,j} \leq d_{2,i} @f$ and @f$ g \cdot d_{i,j} \leq d_{2,j} @f$. This ensures that
the resulting quality is always between one (best) and zero (worst).
For the final quality @em q of the consensus feature produced by merging two paired elements
(@em i and @em j), the existing quality values of the two elements are taken into account. The
final quality is a weighted average of the existing qualities (@f$ q_i @f$ and @f$ q_j @f$) and
the quality of the pairing (@f$ q_{i,j} @f$, see above):
@f[
q = \frac{q_{i,j} + (s_i - 1) \cdot q_i + (s_j - 1) \cdot q_j}{s_i + s_j - 1}
@f]
The weighting factors @f$ s_i @f$ and @f$ s_j @f$ are the sizes (i.e. numbers of subelements)
of the two consensus features @em i and @em j. That way, it is possible to link several feature
maps to a growing consensus map in a stepwise fashion (as done by @ref
FeatureGroupingAlgorithmUnlabeled), and in the end obtain quality values that incorporate the
qualities of all pairings that occurred during the generation of a consensus feature. Note that
"missing" elements (if a consensus feature does not contain sub-features from all input maps)
are not punished in this definition of quality.
@htmlinclude OpenMS_StablePairFinder.parameters
@ingroup FeatureGrouping
*/
class OPENMS_DLLAPI StablePairFinder :
public BaseGroupFinder
{
public:
///Base class
typedef BaseGroupFinder Base;
/// Constructor
StablePairFinder();
/// Destructor
~StablePairFinder() override
{
}
/**
@brief Run the algorithm
@note Exactly two @em input maps must be provided.
@exception Exception::IllegalArgument is thrown if the input data is not valid.
*/
void run(const std::vector<ConsensusMap>& input_maps,
ConsensusMap& result_map) override;
protected:
///@name Internal helper classes and enums
//@{
enum
{
RT = Peak2D::RT,
MZ = Peak2D::MZ
};
//@}
//docu in base class
void updateMembers_() override;
/**
@brief Checks if the peptide IDs of two features are compatible.
A feature without identification is always compatible. Otherwise,
two features are compatible if the best peptide hits of their
identifications have the same sequences.
*/
bool compatibleIDs_(const ConsensusFeature& feat1,
const ConsensusFeature& feat2) const;
/// The distance to the second nearest neighbors must be by this factor larger than the distance to the matched element itself.
double second_nearest_gap_;
/// Only match if peptide IDs are compatible?
bool use_IDs_;
/**
@brief Returns the highest scoring peptide hit in the the given peptide identification.
@param[in] peptideIdentification The peptideIdentification to scan.
*/
const AASequence& getBestHitSequence_(const PeptideIdentification& peptideIdentification) const;
};
} // namespace OpenMS
#endif // OPENMS_ANALYSIS_MAPMATCHING_STABLEPAIRFINDER_H
/*
gnuplot history - how the plot was created - please do not delete this receipt
f(x,intercept,exponent)=1/(1+(abs(x)*intercept)**exponent)
set terminal postscript enhanced color
set output "choosingstablepairfinderparams.ps"
set size ratio .3
plot [-3:3] [0:1] f(x,1,1), f(x,2,1), f(x,1,2), f(x,2,2)
*/
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/MapAlignmentAlgorithmPoseClustering.h | .h | 2,978 | 88 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Eva Lange, Clemens Groepl $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/ANALYSIS/MAPMATCHING/TransformationDescription.h>
#include <OpenMS/ANALYSIS/MAPMATCHING/StablePairFinder.h>
#include <OpenMS/ANALYSIS/MAPMATCHING/PoseClusteringAffineSuperimposer.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/KERNEL/ConsensusMap.h>
#include <OpenMS/KERNEL/ConversionHelper.h>
namespace OpenMS
{
/**
@brief A map alignment algorithm based on pose clustering.
Pose clustering analyzes pair distances to find the most probable
transformation of retention times.
The algorithm chooses the x most intensity peaks/features per map. This is
modeled via the parameter 'max_num_peaks_considered', which in turn
influences the runtime and stability of the results. Bigger values prolong
computation, smaller values might lead to no or unstable trafos. Set to -1
to use all features (might take very long for large maps).
For further details see:
@n Eva Lange et al.
@n A Geometric Approach for the Alignment of Liquid Chromatography-Mass Spectrometry Data
@n ISMB/ECCB 2007
@htmlinclude OpenMS_MapAlignmentAlgorithmPoseClustering.parameters
@ingroup MapAlignment
*/
class OPENMS_DLLAPI MapAlignmentAlgorithmPoseClustering :
public DefaultParamHandler,
public ProgressLogger
{
public:
/// Default constructor
MapAlignmentAlgorithmPoseClustering();
/// Destructor
~MapAlignmentAlgorithmPoseClustering() override;
void align(const FeatureMap& map, TransformationDescription& trafo);
void align(const PeakMap& map, TransformationDescription& trafo);
void align(const ConsensusMap& map, TransformationDescription& trafo);
/// Sets the reference for the alignment
template <typename MapType>
void setReference(const MapType& map)
{
MapType map2 = map; // todo: avoid copy (MSExperiment version of convert() demands non-const version)
MapConversion::convert(0, map2, reference_, max_num_peaks_considered_);
}
protected:
void updateMembers_() override;
PoseClusteringAffineSuperimposer superimposer_;
StablePairFinder pairfinder_;
ConsensusMap reference_;
Int max_num_peaks_considered_;
private:
/// Copy constructor intentionally not implemented -> private
MapAlignmentAlgorithmPoseClustering(const MapAlignmentAlgorithmPoseClustering&);
/// Assignment operator intentionally not implemented -> private
MapAlignmentAlgorithmPoseClustering& operator=(const MapAlignmentAlgorithmPoseClustering&);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/QTClusterFinder.h | .h | 11,394 | 284 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hendrik Weisser $
// $Authors: Steffen Sass, Hendrik Weisser $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/ANALYSIS/MAPMATCHING/BaseGroupFinder.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/ML/CLUSTERING/HashGrid.h>
#include <OpenMS/DATASTRUCTURES/GridFeature.h>
#include <OpenMS/DATASTRUCTURES/QTCluster.h>
#include <OpenMS/ANALYSIS/MAPMATCHING/FeatureDistance.h>
#include <boost/heap/fibonacci_heap.hpp>
#include <unordered_map>
#include <list>
#include <vector>
#include <unordered_set>
#include <utility> // for pair<>
namespace OpenMS
{
/**
@brief A variant of QT clustering for the detection of feature groups.
The algorithm accumulates all features from all input maps, then applies a
variant of QT clustering to find groups of corresponding features. In more
detail, every feature from every input map is considered as a potential
cluster center. For every center, its nearest neighbors from the other input
maps are detected and added to the potential cluster. Iteratively, the
cluster with the highest quality is extracted and the clustering is updated.
<b>Properties affecting the grouping</b>
To be included in a particular cluster, a feature has to fulfill the following conditions:
@li differences in RT and m/z from the cluster center must be below
user-defined thresholds (@p distance_RT:max_difference and @p distance_MZ:max_difference),
@li the charge state must match that of the cluster center (unless @p
ignore_charge is set),
@li if @p use_identifications is set and both the feature and the cluster
center are annotated with peptide identifications, the identifications have
to match.
Every cluster contains at most one feature from each input map - namely the
feature closest to the cluster center that meets the criteria and does not
belong to a better cluster.
The notion of "closeness" for features is defined by the distance function
implemented in @ref FeatureDistance, the parameters of which can be set by
the user.
The quality of a cluster is computed from the number of elements in it and
their distances to the cluster center. For more details see QTCluster.
<b>Optimization</b>
This algorithm includes a number of optimizations to reduce run-time:
@li two-dimensional hashing of features,
@li a look-up table for feature distances,
@li a variant of QT clustering that requires only one round of clustering.
@see FeatureGroupingAlgorithmQT
@htmlinclude OpenMS_QTClusterFinder.parameters
@ingroup FeatureGrouping
*/
class OPENMS_DLLAPI QTClusterFinder :
public BaseGroupFinder
{
public:
/// Distances between pairs of grid features
typedef std::unordered_map<
std::pair<OpenMS::GridFeature*, OpenMS::GridFeature*>,
double> PairDistances;
/// Map to store which grid features are next to which clusters (saves the clusters ids)
typedef std::unordered_map<
const OpenMS::GridFeature*, std::unordered_set<Size> > ElementMapping;
/// Heap to efficiently find the best clusters
typedef boost::heap::fibonacci_heap<QTCluster> Heap;
typedef HashGrid<OpenMS::GridFeature*> Grid;
private:
/// Number of input maps
Size num_maps_;
/// Consider peptide identifications for grouping?
bool use_IDs_;
//TODO we could also bin by equal sized RT bins, or by a fixed RT size
//TODO could be made dependent on nr. of maps (e.g. with 5 maps you get [around] 4 diffs per ID already)
/// Min. nr. of differences from matched IDs requested to calculate a linking tolerance per RT bin
Size min_nr_diffs_per_bin_;
/// Min. score for an ID to be considered for tolerance estimation
double min_score_;
/// Distance penalty for unidentified features when finding best neighbor per map and for cluster quality calculation
/// and therefore the order in which they are popped from the heap.
/// Since distances are normalized, a penalty of 1.0 will always prefer IDed features.
double noID_penalty_;
/// Maximum RT difference
double max_diff_rt_;
/// Maximum m/z difference
double max_diff_mz_;
/// Maximum m/z difference
int nr_partitions_;
/// Feature distance functor
FeatureDistance feature_distance_;
/// Set of features already used
std::unordered_set<const OpenMS::GridFeature*> already_used_;
/// Map of median RTs to allowed linking tolerances (on the same RT scale) for unIDed features.
/// This should be interpreted as bins from the current median RT to the next.
std::map<double, double> bin_tolerances_;
/**
@brief Calculates the distance between two grid features.
*/
double getDistance_(const OpenMS::GridFeature* left, const
OpenMS::GridFeature* right);
/// Sets algorithm parameters
void setParameters_(double max_intensity, double max_mz);
/**
* @brief Extract the best cluster from cluster_heads and turn it into a consensus feature
*
* @param[in] cluster_heads the heap where the clusters are stored, must not be empty
* @param[out] feature The resulting consensus feature which is constructed here
* @param[in,out] element_mapping the element mapping is used to update clusters when features are removed
* @param[in] grid the grid is used to find new features for clusters that have to be updated
* @param[in] handles used to access clusters if we know their id from the element mapping
*
* @return bool whether a consensus feature was made or not
*/
bool makeConsensusFeature_(Heap& cluster_heads,
ConsensusFeature& feature,
ElementMapping& element_mapping,
const Grid& grid,
const std::vector<Heap::handle_type>& handles);
/**
* @brief Computes an initial QT clustering of the points in the hash grid
*
* @param[in,out] grid the grid is used to find new features for clusters that have to be updated
* @param[in,out] cluster_heads the heap where the QTClusters are inserted
* @param[in] cluster_data vector where the BulkData objects of the clusters are stored
* @param[out] handles vector where handles of the inserted clusters are stored
* @param[in] element_mapping the element mapping where all the clusters get registered for their features
*/
void computeClustering_(const Grid& grid,
Heap& cluster_heads,
std::vector<QTCluster::BulkData>& cluster_data,
std::vector<Heap::handle_type>& handles,
ElementMapping& element_mapping);
/**
* @brief Removes id of current top cluster in the heap from element mapping
*
* @param[in] cluster the current top cluster in the heap which id is removed
* @param[in] element_mapping the element mapping from which the ids are removed
*/
void removeFromElementMapping_(const QTCluster& cluster,
ElementMapping& element_mapping);
/**
* @brief creates a consensus feature from the given elements
*
* @param[out] feature The resulting consensus feature which is constructed here
* @param[in] quality the quality of the new consensus feature
* @param[in] elements the original features that from the new consensus feature
*
* @note the features from elements are registered in the already_used_ member of this class
*/
void createConsensusFeature_(ConsensusFeature& feature, const double quality,
const QTCluster::Elements& elements);
/**
* @brief update the clustering:
*
* 1. remove current best cluster from the heap
* 2. update all clusters accordingly by removing neighbors used by the current best
* 3. invalidate clusters whose center has been used by the current best
*
* @param[in] element_mapping the element mapping is used to update clusters and updated itself
* @param[in,out] grid the grid is used to find new features for clusters that have to be updated
* @param[in] cluster_heads the heap is updated for changing clusters and popped in the end
* @param[in] elements the features that now have to be removed from other clusters than the current best
* @param[in] handles used to access clusters if we know their id from the element mapping
* @param[in] best_id id of the current best cluster, will be removed from the element mapping
*
* @note The feature from elements are not deleted from the element mapping.
* After this function is called we don't have any cluster with those features left and
* therefore don't have to delete them.
*/
void updateClustering_(ElementMapping& element_mapping,
const Grid& grid,
const QTCluster::Elements& elements,
Heap& cluster_heads,
const std::vector<Heap::handle_type>& handles,
Size best_id);
/// Runs the algorithm on feature maps or consensus maps
template <typename MapType>
void run_(const std::vector<MapType>& input_maps, ConsensusMap& result_map);
/// Runs the algorithm on feature maps or consensus maps (internal)
template <typename MapType>
void run_internal_(const std::vector<MapType>& input_maps,
ConsensusMap& result_map, bool do_progress);
/**
* @brief Adds elements to the cluster based on the elements hashed in the grid
*
* @param[in,out] grid the grid is used to find neighboring features the cluster
* @param[in] cluster cluster to which the new elements are added
*/
void addClusterElements_(const Grid& grid, QTCluster& cluster);
/**
* @brief Looks up the matching bin for @p rt in bin_tolerances_ and checks if @p dist is in the allowed range.
*/
bool distIsOutlier_(double dist, double rt);
protected:
enum
{
RT = Peak2D::RT,
MZ = Peak2D::MZ
};
public:
/// Constructor
QTClusterFinder();
/// Destructor
~QTClusterFinder() override;
/**
@brief Runs the algorithm on consensus maps
@pre The data ranges of the input maps have to be up-to-date (use ConsensusMap::updateRanges).
@exception Exception::IllegalArgument is thrown if the input data is not valid.
*/
void run(const std::vector<ConsensusMap>& input_maps,
ConsensusMap& result_map) override;
/**
@brief Runs the algorithm on feature maps
@pre The data ranges of the input maps have to be up-to-date (use FeatureMap::updateRanges).
@exception Exception::IllegalArgument is thrown if the input data is not valid.
*/
void run(const std::vector<FeatureMap>& input_maps,
ConsensusMap& result_map);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/ConsensusMapNormalizerAlgorithmMedian.h | .h | 3,345 | 79 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Johannes Veit $
// $Authors: Johannes Junker $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/ConsensusMap.h>
#include <OpenMS/ANALYSIS/MAPMATCHING/ConsensusMapNormalizerAlgorithmThreshold.h>
namespace OpenMS
{
/**
* @brief Algorithms of ConsensusMapNormalizer
*
*/
class OPENMS_DLLAPI ConsensusMapNormalizerAlgorithmMedian
{
/// our friend can use our passesWhitelist_() method in order to avoid code duplication (without overdesigning this)
friend class ConsensusMapNormalizerAlgorithmThreshold;
private:
/// copy constructor is not implemented -> private
ConsensusMapNormalizerAlgorithmMedian(const ConsensusMapNormalizerAlgorithmMedian & copyin);
/// assignment operator is not implemented -> private
ConsensusMapNormalizerAlgorithmMedian & operator=(const ConsensusMapNormalizerAlgorithmMedian & rhs);
public:
/// default constructor is not implemented -> private
ConsensusMapNormalizerAlgorithmMedian();
/// destructor is not implemented -> private
virtual ~ConsensusMapNormalizerAlgorithmMedian();
/**
* @brief The NormalizationMethod enum
* Whether to scale to same median using division/multiplication or shift using subtraction/addition
*/
enum NormalizationMethod { NM_SCALE, NM_SHIFT };
/**
* @brief normalizes the maps of the consensusMap
* @param[in] map ConsensusMap
* @param[in] method whether to use scaling or shifting to same median
* @param[in] acc_filter string describing the regular expression for filtering accessions
* @param[in] desc_filter string describing the regular expression for filtering descriptions
*/
static void normalizeMaps(ConsensusMap & map, NormalizationMethod method, const String& acc_filter, const String& desc_filter);
/**
* @brief computes medians of all maps and returns index of map with most features
* @param[in] map ConsensusMap
* @param[out] medians vector of medians to be filled
* @param[in] acc_filter string describing the regular expression for filtering accessions
* @param[in] desc_filter string describing the regular expression for filtering descriptions
* @return index of map with largest number of features
*/
static Size computeMedians(const ConsensusMap & map, std::vector<double> & medians, const String& acc_filter, const String& desc_filter);
/**
* @brief returns whether consensus feature passes filters
* returns whether consensus feature @p cf_it in @p map passes accession
* regexp @p acc_filter and description regexp @p desc_filter
* @param[in] cf_it consensus feature
* @param[in] map consensus map
* @param[in] acc_filter string describing the regular expression for filtering accessions
* @param[in] desc_filter string describing the regular expression for filtering descriptions
*/
static bool passesFilters_(ConsensusMap::ConstIterator cf_it, const ConsensusMap& map, const String& acc_filter, const String& desc_filter);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithmUnlabeled.h | .h | 3,536 | 104 | // 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/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithm.h>
#include <OpenMS/KERNEL/ConversionHelper.h>
namespace OpenMS
{
/**
@brief A map feature grouping algorithm for unlabeled data.
It takes multiple maps and searches for corresponding features.
The corresponding features must be aligned, but may have small position deviations.
There are two ways to run the algorithm:
- a) Simply call "group" with all maps in memory.
- b) Call "setReference", "addToGroup" (n times), "getResultMap" in that order.
The second way is more memory efficient because at all times, only the
reference map and the current map need to be in memory
@htmlinclude OpenMS_FeatureGroupingAlgorithmUnlabeled.parameters
@ingroup FeatureGrouping
*/
class OPENMS_DLLAPI FeatureGroupingAlgorithmUnlabeled :
public FeatureGroupingAlgorithm
{
public:
/// Default constructor
FeatureGroupingAlgorithmUnlabeled();
/// Destructor
~FeatureGroupingAlgorithmUnlabeled() override;
/**
@brief Sets the reference map for the algorithm
This will store the input map in the first argument of the pairfinder_input_ vector.
Note that map_id needs to be unique (see addToGroup docu).
*/
template <typename MapType>
void setReference(int map_id, const MapType & map)
{
MapConversion::convert(map_id, map, pairfinder_input_[0]);
}
/**
@brief Returns the computed consensus map (after calling addToGroup with all maps)
*/
ConsensusMap & getResultMap()
{
return pairfinder_input_[0];
}
/**
@brief Applies the algorithm
@exception IllegalArgument is thrown if less than two input maps are given.
*/
void group(const std::vector<FeatureMap > & maps, ConsensusMap & out) override;
/**
@brief Adds one map to the group
This assumes that setReference has been called before. It is the callers
responsibility to provide a valid map_id. Note that all calls to
addToGroup _must_ use different map_ids and they all need to be
different from the one used to call setReference!
@exception IllegalArgument is thrown if the map_id has been used before
*/
void addToGroup(int map_id, const FeatureMap & feature_map);
private:
// This vector should always have 2 elements
// - the first element is the currently computed consensus map.
// After initialization of the algorithm, it will consist of the reference
// map alone, after adding all maps through addToGroup it will contain the
// final result (e.g. the consensus result of all maps).
// - the second element is the map which was last added to the consensus map
std::vector<ConsensusMap> pairfinder_input_;
/// Copy constructor intentionally not implemented -> private
FeatureGroupingAlgorithmUnlabeled(const FeatureGroupingAlgorithmUnlabeled &);
/// Assignment operator intentionally not implemented -> private
FeatureGroupingAlgorithmUnlabeled & operator=(const FeatureGroupingAlgorithmUnlabeled &);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/MapAlignmentEvaluationAlgorithmPrecision.h | .h | 1,580 | 48 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Katharina Albers $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/ANALYSIS/MAPMATCHING/MapAlignmentEvaluationAlgorithm.h>
namespace OpenMS
{
/**
@brief Caap evaluation algorithm to obtain a precision value.
It evaluates an input consensus map with respect to a ground truth.
@ingroup MapAlignment
*/
class OPENMS_DLLAPI MapAlignmentEvaluationAlgorithmPrecision :
public MapAlignmentEvaluationAlgorithm
{
public:
/// Default constructor
MapAlignmentEvaluationAlgorithmPrecision();
/// Destructor
~MapAlignmentEvaluationAlgorithmPrecision() override;
/**
@brief Applies the algorithm
*/
void evaluate(const ConsensusMap & consensus_map_in, const ConsensusMap & consensus_map_gt, const double & rt_dev, const double & mz_dev, const Peak2D::IntensityType & int_dev, const bool use_charge, double & out) override;
private:
/// Copy constructor intentionally not implemented -> private
MapAlignmentEvaluationAlgorithmPrecision(const MapAlignmentEvaluationAlgorithmPrecision &);
/// Assignment operator intentionally not implemented -> private
MapAlignmentEvaluationAlgorithmPrecision & operator=(const MapAlignmentEvaluationAlgorithmPrecision &);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/ConsensusMapNormalizerAlgorithmQuantile.h | .h | 2,469 | 67 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Johannes Veit $
// $Authors: Johannes Junker $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/ConsensusMap.h>
namespace OpenMS
{
/**
* @brief Algorithms of ConsensusMapNormalizer
*
*/
class OPENMS_DLLAPI ConsensusMapNormalizerAlgorithmQuantile
{
private:
/// copy constructor is not implemented -> private
ConsensusMapNormalizerAlgorithmQuantile(const ConsensusMapNormalizerAlgorithmQuantile & copyin);
/// assignment operator is not implemented -> private
ConsensusMapNormalizerAlgorithmQuantile & operator=(const ConsensusMapNormalizerAlgorithmQuantile & rhs);
public:
/// default constructor is not implemented -> private
ConsensusMapNormalizerAlgorithmQuantile();
/// destructor is not implemented -> private
virtual ~ConsensusMapNormalizerAlgorithmQuantile();
/**
* @brief normalizes the maps of the consensusMap
* @param[in,out] map ConsensusMap
*/
static void normalizeMaps(ConsensusMap & map);
/**
* @brief resamples data_in and writes the results to data_out
* @param[in] data_in the data to be resampled
* @param[out] data_out the results are written to this vector
* @param[in] n_resampling_points the number of points to resample from data_in
*/
static void resample(const std::vector<double> & data_in, std::vector<double> & data_out, UInt n_resampling_points);
/**
* @brief extracts the intensities of the features of the different maps
* @param[in] map ConsensusMap
* @param[out] out_intensities resulting data, contains the feature intensities for each map of the consensus map
*/
static void extractIntensityVectors(const ConsensusMap & map, std::vector<std::vector<double> > & out_intensities);
/**
* @brief writes the intensity values in feature_ints to the corresponding features in map
* @param[in] feature_ints contains the new feature intensities for each map of the consensus map
* @param[in] map ConsensusMap the map to be updated
*/
static void setNormalizedIntensityValues(const std::vector<std::vector<double> > & feature_ints, ConsensusMap & map);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/MapAlignmentAlgorithmIdentification.h | .h | 13,460 | 348 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hendrik Weisser $
// $Authors: Eva Lange, Clemens Groepl, Hendrik Weisser $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/ANALYSIS/MAPMATCHING/TransformationDescription.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
#include <OpenMS/KERNEL/ConsensusMap.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <OpenMS/METADATA/ID/IdentificationData.h>
#include <cmath> // for "abs"
#include <limits> // for "max"
#include <map>
namespace OpenMS
{
/* Concept for FeatureMap or ConsensusMap*/
template <typename MapType>
concept IsFCMap = std::same_as<MapType, OpenMS::FeatureMap> || std::same_as<MapType, OpenMS::ConsensusMap>;
class AnnotatedMSRun;
/**
@brief A map alignment algorithm based on peptide identifications from MS2 spectra.
PeptideIdentification instances are grouped by sequence of the respective best-scoring PeptideHit and retention time data is collected (PeptideIdentification::getRT()).
ID groups with the same sequence in different maps represent points of correspondence between the maps and form the basis of the alignment.
Only the best PSM per spectrum is considered as the correct identification.
Each map is aligned to a reference retention time scale.
This time scale can either come from a reference file (@p reference parameter) or be computed as a consensus of the input maps (median retention times over all maps of the ID groups).
The maps are then aligned to this scale as follows:\n
The median retention time of each ID group in a map is mapped to the reference retention time of this group.
Cubic spline smoothing is used to convert this mapping to a smooth function.
Retention times in the map are transformed to the consensus scale by applying this function.
@htmlinclude OpenMS_MapAlignmentAlgorithmIdentification.parameters
@ingroup MapAlignment
*/
class OPENMS_DLLAPI MapAlignmentAlgorithmIdentification :
public DefaultParamHandler,
public ProgressLogger
{
public:
/// Default constructor
MapAlignmentAlgorithmIdentification();
/// Destructor
~MapAlignmentAlgorithmIdentification() override;
// Set a reference for the alignment
template <typename DataType> void setReference(const DataType& data)
{
reference_.clear();
if (data.empty()) return; // empty input resets the reference
SeqToList rt_data;
// set these here because "checkParameters_" may not have been called yet:
use_feature_rt_ = param_.getValue("use_feature_rt").toBool();
score_cutoff_ = param_.getValue("score_cutoff").toBool();
score_type_ = (std::string)param_.getValue("score_type");
bool sorted = getRetentionTimes_(data, rt_data);
computeMedians_(rt_data, reference_, sorted);
if (reference_.empty())
{
throw Exception::MissingInformation(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not extract retention time information from the reference file");
}
}
/**
@brief Align feature maps, consensus maps, or peptide identifications.
@param[in] data Vector of input data (FeatureMap, ConsensusMap, or @p PeptideIdentificationList) that should be aligned.
@param[in] transformations Vector of RT transformations that will be computed.
@param[in] reference_index Index in @p data of the reference to align to, if any
@throw Exception::MissingInformation Not enough suitable RT data to perform alignment
*/
template <typename DataType>
void align(const std::vector<DataType>& data,
std::vector<TransformationDescription>& transformations,
Int reference_index = -1)
{
checkParameters_(data.size());
startProgress(0, 3, "aligning maps");
reference_index_ = reference_index;
// is reference one of the input files?
bool use_internal_reference = (reference_index >= 0);
if (use_internal_reference)
{
if (reference_index >= Int(data.size()))
{
throw Exception::IndexOverflow(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION,
reference_index, data.size());
}
setReference(data[reference_index]);
}
// one set of RT data for each input map, except reference (if any):
std::vector<SeqToList> rt_data(data.size() - use_internal_reference);
bool all_sorted = true;
for (Size i = 0, j = 0; i < data.size(); ++i)
{
if ((reference_index >= 0) && (i == Size(reference_index)))
{
continue; // skip reference map, if any
}
all_sorted &= getRetentionTimes_(data[i], rt_data[j++]);
}
setProgress(1);
computeTransformations_(rt_data, transformations, all_sorted);
setProgress(2);
setProgress(3);
endProgress();
}
protected:
/// Type to store retention times given for individual peptide sequences
typedef std::map<String, DoubleList> SeqToList;
/// Type to store one representative retention time per peptide sequence
typedef std::map<String, double> SeqToValue;
/// Index of input file to use as reference (if any)
Int reference_index_;
/// Reference retention times (per peptide sequence)
SeqToValue reference_;
/// Minimum number of runs a peptide must occur in
Size min_run_occur_;
/// Use feature RT instead of RT from best peptide ID in the feature?
bool use_feature_rt_{};
/// Consider differently adducted IDs as different?
bool use_adducts_{};
/// Minimum score to reach for a peptide to be considered
double min_score_;
/// Actually use the above defined score_cutoff? Needed since it is hard to define a non-cutting score for a user.
bool score_cutoff_{};
/// Score type to use for filtering
String score_type_;
/// Score better?
bool (*better_) (double, double) = [](double, double) {return true;};
/**
@brief Compute the median retention time for each peptide sequence
@param[in] rt_data Lists of RT values for diff. peptide sequences (input, will be sorted)
@param[out] medians Median RT values for the peptide sequences (output)
@param[in] sorted Are RT lists already sorted?
@throw Exception::IllegalArgument if the input list is empty
*/
void computeMedians_(SeqToList& rt_data, SeqToValue& medians,
bool sorted = false);
/**
@brief Collect retention time data from peptide IDs
@param[in] peptides Input peptide IDs (lists of peptide hits will be sorted)
@param[out] rt_data Lists of RT values for diff. peptide sequences (output)
@return Are the RTs already sorted? (Here: false)
*/
bool getRetentionTimes_(const PeptideIdentificationList& peptides,
SeqToList& rt_data);
/**
@brief Collect retention time data from spectrum matches
@param[in] id_data Input identification data
@param[out] rt_data Lists of RT values for diff. spectrum matches (output)
@return Are the RTs already sorted? (Here: false)
*/
// "id_data" can't be "const" here or template resolution will fail
bool getRetentionTimes_(const IdentificationData& id_data, SeqToList& rt_data);
/**
@brief Collect retention time data from peptide IDs contained in feature maps or consensus maps
The following global flags (mutually exclusive) influence the processing:\n
Depending on @p use_unassigned_peptides, unassigned peptide IDs are used in addition to IDs annotated to features.\n
Depending on @p use_feature_rt, feature retention times are used instead of peptide retention times.
Depending on @p score_cutoff and min_score, only peptide IDs with minimum score X are used. Higher score better is
determined from the first PeptideID encountered. Make sure they are the same. This param is useless with use_feature_rt yet.
@param[in] features Input features for RT data
@param[out] rt_data Lists of RT values for diff. peptide sequences (output)
@return Are the RTs already sorted? (Here: true)
*/
bool getRetentionTimes_(const IsFCMap auto& features, SeqToList& rt_data)
{
if (!score_cutoff_)
{
better_ = [](double, double)
{return true;};
}
else if (features[0].getPeptideIdentifications()[0].isHigherScoreBetter())
{
better_ = [](double a, double b)
{ return a >= b; };
}
else
{
better_ = [](double a, double b)
{ return a <= b; };
}
for (auto feat_it = features.cbegin(); feat_it != features.cend(); ++feat_it)
{
if (use_feature_rt_)
{
// find the peptide ID closest in RT to the feature centroid:
String sequence;
double rt_distance = std::numeric_limits<double>::max();
bool any_hit = false;
for (PeptideIdentificationList::const_iterator pep_it =
feat_it->getPeptideIdentifications().begin(); pep_it !=
feat_it->getPeptideIdentifications().end(); ++pep_it)
{
if (!pep_it->getHits().empty())
{
any_hit = true;
double current_distance = fabs(pep_it->getRT() -
feat_it->getRT());
if (current_distance < rt_distance)
{
const PeptideHit* best_hit = getBestScoringHit(pep_it->getHits(), pep_it->isHigherScoreBetter());
if (best_hit && better_(best_hit->getScore(), min_score_))
{
sequence = best_hit->getSequence().toString();
rt_distance = current_distance;
}
}
}
}
if (any_hit) rt_data[sequence].push_back(feat_it->getRT());
}
else
{
getRetentionTimes_(feat_it->getPeptideIdentifications(), rt_data);
}
}
if (!use_feature_rt_ &&
param_.getValue("use_unassigned_peptides").toBool())
{
getRetentionTimes_(features.getUnassignedPeptideIdentifications(),
rt_data);
}
// remove duplicates (can occur if a peptide ID was assigned to several
// features due to overlap or annotation tolerance):
for (SeqToList::iterator rt_it = rt_data.begin(); rt_it != rt_data.end();
++rt_it)
{
DoubleList& rt_values = rt_it->second;
sort(rt_values.begin(), rt_values.end());
DoubleList::iterator it = unique(rt_values.begin(), rt_values.end());
rt_values.resize(it - rt_values.begin());
}
return true; // RTs were already sorted for duplicate detection
}
/**
@brief Compute retention time transformations from RT data grouped by peptide sequence
@param[in] rt_data Lists of RT values for diff. peptide sequences, per dataset (input, will be sorted)
@param[out] transforms Resulting transformations, per dataset (output)
@param[in] sorted Are RT lists already sorted?
*/
void computeTransformations_(std::vector<SeqToList>& rt_data,
std::vector<TransformationDescription>&
transforms, bool sorted = false);
/**
@brief Check that parameter values are valid
Currently only 'min_run_occur' is checked.
@param[in] runs Number of runs (input files) to be aligned
*/
void checkParameters_(const Size runs);
/**
@brief Get reference retention times
If a reference file is supplied via the @p reference parameter, extract retention time information and store it in #reference_.
*/
void getReference_();
/**
@brief Helper function to find/define the score type for processing IdentificationData
@return Reference to the score type denoted by algorithm parameter "score_type"
*/
IdentificationData::ScoreTypeRef handleIdDataScoreType_(const IdentificationData& id_data);
/**
@brief Get the best-scoring PeptideHit from a list of hits
@param[in] hits List of peptide hits
@param[in] is_higher_score_better Decides if higher score is better in deciding best scoring hit
@return Pointer to the best-scoring hit, or nullptr if the list is empty
*/
const PeptideHit* getBestScoringHit(const std::vector<PeptideHit>& hits, const bool is_higher_score_better);
private:
/// Copy constructor intentionally not implemented -> private
MapAlignmentAlgorithmIdentification(const MapAlignmentAlgorithmIdentification&);
///Assignment operator intentionally not implemented -> private
MapAlignmentAlgorithmIdentification& operator=(const MapAlignmentAlgorithmIdentification&);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithmQT.h | .h | 2,801 | 77 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hendrik Weisser $
// $Authors: Steffen Sass, Hendrik Weisser $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithm.h>
namespace OpenMS
{
/**
@brief A feature grouping algorithm for unlabeled data.
The algorithm takes a number of feature or consensus maps and searches for corresponding (consensus) features across different maps. The maps have to be aligned (i.e. retention time distortions corrected,
using one of the map-alignment algorithms, e.g. @ref MapAlignmentAlgorithmKD), but small deviations are tolerated.
This particular algorithm accumulates the features from all input maps, then applies a variant of QT clustering to find groups of corresponding features. For more details, see QTClusterFinder.
@htmlinclude OpenMS_FeatureGroupingAlgorithmQT.parameters
@ingroup FeatureGrouping
*/
class OPENMS_DLLAPI FeatureGroupingAlgorithmQT :
public FeatureGroupingAlgorithm
{
public:
/// Default constructor
FeatureGroupingAlgorithmQT();
/// Destructor
~FeatureGroupingAlgorithmQT() override;
/**
@brief Applies the algorithm to feature maps
@pre The data ranges of the input maps have to be up-to-date (use FeatureMap::updateRanges).
@exception IllegalArgument is thrown if less than two input maps are given.
*/
void group(const std::vector<FeatureMap>& maps, ConsensusMap& out) override;
/**
@brief Applies the algorithm to consensus maps
@pre The data ranges of the input maps have to be up-to-date (use ConsensusMap::updateRanges).
@exception IllegalArgument is thrown if less than two input maps are given.
*/
void group(const std::vector<ConsensusMap>& maps,
ConsensusMap& out) override;
private:
/// Copy constructor intentionally not implemented -> private
FeatureGroupingAlgorithmQT(const FeatureGroupingAlgorithmQT&);
/// Assignment operator intentionally not implemented -> private
FeatureGroupingAlgorithmQT& operator=(const FeatureGroupingAlgorithmQT&);
/**
@brief Applies the algorithm to feature or consensus maps
@pre The data ranges of the input maps have to be up-to-date (use MapType::updateRanges).
@exception IllegalArgument is thrown if less than two input maps are given.
*/
template <typename MapType>
void group_(const std::vector<MapType>& maps, ConsensusMap& out);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/TransformationModelBSpline.h | .h | 1,745 | 62 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hendrik Weisser $
// $Authors: Hendrik Weisser $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/config.h> // is this needed?
#include <OpenMS/ANALYSIS/MAPMATCHING/TransformationModel.h>
#include <OpenMS/MATH/MISC/BSpline2d.h>
namespace OpenMS
{
/**
@brief B-spline (non-linear) model for transformations
@ingroup MapAlignment
*/
class OPENMS_DLLAPI TransformationModelBSpline :
public TransformationModel
{
public:
/**
@brief Constructor
@exception Exception::IllegalArgument is thrown if a parameter is invalid.
@exception Exception::UnableToFit is thrown if the B-spline fit fails.
*/
TransformationModelBSpline(const DataPoints& data, const Param& params);
/// Destructor
~TransformationModelBSpline() override;
/// Evaluates the model at the given value
double evaluate(double value) const override;
using TransformationModel::getParameters;
/// Gets the default parameters
static void getDefaultParameters(Param& params);
protected:
/// Pointer to the actual B-spline
BSpline2d* spline_;
/// Min./max. x value (endpoints of the data range)
double xmin_, xmax_;
/// Method to use for extrapolation (beyond 'xmin_'/'xmax_')
enum { EX_LINEAR, EX_BSPLINE, EX_CONSTANT, EX_GLOBAL_LINEAR } extrapolate_;
/// Parameters for constant or linear extrapolation
double offset_min_, offset_max_, slope_min_, slope_max_;
};
} // namespace
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/TransformationDescription.h | .h | 8,343 | 198 | // 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, Hendrik Weisser $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/Param.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
#include <OpenMS/ANALYSIS/MAPMATCHING/TransformationModel.h>
#include <iosfwd>
#include <map>
namespace OpenMS
{
/**
@brief Generic description of a coordinate transformation.
This description primarily stores data points (coordinate pairs) from which a @ref TransformationModel "transformation model" can be estimated. Applying the transformation to a coordinate (via @p apply) then means evaluating the model at that coordinate.
The following models are available:
- @p none (TransformationModel): \f$ f(x) = x \f$ (identity)
- @p identity: Same as @p none, but intended for reference files (used to indicate that no other model should be fit, because the identity is already optimal).
- @p linear (TransformationModelLinear): \f$ f(x) = slope * x + intercept \f$
- @p interpolated (TransformationModelInterpolated): Interpolation between pairs, extrapolation using first and last pair. Supports different interpolation types.
- @p b-spline (TransformationModelBSpline): Non-linear smoothing spline, with different options for extrapolation.
- @b lowess (TransformationModelLowess): Non-linear smoothing via local regression, with different options for extrapolation.
@remark TransformationDescription stores data points, TransformationModel stores parameters. That way, data can be modeled using different models/parameters, and models can still keep a representation of the data in the format they need (if at all).
@ingroup MapAlignment
*/
class OPENMS_DLLAPI TransformationDescription
{
// friend class MapAlignmentAlgorithm;
public:
/** @brief Summary statistics before/after applying the transformation.
For deviations before/after transformation, the percentiles
100, 99, 95, 90, 75, 50, 25 are returned.
*/
struct TransformationStatistics
{
// default constructor
TransformationStatistics() = default;
// copy constructor
TransformationStatistics(const TransformationStatistics& rhs) = default;
// copy assignment
TransformationStatistics& operator=(const TransformationStatistics& rhs) = default;
std::vector<Size> percents = {100, 99, 95, 90, 75, 50, 25}; // TODO: use constexpr array
double xmin = 0; ///< smallest x value before transformation
double xmax = 0; ///< largest x value before transformation
double ymin = 0; ///< smallest y value before transformation
double ymax = 0; ///< largest y value before transformation
std::map<Size, double> percentiles_before; ///< percentiles of x/y deviations before transformation
std::map<Size, double> percentiles_after; ///< percentiles of x/y deviations after transformation
};
/// Coordinate pair
typedef TransformationModel::DataPoint DataPoint;
/// Vector of coordinate pairs
typedef TransformationModel::DataPoints DataPoints;
/// Default constructor
TransformationDescription();
/// Constructor from data
explicit TransformationDescription(const DataPoints& data);
/// Destructor
~TransformationDescription();
/// Copy constructor
TransformationDescription(const TransformationDescription& rhs);
/// Assignment operator
TransformationDescription& operator=(const TransformationDescription& rhs);
/// Fits a model to the data
void fitModel(const String& model_type, const Param& params = Param());
/**
@brief Applies the transformation to @p value.
Returns the result of evaluating the fitted model at @p value.
Returns @p value unchanged if no model was fitted.
*/
double apply(double value) const;
/// Gets the type of the fitted model
const String& getModelType() const;
/// Gets the possible types of models
static void getModelTypes(StringList& result);
/**
@brief Sets the data points
Removes the model that was previously fitted to the data (if any).
*/
void setDataPoints(const DataPoints& data);
/**
@brief Sets the data points (backwards-compatible overload)
Removes the model that was previously fitted to the data (if any).
*/
void setDataPoints(const std::vector<std::pair<double, double> >& data);
/// Returns the data points
const DataPoints& getDataPoints() const;
/// Non-mutable access to the model parameters
const Param& getModelParameters() const;
/// Computes an (approximate) inverse of the transformation
void invert();
/**
@brief Get the deviations between the data pairs
@param[out] diffs Output
@param[in] do_apply Get deviations after applying the model?
@param[in] do_sort Sort @p diffs before returning?
*/
void getDeviations(std::vector<double>& diffs, bool do_apply = false,
bool do_sort = true) const;
/// Get summary statistics (ranges and errors before/after)
TransformationStatistics getStatistics() const;
/// Print summary statistics for the transformation
void printSummary(std::ostream& os) const;
/**
@brief Estimate a coordinate-transformation, residual-based extraction window.
Given stored data points (x_i, y_i) and a fitted transform T relating them,
this computes absolute residuals between experimental and theoretical
coordinates and returns an extraction window derived from a chosen quantile. \n
Residual definition: \n
- If invert == false: r_i = | T(x_i) - y_i | (in transformed y units) \n
- If invert == true : r_i = | x_i - T^{-1}(y_i) | (in original x units) \n
The window is computed using an adaptive quantile that is robust to sparse outliers
but permissive when tails are genuinely dense: \n
1) Let |r| be the absolute residuals. Compute the Tukey upper fence
UF = Q3 + k*IQR (with k = 1.5). \n
2) Compute: \n
- h_raw = quantile(|r|, q) \n
- h_rob = quantile(winsorize(|r|, UF), q), where values above UF are capped at UF
(lower cap is 0 for absolute residuals). \n
3) Let tail = fraction(|r| > UF). Blend h = (1 - w)*h_rob + w*h_raw with a weight w
that increases linearly from 0 at tail <= 1% (favor robust) to 1 at tail >= 10% (favor raw).
If UF is undefined (too few points or IQR <= 0), the method falls back to the raw quantile. \n
The chosen quantile q (e.g. 0.99) is interpreted as a half-width h such that
approximately q*100% of residuals satisfy |r| <= h. If full_window is true, the function
returns 2*h (full width), otherwise h (half-width). The padding_factor multiplies the final result. \n
Typical usage: \n
- RT: set invert = true to obtain residuals in seconds (original x units). \n
- IM: same pattern; units are the instrument’s native mobility units (e.g., 1/k0). \n
@param[in] quantile Quantile of |residual| to use (0 < quantile ≤ 1), e.g. 0.99.
@param[in] invert If true, compute residuals in original x-units via T^{-1};
otherwise compute in transformed y-units via T.
@param[in] full_window If true, return full width (2·half-width); else return half-width.
@param[in] padding_factor A padding factor to add to the estimated window.
@return Estimated window (in the units implied by @p invert).
If no data points are available, returns 0.0.
*/
double estimateWindow(double quantile = 0.99,
bool invert = true,
bool full_window = true,
double padding_factor = 1.0) const;
protected:
/// Data points
DataPoints data_;
/// Type of model
String model_type_;
/// Pointer to model
TransformationModel* model_;
};
} // end of namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/BaseSuperimposer.h | .h | 1,731 | 65 | // 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/ANALYSIS/MAPMATCHING/TransformationDescription.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/KERNEL/ConsensusMap.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <utility>
#include <fstream>
namespace OpenMS
{
/**
@brief The base class of all superimposer algorithms.
This class defines the basic interface for all superimposer algorithms. It
works on several element maps and computes transformations that map the
elements of the maps as near as possible to each other.
*/
class OPENMS_DLLAPI BaseSuperimposer :
public DefaultParamHandler,
public ProgressLogger
{
public:
/// Constructor
BaseSuperimposer();
/// Destructor
~BaseSuperimposer() override;
/**
@brief Estimates the transformation between input @p maps and returns the
estimated transformations
@exception IllegalArgument is thrown if the input maps are invalid.
*/
virtual void run(const ConsensusMap& map_model, const ConsensusMap& map_scene, TransformationDescription& transformation) = 0;
private:
/// Copy constructor intentionally not implemented
BaseSuperimposer(const BaseSuperimposer&);
/// Assignment operator intentionally not implemented
BaseSuperimposer& operator=(const BaseSuperimposer&);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithmKD.h | .h | 6,288 | 226 | // 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/ANALYSIS/MAPMATCHING/FeatureGroupingAlgorithm.h>
#include <OpenMS/ANALYSIS/QUANTITATION/KDTreeFeatureMaps.h>
#include <OpenMS/ANALYSIS/MAPMATCHING/FeatureDistance.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
namespace OpenMS
{
///
/**
@brief Proxy for a (potential) cluster.
Proxy for a (potential) cluster. Instead of storing the entire cluster,
this stores only its size, average distance to center, and the index of
the center point. Objects of this class are kept in a sorted binary search
tree (aka std::set) and operator< is defined in such a way that the first
element of the set is always a cluster proxy for a cluster of current
maximum size and smallest intra-cluster distance. The actual cluster points
are then retrieved again from the kd-tree and a consensus feature is added
to the output consensus map.
*/
class OPENMS_DLLAPI ClusterProxyKD
{
public:
/// Default constructor
ClusterProxyKD() :
size_(0), // => isValid() returns false
avg_distance_(0),
center_index_(0)
{
}
/// Constructor
ClusterProxyKD(Size size, double avg_distance, Size center_index) :
size_(size),
avg_distance_(avg_distance),
center_index_(center_index)
{
}
/// Copy constructor
ClusterProxyKD(const ClusterProxyKD& rhs) :
size_(rhs.size_),
avg_distance_(rhs.avg_distance_),
center_index_(rhs.center_index_)
{
}
/// Destructor (non-virtual to save memory)
~ClusterProxyKD()
{
}
/// Assignment operator
ClusterProxyKD& operator=(const ClusterProxyKD& rhs)
{
size_ = rhs.size_;
avg_distance_ = rhs.avg_distance_;
center_index_ = rhs.center_index_;
return *this;
}
/// Less-than operator for sorting / equality check in std::set. We use the ordering in std::set as a "priority queue", hence a < b means cluster a will be preferred over b.
bool operator<(const ClusterProxyKD& rhs) const
{
if (size_ > rhs.size_) return true;
if (size_ < rhs.size_) return false;
if (avg_distance_ < rhs.avg_distance_) return true;
if (avg_distance_ > rhs.avg_distance_) return false;
// arbitrary, but required for finding unambiguous elements in std::set
if (center_index_ > rhs.center_index_) return true;
if (center_index_ < rhs.center_index_) return false;
// they are equal
return false;
}
/// Inequality operator
bool operator!=(const ClusterProxyKD& rhs) const
{
return *this < rhs || rhs < *this;
}
/// Equality operator
bool operator==(const ClusterProxyKD& rhs) const
{
return !(*this != rhs);
}
/// Cluster size
Size getSize() const
{
return size_;
}
/// Valid?
bool isValid() const
{
return size_;
}
/// Average distance to center
double getAvgDistance() const
{
return avg_distance_;
}
/// Index of center point
Size getCenterIndex() const
{
return center_index_;
}
private:
/// Cluster size
Size size_;
/// Average distance to center
double avg_distance_;
/// Index of center point
Size center_index_;
};
/**
@brief A feature grouping algorithm for unlabeled data.
The algorithm takes a number of feature or consensus maps and searches
for corresponding (consensus) features across different maps.
@htmlinclude OpenMS_FeatureGroupingAlgorithmKD.parameters
@ingroup FeatureGrouping
*/
class OPENMS_DLLAPI FeatureGroupingAlgorithmKD :
public FeatureGroupingAlgorithm,
public ProgressLogger
{
public:
/// Default constructor
FeatureGroupingAlgorithmKD();
/// Destructor
~FeatureGroupingAlgorithmKD() override;
/**
@brief Applies the algorithm to feature maps
@exception IllegalArgument is thrown if less than two input maps are given.
*/
void group(const std::vector<FeatureMap>& maps, ConsensusMap& out) override;
/**
@brief Applies the algorithm to consensus maps
@exception IllegalArgument is thrown if less than two input maps are given.
*/
void group(const std::vector<ConsensusMap>& maps,
ConsensusMap& out) override;
private:
/// Copy constructor intentionally not implemented -> private
FeatureGroupingAlgorithmKD(const FeatureGroupingAlgorithmKD&);
/// Assignment operator intentionally not implemented -> private
FeatureGroupingAlgorithmKD& operator=(const FeatureGroupingAlgorithmKD&);
/**
@brief Applies the algorithm to feature or consensus maps
@exception IllegalArgument is thrown if less than two input maps are given.
*/
template <typename MapType>
void group_(const std::vector<MapType>& input_maps, ConsensusMap& out);
/// Run the actual clustering algorithm
void runClustering_(const KDTreeFeatureMaps& kd_data, ConsensusMap& out);
/// Update maximum possible sizes of potential consensus features for indices specified in @p update_these
void updateClusterProxies_(std::set<ClusterProxyKD>& potential_clusters, std::vector<ClusterProxyKD>& cluster_for_idx, const std::set<Size>& update_these, const std::vector<Int>& assigned, const KDTreeFeatureMaps& kd_data);
/// Compute the current best cluster with center index @p i (mutates @p proxy and @p cf_indices)
ClusterProxyKD computeBestClusterForCenter_(Size i, std::vector<Size>& cf_indices, const std::vector<Int>& assigned, const KDTreeFeatureMaps& kd_data) const;
/// Construct consensus feature and add to out map
void addConsensusFeature_(const std::vector<Size>& indices, const KDTreeFeatureMaps& kd_data, ConsensusMap& out) const;
/// Current progress for logging
SignedSize progress_;
/// RT tolerance
double rt_tol_secs_;
/// m/z tolerance
double mz_tol_;
/// m/z unit ppm?
bool mz_ppm_;
/// Feature distance functor
FeatureDistance feature_distance_;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/TransformationModelLowess.h | .h | 4,030 | 119 | // 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> // is this needed?
#include <OpenMS/ANALYSIS/MAPMATCHING/TransformationModel.h>
#include <OpenMS/ANALYSIS/MAPMATCHING/TransformationModelInterpolated.h>
namespace OpenMS
{
/**
@brief Lowess (non-linear) model for transformations
@ingroup MapAlignment
*/
class OPENMS_DLLAPI TransformationModelLowess :
public TransformationModel
{
public:
/**
@brief Constructor
@exception Exception::IllegalArgument is thrown if too few data points are provided.
*/
TransformationModelLowess(const DataPoints& data, const Param& params);
/// Destructor
~TransformationModelLowess() override;
/// Evaluates the model at the given value
double evaluate(double value) const override
{
return model_->evaluate(value);
}
using TransformationModel::getParameters;
/// Gets the default parameters
static void getDefaultParameters(Param& params);
private:
// Hide helper utilities from public API. Defined in the .cpp.
/// @cond INTERNAL
/**
@brief Build the candidate LOWESS span grid with neighbor-based flooring and min/max clamping.
Rules applied:
- If @p grid_str is empty, use a sensible default grid.
- Enforce a lower bound based on both @p span_min_param and the minimum number
of neighbors in the window: `lower = max(span_min_param, min(0.9, min_neighbors/n_pts))`.
- Clamp candidates to `[lower, span_max_param]`, with an additional safety cap at `0.99`.
- Sort and de-duplicate candidates with a small tolerance.
- Guarantee a non-empty result by falling back to a single value if necessary.
@param[in] n_pts Number of data points available.
@param[in] grid_str Span candidates in (0, 1). If empty, a default span grid is used.
@param[in] span_min_param Minimum allowed span (will be raised to at least `0.01`).
@param[in] span_max_param Maximum allowed span (will be lowered to at most `0.99`).
@param[in] min_neighbors Minimum number of neighbors to include in each local regression.
@return Vector of candidate spans after clamping and de-duplication.
*/
static std::vector<double> buildSpanGrid(Size n_pts,
const std::vector<double>& candidate_spans,
double span_min_param,
double span_max_param,
int min_neighbors);
/// Cross-validation metric for auto-span selection
enum class CVMetric
{
RMSE,
MAE,
P90,
P95,
P99,
SIZE_OF_CVMETRIC
};
static const std::array<std::string, (Size)CVMetric::SIZE_OF_CVMETRIC> names_of_cvmetric;
/**
@brief Score absolute residuals according to the selected metric.
Supported @p metric values:
- `"rmse"`: root mean square of errors (vs zero)
- `"mae"` : mean absolute error
- `"p90"`, `"p95"`, `"p99"`: corresponding empirical quantiles of |errors|
If @p errs is empty, returns `+inf` to signal an unusable model fit.
@param[in] errs Absolute residuals (validation errors).
@param[in] metric Metric name (`"rmse"`, `"mae"`, `"p90"`, `"p95"`, `"p99"`).
@return Scalar loss; lower values indicate better fit.
*/
static double scoreResiduals(const std::vector<double>& errs, CVMetric metric);
/// Numerical tie tolerance for CV score comparisons (absolute difference)
static constexpr double kTieTol = 1e-12;
/// @endcond
protected:
/// Pointer to the underlying interpolation
TransformationModelInterpolated* model_;
};
} // namespace
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/MapAlignmentTransformer.h | .h | 3,465 | 91 | // 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 <vector>
#include <OpenMS/config.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/METADATA/MetaInfoInterface.h>
#include <OpenMS/METADATA/ID/IdentificationData.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
namespace OpenMS
{
class TransformationDescription;
class ConsensusMap;
class PeptideIdentification;
class ConsensusFeature;
/**
* @brief This class collects functions for applying retention time transformations to data structures.
*/
class OPENMS_DLLAPI MapAlignmentTransformer
{
public:
/// Applies the given transformation to a peak map
static void transformRetentionTimes(PeakMap& msexp,
const TransformationDescription& trafo,
bool store_original_rt = false);
/// Applies the given transformation to a feature map
static void transformRetentionTimes(FeatureMap& fmap,
const TransformationDescription& trafo,
bool store_original_rt = false);
/// Applies the given transformation to a consensus map
static void transformRetentionTimes(ConsensusMap& cmap,
const TransformationDescription& trafo,
bool store_original_rt = false);
/// Applies the given transformation to peptide identifications
static void transformRetentionTimes(
PeptideIdentificationList& pep_ids,
const TransformationDescription& trafo, bool store_original_rt = false);
/// Applies the given transformation to input items in IdentificationData
static void transformRetentionTimes(IdentificationData& id_data,
const TransformationDescription& trafo,
bool store_original_rt = false);
private:
/// Applies a transformation to a feature
static void applyToFeature_(Feature& feature,
const TransformationDescription& trafo,
bool store_original_rt = false);
/// Applies a transformation to a basic feature
static void applyToBaseFeature_(BaseFeature& feature,
const TransformationDescription& trafo,
bool store_original_rt = false);
/// Applies a transformation to a consensus feature
static void applyToConsensusFeature_(
ConsensusFeature& feature, const TransformationDescription& trafo,
bool store_original_rt = false);
/**
@brief Stores the original RT in a meta value
The original RT is written to a meta value "original_RT", but only if that meta value doesn't already exist.
@returns True if the meta value was written, false if it already exists.
*/
static bool storeOriginalRT_(MetaInfoInterface& meta_info,
double original_rt);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/BaseGroupFinder.h | .h | 2,119 | 76 | // 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/KERNEL/ConsensusMap.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <utility>
#include <fstream>
namespace OpenMS
{
/**
@brief The base class of all element group finding algorithms.
This class defines the basic interface for all element group finding
algorithms.
All derived algorithms take one or several consensus maps and find
corresponding features across the maps (or within one map). They return one
consensus map containing the found consensus features.
The element indices of the result consensus features are the container
access indices of the input maps. The map indices of the result consensus
features are are the indices in the input map vector.
*/
class OPENMS_DLLAPI BaseGroupFinder :
public DefaultParamHandler,
public ProgressLogger
{
public:
/// Default constructor
BaseGroupFinder();
/// Destructor
~BaseGroupFinder() override;
/**
@brief Run the algorithm
@exception Exception::IllegalArgument is thrown if the input data is not valid.
*/
virtual void run(const std::vector<ConsensusMap> & input, ConsensusMap & result) = 0;
protected:
/**
@brief Checks if all file descriptions have disjoint map identifiers
@exception Exception::IllegalArgument Is thrown if a file id is found twice
*/
void checkIds_(const std::vector<ConsensusMap> & maps) const;
private:
/// Copy constructor intentionally not implemented
BaseGroupFinder(const BaseGroupFinder &);
/// Assignment operator intentionally not implemented
BaseGroupFinder & operator=(const BaseGroupFinder &);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/PoseClusteringAffineSuperimposer.h | .h | 2,726 | 80 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Eva Lange, Clemens Groepl $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/ANALYSIS/MAPMATCHING/BaseSuperimposer.h>
#include <OpenMS/KERNEL/ConsensusMap.h>
#include <OpenMS/KERNEL/Peak2D.h>
namespace OpenMS
{
/**
@brief A superimposer that uses a voting scheme, also known as pose clustering,
to find a good affine transformation.
This algorithm works on two consensus maps. It computes an affine
transformation that maps the elements of second map as near as possible
to the elements in the first map.
The voting scheme hashes affine transformations between pairs of features in
map one and pairs of features in map two. Each such pair of pairs defines a
(potential) "pose" of the second map relative to the first.
Then it finds a cluster in the parameter space of these poses.
The affine transformation is then computed from this
cluster of potential poses, hence the name pose clustering.
@sa PoseClusteringShiftSuperimposer
@htmlinclude OpenMS_PoseClusteringAffineSuperimposer.parameters
@ingroup MapAlignment
*/
class OPENMS_DLLAPI PoseClusteringAffineSuperimposer :
public BaseSuperimposer
{
public:
/// Default ctor
PoseClusteringAffineSuperimposer();
/// Destructor
~PoseClusteringAffineSuperimposer() override
{}
/**
@brief Estimates the transformation and fills the given mapping function. (Has a precondition!)
@note Exactly two input maps must be given.
@pre For performance reasons, we trust that (the equivalent of:)
<code>
maps[0].updateRanges();
maps[1].updateRanges();
</code>
has been done <i>before</i> calling this. You have been warned!
@param[in] map_model The model map (first input map)
@param[in] map_scene The scene map (second input map)
@param[out] transformation The output affine transformation (linear model transforming the scene map onto the model map)
@exception IllegalArgument is thrown if the input maps are invalid.
*/
void run(const ConsensusMap & map_model, const ConsensusMap & map_scene, TransformationDescription & transformation) override;
/// Perform alignment on vector of 1D peaks
virtual void run(const std::vector<Peak2D> & map_model, const std::vector<Peak2D> & map_scene, TransformationDescription & transformation);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/LabeledPairFinder.h | .h | 2,365 | 82 | // 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/ANALYSIS/MAPMATCHING/BaseGroupFinder.h>
#include <cmath>
namespace OpenMS
{
/**
@brief The LabeledPairFinder allows the matching of labeled features (features with a fixed distance).
Finds feature pairs that have a defined distance in RT and m/z in the same map.
@htmlinclude OpenMS_LabeledPairFinder.parameters
@todo Implement support for labeled MRM experiments, Q1 m/z value and charges. (Andreas)
@todo Implement support for more than one mass delta, e.g. from missed cleavages and so on (Andreas)
@ingroup FeatureGrouping
*/
class OPENMS_DLLAPI LabeledPairFinder :
public BaseGroupFinder
{
public:
/// Default constructor
LabeledPairFinder();
/// Destructor
inline ~LabeledPairFinder() override
{
}
/**
@brief Run the algorithm
@note Exactly one @em input map has to be provided.
@note The @em output map has to have two file descriptions, containing
the same file name. The file descriptions have to be labeled 'heavy'
and 'light'.
@exception Exception::IllegalArgument is thrown if the input data is not valid.
*/
void run(const std::vector<ConsensusMap> & input_maps, ConsensusMap & result_map) override;
protected:
/// return the p-value at position x for the bi-Gaussian distribution with mean @p m and standard deviation @p sig1 (left) and @p sig2 (right)
inline double PValue_(double x, double m, double sig1, double sig2)
{
if (m < x)
{
return 1 - std::erf((x - m) / sig2 / 0.707106781);
}
else
{
return 1 - std::erf((m - x) / sig1 / 0.707106781);
}
}
private:
/// Copy constructor not implemented => private
LabeledPairFinder(const LabeledPairFinder & source);
/// Assignment operator not implemented => private
LabeledPairFinder & operator=(const LabeledPairFinder & source);
}; // end of class LabeledPairFinder
} // end of namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/MapAlignmentAlgorithmTreeGuided.h | .h | 9,256 | 157 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Julia Thueringer$
// $Authors: Julia Thueringer $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/DATASTRUCTURES/BinaryTreeNode.h>
#include <OpenMS/ANALYSIS/MAPMATCHING/MapAlignmentAlgorithmIdentification.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
namespace OpenMS
{
/**
@brief A map alignment algorithm based on peptide identifications from MS2 spectra.
ID groups with the same sequence in different maps represent points of correspondence in RT between the maps. They are used to evaluate the distances between the maps for hierarchical clustering and form the basis for the alignment.
Only the best PSM per spectrum is considered as the correct identification.
For each pair of maps, the similarity is determined based on the intersection of the contained identifications using Pearson correlation. For small intersections, the Pearson value is reduced by multiplying the ratio of the intersection size to the union size: \f$\texttt{PearsonValue(map1}\cap \texttt{map2)}*\Bigl(\frac{\texttt{N(map1 }\cap\texttt{ map2})}{\texttt{N(map1 }\cup\texttt{ map2})}\Bigr)\f$
Using hierarchical clustering together with average linkage a binary tree is produced.
Following the tree, the maps are aligned, resulting in a transformed feature map that contains both the original and the transformed retention times.
As long as there are at least two clusters, the alignment is done as follows:
Of every pair of clusters, the one with the larger 10/90 percentile retention time range is selected as reference for the align() method of @ref OpenMS::MapAlignmentAlgorithmIdentification.
align() aligns the median retention time of each ID group in the second cluster to the reference retention time of this group.
Cubic spline smoothing is used to convert this mapping to a smooth function.
Retention times in the second cluster are transformed to the reference scale by applying this function.
Additionally, the original retention times are stored in the meta information of each feature.
The reference is combined with the transformed cluster.
The resulting map is used to extract transformation descriptions for each input map.
For each map cubic spline smoothing is used to convert the mapping to a smooth function.
Retention times of each map are transformed by applying the smoothed function.
@htmlinclude OpenMS_MapAlignmentAlgorithmTreeGuided.parameters
@ingroup MapAlignment
*/
class OPENMS_DLLAPI MapAlignmentAlgorithmTreeGuided :
public DefaultParamHandler,
public ProgressLogger
{
public:
/// Default constructor
MapAlignmentAlgorithmTreeGuided();
/// Destructor
~MapAlignmentAlgorithmTreeGuided() override;
/**
* @brief Extract RTs given for individual features of each map, calculate distances for each pair of maps and cluster hierarchical using average linkage.
*
* @param[in] feature_maps Vector of input maps (FeatureMap) whose distance is to be calculated.
* @param[in] tree Vector of BinaryTreeNodes that will be computed
* @param[out] maps_ranges Vector to store all sorted RTs of extracted identifications for each map in @p feature_maps; needed to determine the 10/90 percentiles
*/
static void buildTree(std::vector<FeatureMap>& feature_maps, std::vector<BinaryTreeNode>& tree, std::vector<std::vector<double>>& maps_ranges);
/**
* @brief Align feature maps tree guided using align() of @ref OpenMS::MapAlignmentAlgorithmIdentification and use TreeNode with larger 10/90 percentile range as reference.
*
* @param[in] tree Vector of BinaryTreeNodes that contains order for alignment.
* @param[out] feature_maps_transformed Vector with input maps for transformation process. Because the transformed maps are stored within this vector it's not const.
* @param[in] maps_ranges Vector that contains all sorted RTs of extracted identifications for each map; needed to determine the 10/90 percentiles.
* @param[in] map_transformed FeatureMap to store all features of combined maps with original and transformed RTs in order of alignment.
* @param[in] trafo_order Vector to store indices of maps in order of alignment.
*/
void treeGuidedAlignment(const std::vector<BinaryTreeNode>& tree, std::vector<FeatureMap>& feature_maps_transformed,
std::vector<std::vector<double>>& maps_ranges, FeatureMap& map_transformed,
std::vector<Size>& trafo_order);
/**
* @brief Align feature maps tree guided using align() of @ref OpenMS::MapAlignmentAlgorithmIdentification and use TreeNode with larger 10/90 percentile range as reference.
*/
void align(std::vector<FeatureMap>& data,
std::vector<TransformationDescription>& transformations);
/**
* @brief Extract original RT ("original_RT" MetaInfo) and transformed RT for each feature to compute RT transformations.
*
* @param[in] feature_maps Vector of input maps for size information.
* @param[out] map_transformed FeatureMap that contains all features of combined maps with original and transformed RTs in order of alignment.
* @param[in] transformations Vector to store transformation descriptions for each map. (output)
* @param[out] trafo_order Vector that contains the indices of aligned maps in order of alignment.
*/
void computeTrafosByOriginalRT(std::vector<FeatureMap>& feature_maps, FeatureMap& map_transformed,
std::vector<TransformationDescription>& transformations, const std::vector<Size>& trafo_order);
/**
* @brief Apply transformations on input maps.
*
* @param[in] feature_maps Vector of maps to be transformed (output)
* @param[out] transformations Vector that contains TransformationDescriptions that are applied to input maps
*/
static void computeTransformedFeatureMaps(std::vector<FeatureMap>& feature_maps, const std::vector<TransformationDescription>& transformations);
protected:
/// Type to store feature retention times given for individual peptide sequence
typedef std::map<String, DoubleList> SeqAndRTList;
// Update defaults model_type_, model_param_ and align_algorithm_
void updateMembers_() override;
/// Type of transformation model
String model_type_;
/// Default params of transformation models linear, b_spline, lowess and interpolated
Param model_param_;
/// Instantiation of alignment algorithm
MapAlignmentAlgorithmIdentification align_algorithm_;
/**
* @brief Similarity functor that provides similarity calculations with the ()-operator for protected type SeqAndRTList.
* SeqAndRTList stores retention times given for individual peptide sequences of a feature map.
Using pearson correlation, calculate the retention time similarity of two maps from their intersection of the peptide identifications.
Small intersections are penalized by multiplication with the quotient of intersection to union.
*/
class PeptideIdentificationsPearsonDistance_;
/**
* @brief For given peptide identifications extract sequences and store with associated feature RT.
*
* @param[in] peptides Vector of peptide identifications to extract sequences.
* @param[out] peptide_rts Map to store a list of feature RTs for each peptide sequence as key.
* @param[out] map_range Vector in which all feature RTs are stored for given peptide identifications.
* @param[in] feature_rt RT value of the feature to which the peptide identifications to be analysed belong.
*/
static void addPeptideSequences_(const PeptideIdentificationList& peptides, SeqAndRTList& peptide_rts,
std::vector<double>& map_range, double feature_rt);
/**
* @brief For each input map, extract peptide identifications (sequences) of existing features with associated feature RT.
*
* @param[in] feature_maps Vector of original maps containing peptide identifications.
* @param[out] maps_seq_and_rt Vector of maps to store feature RTs given for individual peptide sequences for each feature map.
* @param[out] maps_ranges Vector to store all feature RTs of extracted identifications for each map; needed to determine the 10/90 percentiles.
*/
static void extractSeqAndRt_(const std::vector<FeatureMap>& feature_maps, std::vector<SeqAndRTList>& maps_seq_and_rt,
std::vector<std::vector<double>>& maps_ranges);
private:
/// Copy constructor intentionally not implemented -> private
MapAlignmentAlgorithmTreeGuided(const MapAlignmentAlgorithmTreeGuided&);
/// Assignment operator intentionally not implemented -> private
MapAlignmentAlgorithmTreeGuided& operator=(const MapAlignmentAlgorithmTreeGuided&);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/PoseClusteringShiftSuperimposer.h | .h | 2,160 | 69 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Eva Lange, Clemens Groepl $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/ANALYSIS/MAPMATCHING/BaseSuperimposer.h>
namespace OpenMS
{
/**
@brief A superimposer that uses a voting scheme, also known as pose clustering,
to find a good shift transformation.
This algorithm works on two consensus maps. It computes an shift
transformation that maps the elements of second map as near as possible
to the elements in the first map.
The voting scheme hashes shift transformations between features in
map one and features in map two. Each such pair defines a
(potential) "pose" of the second map relative to the first.
Then it finds a cluster in the parameter space of these poses.
The shift transformation is then computed from this
cluster of potential poses, hence the name pose clustering.
@sa PoseClusteringAffineSuperimposer
@htmlinclude OpenMS_PoseClusteringShiftSuperimposer.parameters
@ingroup MapAlignment
*/
class OPENMS_DLLAPI PoseClusteringShiftSuperimposer :
public BaseSuperimposer
{
public:
/// Default ctor
PoseClusteringShiftSuperimposer();
/// Destructor
~PoseClusteringShiftSuperimposer() override
{}
/**
@brief Estimates the transformation and fills the given mapping function. (Has a precondition!)
@note Exactly two input maps must be given.
@pre For performance reasons, we trust that (the equivalent of:)
<code>
maps[0].updateRanges();
maps[1].updateRanges();
</code>
has been done <i>before</i> calling this. You have been warned!
@exception IllegalArgument is thrown if the input maps are invalid.
*/
void run(const ConsensusMap & map_model, const ConsensusMap & map_scene, TransformationDescription & transformation) override;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/MAPMATCHING/TransformationModelLinear.h | .h | 2,295 | 74 | // 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/MAPMATCHING/TransformationModel.h>
#include <OpenMS/KERNEL/StandardTypes.h>
namespace OpenMS
{
/**
@brief Linear model for transformations
The model can be inferred from data or specified using explicit parameters.
If data is given, a least squares fit is used to find the model parameters (slope and intercept).
Depending on parameter @p symmetric_regression, a normal regression (@e y on @e x) or
symmetric regression (@f$ y - x @f$ on @f$ y + x @f$) is performed.
Without data, the model can be specified by giving the parameters @p slope, @p intercept,
@p x_weight, @p y_weight explicitly.
@ingroup MapAlignment
*/
class OPENMS_DLLAPI TransformationModelLinear :
public TransformationModel
{
public:
/**
@brief Constructor
@exception IllegalArgument is thrown if neither data points nor explicit parameters (slope/intercept) are given.
*/
TransformationModelLinear(const DataPoints& data, const Param& params);
/// Destructor
~TransformationModelLinear() override = default;
/// Evaluates the model at the given value
double evaluate(double value) const override;
using TransformationModel::getParameters;
/// Gets the "real" parameters
void getParameters(double& slope, double& intercept, String& x_weight, String& y_weight, double& x_datum_min, double& x_datum_max, double& y_datum_min, double& y_datum_max) const;
/// Gets the default parameters
static void getDefaultParameters(Param& params);
/**
@brief Computes the inverse
@exception DivisionByZero is thrown if the slope is zero.
*/
void invert();
protected:
/// Parameters of the linear model
double slope_, intercept_;
/// Was the model estimated from data?
bool data_given_;
/// Use symmetric regression?
bool symmetric_;
};
} // namespace
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/DECHARGING/ILPDCWrapper.h | .h | 2,139 | 74 | // 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/DATASTRUCTURES/String.h>
#include <vector>
#include <set>
#include <map>
namespace OpenMS
{
class MassExplainer;
class FeatureMap;
class ChargePair;
class OPENMS_DLLAPI ILPDCWrapper
{
public:
typedef std::vector<ChargePair> PairsType;
typedef PairsType::size_type PairsIndex;
///Constructor
ILPDCWrapper();
///Destructor
virtual ~ILPDCWrapper();
/// Compute optimal solution and return value of objective function
/// If the input feature map is empty, a warning is issued and -1 is returned.
/// @return value of objective function
/// and @p pairs will have all realized edges set to "active"
double compute(const FeatureMap& fm, PairsType& pairs, Size verbose_level) const;
private:
/// slicing the problem into subproblems
double computeSlice_(const FeatureMap& fm,
PairsType& pairs,
const PairsIndex margin_left,
const PairsIndex margin_right,
const Size verbose_level) const;
/// slicing the problem into subproblems
double computeSliceOld_(const FeatureMap& fm,
PairsType& pairs,
const PairsIndex margin_left,
const PairsIndex margin_right,
const Size verbose_level) const;
/// calculate a score for the i_th edge
double getLogScore_(const PairsType::value_type& pair, const FeatureMap& fm) const;
typedef std::map<String, std::set<Size> > FeatureType_;
// add another charge annotation variant for a feature
void updateFeatureVariant_(FeatureType_& f_set, const String& rota_l, const Size& v) const;
}; // !class
} // !namespace
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/DECHARGING/FeatureDeconvolution.h | .h | 4,303 | 134 | // 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
// OpenMS
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/KERNEL/ConsensusMap.h>
#include <OpenMS/ANALYSIS/DECHARGING/ILPDCWrapper.h>
#include <OpenMS/DATASTRUCTURES/DPosition.h>
#include <OpenMS/DATASTRUCTURES/MassExplainer.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <map>
namespace OpenMS
{
class Compomer;
/**
@brief An algorithm to decharge features (i.e. as found by FeatureFinder).
@htmlinclude OpenMS_FeatureDeconvolution.parameters
@ingroup Analysis
*/
class OPENMS_DLLAPI FeatureDeconvolution :
public DefaultParamHandler
{
public:
enum class CHARGEMODE {QFROMFEATURE = 1, QHEURISTIC, QALL};
typedef DPosition<2> ClusterPointType;
typedef Feature::CoordinateType CoordinateType;
typedef ILPDCWrapper::PairsType PairsType;
/** @name Constructors and Destructor s
*/
//@{
/// default constructor
FeatureDeconvolution();
/// Copy constructor
FeatureDeconvolution(const FeatureDeconvolution& source);
/// Assignment operator
FeatureDeconvolution& operator=(const FeatureDeconvolution& source);
/// destructor
~FeatureDeconvolution() override;
//@}
/**
@brief Compute a zero-charge feature map from a set of charged features
Find putative ChargePairs, then score them and hand over to ILP.
@param[in] fm_in Input feature-map
@param[out] fm_out Output feature-map (sorted by position and augmented with user params)
@param[out] cons_map Output of grouped features belonging to a charge group
@param[out] cons_map_p Output of paired features connected by an edge
*/
void compute(const FeatureMap& fm_in, FeatureMap& fm_out, ConsensusMap& cons_map, ConsensusMap& cons_map_p);
protected:
void updateMembers_() override;
/**
@brief 1-sided Compomer for a feature
Holds information on an explicit (with H+) 1-sided Compomer of a feature.
*/
struct CmpInfo_;
/*
@brief test for obviously wrong parameter settings and warn
Currently supports the following scenarios:
* If the lower charge bound is too high, consensus features with gapped, even charges will occur (e.g. 30,32,34), instead of the true (15,16,17)
When more than 5% of the cf's look like this, we report it.
*/
void checkSolution_(const ConsensusMap& cons_map) const;
/// test if "simple" edges have alternative
/// (more difficult explanation) supported by neighboring edges
/// e.g. (.) -> (H+) might be augmented to
/// (Na+) -> (H+Na+)
void inferMoreEdges_(PairsType& edges, std::map<Size, std::set<CmpInfo_> >& feature_adducts);
/// A function mostly for debugging
void printEdgesOfConnectedFeatures_(Size idx_1, Size idx_2, const PairsType& feature_relation);
/**
@brief returns true if the intensity filter was passed or switched off
Filter for adding an edge only when the two features connected by it, fulfill the
intensity criterion.
**/
inline bool intensityFilterPassed_(const Int q1, const Int q2, const Compomer& cmp, const Feature& f1, const Feature& f2) const;
/**
@brief determines if we should test a putative feature charge
Answer query given the internal status of @em q_try.
Features with q<=0 always return true.
**/
bool chargeTestworthy_(const Int feature_charge, const Int putative_charge, const bool other_unchanged) const;
/// List of adducts used to explain mass differences
MassExplainer::AdductsType potential_adducts_;
/// labeling table
std::map<Size, String> map_label_;
/// labeling table inverse
std::map<String, Size> map_label_inverse_;
/// status of intensity filter for edges
bool enable_intensity_filter_;
/// status of charge discovery
CHARGEMODE q_try_;
/// amount of debug information displayed
Int verbose_level_;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/DECHARGING/MetaboliteFeatureDeconvolution.h | .h | 4,776 | 143 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Fabian Aicheler $
// $Authors: $
// --------------------------------------------------------------------------
#pragma once
// OpenMS
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/KERNEL/ConsensusMap.h>
#include <OpenMS/ANALYSIS/DECHARGING/ILPDCWrapper.h>
#include <OpenMS/DATASTRUCTURES/DPosition.h>
#include <OpenMS/DATASTRUCTURES/MassExplainer.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <map>
namespace OpenMS
{
class Compomer;
/**
@brief An algorithm to decharge small molecule features (i.e. as found by FeatureFinder).
@htmlinclude OpenMS_MetaboliteFeatureDeconvolution.parameters
@ingroup Analysis
*/
class OPENMS_DLLAPI MetaboliteFeatureDeconvolution :
public DefaultParamHandler
{
public:
enum class CHARGEMODE {QFROMFEATURE = 1, QHEURISTIC, QALL};
typedef DPosition<2> ClusterPointType;
typedef Feature::CoordinateType CoordinateType;
typedef ILPDCWrapper::PairsType PairsType;
/** @name Constructors and Destructor s
*/
//@{
/// default constructor
MetaboliteFeatureDeconvolution();
/// Copy constructor
MetaboliteFeatureDeconvolution(const MetaboliteFeatureDeconvolution& source);
/// Assignment operator
MetaboliteFeatureDeconvolution& operator=(const MetaboliteFeatureDeconvolution& source);
/// destructor
~MetaboliteFeatureDeconvolution() override;
//@}
/**
@brief Compute a zero-charge feature map from a set of charged features
Find putative ChargePairs, then score them and hand over to ILP.
@param[in] fm_in Input feature-map
@param[out] fm_out Output feature-map (sorted by position and augmented with user params)
@param[out] cons_map Output of grouped features belonging to a charge group
@param[out] cons_map_p Output of paired features connected by an edge
*/
void compute(const FeatureMap& fm_in, FeatureMap& fm_out, ConsensusMap& cons_map, ConsensusMap& cons_map_p);
protected:
void updateMembers_() override;
/**
@brief 1-sided Compomer for a feature
Holds information on an explicit (with H+) 1-sided Compomer of a feature.
*/
struct CmpInfo_;
/*
@brief test for obviously wrong parameter settings and warn
Currently supports the following scenarios:
* If the lower charge bound is too high, consensus features with gapped, even charges will occur (e.g. 30,32,34), instead of the true (15,16,17)
When more than 5% of the cf's look like this, we report it.
*/
void checkSolution_(const ConsensusMap& cons_map) const;
/// test if "simple" edges have alternative
/// (more difficult explanation) supported by neighboring edges
/// e.g. (.) -> (H+) might be augmented to
/// (Na+) -> (H+Na+)
void inferMoreEdges_(PairsType& edges, std::map<Size, std::set<CmpInfo_>>& feature_adducts);
void candidateEdges_(FeatureMap& fm_out, const Adduct& default_adduct, PairsType& feature_relation, std::map<Size, std::set<CmpInfo_>>& feature_adducts);
void annotate_feature_(FeatureMap& fm_out, Adduct& default_adduct, Compomer& c, const Size f_idx, const UInt side, const Int new_q, const Int old_q);
/// A function mostly for debugging
void printEdgesOfConnectedFeatures_(Size idx_1, Size idx_2, const PairsType& feature_relation);
/**
@brief returns true if the intensity filter was passed or switched off
Filter for adding an edge only when the two features connected by it, fulfill the
intensity criterion.
**/
inline bool intensityFilterPassed_(const Int q1, const Int q2, const Compomer& cmp, const Feature& f1, const Feature& f2) const;
/**
@brief determines if we should test a putative feature charge
Answer query given the internal status of @em q_try.
Features with q<=0 always return true.
**/
bool chargeTestworthy_(const Int feature_charge, const Int putative_charge, const bool other_unchanged) const;
/// List of adducts used to explain mass differences
MassExplainer::AdductsType potential_adducts_;
/// labeling table
std::map<Size, String> map_label_;
/// labeling table inverse
std::map<String, Size> map_label_inverse_;
/// status of intensity filter for edges
bool enable_intensity_filter_;
/// status of ionization mode
bool negative_mode_;
/// status of charge discovery
CHARGEMODE q_try_;
/// amount of debug information displayed
Int verbose_level_;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/ID/BasicProteinInferenceAlgorithm.h | .h | 7,130 | 151 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Julianus Pfeuffer $
// $Authors: Julianus Pfeuffer $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/METADATA/ProteinIdentification.h>
#include <OpenMS/METADATA/PeptideHit.h>
#include <OpenMS/KERNEL/ConsensusMap.h>
#include <OpenMS/ANALYSIS/ID/IDScoreSwitcherAlgorithm.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
namespace OpenMS
{
/** \brief Algorithm class that implements simple protein inference by aggregation of peptide scores.
* It has multiple parameter options like the aggregation method, when to distinguish peptidoforms,
* and if you want to use shared peptides ("use_shared_peptides").
* First, the best PSM per spectrum is used, then only the best PSM per peptidoform is aggregated.
* Peptidoforms can optionally be distinguished via the treat_X_separate parameters:
* - Modifications (modified sequence string)
* - Charge states
* The algorithm assumes posteriors or posterior error probabilities and converts to posteriors initially.
* Possible aggregation methods that can be set via the parameter "aggregation_method" are:
* - "maximum" (default)
* - "sum"
* - "product" (ignoring zeroes)
* Annotation of the number of peptides used for aggregation can be disabled (see parameters).
* Supports multiple runs but goes through them one by one iterating over the full PeptideIdentification vector.
*/
class OPENMS_DLLAPI BasicProteinInferenceAlgorithm :
public DefaultParamHandler,
public ProgressLogger
{
public:
typedef std::unordered_map<std::string, std::map<Int, PeptideHit*>> SequenceToChargeToPSM;
/**
* @brief The aggregation method
*/
enum class AggregationMethod
{
PROD, ///< aggregate by product (ignore zeroes)
SUM, ///< aggregate by summing
BEST ///< aggregate by maximum/minimum
};
/// Default constructor
BasicProteinInferenceAlgorithm();
/**
* Performs the actual inference based on best psm per peptide in @p pep_ids per run in @p prot_ids.
* Sorts and filters psms in @p pep_ids. Annotates results in @p prot_ids.
* Associations (via getIdentifier) for peptides to protein runs need to be correct.
*/
void run(PeptideIdentificationList& pep_ids, std::vector<ProteinIdentification>& prot_ids) const;
/**
* Performs the actual inference based on best psm per peptide in @p pep_ids per run in @p prot_id.
* Sorts and filters psms in @p pep_ids. Annotates results in @p prot_id.
* Associations (via getIdentifier) for peptides to protein runs need to be correct.
*/
void run(PeptideIdentificationList& pep_ids, ProteinIdentification& prot_id) const;
/**
* Performs the actual inference based on best psm per peptide in @p cmap for proteins from @p prot_id.
* Ideally @p prot_id is the union of proteins in all runs of @p cmap.
* Sorts and filters psms in @p pep_ids. Annotates results in @p prot_id.
* Associations (via getIdentifier) for peptides to protein runs ARE IGNORED and all pep_ids used.
* @todo allow checking matching IDs
*/
void run(ConsensusMap& cmap, ProteinIdentification& prot_id, bool include_unassigned) const;
private:
/**
* @brief Performs simple aggregation-based inference on one protein run.
* @param[in,out] acc_to_protein_hitP_and_count Maps Accessions to a pair of ProteinHit pointers
* and number of peptidoforms encountered
* @param[in,out] best_pep Maps (un)modified peptide sequence to a map from charge (0 when unconsidered) to the
* best PeptideHit pointer
* @param[in,out] prot_run The current run to process
* @param[in,out] pep_ids Peptides for the current run to process
*/
void processRun_(
std::unordered_map<std::string, std::pair<ProteinHit*, Size>>& acc_to_protein_hitP_and_count,
SequenceToChargeToPSM& best_pep,
ProteinIdentification& prot_run,
PeptideIdentificationList& pep_ids) const;
/**
* @brief fills and updates the map of best peptide scores @p best_pep (by sequence or modified sequence, depending on algorithm settings)
* @param[in,out] best_pep (mod.) sequence to charge to pointer of best PSM (PeptideHit*)
* @param[in,out] pep_ids the spectra with PSMs
* @param[in] overall_score_type the pre-determined type name to raise an error if mixed types occur
* @param[in] higher_better if for this score type higher is better
* @param[in] run_id only process peptides associated with this run_id (e.g. proteinID run getIdentifier())
*/
void aggregatePeptideScores_(
SequenceToChargeToPSM& best_pep,
PeptideIdentificationList& pep_ids,
const String& overall_score_type,
bool higher_better,
const std::string& run_id) const;
/**
* @brief aggregates and updates protein scores based on aggregation settings and aggregated peptide level results in
* prefilled @p best_pep
* @param[in,out] acc_to_protein_hitP_and_count the results to fill
* @param[in] best_pep best psm per peptide to read the score
* @param[in] pep_scores if the score is a posterior error probability -> Auto-converts to posterior probability
* @param[in] higher_better if for the score higher is better. Assume score is unconverted.
*/
void updateProteinScores_(
std::unordered_map<std::string, std::pair<ProteinHit*, Size>>& acc_to_protein_hitP_and_count,
const SequenceToChargeToPSM& best_pep,
bool pep_scores,
bool higher_better) const;
/// get the AggregationMethod enum from a @p method_string
AggregationMethod aggFromString_(const std::string& method_string) const;
/// check if a @p score_name is compatible to the chosen @p aggregation_method
/// I.e. only probabilities can be used for multiplication
void checkCompat_(
const String& score_type,
const AggregationMethod& aggregation_method
) const;
/// check if a @p score_type is compatible to the chosen @p aggregation_method
/// I.e. only probabilities can be used for multiplication
void checkCompat_(
const IDScoreSwitcherAlgorithm::ScoreType& score_type,
const AggregationMethod& aggregation_method
) const;
/// get the initial score value based on the chosen @p aggregation_method, @p higher_better is needed for "best" score
double getInitScoreForAggMethod_(const AggregationMethod& aggregation_method, bool higher_better) const;
/// get lambda function to aggregate scores
typedef double (*fptr)(double, double);
fptr aggFunFromEnum_(const BasicProteinInferenceAlgorithm::AggregationMethod& agg_method, bool higher_better) const;
};
} //namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/ID/AhoCorasickAmbiguous.h | .h | 22,343 | 551 | // 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/CONCEPT/Macros.h>
#include <bitset>
#include <cassert>
#include <cstring>
#include <functional> // for std::hash
#include <limits>
#include <queue>
#include <string>
#include <cstdint>
#include <unordered_map>
#include <vector>
#include <bit> // for std::popcount
namespace OpenMS
{
/// representation of an AminoAcid (see AA class).
/// Ambiguous AA's are consecutive (which saves effort during their enumeration)
constexpr char const AAtoChar[28] = {
'A', // 00 Ala Alanine
'Y', // 01 Tyr Tyrosine
'C', // 02 Cys Cysteine
'D', // 03 Asp Aspartic Acid // B
'N', // 04 Asn Asparagine // B
'F', // 05 Phe Phenylalanine
'G', // 06 Gly Glycine
'H', // 07 His Histidine
'I', // 08 Ile Isoleucine // J
'L', // 09 Leu Leucine // J
'K', // 10 Lys Lysine
'W', // 11 Trp Tryptophan
'M', // 12 Met Methionine
'O', // 13 Pyl Pyrrolysine
'P', // 14 Pro Proline
'E', // 15 Glu Glutamic Acid // Z
'Q', // 16 Gln Glutamine // Z
'R', // 17 Arg Arginine
'S', // 18 Ser Serine
'T', // 19 Thr Threonine
'U', // 20 Selenocysteine
'V', // 21 Val Valine
// ambiguous AAs start here (index: 22...25)
'B', // 22 Aspartic Acid, Asparagine $ // the ambAA's need to be consecutive (B,J,Z,X,$)
'J', // 23 Leucine, Isoleucine $
'Z', // 24 Glutamic Acid, Glutamine $
'X', // 25 Unknown
// non-regular AA's, which are special
'$', // 26 superAA, i.e. it models a mismatch, which can be anything, including AAAs
'?', // 27 invalid AA (will usually be skipped) -- must be the last AA (AA::operator++ and others rely on it)
};
/// Conversion table from 7-bit ASCII char to internal value representation for an amino acid (AA)
constexpr char const CharToAA[128] = {
// ASCII char (7-bit Int with values from 0..127) --> amino acid
27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, // 0
27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, // 1
// $
27, 27, 27, 27, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, // 2
27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, // 3
// , A, B, C, D, E, F, G, H, I, J, K, L, M, N, O,
27, 00, 22, 02, 03, 15, 05, 06, 07, 8, 23, 10, 9, 12, 04, 13, // 4
// P, Q, R, S, T, U, V, W, X, Y, Z, , , , , ,
14, 16, 17, 18, 19, 20, 21, 11, 25, 01, 24, 27, 27, 27, 27, 27, // 5
// , a, b, c, d, e, f, g, h, i, j, k, l, m, n, o,
27, 00, 22, 02, 03, 15, 05, 06, 07, 8, 23, 10, 9, 12, 04, 13, // 6
// p, q, r, s, t, u, v, w, x, y, z, , , , , ,
14, 16, 17, 18, 19, 20, 21, 11, 25, 01, 24, 27, 27, 27, 27, 27, // 7
};
/// Represents a needle found in the query.
/// A needle (at position @p needle_index, as passed into ACTrie's addNeedle()) of length @p needle_length was found in the haystack (query) at position @p query_pos
struct OPENMS_DLLAPI Hit {
using T = uint32_t;
Hit() = default;
Hit(T needle_index, T needle_length, T query_pos) : needle_index(needle_index), needle_length(needle_length), query_pos(query_pos) {};
T needle_index;
T needle_length;
T query_pos;
bool operator==(const Hit& rhs) const
{
return needle_index == rhs.needle_index && needle_length == rhs.needle_length && query_pos == rhs.query_pos;
}
};
/// An AminoAcid, which supports construction from char and has convenience functions such as
/// isAmbiguous() or isValid()
struct OPENMS_DLLAPI AA
{
/// Default C'tor; creates an invalid AA
constexpr AA() : aa_(AA('?').aa_)
{
}
/// C'tor from char; any char A-Z or a-z yields a valid AA.
/// '$' is a special AA, which should only be used when modeling mismatches.
/// All other chars produce an invalid AA ('?')
constexpr explicit AA(const char c) : aa_(CharToAA[(unsigned char)c])
{
}
/// yields the internal 8bit representation
constexpr uint8_t operator()() const
{
return aa_;
}
/// equality operator
constexpr bool operator==(const AA other) const
{
return aa_ == other.aa_;
}
/// less-or-equal operator
constexpr bool operator<=(const AA other) const
{
return aa_ <= other.aa_;
}
/// is AA a 'B', 'J', 'Z', 'X', or '$' ?
constexpr bool isAmbiguous() const
{
return aa_ >= AA('B').aa_;
}
/// is AA a letter or '$' ?
constexpr bool isValid() const
{
return aa_ != AA('?').aa_;
}
/// is the AA a letter, i.e. A-Z or a-z?
constexpr bool isValidForPeptide() const
{
return aa_ <= AA('X').aa_; // '$' or '?'
}
/// Pre-increment operator (advance to next AA)
constexpr AA& operator++()
{
++aa_;
assert(aa_ <= AA('?').aa_); // make sure we don't overflow
return *this;
}
/// Post-increment operator (advance to next AA)
constexpr AA operator++(int)
{
AA r(*this);
++aa_;
assert(aa_ <= AA('?').aa_); // make sure we don't overflow
return r;
}
/// Decrement operator
constexpr AA operator-(const AA rhs) const
{
AA r(*this);
r.aa_ -= rhs.aa_;
return r;
}
/// Convert this AA to a single letter representation, i.e. 'A'..'V', 'B', 'J', 'Z', 'X', '$', or '?' (invalid AA)
constexpr char toChar() const
{
return AAtoChar[aa_];
}
/// Create an unambiguous AA from an index (0..21 inclusive -> 'A'..'V').
/// @throw OpenMS::Precondition if not index < unambiguousAACount().
static AA fromIndex(size_t index) noexcept
{
OPENMS_PRECONDITION(index < unambiguousAACount(), "AA::fromIndex(): index must be in [0, unambiguousAACount())");
AA r;
r.aa_ = static_cast<uint8_t>(index);
return r;
}
/// Returns the number of unambiguous amino acids (A-Z, excluding B, J, Z, X), i.e. 22
static size_t unambiguousAACount()
{
static_assert(AA('V').aa_ - AA('A').aa_ + 1 == 22, "Unambiguous AA count must be 22 (A-Z, excluding B, J, Z, X)");
static_assert(AA('A').aa_ == 0, "A must be the first AA in the enumeration");
static_assert(AA('V').aa_ == 21, "V must be the last unambiguous AA in the enumeration");
return AA('V').aa_ - AA('A').aa_ + 1;
}
private:
uint8_t aa_; ///< internal representation as 1-byte integer
};
/// An index with 32-bit representing the location of a node
/// Allows to model invalid indices, see isInvalid() and isValid().
class OPENMS_DLLAPI Index
{
public:
using T = uint32_t;
/// default C'tor; creates an invalid index
constexpr Index() = default;
/// C'tor from T
constexpr Index(T val) : i_(val) {};
/// is this Index invalid, i.e. should not be dereferenced
constexpr bool isInvalid() const
{
return i_ == std::numeric_limits<T>::max();
}
/// is this Index valid, i.e. an actual index into a vector?
constexpr bool isValid() const
{
return i_ != std::numeric_limits<T>::max();
}
/// convert to a number (might be invalid, check with .isValid() first)
constexpr T operator()() const
{
return i_;
}
/// equality operator
constexpr bool operator==(const Index other) const
{
return i_ == other.i_;
}
/// allows to set the index, using `index.pos() = 3;` or simply read its value
constexpr T& pos()
{
return i_;
}
/// allows to read the index, using `index.pos()`
constexpr T pos() const
{
return i_;
}
private:
T i_ = std::numeric_limits<T>::max(); ///< internal number representation; invalid state by default
};
} // namespace OpenMS
// this needs to go into namespace std
template<> struct std::hash<OpenMS::Index>
{
std::size_t operator()(OpenMS::Index const& s) const noexcept
{
return std::hash<OpenMS::Index::T> {}(s());
}
};
namespace OpenMS
{
/// Custom bitset which uses a 32-bit integer to store bits (instead of 8 bytes for std::bitset<32> on Clang/GCC).
struct Bitset {
uint32_t bits = 0;
// Set bit at position `pos` (0-based)
void set(int pos) {
bits |= (1u << pos);
}
// Clear bit at position `pos`
void clear(int pos) {
bits &= ~(1u << pos);
}
// Check if bit at position `pos` is set
bool test(int pos) const {
return (bits >> pos) & 1u;
}
// Left shift the bitset by `n` positions
Bitset operator<<(int n) const {
Bitset o = *this;
return o <<= n;
}
// Left shift the bitset by `n` positions
Bitset& operator<<=(int n) {
if (n > 31)
{ // if we shift more than 31 bits, behaviour is undefined (e.g. GCC/Clang/MSVC will not modify 'bits' if n==32)
bits = 0; // shift out all bits
}
else
{
bits <<= n;
}
return *this;
}
// Count number of set bits (population count)
int pop_count() const {
return std::popcount(bits);
}
}; // end Bitset
/// A node in the AhoCorasick trie.
/// Internally manages the suffix link and an index where its children start (this relies on the trie being stored in BFS order)
struct OPENMS_DLLAPI ACNode
{
/// Default C'tor
ACNode() {};
/// C'tor from an edge @p label (from parent to this node) and a @p depth in the tree
ACNode(const AA label, const uint8_t depth) : edge(label)
{
depth_and_hits.depth = depth;
}
/// internal struct to steal one bit from @p depth to use as hit indicator
struct DepthHits {
DepthHits()
{
memset(this, 0, sizeof *this); // make sure bitfields are 0; C++20 allows {} initialization ...
};
uint8_t has_hit: 1; ///< does a pattern end here (or when following suffix links)?
// we could add another bit here to distinguish between a local hit and suffix hit, but on Windows, this slows it down
uint8_t depth : 7; ///< depth of node in the trie
};
using ChildCountType = uint8_t;
// do not use std::bitset, since GCC/clang wastes 8 bytes here.
//std::bitset<26> children_bitset; ///< bitfield of children (if tree is in BFS order); 26 bits are enough to cover all AA incl. (B,J,X,Z)
Bitset children_bitset; ///< bitfield of children (if tree is in BFS order); 26 bits are enough to cover all AA incl. (B,J,X,Z)
Index suffix {0}; ///< which node is our suffix?
Index first_child {0}; ///< which node contains our first child node (if tree is in BFS order)
AA edge {0}; ///< what is the edge label (from parent to this node)
ChildCountType nr_children = 0; ///< number of children (if tree is in BFS order); (popcount on children_bitset will do the same but we have the space due to padding)
DepthHits depth_and_hits; ///< depth of node in the tree and one bit if a needle ends in this node or any of its suffices
};
// forward declaration
struct ACTrieState;
/// a spin-off search path through the trie, which can deal with ambiguous AAs and mismatches
struct OPENMS_DLLAPI ACScout
{
/// No default C'tor
ACScout() = delete;
/// C'tor with arguments
ACScout(const char* query_pos, Index tree_pos, uint8_t max_aa, uint8_t max_mm, uint8_t max_prefix_loss);
/// Where in the text are we currently?
size_t textPos(const ACTrieState& state) const;
/// Return the next valid AA in the query. If the query was fully traversed, an invalid AA is returned.
/// This moves the internal iterator for the query forwards.
AA nextValidAA();
const char* it_query = 0; ///< position in query
Index tree_pos; ///< position in trie
uint8_t max_aaa_leftover {0}; ///< number of ambiguous AAs the scout can yet tolerate before exceeding the limit
uint8_t max_mm_leftover {0}; ///< number of mismatches the scout can yet tolerate before exceeding the limit
uint8_t max_prefix_loss_leftover {0}; ///< number of AA's which can get lost by following suffix links, before the scout must retire; reaching 0 means retire
};
/// Return the first valid AA from current position of @p it_q in the string, or (if the string ends) an invalid AA
/// On return, @p it_q points to AA after the returned AA.
AA nextValidAA(const char*& it_q);
/// A state object for an ACTrie, i.e. dynamic information when traversing the trie (which is 'const' after construction)
/// Useful when using multi-threading; each thread can walk the trie and keep track of its state using an instance of this class
struct OPENMS_DLLAPI ACTrieState
{
friend ACScout;
/// Set a haystack (query) where the needles (patterns) are to be searched
/// This also resets the current trie-node to ROOT, and voids the hits
void setQuery(const std::string& haystack);
/// Where in the text are we currently?
size_t textPos() const;
/// Where in the text are we currently?
const char* textPosIt() const;
/// The current query
const std::string& getQuery() const;
/// Return the next valid AA in the query. If the query was fully traversed, an invalid AA is returned.
/// This moves the internal iterator for the query forwards.
AA nextValidAA();
std::vector<Hit> hits; ///< current hits found
std::queue<ACScout> scouts; ///< initial scout points which are currently active and need processing
Index tree_pos; ///< position in trie (for the Primary)
private:
const char* it_q_; ///< position in query
std::string query_; ///< current query ( = haystack = text)
};
/// An Aho Corasick trie (a set of nodes with suffix links mainly)
class OPENMS_DLLAPI ACTrie
{
public:
/**
@brief Default C'tor which just creates a root node
@param[in] max_aaa Maximum number of ambiguous amino acids (B,J,Z,X) allowed in a hit
@param[in] max_mm Maximum number of mismatched amino acids allowed in a hit
*/
ACTrie(uint32_t max_aaa = 0, uint32_t max_mm = 0);
/// D'tor
~ACTrie();
/// Add a needle to build up the trie.
/// Call compressTrie() after the last needle was added before searching
/// @throw Exception::InvalidValue if @p needle contains an invalid amino acid (such as '*')
void addNeedle(const std::string& needle);
/// Convenience function; adds needles to build up the trie.
/// Call compressTrie() after the last needle was added before searching
/// @throw Exception::InvalidValue if @p needles contains an invalid amino acid (such as '*'); you can use getNeedleCount() to trace which needle did cause the exception
void addNeedles(const std::vector<std::string>& needles);
/// Convenience function which adds needles and immediately compresses the trie (i.e. no more needles can be added)
/// @throw Exception::InvalidValue if @p needles contains an invalid amino acid (such as '*'); you can use getNeedleCount() to trace which needle did cause the exception
void addNeedlesAndCompress(const std::vector<std::string>& needles);
size_t size() const
{
return trie_.size();
}
/**
@brief Traverses the trie in BFS order and makes it more compact and efficient to traverse
Also creates the suffix links.
Call this function after adding all needles, and before searching any queries.
*/
void compressTrie();
/// How many needles were added to the trie?
size_t getNeedleCount() const;
/// Set maximum number of ambiguous amino acids allowed during search.
/// This must not be called in the middle of a search. Otherwise search results will be mixed.
void setMaxAAACount(const uint32_t max_aaa);
/// Maximum number of ambiguous amino acids allowed during search
uint32_t getMaxAAACount() const;
/// Set maximum number of mismatches allowed during search.
/// This must not be called in the middle of a search. Otherwise search results will be mixed.
void setMaxMMCount(const uint32_t max_mm);
/// Maximum number of mismatches allowed during search
uint32_t getMaxMMCount() const;
/// Resume search at the last position in the query and node in the trie.
/// If a node (or any suffices) are a hit, then @p state.hits is cleared & filled and true is returned.
/// If the query ends and there is no hit, false is returned.
bool nextHits(ACTrieState& state) const;
/// Collects all hits from the current position in the query until the end of the query
/// I.e. similar to while(next(state)) merge(hits_all, state.hits);
void getAllHits(ACTrieState& state) const;
private:
/// Resume search at the last position in the query and node in the trie.
/// If a node (or any suffices) are a hit, then @p state.hits is NOT cleared, but filled and true is returned.
/// If the query ends and all scouts are processed, false is returned (but hits might still have changed)
bool nextHitsNoClear_(ACTrieState& state) const;
/// Insert a new child node into the trie (unless already present) when starting at parent node @p from and following the edge labeled @p edge.
/// Return the index of the (new) child node.
/// Note: This operates on the naive trie, not the BFS.
Index add_(const Index from, const AA edge);
/**
@brief Add all hits occurring in node @p i (including all its suffix hits)
@param[in] i The ACNode where a needle ends (also all its suffices are checked)
@param[in] text_pos current position in query (i.e. end of matched hit)
@param[out] hits Result vector which will be expanded with hits (if any)
@return true if hits were found
**/
bool addHits_(Index i, const size_t text_pos, std::vector<Hit>& hits) const;
/// same as addHits_, but only follows the suffix chain until the scout loses its prefix
bool addHitsScout_(Index i, const ACScout& scout, const size_t text_pos, std::vector<Hit>& hits, const int current_scout_depths) const;
/// Starting at node @p i, find the child with label @p edge
/// This requires an exact match, e.g. if @p edge is an 'X' it will only match to 'X' in the trie (=needles)
/// If no child exists, follow the suffix link and try again (until root is reached)
/// Note: This operates on the BFS trie (after compressTrie()), not the naive one.
Index follow_(const Index i, const AA edge) const;
/// Advances @p scout by consuming @p edge; same as follow_(), just for a scout
/// Returns true if scout is still alive, false otherwise
bool followScout_(ACScout& scout, const AA edge, ACTrieState& state) const;
/// Same as follow_, but considers trying mismatches and AAA's if possible (by adding scouts to @p state)
/// @return The new tree node, where Primary is at after consuming @p edge
Index stepPrimary_(const Index i, const AA edge, ACTrieState& state) const;
/// Same as follow_, but considers trying mismatches and AAA's if possible (by adding scouts to @p state)
/// @return true if scout is still alive, false otherwise (i.e. did loose its prefix)
bool stepScout_(ACScout& scout, ACTrieState& state) const;
/// Create scouts from an AAA or MM, starting at trie node @p i, following edges in range @p fromAA to @p toAA
/// The number of AAA's/MM's left for the scout must be passed (these numbers already reflect the original edge label)
void createScouts_(const Index i, const AA fromAA, const AA toAA, ACTrieState& state, const uint32_t aaa_left, const uint32_t mm_left) const;
/// Create scouts from a scout with an AAA or MM, using @p prototype as template, following edges in range @p fromAA to @p toAA
void createSubScouts_(const ACScout& prototype, const AA fromAA, const AA toAA, ACTrieState& state) const;
/// Same as createScouts_, but instantiate all possible AA's except for those in the range from @p except_fromAA to @p except_toAA and the @p except_edge itself.
void createMMScouts_(const Index i, const AA except_fromAA, const AA except_toAA, const AA except_edge, ACTrieState& state, const uint32_t aaa_left, const uint32_t mm_left) const;
/// Same as createSubScouts_, but instantiate all possible AA's except for those in the range from @p except_fromAA to @p except_toAA and the @p except_edge itself.
void createMMSubScouts_(const ACScout& prototype, const AA except_fromAA, const AA except_toAA, const AA except_edge, ACTrieState& state) const;
/// During needle addition (naive trie), obtain the child with edge @p child_label from @p parent; if it does not exist, an invalid Index is returned
Index findChildNaive_(Index parent, AA child_label);
/// After compression (BFS trie), obtain the child with edge @p child_label from @p parent; if it does not exist, an invalid Index is returned
Index findChildBFS_(const Index parent, const AA child_label) const;
std::vector<ACNode> trie_; ///< the trie, in either naive structure or BFS order (after compressTrie)
uint32_t needle_count_ {0}; ///< total number of needles in the trie
uint32_t max_aaa_ {0}; ///< maximum number of ambAAs allowed
uint32_t max_mm_ {0}; ///< maximum number of mismatches allowed
/// maps a node to which needles end there (valid for both naive and BFS tree)
std::vector<std::vector<uint32_t>> vec_index2needles_ = { {} }; // one empty element to allow capacity doubling; note: sparse vector but still much faster and less memory than unordered_map
/// maps the child nodes of a node for the naive tree; only needed during naive trie construction; storing children in the BFS trie modeled in the ACNodes directly
std::vector<std::vector<Index>> vec_index2children_naive_ = { {} }; // one empty element to allow capacity doubling
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/ID/IDScoreGetterSetter.h | .h | 23,088 | 610 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Julianus Pfeuffer $
// $Authors: Julianus Pfeuffer $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/METADATA/ID/IdentificationData.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <OpenMS/METADATA/ProteinIdentification.h>
#include <OpenMS/KERNEL/ConsensusMap.h>
#include <vector>
#include <unordered_set>
#include <unordered_map>
namespace OpenMS
{
/// Used to collect data from the ID structures with the original score as first and
/// target decoy annotation as second member of the pair. Target = 1.0.
/// Usually Target+decoy for peptides = target and protein groups with at least one target = target.
/// But could also be proportional
typedef std::pair<double, double> ScoreToTgtDecLabelPair;
struct ScoreToTgtDecLabelPairs // Not a typedef to allow forward declaration.
: public std::vector<ScoreToTgtDecLabelPair>
{
typedef std::vector<ScoreToTgtDecLabelPair> Base;
using Base::Base;
};
/**
* @brief A class for extracting and reinserting IDScores from Peptide/ProteinIdentifications and from ConsensusMaps
*/
class IDScoreGetterSetter
{
private:
template<typename T>
struct IsIDType
{
static bool const value =
std::is_same<T, PeptideIdentification>::value || std::is_same<T, ProteinIdentification>::value;
};
template<typename T>
struct IsHitType
{
static bool const value = std::is_same<T, PeptideHit>::value || std::is_same<T, ProteinHit>::value;
};
public:
/**
* @brief Fills the scores_labels vector from an ProteinIdentification @p id for picked protein FDR.
* I.e. it only takes the better of the two scores for each target-decoy pair (based on the accession after
* removal of the @p decoy_prefix.
* @param[out] picked_scores Target accessions to pairs of scores and target decoy labels (usually 1.0 for target and 0.0 for decoy) to be filled.
* @param[in] id The hits to iterate over
* @param[in] decoy_string The decoy string to remove before comparing accesions for pairs.
* @param[in] decoy_prefix If the @p decoy_string is a prefix (true) or suffix.
*/
static void getPickedProteinScores_(
std::unordered_map<String, ScoreToTgtDecLabelPair>& picked_scores,
const ProteinIdentification& id,
const String& decoy_string,
bool decoy_prefix);
/**
* @brief Fills the scores_labels vector from a vector of ProteinGroups @p grps for picked protein group FDR.
* @todo describe more
* @param[out] picked_scores Target accessions to pairs of scores and target decoy labels (usually 1.0 for target and 0.0 for decoy) to be used for lookup.
* @param[out] scores_labels Scores and target-decoy value for all groups that had at least one picked protein. Targets preferred.
* @param[in] grps The groups to iterate over
* @param[in] decoy_string The decoy string to remove before comparing accesions for pairs.
* @param[in] decoy_prefix If the @p decoy_string is a prefix (true) or suffix.
*/
static void getPickedProteinGroupScores_(
const std::unordered_map<String, ScoreToTgtDecLabelPair>& picked_scores,
ScoreToTgtDecLabelPairs& scores_labels,
const std::vector<ProteinIdentification::ProteinGroup>& grps,
const String& decoy_string,
bool decoy_prefix);
/// removes the @p decoy_string from @p acc if present. Returns if string was removed and the new string.
static std::pair<bool,String> removeDecoyStringIfPresent_(const String& acc, const String& decoy_string, bool decoy_prefix);
static void fillPeptideScoreMap_(
std::unordered_map<String, ScoreToTgtDecLabelPair>& seq_to_score_labels,
PeptideIdentificationList const& ids);
static void fillPeptideScoreMap_(
std::unordered_map<String, ScoreToTgtDecLabelPair>& seq_to_score_labels,
ConsensusMap const& map,
bool include_unassigned);
/**
* \defgroup getScoresFunctions Get scores from ID structures for FDR
* @brief Fills the scores_labels vector from an ID data structure
* @param[out] scores_labels Pairs of scores and boolean target decoy labels to be filled. target = true.
*
* Just use the one you need.
* @{
*/
//TODO could be done with set of target accessions, too
//TODO even better: store nr targets and nr decoys when creating the groups!
//TODO alternative scoring is possible, too (e.g. ratio of tgts vs decoys)
static void getScores_(
ScoreToTgtDecLabelPairs &scores_labels,
const std::vector<ProteinIdentification::ProteinGroup> &grps,
const std::unordered_set<std::string> &decoy_accs);
template<class ...Args>
static void getScores_(
ScoreToTgtDecLabelPairs &scores_labels,
const PeptideIdentificationList &ids,
Args &&... args)
{
for (const PeptideIdentification &id : ids)
{
getScores_(scores_labels, id, std::forward<Args>(args)...);
}
}
static void getScores_(
ScoreToTgtDecLabelPairs &scores_labels,
const ProteinIdentification &id)
{
scores_labels.reserve(scores_labels.size() + id.getHits().size());
std::transform(id.getHits().begin(), id.getHits().end(),
std::back_inserter(scores_labels),
[](const ProteinHit &hit)
{
checkTDAnnotation_(hit);
return std::make_pair<double, bool>(hit.getScore(), getTDLabel_(hit));
}
);
}
template<class ...Args>
static void getScores_(
ScoreToTgtDecLabelPairs &scores_labels,
const PeptideIdentification &id,
bool all_hits,
Args &&... args
)
{
if (all_hits)
{
for (const PeptideHit &hit : id.getHits())
{
getScores_(scores_labels, hit, std::forward<Args>(args)...);
}
}
else
{
//TODO for speed and constness I assume that they are sorted and first = best.
//id.sort();
const PeptideHit &hit = id.getHits()[0];
getScores_(scores_labels, hit, std::forward<Args>(args)...);
}
}
template<typename IDPredicate, class ...Args>
static void getScores_(
ScoreToTgtDecLabelPairs &scores_labels,
const PeptideIdentification &id,
IDPredicate &&fun,
bool all_hits,
Args &&... args
)
{
if (fun(id))
{
if (all_hits)
{
for (const PeptideHit &hit : id.getHits())
{
getScores_(scores_labels, hit, std::forward<Args>(args)...);
}
}
else
{
//TODO for speed I assume that they are sorted and first = best.
//id.sort();
const PeptideHit &hit = id.getHits()[0];
getScores_(scores_labels, hit, std::forward<Args>(args)...);
}
}
}
template<typename HitPredicate>
static void getScores_(
ScoreToTgtDecLabelPairs &scores_labels,
const PeptideHit &hit,
HitPredicate &&fun)
{
if (fun(hit))
{
getScores_(scores_labels, hit);
}
}
template<typename HitType, typename std::enable_if<IsHitType<HitType>::value>::type * = nullptr>
static void getScores_(
ScoreToTgtDecLabelPairs &scores_labels,
const HitType &hit)
{
checkTDAnnotation_(hit);
scores_labels.emplace_back(hit.getScore(), getTDLabel_(hit));
}
/** @} */
/**
* @brief Helper for getting scores in ConsensusMaps
* @todo allow FeatureMap?
*/
template<class ...Args>
static void getPeptideScoresFromMap_(
ScoreToTgtDecLabelPairs &scores_labels,
const ConsensusMap &cmap, bool include_unassigned_peptides, Args &&... args)
{
auto f =
[&](const PeptideIdentification &id) -> void
{ getScores_(scores_labels, id, std::forward<Args>(args)...); };
cmap.applyFunctionOnPeptideIDs(f, include_unassigned_peptides);
}
/**
* @brief For peptide hits, a hit is considered target also if it maps to both
* a target and a decoy protein (i.e. "target+decoy") as value in the
* "target_decoy" metavalue e.g. annotated by PeptideIndexer
*/
static bool getTDLabel_(const MetaInfoInterface &idOrHit)
{
return std::string(idOrHit.getMetaValue("target_decoy"))[0] == 't';
}
/**
* \defgroup setScoresFunctions Sets scores to FDRs/qVals in ID data structures to the closest in a given mapping
* @brief Sets FDRs/qVals from a scores_to_FDR map in the ID data structures
* @param[in] scores_to_FDR Maps original score to calculated FDR or q-Value
* @param[in] score_type e.g. FDR or q-Value
* @param[in] higher_better the new ordering, should usually be false for FDR/qval
*
* Just use the one you need.
* @{
*/
template<typename IDType, class ...Args>
static void setScores_(const std::map<double, double> &scores_to_FDR,
std::vector<IDType> &ids,
const std::string &score_type,
bool higher_better,
Args &&... args)
{
for (auto &id : ids)
{
setScores_(scores_to_FDR, id, score_type, higher_better, std::forward<Args>(args)...);
}
}
template<typename IDType>
static String setScoreType_(IDType &id, const std::string &score_type,
bool higher_better)
{
String old_score_type = id.getScoreType() + "_score";
id.setScoreType(score_type);
id.setHigherScoreBetter(higher_better);
return old_score_type;
}
template<typename IDType>
static void setScores_(const std::map<double, double> &scores_to_FDR, IDType &id, const std::string &score_type,
bool higher_better, bool keep_decoy)
{
bool old_higher_better = id.isHigherScoreBetter();
String old_score_type = setScoreType_(id, score_type, higher_better);
if (keep_decoy) //in-place set scores
{
if (old_higher_better)
{
setScores_(scores_to_FDR, id, old_score_type);
}
else
{
setScoresHigherWorse_(scores_to_FDR, id, old_score_type);
}
}
else
{
if (old_higher_better)
{
setScoresAndRemoveDecoys_(scores_to_FDR, id, old_score_type);
}
else
{
setScoresHigherWorseAndRemoveDecoys_(scores_to_FDR, id, old_score_type);
}
}
}
template<typename IDType>
static void setScores_(const std::map<double, double> &scores_to_FDR, IDType &id,
const String &old_score_type)
{
std::vector<typename IDType::HitType> &hits = id.getHits();
for (auto &hit : hits)
{
setScore_(scores_to_FDR, hit, old_score_type);
}
}
template<typename IDType>
static void setScoresHigherWorse_(const std::map<double, double> &scores_to_FDR, IDType &id,
const String &old_score_type)
{
std::vector<typename IDType::HitType> &hits = id.getHits();
for (auto &hit : hits)
{
setScoreHigherWorse_(scores_to_FDR, hit, old_score_type);
}
}
template<typename IDType, class ...Args>
static void setScoresAndRemoveDecoys_(const std::map<double, double> &scores_to_FDR, IDType &id,
const String &old_score_type, Args&& ... args)
{
std::vector<typename IDType::HitType> &hits = id.getHits();
std::vector<typename IDType::HitType> new_hits;
new_hits.reserve(hits.size());
for (auto &hit : hits)
{
setScoreAndMoveIfTarget_(scores_to_FDR, hit, old_score_type, new_hits, std::forward<Args>(args)...);
}
hits.swap(new_hits);
}
template<typename IDType, class ...Args>
static void setScoresHigherWorseAndRemoveDecoys_(const std::map<double, double> &scores_to_FDR, IDType &id,
const String &old_score_type, Args&& ... args)
{
std::vector<typename IDType::HitType> &hits = id.getHits();
std::vector<typename IDType::HitType> new_hits;
new_hits.reserve(hits.size());
for (auto &hit : hits)
{
setScoreHigherWorseAndMoveIfTarget_(scores_to_FDR, hit, old_score_type, new_hits, std::forward<Args>(args)...);
}
hits.swap(new_hits);
}
template<typename HitType>
static void setScore_(const std::map<double, double> &scores_to_FDR, HitType &hit, const std::string &old_score_type)
{
hit.setMetaValue(old_score_type, hit.getScore());
hit.setScore(scores_to_FDR.lower_bound(hit.getScore())->second);
}
template<typename HitType>
static void setScoreHigherWorse_(const std::map<double, double> &scores_to_FDR, HitType &hit, const std::string &old_score_type)
{
hit.setMetaValue(old_score_type, hit.getScore());
auto ub = scores_to_FDR.upper_bound(hit.getScore());
if (ub != scores_to_FDR.begin()) ub--;
hit.setScore(ub->second);
}
/*template<typename IDType>
static void setScores_(const std::map<double, double> &scores_to_FDR, IDType &id, const std::string &score_type,
bool higher_better)
{
bool old_higher_better = id.isHigherScoreBetter();
String old_score_type = setScoreType_(id, score_type, higher_better);
setScores_(scores_to_FDR, id, old_score_type, old_higher_better);
}*/
static void setScores_(const std::map<double, double> &scores_to_FDR,
PeptideIdentification &id,
const std::string &score_type,
bool higher_better,
bool keep_decoy,
int charge)
{
String old_score_type = setScoreType_(id, score_type, higher_better);
if (keep_decoy) //in-place set scores
{
setScores_(scores_to_FDR, id, old_score_type, higher_better, charge);
}
else
{
setScoresAndRemoveDecoys_<PeptideIdentification>(scores_to_FDR, id, old_score_type, charge);
}
}
static void setScores_(const std::map<double, double> &scores_to_FDR,
PeptideIdentification &id,
const std::string &score_type,
bool higher_better,
bool keep_decoy,
int charge,
const String &identifier)
{
if (id.getIdentifier() == identifier)
{
setScores_(scores_to_FDR, id, score_type, higher_better, keep_decoy, charge);
}
}
template<typename IDType>
static void setScores_(const std::map<double, double> &scores_to_FDR, IDType &id, const std::string &score_type,
bool higher_better, bool keep_decoy, const String &identifier)
{
if (id.getIdentifier() == identifier)
{
setScores_(scores_to_FDR, id, score_type, higher_better, keep_decoy);
}
}
static void setScores_(const std::map<double, double> &scores_to_FDR,
PeptideIdentification &id,
const std::string &score_type,
bool higher_better,
int charge,
const String &identifier)
{
if (id.getIdentifier() == identifier)
{
setScores_(scores_to_FDR, id, score_type, higher_better, charge);
}
}
template<typename IDType>
static void setScores_(const std::map<double, double> &scores_to_FDR, IDType &id, const std::string &score_type,
bool higher_better, const String &identifier)
{
if (id.getIdentifier() == identifier)
{
setScores_(scores_to_FDR, id, score_type, higher_better);
}
}
template<typename IDType>
static void setScores_(const std::map<double, double> &scores_to_FDR, IDType &id, const std::string &score_type,
bool higher_better, int charge)
{
for (auto& hit : id.getHits())
{
if (hit.getCharge() == charge)
{
if (higher_better)
{
setScore_(scores_to_FDR, hit, score_type);
}
else
{
setScoreHigherWorse_(scores_to_FDR, hit, score_type);
}
}
}
}
//TODO could also get a keep_decoy flag when we define what a "decoy group" is -> keep all always for now
static void setScores_(
const std::map<double, double> &scores_to_FDR,
std::vector<ProteinIdentification::ProteinGroup> &grps,
const std::string &score_type,
bool higher_better);
/** @} */
/**
* @brief Used when keep_decoy_peptides or proteins is false
* @tparam HitType ProteinHit or PeptideHit
* @param[in] scores_to_FDR map from original score to FDR/qVal
* @param[in] hit The hit (moved to @p new_hits if its a target hit)
* @param[in] old_score_type to save it in metavalue
* @param[out] new_hits where to move if target (i.e. target or target+decoy)
*/
template<typename HitType>
static void setScoreAndMoveIfTarget_(const std::map<double, double> &scores_to_FDR,
HitType &hit,
const std::string &old_score_type,
std::vector<HitType> &new_hits)
{
const String &target_decoy(hit.getMetaValue("target_decoy"));
if (target_decoy[0] == 't')
{
hit.setMetaValue(old_score_type, hit.getScore());
hit.setScore(scores_to_FDR.lower_bound(hit.getScore())->second);
new_hits.push_back(std::move(hit));
} // else do not move over
}
template<typename HitType>
static void setScoreHigherWorseAndMoveIfTarget_(const std::map<double, double> &scores_to_FDR,
HitType &hit,
const std::string &old_score_type,
std::vector<HitType> &new_hits)
{
const String &target_decoy(hit.getMetaValue("target_decoy"));
if (target_decoy[0] == 't')
{
hit.setMetaValue(old_score_type, hit.getScore());
auto ub = scores_to_FDR.upper_bound(hit.getScore());
if (ub != scores_to_FDR.begin()) ub--;
hit.setScore(ub->second);
new_hits.push_back(std::move(hit));
} // else do not move over
}
/**
* @brief Used when keep_decoy_peptides is false and charge states are considered
* @param[in] scores_to_FDR map from original score to FDR/qVal
* @param[out] hit the PeptideHit itself
* @param[in] old_score_type to save it in metavalue
* @param[out] new_hits where to move if target (i.e. target or target+decoy)
* @param[in] charge If only peptides with charge X are currently considered
*/
static void setScoreAndMoveIfTarget_(const std::map<double, double> &scores_to_FDR,
PeptideHit &hit,
const std::string &old_score_type,
std::vector<PeptideHit> &new_hits,
int charge)
{
if (charge == hit.getCharge())
{
const String &target_decoy(hit.getMetaValue("target_decoy"));
if (target_decoy[0] == 't')
{
hit.setMetaValue(old_score_type, hit.getScore());
hit.setScore(scores_to_FDR.lower_bound(hit.getScore())->second);
new_hits.push_back(std::move(hit));
} // else do not move over
}
else // different charge, move over unchanged to process later at correct charge.
{
new_hits.push_back(std::move(hit));
}
}
/**
* @brief Helper for applying set Scores on ConsensusMaps
* @tparam Args optional additional arguments (charge, run ID)
* @param[in] scores_to_FDR maps original scores to FDR
* @param[in] cmap the ConsensusMap
* @param[in] include_unassigned_peptides Also modify unassigned peptide IDs in @p cmap?
* @param[in] score_type FDR or q-Value
* @param[in] higher_better usually false
* @param[in] keep_decoy read from Param object
* @param[in] args optional additional arguments (int charge, string run ID)
*/
template<class ...Args>
static void setPeptideScoresForMap_(const std::map<double, double>& scores_to_FDR,
ConsensusMap& cmap,
bool include_unassigned_peptides,
const std::string& score_type,
bool higher_better,
bool keep_decoy,
Args&&... args)
{
//Note: Gcc4.8 cannot handle variadic templates in lambdas
auto f =
[&](PeptideIdentification &id) -> void
{ setScores_(scores_to_FDR, id, score_type,
higher_better, keep_decoy, std::forward<Args>(args)...); };
cmap.applyFunctionOnPeptideIDs(f, include_unassigned_peptides);
}
/**
* @brief To check the metavalues before we do anything
* @param[in] id_or_hit Any Object with MetaInfoInterface. Specifically ID or Hit Type here.
* @throws Exception::MissingInformation if target_decoy annotation does not exist
*/
static void checkTDAnnotation_(const MetaInfoInterface &id_or_hit)
{
if (!id_or_hit.metaValueExists("target_decoy"))
{
throw Exception::MissingInformation(__FILE__,
__LINE__,
OPENMS_PRETTY_FUNCTION,
"Meta value 'target_decoy' does not exist in all ProteinHits! Reindex the idXML file with 'PeptideIndexer'");
}
}
static void setPeptideScoresFromMap_(std::unordered_map<String, ScoreToTgtDecLabelPair> const& seq_to_fdr,
PeptideIdentificationList& ids,
std::string const& score_type,
bool keep_decoys);
static void setPeptideScoresFromMap_(std::unordered_map<String, ScoreToTgtDecLabelPair> const& seq_to_fdr,
ConsensusMap& map,
std::string const& score_type,
bool keep_decoys,
bool include_unassigned);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/ID/SiriusMSConverter.h | .h | 8,531 | 177 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Oliver Alka, Axel Walter $
// $Authors: Oliver Alka $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/ANALYSIS/MAPMATCHING/FeatureMapping.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/METADATA/SpectrumLookup.h>
#include <fstream>
namespace OpenMS
{
class OPENMS_DLLAPI SiriusMSFile
{
public:
///< class to store information about accessions
class AccessionInfo
{
public:
String sf_path; ///< sourcefile path for mztab-m
String sf_type; ///< sourcefile type for mztab-m
String sf_filename; ///< sourcefile name for mztab-m
String sf_accession; ///< sourcefile accessions for mztab-m
String native_id_accession; ///< nativeID accession for mztab-m
String native_id_type; ///< nativeID type for mztab-m
};
///< class to store the compound information
///< needed for the mapping of compound and fragment annotated spectrum
class CompoundInfo
{
public:
String cmp; ///< query_id used compound in .ms file
double pmass; ///< parent/precursor mass of the compound
double pint_mono; ///< parent/precursor intensity of the compound
double rt; ///< retention time of the compound
double fmz; ///< annotated mass of a feature (if available)
String fid; ///< annotated feature_id (if available)
String formula; ///< sumformula of the compound
int charge; ///< precursor/feature charge
String ionization; ///< adduct information
String des; ///< description/name of the compound
String specref_format; ///< spectra ref format for mztab-m
String source_file; ///< sourcefile for mztab-m
String source_format; ///< format of the sourcefile for mztab-m
std::vector<String> native_ids; ///< native ids of the associated spectra
String native_ids_id; ///< concatenated list of the associated spectra
std::vector<String> m_ids; ///< native ids and identifier for multiple possible identification via AMS ("|" separator)
String m_ids_id; ///< concatenated list of native ids and identifier for multiple possible identification via AMS ("|" separator) used for mapping of compounds and the annotated spectrum.
std::vector<String> scan_indices; ///< index of the associated spectra
std::vector<String> specrefs; ///< spectra reference for mztab-m
int file_index; ///< source file index >
};
/**
@brief Internal structure used in @ref TOPP_SiriusExport that is used
for the conversion of a MzMlFile to an internal format.
@ingroup Analysis_ID
Write content of one mzML/featureXML(optional) file pair to SIRIUS .ms file ofstream.
Comments (see CompoundInfo) are written to SIRIUS .ms file and additionally stored in CompoundInfo struct.
If adduct information for a spectrum is missing, no adduct information is added.
In this case, SIRIUS assumes default adducts for the respective spectrum.
@param[in] spectra: Peakmap from input mzML.
@param[in] os: Write output for .ms file to ofstream.
@param[in] feature_mapping: Adducts and features (index).
@param[in] feature_only: Only use features.
@param[in] isotope_pattern_iterations: At which depth to stop isotope_pattern extraction (if possible).
@param[in] no_masstrace_info_isotope_pattern: bool if isotope pattern should be extracted (if not in feature)
@param[in] v_cmpinfo: Vector of CompoundInfo.
@param[in] file_index: file index (to differentiate entries derived from different mzML files and resolve ambiguities)
*/
static void store(const MSExperiment& spectra,
std::ofstream& os,
const FeatureMapping::FeatureToMs2Indices& feature_mapping,
const bool& feature_only,
const int& isotope_pattern_iterations,
const bool no_masstrace_info_isotope_pattern,
std::vector<SiriusMSFile::CompoundInfo>& v_cmpinfo,
const size_t& file_index);
/**
@brief Store CompoundInfo objects in tsv file format
@param[in] v_cmpinfo: Vector with CompoundInfo objects
@param[in] filename: Filename for tsv file
*/
static void saveFeatureCompoundInfoAsTSV(const std::vector<SiriusMSFile::CompoundInfo>& v_cmpinfo,
const std::string& filename);
protected:
/**
@brief Internal structure to write the .ms file (called in store function)
@param[out] os: stream
@param[in] spectra: spectra
@param[in] ms2_spectra_index: vector of index ms2 spectra (in feature)
@param[in] ainfo: accession information
@param[in] adducts: vector of adducts
@param[in] v_description: vector of descriptions
@param[in] v_sumformula: vector of sumformulas
@param[in] f_isotopes: isotope pattern of the feature
@param[in] feature_charge: feature charge
@param[in] feature_id: feature id
@param[in] feature_rt: features retention time
@param[in] feature_mz: feature mass to charge
@param[out] writecompound: bool if new compound should be written in .ms file
@param[in] no_masstrace_info_isotope_pattern: bool if isotope pattern should be extracted (if not in feature)
@param[in] isotope_pattern_iterations: number of iterations (trying to find a C13 pattern)
@param[in] count_skipped_spectra: count number of skipped spectra
@param[in] count_assume_mono: count number of features where mono charge was assumed
@param[in] count_no_ms1: count number of compounds without a valid ms1 spectrum
@param[in] v_cmpinfo: vector of CompoundInfo
@param[in] file_index: file index (to differentiate entries derived from different mzML files and resolve ambiguities)
*/
static void writeMsFile_(std::ofstream& os,
const MSExperiment& spectra,
const std::vector<size_t>& ms2_spectra_index,
const SiriusMSFile::AccessionInfo& ainfo,
const StringList& adducts,
const std::vector<String>& v_description,
const std::vector<String>& v_sumformula,
const std::vector<std::pair<double,double>>& f_isotopes,
int& feature_charge,
uint64_t& feature_id,
const double& feature_rt,
const double& feature_mz,
bool& writecompound,
const bool& no_masstrace_info_isotope_pattern,
const int& isotope_pattern_iterations,
int& count_skipped_spectra,
int& count_assume_mono,
int& count_no_ms1,
std::vector<SiriusMSFile::CompoundInfo>& v_cmpinfo,
const size_t& file_index);
/**
@brief Find highest intensity peak near target mz to test if within a margin of error
@param[in] test_mz: Mass-to-charge to test
@param[in] spectrum: Spectrum to test
@param[in] tolerance: Tolerance window (e.g. 10)
@param[in] ppm: Unit of tolerance window either ppm or Da
*/
static Int getHighestIntensityPeakInMZRange_(double test_mz,
const MSSpectrum& spectrum,
double tolerance,
bool ppm);
/**
@brief Extract precursor isotope pattern if no feature information is available
based on C12C13 distance.
@param[in] precursor_mz: Precursor mass-to-charge
@param[in] precursor_spectrum: Precursor spectrum
@param[in] iterations: Number of isotopes, which are tried to be extracted
@param[in] charge: Charge of the precursor
*/
static std::vector<Peak1D> extractPrecursorIsotopePattern_(const double& precursor_mz,
const MSSpectrum& precursor_spectrum,
int& iterations,
const int& charge);
};
} // namespace OpenMS | Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/ID/PeptideProteinResolution.h | .h | 7,527 | 152 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Julianus Pfeuffer $
// $Authors: Julianus Pfeuffer $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CONCEPT/Types.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/METADATA/ProteinIdentification.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <vector>
#include <set>
namespace OpenMS
{
/// Represents a connected component of the bipartite graph
/// Holds indices of peptides and (indist.) protein groups in them
struct OPENMS_DLLAPI ConnectedComponent
{
std::set<Size> prot_grp_indices;
std::set<Size> pep_indices;
/// Overloaded operator '<<' for ConnectedComponents
friend std::ostream& operator<<(std::ostream& os, const ConnectedComponent& conn_comp);
};
/**
@brief Resolves shared peptides based on protein scores
Resolves connected components of the bipartite protein-peptide graph based
on protein probabilities/scores and adds them as additional protein_groups
to the protein identification run processed.
Thereby greedily assigns shared peptides in this component uniquely to the
proteins of the current @em best @em indistinguishable protein group, until
every peptide is uniquely assigned. This effectively allows more peptides to
be used in ProteinQuantifier at the cost of potentially additional noise in
the peptides quantities.
In accordance with most state-of-the-art protein inference tools, only the
best hit (PSM) for a peptide ID is considered. Probability ties are
currently resolved by taking the protein with larger number of peptides.
@improvement The class could provide iterator for ConnectedComponents in the
future. One could extend the graph to include all PeptideHits (not only the
best). It becomes a tripartite graph with larger connected components then.
Maybe extend it to work with MS1 features. Separate resolution and adding
groups to output.
@ingroup Analysis_ID
*/
class OPENMS_DLLAPI PeptideProteinResolution
{
private:
/// to build bipartite graph as two maps (adjacency "lists"):
/// ProtGroups-Indices <-> PepID-Indices
/// so we get bidirectional connectivity
/// We always take first PepHit from PepID, because those are usually used
/// for inference
typedef std::map<Size, std::set<Size> > IndexMap_;
/// if the protein group at index i contains a target (first) and/or decoy (second)
// TODO WIP for better tie resolution
// std::vector<std::pair<bool,bool>> indist_prot_grp_td_;
/// mapping indist. protein group indices -> peptide identification indices
IndexMap_ indist_prot_grp_to_pep_;
/// mapping indist. protein group indices <- peptide identification indices
IndexMap_ pep_to_indist_prot_grp_;
/** represents the middle layer of an implicit tripartite graph:
consists of single protein accessions and their mapping to the (indist.)
group's indices */
std::map<String, Size> prot_acc_to_indist_prot_grp_;
/// log debug information?
bool statistics_;
public:
/// Constructor
/// @param[in] statistics Specifies if the class stores/outputs info about statistics
PeptideProteinResolution(bool statistics = false);
/// A peptide-centric reimplementation of the resolution process. Can be used statically
/// without building a bipartite graph first.
/// @param[in,out] protein ProteinIdentification object storing IDs and groups
/// @param[in,out] peptides vector of ProteinIdentifications with links to the proteins
/// @param[in] resolve_ties If ties should be resolved or multiple best groups reported
/// @param[in] targets_first If target groups should get picked first no matter the posterior
/// @todo warning: all peptides are used (not filtered for matching protein ID run yet).
static void resolve(ProteinIdentification& protein,
PeptideIdentificationList& peptides,
bool resolve_ties,
bool targets_first);
/// Convenience function that performs graph building and group resolution.
/// After resolution, all unreferenced proteins are removed and groups updated.
/// @param[in,out] inferred_protein_id ProteinIdentification object storing IDs and groups
/// @param[in,out] inferred_peptide_ids Vector of ProteinIdentifications with links to the proteins
static void run(std::vector<ProteinIdentification>& inferred_protein_id,
PeptideIdentificationList& inferred_peptide_ids);
/// Initialize and store the graph (= maps), needs sorted groups for
/// correct functionality. Therefore sorts the indist. protein groups
/// if not skipped.
/// @param[in,out] protein ProteinIdentification object storing IDs and groups
/// @param[in] peptides vector of ProteinIdentifications with links to the proteins
/// @param[in] skip_sort Skips sorting of groups, nothing is modified then.
void buildGraph(ProteinIdentification& protein,
const PeptideIdentificationList& peptides,
bool skip_sort = false);
/// Applies resolveConnectedComponent to every component of the graph and
/// is able to write statistics when specified. Parameters will
/// both be mutated in this method.
/// @param[in,out] protein ProteinIdentification object storing IDs and groups
/// @param[in,out] peptides vector of ProteinIdentifications with links to the proteins
/// @todo warning: all peptides are used (not filtered for matching protein ID run yet).
void resolveGraph(ProteinIdentification& protein,
PeptideIdentificationList& peptides);
/// Does a BFS on the two maps (= two parts of the graph; indist. prot. groups
/// and peptides), switching from one to the other in each step.
/// @param[in,out] root_prot_grp Starts the BFS at this protein group index
/// @return Returns a Connected Component as set of group and peptide indices.
ConnectedComponent findConnectedComponent(Size& root_prot_grp);
/*! Resolves connected components based on posterior probabilities and adds them
as additional protein_groups to the output idXML.
Thereby greedily assigns shared peptides in this component uniquely to
the proteins of the current BEST INDISTINGUISHABLE protein group,
ready to be used in ProteinQuantifier then.
This is achieved by removing all other evidence from the input
PeptideIDs and iterating until each peptide is uniquely assigned.
In accordance with Fido only the best hit (PSM) for an ID is considered.
Probability ties resolved by taking protein with largest number of peptides.
@param[in,out] conn_comp The component to be resolved
@param[in,out] protein ProteinIdentification object storing IDs and groups
@param[in,out] peptides vector of ProteinIdentifications with links to the proteins
*/
void resolveConnectedComponent(ConnectedComponent& conn_comp,
ProteinIdentification& protein,
PeptideIdentificationList& peptides);
};
} //namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/ID/IonIdentityMolecularNetworking.h | .h | 1,808 | 30 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Axel Walter $
// $Authors: Axel Walter $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/ConsensusMap.h>
namespace OpenMS
{
class OPENMS_DLLAPI IonIdentityMolecularNetworking
{
public:
/// Annotate ConsensusMap for ion identity molecular networking (IIMN) workflow by GNPS.
/// Adds meta values Constants::UserParams::IIMN_ROW_ID (unique index for each feature), Constants::UserParams::IIMN_ADDUCT_PARTNERS (related features row IDs)
/// and Constants::UserParams::IIMN_ANNOTATION_NETWORK_NUMBER (all related features with different adduct states) get the same network number).
/// This method requires the features annotated with the Constants::UserParams::IIMN_LINKED_GROUPS meta value.
/// If at least one of the features has an annotation for Constants::UserParam::IIMN_LINKED_GROUPS, annotate ConsensusMap for IIMN.
static void annotateConsensusMap(ConsensusMap& consensus_map);
/// Write supplementary pair table (csv file) from a consensusXML file with edge annotations for connected features. Required for GNPS IIMN.
/// The table contains the columns "ID 1" (row ID of first feature), "ID 2" (row ID of second feature), "EdgeType" (MS1/2 annotation),
/// "Score" (the number of direct partners from both connected features) and "Annotation" (adducts and delta m/z between two connected features).
static void writeSupplementaryPairTable(const ConsensusMap& consensus_map, const String& output_file);
};
} // closing namespace OpenMS | Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/ID/IDScoreSwitcherAlgorithm.h | .h | 38,307 | 840 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Julianus Pfeuffer $
// $Authors: Julianus Pfeuffer $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/KERNEL/ConsensusMap.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
namespace OpenMS
{
/**
@brief This class is used to switch identification scores within identification or consensus feature maps.
This class provides functionality to switch the main scoring type used in peptide or protein identification data.
It supports switching between different score types, such as raw scores, E-values, posterior probabilities,
posterior error probabilities, FDR, and q-values. The class also handles the direction of the score (whether a higher
score is better) and can store the original scores as meta values to prevent data loss.
The score switching process is configurable through parameters that specify the score types,
as well as the desired score direction and how old scores are annotated in the meta information.
The class can operate on individual identification objects or
ConsensusMaps, updating the main scores of all hits based on the specified criteria.
*/
class OPENMS_DLLAPI IDScoreSwitcherAlgorithm :
public DefaultParamHandler
{
public:
/// Default constructor. Initializes the parameter handler with default values.
IDScoreSwitcherAlgorithm();
/**
@brief This is a rough hierarchy of possible score types in MS.
In an ideal case, this should be reimplemented to follow
ontology hierarchies as soon as e.g. MS-OBO is complete
and we switched the Metavalues to CV terms.
*/
enum class ScoreType
{
RAW, ///< Raw score, e.g., search engine specific scores like hyperscore.
RAW_EVAL, ///< Raw score with E-value, e.g., search engine specific scores like expect score.
PP, ///< Posterior probability.
PEP, ///< Posterior error probability.
FDR, ///< False discovery rate.
QVAL, ///< Q-value.
};
/**
@brief Checks if the given score name corresponds to a specific score type.
This method determines if a given score name, typically derived from an identification object or meta value,
matches a specified ScoreType. It performs a case-insensitive comparison and optionally removes the "_score"
suffix if present.
@param[in] score_name The name of the score to check.
@param[in] type The ScoreType to compare against.
@return True if the score name matches the given ScoreType, false otherwise.
*/
bool isScoreType(const String& score_name, const ScoreType& type) const
{
String chopped = score_name;
if (chopped.hasSuffix("_score"))
{
chopped = chopped.chop(6);
}
const std::set<String>& possible_types = type_to_str_.at(type);
return possible_types.find(chopped) != possible_types.end();
}
/**
@brief Converts a string representation of a score type to a ScoreType enum.
This static method attempts to map a given string, representing a score type, to the corresponding
ScoreType enum value. It handles various common representations of score types, including those
with or without the "_score" suffix, and ignores case and special characters like '-', '_', and ' '.
@param[out] score_type The string representation of the score type.
@return The corresponding ScoreType enum value.
@throws Exception::MissingInformation If the provided score_type string does not match any known
score type.
*/
static ScoreType toScoreTypeEnum(String score_type)
{
if (score_type.hasSuffix("_score"))
{
score_type = score_type.chop(6);
}
score_type.toLower();
score_type.erase(std::remove_if(score_type.begin(), score_type.end(),
[](unsigned char c) { return c == '-' || c == '_' || c == ' '; }),
score_type.end());
const std::map<String, ScoreType> s_to_type =
{
{"raw", ScoreType::RAW},
{"rawevalue", ScoreType::RAW_EVAL},
{"qvalue", ScoreType::QVAL},
{"fdr", ScoreType::FDR},
{"falsediscoveryrate", ScoreType::FDR},
{"pep", ScoreType::PEP},
{"posteriorerrorprobability", ScoreType::PEP},
{"posteriorprobability", ScoreType::PP},
{"pp", ScoreType::PP}
};
if (auto it = s_to_type.find(score_type); it != s_to_type.end())
{
return it->second;
}
else
{
throw Exception::MissingInformation(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION, String("Unknown score type '") + score_type + "'.");
}
}
/**
@brief Determines whether a higher score type is better given a ScoreType enum.
@param[out] score_type The score type to check.
@return True if a higher score type is better, false otherwise.
*/
bool isScoreTypeHigherBetter(ScoreType score_type)
{
return type_to_better_[score_type];
}
/**
@brief Gets a vector of all score names that are used in OpenMS.
@return A vector of all score names that are used in OpenMS (e.g., "q-value", "ln(hyperscore)").
*/
std::vector<String> getScoreNames();
/**
@brief Structure to hold score detection results for any ScoreType.
*/
struct ScoreSearchResult
{
bool is_main_score_type = false; ///< True if the main score is already of the requested score type
String score_name; ///< Name of score to use (main score name if is_main_score_type=true, meta value name if found in meta values, empty if not found anywhere)
};
/**
@brief Searches for a general score type (e.g. PEP, QVAL) in an identification data structure.
Returns a ScoreSearchResult for any identification type,
checking if the main score of an identification object is already of the requested score type,
and if not, searches for scores of that type in the meta values of the first hit.
@tparam IDType The type of the identification object (e.g., PeptideIdentification, ProteinIdentification)
@param[in] id The identification object to analyze for scores
@param[in] score_type The ScoreType to search for (e.g., ScoreType::PEP, ScoreType::QVAL, etc.)
@return ScoreSearchResult containing whether main score is of the requested type and its name.
@note This method only checks the first hit for meta values, similar to other methods in this class.
@note Returns empty score_name if no score of the requested type is found.
*/
template <typename IDType>
ScoreSearchResult findScoreType(const IDType& id, ScoreType score_type) const
{
ScoreSearchResult result;
// First check if main score is already of the requested score type using existing infrastructure
const String& main_score_type = id.getScoreType();
result.is_main_score_type = isScoreType(main_score_type, score_type);
if (result.is_main_score_type)
{
// Main score is of the requested type, so return the main score name
result.score_name = main_score_type;
}
else if (!id.getHits().empty())
{
// Main score is not of the requested type, look for it in meta values
const auto& first_hit = id.getHits()[0];
const std::set<String>& score_types = type_to_str_.at(score_type);
// Search for scores of the requested type in meta values using the existing score type collection
for (const String& score_name : score_types)
{
if (first_hit.metaValueExists(score_name))
{
result.score_name = score_name;
break;
}
// Also check for "_score" suffix variant
String score_name_with_suffix = score_name + "_score";
if (first_hit.metaValueExists(score_name_with_suffix))
{
result.score_name = score_name_with_suffix;
break;
}
}
}
// If neither main score nor meta values contain the requested type, score_name remains empty
return result;
}
/**
* @brief Switches the main scores of all hits in an identification object based on the new scoring settings.
*
* This method iterates through all hits in the provided identification object and updates their main scores
* according to the new scoring settings defined in the switcher class's parameter object. If the old and new
* score types share the same name (e.g., "q-value"), the method safeguards the original scores by storing them
* as meta values with a "~" appended to the old score type. This prevents overwriting the meta value of the new score.
*
* @tparam IDType The type of the identification object, which must support getHits(), getScoreType(),
* setScoreType(), and setHigherScoreBetter() methods, along with the ability to handle meta values.
* @param[in,out] id An identification object containing hits whose scores are to be switched. The object will
* be modified in place, with updated scores and score type.
* @param[in,out] counter A reference to a Size variable that counts the number of hits processed.
*
* @throws Exception::MissingInformation If a required meta value (specified as the new score) is not found
* in any of the hits, indicating incomplete or incorrect score setup.
*
* @note The method assumes that the identification object's hits are properly initialized with all necessary
* meta values. It also relies on the tolerance_ value to determine significant differences between scores.
*/
template <typename IDType>
void switchScores(IDType& id, Size& counter)
{
for (auto hit_it = id.getHits().begin();
hit_it != id.getHits().end(); ++hit_it, ++counter)
{
if (!hit_it->metaValueExists(new_score_))
{
std::stringstream msg;
msg << "Meta value '" << new_score_ << "' not found for " << *hit_it;
throw Exception::MissingInformation(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION, msg.str());
}
const String& old_score_meta = (old_score_.empty() ? id.getScoreType() :
old_score_);
const DataValue& dv = hit_it->getMetaValue(old_score_meta);
if (!dv.isEmpty()) // meta value for old score already exists
{
// TODO: find a better way to check if old score type is something different (even if it has same name)
// This currently, is a workaround for e.g., having Percolator_qvalue as meta value and same q-value as main score (getScore()).
// Note by jpfeuffer: The problem with this is, that this may add the old score to some of the hits if different, but not
// all, in case one is by chance the same. I would be fine with this, if it was done in the beginning and checked
// for every score.
if (fabs((double(dv) - hit_it->getScore()) * 2.0 /
(double(dv) + hit_it->getScore())) > tolerance_)
{
hit_it->setMetaValue(old_score_meta + "~", hit_it->getScore());
}
}
else
{
hit_it->setMetaValue(old_score_meta, hit_it->getScore());
}
hit_it->setScore(hit_it->getMetaValue(new_score_));
}
id.setScoreType(new_score_type_);
id.setHigherScoreBetter(higher_better_);
}
/**
* @brief Switches the scoring type of identification objects to a general score type.
*
* This method iterates over a vector of identification objects and changes their scoring type
* to a specified general score type. It first checks the score type of the first identification
* object in the vector to determine the necessary conversion. If the first ID does not have the
* requested score type, an exception is thrown. The method also adjusts the score direction
* (higher_better_) based on the specified score type if it's different from the raw score.
*
* @tparam IDType The type of the identification objects contained in the vector. Must have
* getScoreType() and other relevant methods for score manipulation.
* @param[in,out] id A vector of identification objects whose score types are to be switched.
* @param[in] type The desired general score type to switch to. This could be an enum or similar
* representing different scoring systems (e.g., RAW, LOG, etc.).
* @param[in,out] counter A reference to a Size variable that may be used to count certain
* operations or changes made by this method. The exact usage depends on
* the implementation details and needs.
*
* @throws Exception::MissingInformation If the first identification object in the vector does not
* have the requested score type, indicating that the
* operation cannot proceed.
*
* @note The method assumes that if the first identification object has the correct score type,
* all subsequent objects in the vector also have the correct score type. This assumption
* might need validation depending on the use case.
*/
template<class IDType>
void switchToGeneralScoreType(std::vector<IDType>& id, ScoreType type, Size& counter)
{
if (id.empty()) return;
auto sr = findScoreType(id[0], type);
// If the main score is already of the requested type, assume all are set correctly
if (sr.is_main_score_type)
{
// we assume that all the other peptide ids
// also already have the correct score set
return;
}
// Otherwise we need a score name to switch to
if (sr.score_name.empty())
{
String msg = "First encountered ID does not have the requested score type.";
throw Exception::MissingInformation(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION, msg);
}
String t = sr.score_name;
if (t.hasSuffix("_score"))
{
new_score_type_ = t.chop(6);
}
else
{
new_score_type_ = t;
}
new_score_ = t;
if (higher_better_ != type_to_better_[type])
{
OPENMS_LOG_WARN << "Requested score type does not match the expected score direction. Correcting!\n";
higher_better_ = type_to_better_[type];
}
for (auto& i : id)
{
switchScores(i, counter);
}
}
/**
@brief Switches the score type of a PeptideIdentificationList to a general score type.
Overload for PeptideIdentificationList to avoid template deduction issues.
@param[in,out] pep_ids The PeptideIdentificationList whose scores need to be switched.
@param[in] type The desired general score type to switch to.
@param[in] counter A reference to a counter that will be incremented for each peptide identification processed.
*/
void switchToGeneralScoreType(PeptideIdentificationList& pep_ids, ScoreType type, Size& counter)
{
std::vector<PeptideIdentification>& vec = pep_ids.getData();
switchToGeneralScoreType(vec, type, counter);
}
/**
@brief Switches the score type of a ConsensusMap to a general score type.
Looks at the first Hit of the given ConsensusMap and according to the given score type,
deduces a fitting score and score direction to be switched to.
Then tries to switch all hits.
@param[in,out] cmap The ConsensusMap containing peptide identifications whose scores need to be switched.
@param[in] type The desired general score type to switch to.
@param[in] counter A reference to a counter that will be incremented for each peptide identification processed.
@param[in] unassigned_peptides_too A boolean flag indicating whether to include unassigned peptides in the score switching process. Default is true.
@throws Exception::MissingInformation If the first encountered ID does not have the requested score type.
*/
void switchToGeneralScoreType(ConsensusMap& cmap, ScoreType type, Size& counter, bool unassigned_peptides_too = true)
{
String new_type = "";
for (const auto& f : cmap)
{
const auto& ids = f.getPeptideIdentifications();
if (!ids.empty())
{
auto sr = findScoreType(ids[0], type);
if (sr.is_main_score_type)
{
return;
}
if (!sr.score_name.empty())
{
new_type = sr.score_name;
break;
}
}
}
if (new_type.empty())
{
String msg = "First encountered ID does not have the requested score type.";
throw Exception::MissingInformation(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION, msg);
}
if (new_type.hasSuffix("_score"))
{
new_score_type_ = new_type.chop(6);
}
else
{
new_score_type_ = new_type;
}
new_score_ = new_type;
if (higher_better_ != type_to_better_[type])
{
OPENMS_LOG_WARN << "Requested score type does not match the expected score direction. Correcting!\n";
higher_better_ = type_to_better_[type];
}
const auto switchScoresSingle = [&counter,this](PeptideIdentification& id){switchScores(id,counter);};
cmap.applyFunctionOnPeptideIDs(switchScoresSingle, unassigned_peptides_too);
}
/**
@brief Determines the score type and orientation of the main score for a set of peptide identifications.
This static method inspects a vector of PeptideIdentification objects to determine the overall score type and
whether a higher score is considered better. It uses the first PeptideIdentification in the vector to make this
determination, assuming that all identifications in the vector have the same score type and orientation.
@param[in] pep_ids The vector of PeptideIdentification objects to inspect.
@param[out] name Output parameter to store the determined overall score type.
@param[out] higher_better Output parameter to store whether a higher score is considered better.
@param[in] score_type Output parameter to store the determined score type.
@note This method assumes that all PeptideIdentification objects in the input vector have the same score type and orientation.
*/
void determineScoreNameOrientationAndType(
const PeptideIdentificationList& pep_ids,
String& name,
bool& higher_better,
ScoreType& score_type)
{
//TODO check all pep IDs? this assumes equality
if (!pep_ids.empty())
{
name = pep_ids[0].getScoreType(); // The name of the score. Typically a name like "XTandem" or "Percolator_qvalue"
higher_better = pep_ids[0].isHigherScoreBetter();
// look up the score category ("RAW", "PEP", "q-value", etc.) for the given score name
for (auto& [scoretype, names] : type_to_str_)
{
if (names.find(name) != names.end())
{
score_type = scoretype;
OPENMS_LOG_INFO << "Found score type " << name << " to be of type "
<< static_cast<std::underlying_type<ScoreType>::type>(scoretype) << std::endl;
return;
}
}
}
}
/**
@brief Determines the score type and orientation of the main score in a ConsensusMap.
This static method inspects a ConsensusMap to determine the overall score type and whether a higher score is
considered better. It iterates through the ConsensusMap's features and uses the first PeptideIdentification found
to determine the score type and orientation. If no assigned peptide identifications are found, it optionally
considers unassigned peptide identifications.
@param[in] cmap The ConsensusMap to inspect.
@param[out] name Output parameter to store the determined overall score type.
@param[out] higher_better Output parameter to store whether a higher score is considered better.
@param[in] score_type Output parameter to store the determined score type.
@param[in] include_unassigned If true, unassigned peptide identifications are considered if no assigned ones are found. Default is true.
*/
void determineScoreNameOrientationAndType(const ConsensusMap& cmap,
String& name,
bool& higher_better,
ScoreType& score_type,
bool include_unassigned = true)
{
name = "";
higher_better = true;
// TODO: check all pep IDs? this assumes equality to first encountered
for (const auto& cf : cmap)
{
const auto& pep_ids = cf.getPeptideIdentifications();
if (!pep_ids.empty())
{
name = pep_ids[0].getScoreType();
higher_better = pep_ids[0].isHigherScoreBetter();
// look up the score category ("RAW", "PEP", "q-value", etc.) for the given score name
for (auto& [scoretype, names] : type_to_str_)
{
if (names.find(name) != names.end())
{
score_type = scoretype;
return;
}
}
}
}
if (name.empty() && include_unassigned)
{
for (const auto& id : cmap.getUnassignedPeptideIdentifications())
{
name = id.getScoreType();
higher_better = id.isHigherScoreBetter();
// look up the score category ("RAW", "PEP", "q-value", etc.) for the given score name
for (auto& [scoretype, names] : type_to_str_)
{
if (names.find(name) != names.end())
{
score_type = scoretype;
return;
}
}
return;
}
}
}
/**
* @brief Switches the scores of peptide identifications in a ConsensusMap.
*
* This function iterates over all peptide identifications in the given ConsensusMap
* and switches their scores using the switchScores function. It also increments the
* provided counter for each peptide identification processed. Score names are
* taken from the algorithm's parameters. If the requested score is already set as the
* main score, the function returns without making any changes.
*
* @param[in] cmap The ConsensusMap containing peptide identifications whose scores need to be switched.
* @param[in] counter A reference to a counter that will be incremented for each peptide identification processed.
* @param[in] unassigned_peptides_too A boolean flag indicating whether to include unassigned peptides in the score switching process. Default is true.
*/
void switchScores(ConsensusMap& cmap, Size& counter, bool unassigned_peptides_too = true)
{
for (const auto& f : cmap)
{
const auto& ids = f.getPeptideIdentifications();
if (!ids.empty())
{
if (new_score_ == ids[0].getScoreType()) // correct score or category already set
{
return;
}
else
{
break;
}
}
}
const auto switchScoresSingle = [&counter,this](PeptideIdentification& id){switchScores(id,counter);};
cmap.applyFunctionOnPeptideIDs(switchScoresSingle, unassigned_peptides_too);
}
/**
* @brief Switches the scores of peptide identifications.
*
* This function iterates over all peptide identifications
* and switches their scores using the switchScores function. It also increments the
* provided counter for each peptide identification processed. Score names are
* taken from the algorithm's parameters. If the requested score is already set as the
* main score, the function returns without making any changes.
*
* @param[in] pep_ids The peptide identifications whose scores need to be switched.
* @param[in] counter A reference to a counter that will be incremented for each peptide identification processed.
*/
void switchScores(PeptideIdentificationList& pep_ids, Size& counter)
{
if (pep_ids.empty()) return;
if (new_score_ == pep_ids[0].getScoreType()) // correct score already set
{
return;
}
for (auto& id : pep_ids)
{
switchScores(id, counter);
}
}
/**
* @brief Structure holding score switching information for IDScoreSwitcherAlgorithm.
*
* This structure contains both the original and requested score details, including
* score names, their orientation (whether higher scores are better), and score types
* before and after the switch. It also includes a flag to indicate if the main score
* has been switched. Used to switch back to the original score if needed.
*/
struct IDSwitchResult
{
// the score name, orientation and type used before the switch
String original_score_name; /// The name of the original score used before the switch.
bool original_score_higher_better = true; /// whether a higher original score is better
IDScoreSwitcherAlgorithm::ScoreType original_score_type = IDScoreSwitcherAlgorithm::ScoreType::RAW; /// the type of the original score
// the score name, orientation and type used after the switch
bool requested_score_higher_better = original_score_higher_better; /// whether a higher requested score is better
IDScoreSwitcherAlgorithm::ScoreType requested_score_type = original_score_type; /// the type of the requested score
String requested_score_name; // the search engine score name (e.g. "X!Tandem_score" or score category (e.g. "PEP")
// wheter the main score was switched
bool score_switched = false; /// flag indicating whether the main score was switched
};
/**
* @brief Switches the score type of a ConsensusMap to the requested score type.
*
* This static method updates the scores within the provided ConsensusMap to the specified
* score type. It determines the original score properties, checks if a switch is necessary
* based on the requested score type, and performs the switch if required.
*
* @param[in] cmap The ConsensusMap object whose score types are to be switched.
* @param[in] requested_score_type_as_string The desired score type as a string (e.g., "RAW", "PEP", "q-value").
* @param[in] include_unassigned Optional flag indicating whether to include unassigned IDs in the score switch. Defaults to true.
*
* @return An IDSwitchResult structure containing information about the score switch operation, including the original and requested score names, types, and whether a switch was performed.
*/
static IDSwitchResult switchToScoreType(ConsensusMap& cmap, String requested_score_type_as_string, bool include_unassigned = true)
{
IDSwitchResult result;
// fill in the original score name, orientation and type
IDScoreSwitcherAlgorithm().determineScoreNameOrientationAndType(cmap,
result.original_score_name,
result.original_score_higher_better,
result.original_score_type,
include_unassigned);
// initalize with the assumption that the main score is the requested score
result.requested_score_name = result.original_score_name; // the search engine score name (e.g. "X!Tandem_score" or score category (e.g. "PEP")
result.requested_score_type = result.original_score_type;
result.requested_score_higher_better = result.original_score_higher_better;
// no score type specified -> use main score
if (requested_score_type_as_string.empty())
{
OPENMS_LOG_DEBUG << "No score type specified. Using main score." << std::endl;
return result;
}
// ENUM for requested score type (e.g. "RAW", "PEP", "q-value")
result.requested_score_type = IDScoreSwitcherAlgorithm::toScoreTypeEnum(requested_score_type_as_string);
if (result.requested_score_type != result.original_score_type) // switch needed because we change type?
{ // user requests a different score type than the main score
result.requested_score_higher_better = IDScoreSwitcherAlgorithm().isScoreTypeHigherBetter(result.requested_score_type);
IDScoreSwitcherAlgorithm idsa;
auto param = idsa.getDefaults();
param.setValue("new_score", result.requested_score_name);
param.setValue("new_score_orientation", result.requested_score_higher_better ? "higher_better" : "lower_better");
param.setValue("proteins", "false");
param.setValue("old_score", ""); // use default name generated for old score
idsa.setParameters(param);
Size counter = 0;
idsa.switchToGeneralScoreType(cmap, result.requested_score_type, counter, include_unassigned);
OPENMS_LOG_DEBUG << "Switched scores for " << counter << " IDs." << std::endl;
result.score_switched = true;
}
// update after potential switch and read out actual score name
IDScoreSwitcherAlgorithm().determineScoreNameOrientationAndType(cmap,
result.requested_score_name,
result.requested_score_higher_better,
result.requested_score_type,
include_unassigned);
return result;
}
/**
* @brief Switches the score type of peptide identifications to the requested type.
*
* This static function modifies the provided vector of PeptideIdentification objects by switching
* their main score to the specified type. If no score type is requested, the original main score
* is retained. The function determines the original score's name, orientation, and type, and updates
* these attributes based on the requested score type. If a different score type is requested,
* it performs the switch and updates the relevant score information.
*
* @param[in] pep_ids A vector of PeptideIdentification objects to be processed.
* @param[in] requested_score_type_as_string The desired score type as a string (e.g., "RAW", "PEP", "q-value").
* @return IDSwitchResult A struct containing details about the original and requested score types,
* whether a switch was performed, and the number of IDs updated.
*/
static IDSwitchResult switchToScoreType(PeptideIdentificationList& pep_ids, String requested_score_type_as_string)
{
IDSwitchResult result;
// fill in the original score name, orientation and type
IDScoreSwitcherAlgorithm().determineScoreNameOrientationAndType(pep_ids,
result.original_score_name,
result.original_score_higher_better,
result.original_score_type
);
// initalize with the assumption that the main score is the requested score
result.requested_score_name = result.original_score_name; // the search engine score name (e.g. "X!Tandem_score" or score category (e.g. "PEP")
result.requested_score_type = result.original_score_type;
result.requested_score_higher_better = result.original_score_higher_better;
// no score type specified -> use main score
if (requested_score_type_as_string.empty())
{
OPENMS_LOG_DEBUG << "No score type specified. Using main score." << std::endl;
return result;
}
// ENUM for requested score type (e.g. "RAW", "PEP", "q-value")
result.requested_score_type = IDScoreSwitcherAlgorithm::toScoreTypeEnum(requested_score_type_as_string);
if (result.requested_score_type != result.original_score_type) // switch needed because we change type?
{ // user requests a different score type than the main score
result.requested_score_higher_better = IDScoreSwitcherAlgorithm().isScoreTypeHigherBetter(result.requested_score_type);
IDScoreSwitcherAlgorithm idsa;
auto param = idsa.getDefaults();
param.setValue("new_score", result.requested_score_name);
param.setValue("new_score_orientation", result.requested_score_higher_better ? "higher_better" : "lower_better");
param.setValue("proteins", "false");
param.setValue("old_score", ""); // use default name generated for old score
idsa.setParameters(param);
Size counter = 0;
idsa.switchToGeneralScoreType(pep_ids, result.requested_score_type, counter);
OPENMS_LOG_DEBUG << "Switched scores for " << counter << " IDs." << std::endl;
result.score_switched = true;
}
// update after potential switch and read out actual score name
IDScoreSwitcherAlgorithm().determineScoreNameOrientationAndType(pep_ids,
result.requested_score_name,
result.requested_score_higher_better,
result.requested_score_type
);
return result;
}
/**
* @brief Reverts the score type of a ConsensusMap to its original type based on the provided IDSwitchResult.
*
* This function checks if the scores have been switched and, if so, it switches them back to the original score type.
* It updates the ConsensusMap by switching the scores, optionally including unassigned PSMs.
*
* @param[in] cmap The ConsensusMap object whose scores will be modified.
* @param[out] isr The IDSwitchResult containing information about the score switch.
* @param[in] include_unassigned A boolean flag indicating whether to include unassigned PSMs in the score switching process. Defaults to true.
*/
static void switchBackScoreType(ConsensusMap& cmap, IDSwitchResult isr, bool include_unassigned = true)
{
if (isr.score_switched)
{
// switch back to original score
IDScoreSwitcherAlgorithm idsa;
auto param = idsa.getDefaults();
param.setValue("new_score", isr.original_score_name);
param.setValue("new_score_orientation", isr.original_score_higher_better ? "higher_better" : "lower_better");
param.setValue("proteins", "false");
param.setValue("old_score", ""); // use default name generated for old score
idsa.setParameters(param);
Size counter = 0;
idsa.switchScores(cmap, counter, include_unassigned);
OPENMS_LOG_DEBUG << "Switched scores back for " << counter << " PSMs." << std::endl;
}
}
/**
* @brief Reverts the scoring type of peptide identifications to their original scores.
*
* This function checks if the scores have been switched. If so, it restores the original scoring parameters
* using the provided IDSwitchResult. It updates the peptide identifications accordingly and logs the number
* of PSMs (Peptide-Spectrum Matches) that were reverted.
*
* @param[in] pep_ids A vector of PeptideIdentification objects to be updated.
* @param[out] isr An IDSwitchResult object containing information about the score switch state and original score details.
*/
static void switchBackScoreType(PeptideIdentificationList& pep_ids, IDSwitchResult isr)
{
if (isr.score_switched)
{
// switch back to original score
IDScoreSwitcherAlgorithm idsa;
auto param = idsa.getDefaults();
param.setValue("new_score", isr.original_score_name);
param.setValue("new_score_orientation", isr.original_score_higher_better ? "higher_better" : "lower_better");
param.setValue("proteins", "false");
param.setValue("old_score", ""); // use default name generated for old score
idsa.setParameters(param);
Size counter = 0;
idsa.switchScores(pep_ids, counter);
OPENMS_LOG_DEBUG << "Switched scores back for " << counter << " PSMs." << std::endl;
}
}
private:
void updateMembers_() override; ///< documented in base class
/// relative tolerance for score comparisons:
const double tolerance_ = 1e-6;
/// will be set according to the algorithm parameters
String new_score_, new_score_type_, old_score_;
/// will be set according to the algorithm parameters
bool higher_better_; // for the new scores, are higher ones better?
/// a map from ScoreType to their names as used around OpenMS
std::map<ScoreType, std::set<String>> type_to_str_ =
{
//TODO introduce real meaningful score names for XTandem, Mascot etc. (e.g., hyperscore)
{ScoreType::RAW, {"svm", "MS:1001492", "XTandem", "OMSSA", "SEQUEST:xcorr", "Mascot", "mvh", "hyperscore", "ln(hyperscore)"}},
//TODO find out reasonable raw scores for SES that provide E-Values as main score or see below
//TODO there is no test for spectraST idXML, so I don't know its score
//TODO check if we should combine RAW and RAW_EVAL:
// What if a SE does not have an e-value score (spectrast, OMSSA, crux/sequest, myrimatch),
// then you need additional if's/try's
{ScoreType::RAW_EVAL, {"expect", "SpecEValue", "E-Value", "evalue", "MS:1002053", "MS:1002257"}},
{ScoreType::PP, {"Posterior Probability"}},
{ScoreType::PEP, {"Posterior Error Probability", "pep", "PEP", "posterior_error_probability", "MS:1001493"}}, // TODO add CV terms
{ScoreType::FDR, {"FDR", "fdr", "false discovery rate"}},
{ScoreType::QVAL, {"q-value", "qvalue", "MS:1001491", "q-Value", "qval"}}
};
/// a map from ScoreType to their ordering
std::map<ScoreType, bool> type_to_better_ =
{
{ScoreType::RAW, true}, //TODO this might actually not always be true
{ScoreType::RAW_EVAL, false},
{ScoreType::PP, true},
{ScoreType::PEP, false},
{ScoreType::FDR, false},
{ScoreType::QVAL, false}
};
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/ID/IDConflictResolverAlgorithm.h | .h | 8,392 | 193 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hendrik Weisser $
// $Authors: Hendrik Weisser, Lucia Espona, Moritz Freidank $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/ConsensusMap.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
//-------------------------------------------------------------
// Doxygen docu
//-------------------------------------------------------------
namespace OpenMS
{
/**
@brief Resolves ambiguous annotations of features with peptide identifications.
The peptide identifications are filtered so that only one identification
with a single hit (with the best score) is associated to each feature.
(If two IDs have the same best score, either one of them may be selected.)
*/
class OPENMS_DLLAPI IDConflictResolverAlgorithm
{
public:
/** @brief Resolves ambiguous annotations of features with peptide identifications.
The the filtered identifications are added to the vector of unassigned peptides
and also reduced to a single best hit.
@param[in] features Features to work on
@param[in,out] keep_matching Keeps all IDs that match the modified sequence of the best
hit in the feature (e.g. keeps all IDs in a ConsensusMap if id'd same across multiple runs)
**/
static void resolve(FeatureMap& features, bool keep_matching = false);
/** @brief Resolves ambiguous annotations of consensus features with peptide identifications.
The the filtered identifications are added to the vector of unassigned peptides
and also reduced to a single best hit.
@param[in] features Features to work on
@param[in,out] keep_matching Keeps all IDs that match the modified sequence of the best
hit in the feature (e.g. keeps all IDs in a ConsensusMap if id'd same across multiple runs)
**/
static void resolve(ConsensusMap& features, bool keep_matching = false);
/** @brief In a single (feature/consensus) map, features with the same (possibly modified) sequence and charge state may appear.
This filter removes the peptide sequence annotations from features, if a higher-intensity feature with the same (charge, sequence)
combination exists in the map. The total number of features remains unchanged. In the final output, each (charge, sequence) combination
appears only once, i.e. no multiplicities.
**/
static void resolveBetweenFeatures(FeatureMap& features);
/** @brief In a single (feature/consensus) map, features with the same (possibly modified) sequence and charge state may appear.
This filter removes the peptide sequence annotations from features, if a higher-intensity feature with the same (charge, sequence)
combination exists in the map. The total number of features remains unchanged. In the final output, each (charge, sequence) combination
appears only once, i.e. no multiplicities.
**/
static void resolveBetweenFeatures(ConsensusMap& features);
protected:
template<class T>
static void resolveConflict_(T& map, bool keep_matching)
{
// annotate as not part of the resolution
for (PeptideIdentification& p : map.getUnassignedPeptideIdentifications())
{
p.setMetaValue("feature_id", "not mapped"); // not mapped to a feature
}
for (auto& c : map)
{
c.setMetaValue("feature_id", String(c.getUniqueId()));
if (!keep_matching)
{
resolveConflict_(c.getPeptideIdentifications(),
map.getUnassignedPeptideIdentifications(),
c.getUniqueId());
}
else
{
resolveConflictKeepMatching_(c.getPeptideIdentifications(),
map.getUnassignedPeptideIdentifications(),
c.getUniqueId());
}
}
}
// compare peptide IDs by score of best hit (hits must be sorted first!)
// (note to self: the "static" is necessary to avoid cryptic "no matching
// function" errors from gcc when the comparator is used below)
static bool compareIDsSmallerScores_(const PeptideIdentification & left,
const PeptideIdentification & right);
static void resolveConflict_(
PeptideIdentificationList & peptides,
PeptideIdentificationList & removed,
UInt64 uid);
static void resolveConflictKeepMatching_(
PeptideIdentificationList & peptides,
PeptideIdentificationList & removed,
UInt64 uid);
template<class T>
static void resolveBetweenFeatures_(T & map)
{
// unassigned peptide identifications in this map
PeptideIdentificationList& unassigned = map.getUnassignedPeptideIdentifications();
// A std::map tracking the set of unique features.
// Uniqueness criterion/key is a pair <charge, sequence> for each feature. The peptide sequence may be modified, i.e. is not stripped.
typedef std::map<std::pair<Int, AASequence>, typename T::value_type*> FeatureSet;
FeatureSet feature_set;
// Create a std::map `feature_set` mapping pairs <charge, sequence> to a pointer to
// the feature with the highest intensity for this sequence.
for (typename T::value_type& element : map)
{
PeptideIdentificationList& pep_ids = element.getPeptideIdentifications();
if (!pep_ids.empty())
{
if (pep_ids.size() != 1)
{
// Should never happen. In IDConflictResolverAlgorithm TOPP tool
// IDConflictResolverAlgorithm::resolve() is called before IDConflictResolverAlgorithm::resolveBetweenFeatures().
throw OpenMS::Exception::IllegalArgument(__FILE__, __LINE__, __FUNCTION__, "Feature does contain multiple identifications.");
}
// Make sure best hit is in front, i.e. sort hits first.
pep_ids.front().sort();
const std::vector<PeptideHit>& hits = pep_ids.front().getHits();
if (!hits.empty())
{
const PeptideHit& highest_score_hit = hits.front();
// Pair <charge, sequence> of charge of the new feature and the sequence of its highest scoring peptide hit.
std::pair<Int, AASequence> pair = std::make_pair(element.getCharge(), highest_score_hit.getSequence());
// If a <charge, sequence> pair is not yet in the FeatureSet or new feature `feature_in_set`
// has higher intensity than its counterpart `feature_set[<charge, sequence>]`
// store a pointer to `feature_in_set` in `feature_set`.
typename FeatureSet::iterator feature_in_set = feature_set.find(pair);
if (feature_in_set != feature_set.end())
{
// Identical (charge, sequence) key found. Remove annotations from either the old or new feature.
if (feature_in_set->second->getIntensity() < element.getIntensity())
{
// Remove annotations from the old low-intensity feature. But only after moving these annotations to the unassigned list.
PeptideIdentificationList& obsolete = feature_in_set->second->getPeptideIdentifications();
unassigned.insert(unassigned.end(), obsolete.begin(), obsolete.end());
PeptideIdentificationList pep_ids_empty;
feature_in_set->second->setPeptideIdentifications(pep_ids_empty);
// Replace feature in the set.
feature_in_set->second = &(element);
}
else
{
// Remove annotations from the new low-intensity feature. But only after moving these annotations to the unassigned list.
PeptideIdentificationList& obsolete = element.getPeptideIdentifications();
unassigned.insert(unassigned.end(), obsolete.begin(), obsolete.end());
PeptideIdentificationList pep_ids_empty;
element.setPeptideIdentifications(pep_ids_empty);
}
}
else
{
// Feature is not yet in our set -- add it.
feature_set[pair] = &(element);
}
}
}
}
}
};
}// namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/ID/HyperScore.h | .h | 5,726 | 108 | // 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, Chris Bielow $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/CONCEPT/Types.h>
#include <OpenMS/CONCEPT/Macros.h>
#include <OpenMS/KERNEL/MSSpectrum.h>
#include <vector>
namespace OpenMS
{
/**
* @brief An implementation of the X!Tandem HyperScore PSM scoring function
*/
struct OPENMS_DLLAPI HyperScore
{
typedef std::pair<Size, double> IndexScorePair;
/** @brief compute the (ln transformed) X!Tandem HyperScore
* 1. the dot product of peak intensities between matching peaks in experimental and theoretical spectrum is calculated
* 2. the HyperScore is calculated from the dot product by multiplying by factorials of matching b- and y-ions
* @note Peak intensities of the theoretical spectrum are typically 1 or TIC normalized, but can also be e.g. ion probabilities
* @param[in] fragment_mass_tolerance mass tolerance applied left and right of the theoretical spectrum peak position
* @param[in] fragment_mass_tolerance_unit_ppm Unit of the mass tolerance is: Thomson if false, ppm if true
* @param[in] exp_spectrum measured spectrum
* @param[in] theo_spectrum theoretical spectrum Peaks need to contain an ion annotation as provided by TheoreticalSpectrumGenerator.
*/
// static double compute(double fragment_mass_tolerance, bool fragment_mass_tolerance_unit_ppm, const PeakSpectrum& exp_spectrum, const RichPeakSpectrum& theo_spectrum);
static double compute(double fragment_mass_tolerance,
bool fragment_mass_tolerance_unit_ppm,
const PeakSpectrum& exp_spectrum,
const PeakSpectrum& theo_spectrum);
/** @brief compute the (ln transformed) X!Tandem HyperScore
* overload that returns some additional information on the match
*/
struct PSMDetail
{
size_t matched_b_ions = 0;
size_t matched_y_ions = 0;
double mean_error = 0.0;
};
static double computeWithDetail(double fragment_mass_tolerance,
bool fragment_mass_tolerance_unit_ppm,
const PeakSpectrum& exp_spectrum,
const PeakSpectrum& theo_spectrum,
PSMDetail& d
);
/* @brief compute the (ln transformed) X!Tandem HyperScore only matching peaks that match in charge
* 1. the dot product of peak intensities between matching peaks in experimental and theoretical spectrum is calculated
* 2. the HyperScore is calculated from the dot product by multiplying by factorials of matching b- and y-ions
* @note Peak intensities of the theoretical spectrum are typically 1 or TIC normalized, but can also be e.g. ion probabilities
* @param[in] fragment_mass_tolerance mass tolerance applied left and right of the theoretical spectrum peak position
* @param[in] fragment_mass_tolerance_unit_ppm Unit of the mass tolerance is: Thomson if false, ppm if true
* @param[in] exp_spectrum measured spectrum
* @param[in] exp_charges charges of measured peaks
* @param[in] theo_spectrum theoretical spectrum Peaks need to contain an ion annotation as provided by TheoreticalSpectrumGenerator.
* @param[in] theo_charges charges of theoretical peaks
*/
static double compute(double fragment_mass_tolerance,
bool fragment_mass_tolerance_unit_ppm,
const PeakSpectrum& exp_spectrum,
const DataArrays::IntegerDataArray& exp_charges,
const PeakSpectrum& theo_spectrum,
const DataArrays::IntegerDataArray& theo_charges);
/* @brief compute the (ln transformed) X!Tandem HyperScore only matching peaks that match in charge
* 1. the dot product of peak intensities between matching peaks in experimental and theoretical spectrum is calculated
* 2. the HyperScore is calculated from the dot product by multiplying by factorials of matching b- and y-ions
* @note Peak intensities of the theoretical spectrum are typically 1 or TIC normalized, but can also be e.g. ion probabilities
* @param[in] fragment_mass_tolerance mass tolerance applied left and right of the theoretical spectrum peak position
* @param[in] fragment_mass_tolerance_unit_ppm Unit of the mass tolerance is: Thomson if false, ppm if true
* @param[in] exp_spectrum measured spectrum
* @param[in] exp_charges charges of measured peaks
* @param[in] theo_spectrum theoretical spectrum Peaks need to contain an ion annotation as provided by TheoreticalSpectrumGenerator.
* @param[in] theo_charges charges of theoretical peaks
* @param[in] intensity_sum summed intensity for observed bond indices (e.g., b3=123 -> intensity_sum[2]=123)
* Note: intensity_sum must be zeroed and of size #AA in peptide
*/
static double compute(double fragment_mass_tolerance,
bool fragment_mass_tolerance_unit_ppm,
const PeakSpectrum& exp_spectrum,
const DataArrays::IntegerDataArray& exp_charges,
const PeakSpectrum& theo_spectrum,
const DataArrays::IntegerDataArray& theo_charges,
std::vector<double>& intensity_sum);
private:
/// helper to compute the log factorial
static double logfactorial_(const int x, int base = 2);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/ID/SimpleSearchEngineAlgorithm.h | .h | 4,266 | 129 | // 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 $
// --------------------------------------------------------------------------
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/CHEMISTRY/ModifiedPeptideGenerator.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/DATASTRUCTURES/StringView.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <vector>
namespace OpenMS
{
class OPENMS_DLLAPI SimpleSearchEngineAlgorithm :
public DefaultParamHandler,
public ProgressLogger
{
public:
SimpleSearchEngineAlgorithm();
/// Exit codes
enum class ExitCodes
{
EXECUTION_OK,
INPUT_FILE_EMPTY,
UNEXPECTED_RESULT,
UNKNOWN_ERROR,
ILLEGAL_PARAMETERS
};
/// @brief search spectra against database
ExitCodes search(const String& in_mzML,
const String& in_db,
std::vector<ProteinIdentification>& prot_ids,
PeptideIdentificationList& pep_ids) const;
protected:
void updateMembers_() override;
/// Slimmer structure as storing all scored candidates in PeptideHit objects takes too much space
struct AnnotatedHit_
{
StringView sequence;
SignedSize peptide_mod_index; ///< enumeration index of the non-RNA peptide modification
double score = 0; ///< main score
double prefix_fraction = 0; ///< fraction of annotated b-ions
double suffix_fraction = 0; ///< fraction of annotated y-ions
double mean_error = 0.0; ///< mean absolute fragment mass error
int isotope_error = 0;
std::vector<PeptideHit::PeakAnnotation> fragment_annotations;
static bool hasBetterScore(const AnnotatedHit_& a, const AnnotatedHit_& b)
{
if (a.score != b.score) return a.score > b.score;
// compare the mod_index first, as it is cheaper than the strncmp() of the sequences
// there doesn't have to be a certain ordering (that makes sense), we just need it to be thread-safe
if (b.peptide_mod_index != a.peptide_mod_index) return a.peptide_mod_index < b.peptide_mod_index;
return a.sequence < b.sequence;
}
};
/// @brief filter, deisotope, decharge spectra
static void preprocessSpectra_(PeakMap& exp, double fragment_mass_tolerance, bool fragment_mass_tolerance_unit_ppm);
/// @brief filter and annotate search results
/// most of the parameters are used to properly add meta data to the id objects
void postProcessHits_(const PeakMap& exp,
std::vector<std::vector<SimpleSearchEngineAlgorithm::AnnotatedHit_> >& annotated_hits,
std::vector<ProteinIdentification>& protein_ids,
PeptideIdentificationList& peptide_ids,
Size top_hits,
const ModifiedPeptideGenerator::MapToResidueType& fixed_modifications,
const ModifiedPeptideGenerator::MapToResidueType& variable_modifications,
Size max_variable_mods_per_peptide,
const StringList& modifications_fixed,
const StringList& modifications_variable,
Int peptide_missed_cleavages,
double precursor_mass_tolerance,
double fragment_mass_tolerance,
const String& precursor_mass_tolerance_unit_ppm,
const String& fragment_mass_tolerance_unit_ppm,
const Int precursor_min_charge,
const Int precursor_max_charge,
const String& enzyme,
const String& database_name) const;
double precursor_mass_tolerance_;
String precursor_mass_tolerance_unit_;
Size precursor_min_charge_;
Size precursor_max_charge_;
IntList precursor_isotopes_;
double fragment_mass_tolerance_;
String fragment_mass_tolerance_unit_;
StringList modifications_fixed_;
StringList modifications_variable_;
Size modifications_max_variable_mods_per_peptide_;
String enzyme_;
bool decoys_;
StringList annotate_psm_;
Size peptide_min_size_;
Size peptide_max_size_;
Size peptide_missed_cleavages_;
String peptide_motif_;
Size report_top_hits_;
};
} // namespace
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/ID/BayesianProteinInferenceAlgorithm.h | .h | 7,224 | 150 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Julianus Pfeuffer $
// $Authors: Julianus Pfeuffer $
// --------------------------------------------------------------------------
#pragma once
//#define INFERENCE_BENCH
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/METADATA/ExperimentalDesign.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/ML/GRIDSEARCH/GridSearch.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <vector>
#include <functional>
#include <optional>
namespace OpenMS
{
class ConsensusMap;
namespace Internal
{
class IDBoostGraph;
}
class PeptideIdentification;
class ProteinIdentification;
/**
* @brief Performs a Bayesian protein inference on Protein/Peptide identifications or ConsensusMap (experimental).
* - Filters for best n PSMs per spectrum.
* - Calculates and filters for best peptide per spectrum.
* - Builds a k-partite graph from the structures.
* - Finds and splits into connected components by DFS
* - Extends the graph by adding layers from indist. protein groups, peptides with the same parents and optionally
* some additional layers (peptide sequence, charge, replicate -> extended model = experimental)
* - Builds a factor graph representation of a Bayesian network using the Evergreen library
* See model param section. It is based on the Fido noisy-OR model with an option for
* regularizing the number of proteins per peptide.
* - Performs loopy belief propagation on the graph and queries protein, protein group and/or peptide posteriors
* See loopy_belief_propagation param section.
* - Learns best parameters via grid search if the parameters were not given in the param section.
* - Writes posteriors to peptides and/or proteins and adds indistinguishable protein groups to the underlying
* data structures.
* - Can make use of OpenMP to parallelize over connected components.
*/
class OPENMS_DLLAPI BayesianProteinInferenceAlgorithm :
public DefaultParamHandler,
public ProgressLogger
{
public:
/// Constructor @todo is there a better way to pass the debug level from TOPPBase?
explicit BayesianProteinInferenceAlgorithm(unsigned int debug_lvl = 0);
/// Destructor
~BayesianProteinInferenceAlgorithm() override = default;
void updateMembers_() override;
/// A function object to pass into the IDBoostGraph class to perform algorithms on
/// connected components
class GraphInferenceFunctor;
/// A function object to pass into the IDBoostGraph class to perform algorithms on
/// connected components. This can make use of additional layers. @todo use static type checking
/// by using two different Graph types
class ExtendedGraphInferenceFunctor;
/// A function object to pass into the GridSearch class
struct GridSearchEvaluator;
/**
* @brief Perform inference. Filter, build graph, run the private inferPosteriorProbabilities_ function.
* Writes its results into protein and (optionally also) peptide hits (as new score).
* Optionally adds indistinguishable protein groups with separate scores, too.
* Output scores are always posterior probabilities. Input can be posterior or error probabilities.
* See Param object defaults_ within the BayesianProteinInferenceAlgorithm for more settings.
* Currently only takes first proteinID run and all peptides (irrespective of getIdentifier()).
* @param[in,out] proteinIDs Input/output proteins
* @param[in,out] peptideIDs Input/output peptides
* @param[in] greedy_group_resolution Do greedy group resolution? Remove all but best association for "razor" peptides.
* @param[in] exp_des Experimental design can be used to create an extended graph with replicate information. (experimental)
*
* @todo loop over all runs
*
*/
void inferPosteriorProbabilities(
std::vector<ProteinIdentification>& proteinIDs,
PeptideIdentificationList& peptideIDs,
bool greedy_group_resolution,
std::optional<const ExperimentalDesign> exp_des = std::optional<const ExperimentalDesign>());
/**
* @brief Perform inference. Filter, build graph, run the private inferPosteriorProbabilities_ function.
* Writes its results into protein and (optionally also) peptide hits (as new score).
* Optionally adds indistinguishable protein groups with separate scores, too.
* Output scores are always posterior probabilities. Input can be posterior or error probabilities.
* See Param object defaults_ within the BayesianProteinInferenceAlgorithm for more settings.
* Requires a single merged ProteinIdentification run in the @p cmap (i.e. @p cmap.getProteinIdentifications().size() == 1)
* with peptide IDs referring to that run. For study-wide inference across multiple runs/files, merge runs first
* (ConsensusMapMergerAlgorithm::mergeAllIDRuns).
* @param[in,out] cmap Features with input/output peptides and proteins (from getProteinIdentifications)
* @param[in] greedy_group_resolution Do greedy group resolution? Remove all but best association for "razor" peptides.
* @param[in] exp_des Experimental design can be used to create an extended graph with replicate information. (experimental)
*/
void inferPosteriorProbabilities(
ConsensusMap& cmap,
bool greedy_group_resolution,
std::optional<const ExperimentalDesign> exp_des = std::optional<const ExperimentalDesign>());
private:
/// after a graph was built, use this method to perform inference and write results to the structures
/// with which the graph was built
void inferPosteriorProbabilities_(Internal::IDBoostGraph& ibg);
/// read Param object and set the grid
GridSearch<double,double,double> initGridSearchFromParams_(
std::vector<double>& alpha_search,
std::vector<double>& beta_search,
std::vector<double>& gamma_search
);
/// set score type and settings for every ProteinID run processed
void setScoreTypeAndSettings_(ProteinIdentification& proteinIDs);
/// reset all protein scores to 0.0, save old ones as Prior MetaValue if requested
// TODO double-check if -1 is maybe the better option
// to distinguish between "untouched/unused/unreferenced" (e.g. if somehow
// not removed/filtered) and an inferred probability of 0.0. But it might give
// problems in FDR algorithms if not ignored/removed correctly
void resetProteinScores_(ProteinIdentification& protein_id, bool keep_old_as_prior);
/// function initialized based on the algorithm parameters that is used to filter PeptideHits
/// @todo extend to allow filtering only for the current run
std::function<void(PeptideIdentification&/*, const String& run_id*/)> checkConvertAndFilterPepHits_;
unsigned int debug_lvl_;
#ifdef INFERENCE_BENCH
std::vector<std::pair<double,Size>> debug_times_;
#endif
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/ID/IDDecoyProbability.h | .h | 4,329 | 129 | // 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/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/MATH/STATISTICS/GammaDistributionFitter.h>
#include <OpenMS/MATH/STATISTICS/GaussFitter.h>
#include <vector>
namespace OpenMS
{
/**
@brief IDDecoyProbability calculates probabilities using decoy approach
This class calculates the probabilities using a target decoy approach. Like
in peptide prophet the forward distribution is modeled using a gaussian
distribution the reverse scores are modeled using a gamma distribution.
@htmlinclude OpenMS_IDDecoyProbability.parameters
@ingroup Analysis_ID
*/
class OPENMS_DLLAPI IDDecoyProbability :
public DefaultParamHandler
{
public:
/// Default constructor
IDDecoyProbability();
/// Copy constructor
IDDecoyProbability(const IDDecoyProbability & rhs);
/// Destructor
~IDDecoyProbability() override;
/// assignment operator
IDDecoyProbability & operator=(const IDDecoyProbability & rhs);
/** @brief Converts the forward and reverse identification into probabilities
@param[out] prob_ids Output of the algorithm which includes identifications with probability based scores
@param[in] fwd_ids Input parameter which represents the identifications of the forward search
@param[in] rev_ids Input parameter which represents the identifications of the reversed search
*/
void apply(PeptideIdentificationList & prob_ids,
const PeptideIdentificationList & fwd_ids,
const PeptideIdentificationList & rev_ids);
void apply(PeptideIdentificationList & ids);
protected:
/** @brief struct to be used to store a transformation (used for fitting)
*/
struct Transformation_
{
Transformation_() :
max_intensity(0),
diff_score(0),
min_score(0),
max_score(0),
max_intensity_bin(0)
{
}
Transformation_(const Transformation_ & rhs) :
max_intensity(rhs.max_intensity),
diff_score(rhs.diff_score),
min_score(rhs.min_score),
max_score(rhs.max_score),
max_intensity_bin(rhs.max_intensity_bin)
{
}
Transformation_ & operator=(const Transformation_ & rhs)
{
if (this != &rhs)
{
max_intensity = rhs.max_intensity;
diff_score = rhs.diff_score;
min_score = rhs.min_score;
max_score = rhs.max_score;
max_intensity_bin = rhs.max_intensity_bin;
}
return *this;
}
double max_intensity;
double diff_score;
double min_score;
double max_score;
Size max_intensity_bin;
};
// normalizes histograms
void normalizeBins_(const std::vector<double> & scores, std::vector<double> & binned, Transformation_ & trafo);
// returns the probability of given score with the transformations of reverse and forward searches and the results of the fits
double getProbability_(const Math::GammaDistributionFitter::GammaDistributionFitResult & result_gamma,
const Transformation_ & gamma_trafo,
const Math::GaussFitter::GaussFitResult & result_gauss,
const Transformation_ & gauss_trafo,
double score);
void generateDistributionImage_(const std::vector<double> & ids, const String & formula, const String & filename);
void generateDistributionImage_(const std::vector<double> & all_ids, const Transformation_ & all_trans, const String & fwd_formula, const String & rev_formula, const String & filename);
void apply_(PeptideIdentificationList & ids, const std::vector<double> & rev_scores, const std::vector<double> & fwd_scores, const std::vector<double> & all_scores);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/ID/PercolatorFeatureSetHelper.h | .h | 8,277 | 181 | // 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, Matthew The $
// --------------------------------------------------------------------------
#pragma once
#include <vector>
#include <cmath>
#include <string>
#include <map>
// #include <algorithm>
#include <limits>
#include <OpenMS/CONCEPT/Types.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/FORMAT/FileHandler.h>
#include <OpenMS/DATASTRUCTURES/DataValue.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <OpenMS/METADATA/ProteinIdentification.h>
namespace OpenMS
{
/**
@brief Percolator feature set and integration helper
This class contains functions to handle (compute, aggregate, integrate)
Percolator features. This includes the calculation or extraction of
Percolator features depending on the search engine(s) for later use with
PercolatorAdapter. It also includes handling the reintegration of the
percolator result into the set of Identifications.
*/
class OPENMS_DLLAPI PercolatorFeatureSetHelper
{
public:
/**
@brief concatMULTISEPeptideIds
@param[in] all_peptide_ids PeptideIdentification vector to append to
@param[in] new_peptide_ids PeptideIdentification vector to be appended
@param[in] search_engine search engine to depend on for feature creation
Appends a vector of PeptideIdentification to another and prepares Percolator features in MetaInfo (With the respective key "CONCAT:" + search_engine).
*/
static void concatMULTISEPeptideIds(PeptideIdentificationList& all_peptide_ids, PeptideIdentificationList& new_peptide_ids, const String& search_engine);
/**
@brief mergeMULTISEPeptideIds
@param[in] all_peptide_ids PeptideIdentification vector to be merged into
@param[in] new_peptide_ids PeptideIdentification vector to merge
@param[in] search_engine search engine to create features from their scores
Merges a vector of PeptideIdentification into another and prepares the merged MetaInfo and scores for collection in addMULTISEFeatures for feature registration.
*/
static void mergeMULTISEPeptideIds(PeptideIdentificationList& all_peptide_ids, PeptideIdentificationList& new_peptide_ids, const String& search_engine);
/**
@brief mergeMULTISEProteinIds
@param[in] all_protein_ids ProteinIdentification vector to be merged into
@param[in] new_protein_ids ProteinIdentification vector to merge
Concatenates SearchParameter of multiple search engine runs and merges PeptideEvidences, collects used search engines in MetaInfo for collection in addMULTISEFeatures for feature registration.
*/
static void mergeMULTISEProteinIds(std::vector<ProteinIdentification>& all_protein_ids, std::vector<ProteinIdentification>& new_protein_ids);
/**
@brief addMSGFFeatures
@param[in] peptide_ids PeptideIdentification vector to create Percolator features in
@param[in] feature_set register of added features
Creates and adds MSGF+ specific Percolator features and registers them in feature_set. MSGF+ should be run with the addFeatures flag enabled.
*/
static void addMSGFFeatures(PeptideIdentificationList& peptide_ids, StringList& feature_set);
/**
@brief addXTANDEMFeatures
@param[in] peptide_ids PeptideIdentification vector to create Percolator features in
@param[in] feature_set register of added features
Creates and adds X!Tandem specific Percolator features and registers them in feature_set
*/
static void addXTANDEMFeatures(PeptideIdentificationList& peptide_ids, StringList& feature_set);
/**
@brief addCOMETFeatures
@param[in] peptide_ids PeptideIdentification vector to create Percolator features in
@param[in] feature_set register of added features
Creates and adds Comet specific Percolator features and registers them in feature_set
*/
static void addCOMETFeatures(PeptideIdentificationList& peptide_ids, StringList& feature_set);
/**
@brief addMASCOTFeatures
@param[in] peptide_ids PeptideIdentification vector to create Percolator features in
@param[in] feature_set register of added features
Creates and adds Mascot specific Percolator features and registers them in feature_set
*/
static void addMASCOTFeatures(PeptideIdentificationList& peptide_ids, StringList& feature_set);
/**
@brief addMULTISEFeatures
@param[in] peptide_ids PeptideIdentification vector to create Percolator features in
@param[in] search_engines_used the list of search engines to be considered
@param[in] feature_set register of added features
@param[in] complete_only will only add features for PeptideIdentifications where all given search engines identified something
@param[in] limits_imputation
Adds multiple search engine specific Percolator features and registers them in feature_set
*/
static void addMULTISEFeatures(PeptideIdentificationList& peptide_ids, StringList& search_engines_used, StringList& feature_set, bool complete_only = true, bool limits_imputation = false);
/**
@brief addCONCATSEFeatures
@param[in] peptide_id_list PeptideIdentification vector to create Percolator features in
@param[in] search_engines_used the list of search engines to be considered
@param[in] feature_set register of added features
Adds multiple search engine specific Percolator features and registers them in feature_set
*/
static void addCONCATSEFeatures(PeptideIdentificationList& peptide_id_list, StringList& search_engines_used, StringList& feature_set);
/**
@brief checkExtraFeatures
@param[in] psms the vector of PeptideHit to be checked
@param[in] extra_features the list of requested extra features
checks and removes requested extra Percolator features that are actually unavailable (to compute)
*/
static void checkExtraFeatures(const std::vector<PeptideHit> &psms, StringList& extra_features);
/**
* @brief addMSFraggerFeatures
* @param[in] extra_features register of added features
*
* Registers the MSFragger specific Percolator features in extra_features.
*/
static void addMSFRAGGERFeatures(StringList& extra_features);
protected:
/// Rescales the fragment features to penalize features calculated by few ions, adapted from MSGFtoPercolator
static double rescaleFragmentFeature_(double featureValue, int NumMatchedMainIons);
/// helper function for assigning the frequently occurring feature delta score
static void assignDeltaScore_(std::vector<PeptideHit>& hits, const String& score_ref, const String& output_ref);
/// gets the scan identifier to merge by
static String getScanMergeKey_(PeptideIdentificationList::iterator it, PeptideIdentificationList::iterator start);
/// For accession dependent sorting of ProteinHits
struct lq_ProteinHit
{
inline bool operator() (const ProteinHit& h1, const ProteinHit& h2)
{
return (h1.getAccession() < h2.getAccession());
}
};
/// For accession dependent sorting of PeptideEvidences
struct lq_PeptideEvidence
{
inline bool operator() (const PeptideEvidence& h1, const PeptideEvidence& h2)
{
return (h1.getProteinAccession() < h2.getProteinAccession());
}
};
};
} //namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/ID/PeptideIndexing.h | .h | 12,214 | 202 | // 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/CONCEPT/ProgressLogger.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/DATASTRUCTURES/FASTAContainer.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
#include <OpenMS/DATASTRUCTURES/StringUtilsSimple.h>
#include <OpenMS/FORMAT/FASTAFile.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <OpenMS/METADATA/ProteinIdentification.h>
namespace OpenMS
{
/**
@brief Refreshes the protein references for all peptide hits in a vector of PeptideIdentifications and adds target/decoy information.
All peptide and protein hits are annotated with target/decoy information, using the meta value "target_decoy". For proteins the possible values are "target" and "decoy",
depending on whether the protein accession contains the decoy pattern (parameter @p decoy_string) as a suffix or prefix, respectively (see parameter @p prefix).
For peptides, the possible values are "target", "decoy" and "target+decoy", depending on whether the peptide sequence is found only in target proteins,
only in decoy proteins, or in both. The target/decoy information is crucial for the @ref TOPP_FalseDiscoveryRate tool.
(For FDR calculations, "target+decoy" peptide hits count as target hits.)
@note Make sure that your protein names in the database contain a correctly formatted decoy string. This can be ensured by using @ref TOPP_DecoyDatabase.
If the decoy identifier is not recognized successfully, all proteins will be assumed to stem from the target-part of the query.<br>
E.g., "sw|P33354_DECOY|YEHR_ECOLI Uncharacterized lipop..." is <b>invalid</b>, since the tool has no knowledge of how SwissProt entries are build up.
A correct identifier could be "DECOY_sw|P33354|YEHR_ECOLI Uncharacterized li ..." or "sw|P33354|YEHR_ECOLI_DECOY Uncharacterized li", depending on whether you are
using prefix or suffix annotation.<br>
Some helpful target/decoy statistics will be reported when done.
By default this tool will fail if an unmatched peptide occurs, i.e. if the database does not contain the corresponding protein.
You can force it to return successfully in this case by setting @p '-unmatched_action' to accept or even remove those hits.
Search engines (such as X!Tandem) will replace ambiguous amino acids ('B', 'J', 'Z' and 'X') in the protein database with unambiguous amino
acids in the reported peptides, e.g. exchange 'X' with 'H'.
This will cause such peptides to not be found by exactly matching their sequences to the protein database.
However, we can recover these cases by using tolerant search for ambiguous amino acids in the protein sequence. This is done by default with
up to three amino acids per peptide hit. If you only want exact matches, set @p aaa_max to zero (but expect that unmatched peptides might occur)!
Leucine/Isoleucine:
Further complications can arise due to the presence of the isobaric amino acids isoleucine ('I') and leucine ('L') in protein sequences.
Since the two have the exact same chemical composition and mass, they generally cannot be distinguished by mass spectrometry.
If a peptide containing 'I' was reported as a match for a spectrum, a peptide containing 'L' instead would be an equally good match (and vice versa).
To account for this inherent ambiguity, setting the flag @p IL_equivalent causes 'I' and 'L' to be considered as indistinguishable.@n
For example, if the sequence "PEPTIDE" (matching "Protein1") was identified as a search hit,
but the database additionally contained "PEPTLDE" (matching "Protein2"), running PeptideIndexer with the @p IL_equivalent option would
report both "Protein1" and "Protein2" as accessions for "PEPTIDE".
(This is independent of ambiguous matching via @p aaa_max.)
Additionally, setting this flag will convert all 'J's in any protein sequence to 'I'. This way, no tolerant search is required for 'J' (but is still possible for all
the other ambiguous amino acids).
If @p write_protein_sequences is requested and @p IL_equivalent is set as well, both the I/L-version and unmodified protein sequences need to be stored internally.
This requires some extra memory, roughly equivalent to the size of the FASTA database file itself.
Enzyme specificity:
Once a peptide sequence is found in a protein sequence, this does <b>not</b> imply that the hit is valid! This is where enzyme specificity comes into play.
By default, the enzyme and the specificity used during search is derived from metadata in the idXML files ('auto' setting).
We make two exceptions to any specificity constraints:
1) for peptides starting at the second or third position of a protein are still considered N-terminally specific,
since the residues can be cleaved off in vivo; X!Tandem reports these peptides. For example, the two peptides ABAR and LABAR would both match a protein starting with MLABAR.
2) adventitious cleavage at Asp|Pro (Aspartate/D | Proline/P) is allowed for all enzymes (as supported by X!Tandem), i.e. counts as a proper cleavage site (see http://www.thegpm.org/tandem/release.html).
You can relax the requirements further by choosing <tt>semi-tryptic</tt> (only one of two "internal" termini must match requirements)
or <tt>none</tt> (essentially allowing all hits, no matter their context). These settings should not be used (due to high risk of reporting false positives),
unless the search engine was instructed to search peptides in the same way (but then the default 'auto' setting will do the correct thing).
X!Tandem treats any occurrence of 'X' as stop codon (and thus as cleavage site). The resulting peptide will be non- or semi-tryptic.
Those hits will not be matched and need to be removed using @p '-unmatched_action' (do not use termini specificity to cheat around it! It adds more false hits!).
The FASTA file should not contain duplicate protein accessions (since accessions are not validated) if a correct unique-matching annotation is important (target/decoy annotation is still correct).
Threading:
This tool support multiple threads (@p threads option) to speed up computation, at the cost of little extra memory.
*/
class OPENMS_DLLAPI PeptideIndexing :
public DefaultParamHandler, public ProgressLogger
{
public:
/// name of enzyme/specificity which signals that the enzyme/specificity should be taken from meta information
static char const* const AUTO_MODE; /* = 'auto' */
/// Exit codes
enum class ExitCodes
{
EXECUTION_OK,
DATABASE_EMPTY,
PEPTIDE_IDS_EMPTY,
ILLEGAL_PARAMETERS,
UNEXPECTED_RESULT
};
/// Action to take when peptide hits could not be matched
enum class Unmatched
{
IS_ERROR, ///< throws an error (and returns no results)
WARN, ///< skips annotation with target/decoy but returns with 'success'
REMOVE, ///< removes unmatched hits entirely and returns with 'success'
SIZE_OF_UNMATCHED
};
static const std::array<std::string, (Size)Unmatched::SIZE_OF_UNMATCHED> names_of_unmatched;
enum class MissingDecoy
{
IS_ERROR,
WARN,
SILENT,
SIZE_OF_MISSING_DECOY
};
static const std::array<std::string, (Size)MissingDecoy::SIZE_OF_MISSING_DECOY> names_of_missing_decoy;
/// Default constructor
PeptideIndexing();
/// Default destructor
~PeptideIndexing() override;
/// forward for old interface and pyOpenMS; use other run() methods for more control
ExitCodes run(std::vector<FASTAFile::FASTAEntry>& proteins, std::vector<ProteinIdentification>& prot_ids, PeptideIdentificationList& pep_ids);
/**
@brief Re-index peptide identifications honoring enzyme cutting rules, ambiguous amino acids and target/decoy hits.
Template parameter 'T' can be either TFI_File or TFI_Vector. If the data is already available, use TFI_Vector and pass the vector.
If the data is still in a FASTA file and its not needed afterwards for additional processing, use TFI_File and pass the filename.
PeptideIndexer refreshes target/decoy information and mapping of peptides to proteins.
The target/decoy information is crucial for the @ref TOPP_FalseDiscoveryRate tool. (For FDR calculations, "target+decoy" peptide hits count as target hits.)
PeptideIndexer allows for ambiguous amino acids (B|J|Z|X) in the protein database, but not in the peptide sequences.
For the latter only I/L can be treated as equivalent (see 'IL_equivalent' flag), but 'J' is not allowed.
Enzyme cutting rules and partial specificity can be specified.
Resulting protein hits appear in the order of the FASTA file, except for orphaned proteins, which will appear first with an empty target_decoy metavalue.
Duplicate protein accessions & sequences will not raise a warning, but create multiple hits (PeptideIndexer scans over the FASTA file once for efficiency
reasons, and thus might not see all accessions & sequences at once).
All peptide and protein hits are annotated with target/decoy information, using the meta value "target_decoy".
For proteins the possible values are "target" and "decoy", depending on whether the protein accession contains the decoy pattern (parameter @p decoy_string)
as a suffix or prefix, respectively (see parameter @p prefix).
Peptide hits are annotated with metavalue 'protein_references', and if matched to at least one protein also with metavalue 'target_decoy'.
The possible values for 'target_decoy' are "target", "decoy" and "target+decoy",
depending on whether the peptide sequence is found only in target proteins, only in decoy proteins, or in both. The metavalue is not present, if the peptide is unmatched.
Runtime: PeptideIndexer is usually very fast (loading and storing the data takes the most time) and search speed can be further improved (linearly), but using more threads.
Avoid allowing too many (>=4) ambiguous amino acids if your database contains long stretches of 'X' (exponential search space).
@param[in] proteins A list of proteins -- either read piecewise from a FASTA file or as existing vector of FASTAEntries.
@param[out] prot_ids Resulting protein identifications associated to pep_ids (will be re-written completely)
@param[in] pep_ids Peptide identifications which should be search within @p proteins and then linked to @p prot_ids
@return Exit status codes.
*/
ExitCodes run(FASTAContainer<TFI_File>& proteins, std::vector<ProteinIdentification>& prot_ids, PeptideIdentificationList& pep_ids);
/// Same as run() with TFI_File, but for proteins which are already in memory
ExitCodes run(FASTAContainer<TFI_Vector>& proteins, std::vector<ProteinIdentification>& prot_ids, PeptideIdentificationList& pep_ids);
/// Which string is used to determine if a protein is a decoy or not
const String& getDecoyString() const;
/// Is the decoy string position a prefix or suffix?
bool isPrefix() const;
protected:
void updateMembers_() override;
template<typename T> ExitCodes run_(FASTAContainer<T>& proteins, std::vector<ProteinIdentification>& prot_ids, PeptideIdentificationList& pep_ids);
String decoy_string_{};
bool prefix_{ false };
MissingDecoy missing_decoy_action_ = MissingDecoy::IS_ERROR;
String enzyme_name_{};
String enzyme_specificity_{};
bool write_protein_sequence_{ false };
bool write_protein_description_{ false };
bool keep_unreferenced_proteins_{ false };
Unmatched unmatched_action_ = Unmatched::IS_ERROR;
bool IL_equivalent_{ false };
bool allow_nterm_protein_cleavage_{ true };
Int aaa_max_{0};
Int mm_max_{0};
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/ID/FragmentIndex.h | .h | 15,239 | 346 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: $
// $Authors: $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CHEMISTRY/AASequence.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/FORMAT/FASTAFile.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/KERNEL/Peak1D.h>
#include <vector>
#include <functional>
namespace OpenMS
{
/** @brief Generates from a set of Fasta files a 2D-datastructure which stores all theoretical masses of all
* b and y ions from all peptides generated from the Fasta file. The datastructure is build such that on one axis
* the fragments are sorted by their own mass and the axis by the mass of their precursor/protein.
* The FI has two options: Bottom-up and Top Down. In later digestion is skiped and the fragments have a direct
* reference to the mass of the proteins instead of digested peptides.
*/
class OPENMS_DLLAPI FragmentIndex : public DefaultParamHandler
{
public:
/** @brief Compact descriptor of a peptide instance held by the FragmentIndex.
*
* Field semantics and how they relate to the braced initializer lists used in tests {a, b, {c, d}, e}:
* - protein_idx .......... 'a' Index into the FASTA entries vector passed to build(); identifies the source protein.
* - modification_idx_ .... 'b' Index into the list of generated modification variants for the given unmodified subsequence.
* In tests, this maps to mod_peptides[modification_idx_] created by ModifiedPeptideGenerator.
* - sequence_ ............ '{c, d}' 0-based start offset and length (in residues) of the peptide subsequence within the protein.
* Note: length (d) is used like std::string::substr(start, length).
* - precursor_mz_ ........ 'e' Mono-isotopic m/z at charge 1 (M+H)+; used for ordering/slicing in the index.
* Many tests use a dummy value here since only ordering invariants are asserted.
*/
struct Peptide {
// We need a constructor in order to emplace back
Peptide(UInt32 protein_idx, UInt32 modification_idx, std::pair<uint16_t , uint16_t> sequence, float precursor_mz):
protein_idx(protein_idx),
modification_idx_(modification_idx),
sequence_(sequence),
precursor_mz_(precursor_mz)
{}
UInt32 protein_idx; ///< 0-based index into FASTA entries provided to build(); identifies the source protein
UInt32 modification_idx_; ///< Index into variant list produced by ModifiedPeptideGenerator for this subsequence (0 = unmodified)
std::pair<uint16_t , uint16_t> sequence_; ///< {start, length} within the source protein sequence (start is 0-based; length in residues)
float precursor_mz_; ///< Mono-isotopic m/z at charge 1 (M+H)+ of this peptide; used for sorting/filtering
};
/**
* @brief Match between a query peak and an entry in the DB
*/
struct SpectrumMatch
{
uint32_t num_matched_{}; ///< Number of peaks-fragment hits
uint16_t precursor_charge_{}; ///< The precursor_charged used for the performed search
int16_t isotope_error_{}; /// < The isotope_error used for the performed search
size_t peptide_idx_{}; ///< The idx this struct belongs to
};
/**
* @brief container for SpectrumMatch. Also keeps count of total number of candidates and total number of matches.
*/
struct SpectrumMatchesTopN
{
std::vector<SpectrumMatch> hits_; ///< The preliminary candidates
SpectrumMatchesTopN() = default;
/**
* @brief Appends the a SpectrumMatchesTopN to another one. Add the number of all matched peaks up. Same for number of scored candidates
* The
* @param[in] other The appended struct
* @return The struct after the attachment
*/
SpectrumMatchesTopN& operator+=(const SpectrumMatchesTopN& other)
{
this->hits_.insert(this->hits_.end(), other.hits_.begin(), other.hits_.end());
return *this;
}
void clear()
{
hits_.clear();
}
};
/**
* @brief Default constructor.
*
* Initializes an empty FragmentIndex. Call build() before using any query
* functions. After clear(), the index returns to this unbuilt state.
*
* Thread-safety: constructing the object is thread-safe as long as the instance
* is not shared across threads before initialization completes.
*/
FragmentIndex();
/**
* @brief Default destructor.
*
* Releases owned memory. If the index was built, all internal buffers and
* fragment buckets are freed. No exceptions are thrown.
*/
~FragmentIndex() override = default;
/**
* @brief Indicates whether the fragment index has been built.
*
* @return true if build() has completed successfully and the index is ready
* for queries; false otherwise (e.g., after construction or after clear()).
*
* Thread-safety: read-only and can be called concurrently with other
* read-only methods. Must not race with build()/clear() on the same instance.
*/
bool isBuild() const;
/**
* @brief Returns a reference to the internal peptide container.
*
* Provides read-only access to all peptides currently held by the index,
* typically populated during build().
*
* @return const reference to the internal std::vector of Peptide.
*
* Preconditions: The vector may be empty if build() has not been called yet.
* Thread-safety: read-only view; safe to access concurrently as long as no
* thread mutates the index (e.g., build()/clear()).
*/
const std::vector<Peptide>& getPeptides() const;
#ifdef DEBUG_FRAGMENT_INDEX
/**
* @brief Manually adds a peptide to the internal peptide list (debug builds only).
*
* Allows injecting a custom peptide sequence into the index prior to building,
* e.g., for targeted testing. This function modifies the internal state and
* must be used with care.
*
* @param[in,out] peptide AASequence of the peptide to add. The sequence may be modified
* internally (e.g., normalization/annotation steps).
* @param[in] source_idx Index of the originating FASTA entry (or synthetic source)
* to maintain provenance in downstream processing.
*
* Preconditions:
* - Must be called after peptides have been generated (e.g., generatePeptides())
* and before build(). Calling it after build() leads to undefined behavior.
*
* Thread-safety:
* - Not thread-safe. Do not call concurrently with build(), clear(), or any
* read operations. Restrict usage to single-threaded setup in debug builds.
*
* Exceptions:
* - Strong exception guarantee: either the peptide is added or the index remains unchanged.
*/
void addSpecialPeptide(AASequence& peptide, Size source_idx);
#endif
/** @brief Given a set of Fasta files, builds the Fragment Index datastructure (FID). First all fragments are sorted
* by their own mass. Next they are placed in buckets. The min-fragment mass is stored for each bucket, whereupon
* the fragments are sorted within the buckets by their originating precursor mass.
*
* @param[in] fasta_entries
*/
void build(const std::vector<FASTAFile::FASTAEntry> & fasta_entries);
/** @brief Delete fragment index. Sets is_build=false*/
void clear();
/** Return index range of all possible Peptides/Proteins, such that a vector can be created fitting that range (safe some memory)
* @param[in] precursor_mass The mono-charged precursor mass (M+H)
* @param[in] window Defines the lower and upper bound for the precusor mass. For closed search it only contains the tolerance. In case of open search
* it contains both tolerance and open-search-window
* @return a pair of indexes defining all possible peptides which the current peak could hit
*/
std::pair<size_t, size_t> getPeptidesInPrecursorRange(float precursor_mass,
const std::pair<float, float>& window);
/**
* A match between a single query peak and a database fragment
*/
struct Hit
{
Hit(UInt32 peptide_idx, float fragment_mz) :
peptide_idx(peptide_idx),
fragment_mz(fragment_mz)
{}
UInt32 peptide_idx; // index in database
float fragment_mz;
};
/**@brief Queries one peak
* @param[in] peak The queried peak
* @param[in] peptide_idx_range The range of precursors/peptides the peptide could potentially belongs to
* @param[in] peak_charge The charge of the peak. Is used to calculate the mass from the mz
* @return a vector of Hits(matching peptide_idx_range and matching fragment_mz_) containing the idx of the hitted peptide and the mass of the hit
*/
std::vector<Hit> query(const Peak1D& peak,
const std::pair<size_t,size_t>& peptide_idx_range,
uint16_t peak_charge);
/**
* @brief: queries one complete experimental spectra against the Database. Loops over all precursor charges
* Starts at min_precursor_charge and iteratively goes to max_precursor_charge. We query all peaks multiple times with all the
* different precursor charges and corresponding precursor masses
* @param[in] spectrum experimental spectrum
* @param[out] sms The n best Spectrum matches
*/
void querySpectrum(const MSSpectrum& spectrum,
SpectrumMatchesTopN& sms);
protected:
/**@brief One entry in the fragment index
*/
struct Fragment
{
Fragment(UInt32 peptide_idx, float fragment_mz):
peptide_idx_(peptide_idx),
fragment_mz_(fragment_mz)
{}
UInt32 peptide_idx_; // 32 bit in sage
float fragment_mz_;
};
bool is_build_{false}; ///< true, if the database has been populated with fragments
void updateMembers_() override;
/**@brief Generates all peptides from given fasta entries. If Bottom-up is set to false
* skips digestion. If set to true the Digestion enzyme can be set in the parameters.
* Additionally introduces fixed and variable modifications for restrictive PSM search.
*
* @param[in] fasta_entries
*/
void generatePeptides(const std::vector<FASTAFile::FASTAEntry>& fasta_entries);
std::vector<Peptide> fi_peptides_; ///< vector of all (digested) peptides
std::vector<Fragment> fi_fragments_; ///< vector of all theoretical fragments (b- and y- ions)
float fragment_min_mz_; ///< smallest fragment mz
float fragment_max_mz_; ///< largest fragment mz
size_t bucketsize_; ///< number of fragments per outer node
std::vector<float> bucket_min_mz_; ///< vector of the smalles fragment mz of each bucket
float precursor_mz_tolerance_;
bool precursor_mz_tolerance_unit_ppm_{true};
float fragment_mz_tolerance_;
bool fragment_mz_tolerance_unit_ppm_{true};
private:
/**
* @brief queries peaks for a given experimental spectrum with a set range of potential peptides, isotope error and precursor charge. Hits are transferred into a PSM list.
* Technically an adapter between query(...) and openSearch(...)/searchDifferentPrecursorRanges(...)
* @param[out] candidates The n best Spectrum matches
* @param[in] spectrum The queried experimental spectrum
* @param[in] candidates_range The range of precursors/peptides the peptide could potentially belong to
* @param[in] isotope_error The applied isotope error
* @param[in] precursor_charge The applied precursor charge
*/
void queryPeaks(SpectrumMatchesTopN& candidates,
const MSSpectrum& spectrum,
const std::pair<size_t, size_t>& candidates_range,
const int16_t isotope_error,
const uint16_t precursor_charge);
/**
* @brief If closed search loops over all isotope errors. For each iteration loop over all peaks with queryPeaks.
* @brief If open search applies a precursor-mass window
* @param[in] spectrum experimental query-spectrum
* @param[in] precursor_mass The mass of the precursor (mz * charge)
* @param[out] sms The Top m SpectrumMatches
* @param[in] charge Applied charge
*/
void searchDifferentPrecursorRanges(const MSSpectrum& spectrum,
float precursor_mass,
SpectrumMatchesTopN& sms,
uint16_t charge);
/** @brief places the k-largest elements in the front of the input array. Inside of the k-largest elements and outside the elements are not sorted
*
*/
void trimHits(SpectrumMatchesTopN& init_hits) const;
//since we work with TheoreticalSpectrumGenerator, we must transfer some of those member variables
bool add_b_ions_;
bool add_y_ions_;
bool add_a_ions_;
bool add_c_ions_;
bool add_x_ions_;
bool add_z_ions_;
// SpectrumGenerator independend member variables
std::string digestion_enzyme_;
size_t missed_cleavages_; ///< number of missed cleavages
float peptide_min_mass_;
float peptide_max_mass_;
size_t peptide_min_length_;
size_t peptide_max_length_;
StringList modifications_fixed_; ///< Modification that are one all peptides
StringList modifications_variable_; ///< Variable Modification -> all possible comibnations are created
size_t max_variable_mods_per_peptide_;
// Search Related member variables
uint16_t min_matched_peaks_; ///< PSM with less hits are discarded
int16_t min_isotope_error_; ///< Minimal possible isotope error
int16_t max_isotope_error_; ///< Maximal possible isotope error (both only used for closed search)
uint16_t min_precursor_charge_; ///< minimal possible precursor charge (usually always 1)
uint16_t max_precursor_charge_; ///< maximal possible precursor charge
uint16_t max_fragment_charge_; ///< The maximal possible charge of the fragments
uint32_t max_processed_hits_; ///< The amount of PSM that will be used. the rest is filtered out
/// Helper function to determine if open search should be used based on tolerance
bool isOpenSearchMode_() const
{
return precursor_mz_tolerance_unit_ppm_
? (precursor_mz_tolerance_ > 1000.0)
: (precursor_mz_tolerance_ > 1.0);
}
float open_precursor_window_lower_; ///< Defines the lower bound of the precursor-mass range
float open_precursor_window_upper_; ///< Defines the upper bound of the precursor-mass range
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/ID/ConsensusIDAlgorithm.h | .h | 4,812 | 116 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hendrik Weisser $
// $Authors: Andreas Bertsch, Marc Sturm, Sven Nahnsen, Hendrik Weisser $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <map>
#include <vector>
namespace OpenMS
{
/**
@brief Abstract base class for all ConsensusID algorithms (that calculate a consensus from multiple ID runs).
The main function is apply(), which aggregates several peptide identifications into one.
Derived classes should implement apply_(), which takes a list of peptide identifications and produces a map of peptide sequences with accompanying scores (and charge states).
Currently there are two derived classes, OpenMS::ConsensusIDAlgorithmIdentity and OpenMS::ConsensusIDAlgorithmSimilarity. They serve as abstract base classes for algorithms that score only
identical peptide sequences together and algorithms that take similarities between peptides into account, respectively.
See also the documentation of the TOPP tool, @ref TOPP_ConsensusID, for more information (e.g. on the @p filter: parameters).
@htmlinclude OpenMS_ConsensusIDAlgorithm.parameters
@ingroup Analysis_ID
*/
class OPENMS_DLLAPI ConsensusIDAlgorithm : public DefaultParamHandler
{
public:
/**
@brief Calculates the consensus ID for a set of peptide identifications of one spectrum or (consensus) feature.
Make sure that the score type (PeptideIdentification::getScoreType()) and the score orientation (PeptideIdentification::isHigherScoreBetter()) are set properly!
@param[in,out] ids Peptide identifications (input: more than one, output: one)
@param[in] number_of_runs Number of ID runs (default: size of "ids")
@param[in] se_info map from run identifiers to search engine infos to retain original search engine information
@todo we could pass the score_types that we want to carry over in the map as well (right now it always takes main)
*/
void apply(PeptideIdentificationList& ids, const std::map<String, String>& se_info, Size number_of_runs = 0);
void apply(PeptideIdentificationList& ids, Size number_of_runs = 0);
/// Virtual destructor
~ConsensusIDAlgorithm() override;
protected:
struct HitInfo {
Int charge;
std::vector<double> scores;
std::vector<String> types;
// in case too much information is stored, TD and evidence
// could be re-annotated with PeptideIndexer later
String target_decoy;
std::set<PeptideEvidence> evidence;
double final_score;
double support;
// TODO: we could gather spectrum_refs here as well,
// to support passing of spectrum_ref if ALL refs of a group are the same
// For now, we do it in the ConsensusID TOPP tool class in cases where we
// know that refs will be the same.
};
/// Mapping: peptide sequence -> (charge, scores)
typedef std::map<AASequence, HitInfo> SequenceGrouping;
/// Number of peptide hits considered per ID run (input parameter)
Size considered_hits_;
/// Number of ID runs
Size number_of_runs_;
/// Fraction of required support by other ID runs (input parameter)
double min_support_;
/// Count empty runs in "min_support" calculation? (input parameter)
bool count_empty_;
/// Keep old scores?
bool keep_old_scores_;
/// Default constructor
ConsensusIDAlgorithm();
/**
@brief Consensus computation (to be implemented by subclasses).
@param[in,out] ids Peptide identifications (input)
@param[in] se_info mapping from run identifier to search engine to carry over infos to result
@param[out] results Algorithm results (output). For each peptide sequence, two scores are expected: the actual consensus score and the "support" value, in this order.
*/
virtual void apply_(PeptideIdentificationList& ids, const std::map<String, String>& se_info, SequenceGrouping& results) = 0;
/// Docu in base class
void updateMembers_() override;
/// Compare (and possibly update) charge state information
void compareChargeStates_(Int& recorded_charge, Int new_charge, const AASequence& peptide);
private:
/// Not implemented
ConsensusIDAlgorithm(const ConsensusIDAlgorithm&) = delete;
/// Not implemented
ConsensusIDAlgorithm& operator=(const ConsensusIDAlgorithm&) = delete;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/ID/FalseDiscoveryRate.h | .h | 14,075 | 257 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Andreas Bertsch, Chris Bielow $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/METADATA/ID/IdentificationData.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <OpenMS/METADATA/ProteinIdentification.h>
#include <OpenMS/KERNEL/ConsensusMap.h>
#include <unordered_map>
#include <vector>
#include <unordered_set>
namespace OpenMS
{
struct ScoreToTgtDecLabelPairs;
/**
@brief Calculates false discovery rates (FDR) from identifications
Either two runs of forward and decoy database identification or one run containing both (with annotations) can be used to annotate each of the peptide hits with an FDR or q-value.
q-values are basically only adjusted p-values, also ranging from 0 to 1, with lower values being preferable.
When looking at the list of hits ordered by q-values, then a specific q-value of @em x means that @em x*100 percent of hits with a q-value <= @em x are expected to be false positives.
Only simple target-decoy FDRs are supported with a formula depending on the "conservative" parameter:
- false: (D+1)/T.
- true: (D+1)/(T+D) [for comparison with protein level FDR used by other tools like e.g., Fido]
For protein groups, a group is considered as a target when it contains at least one target protein.
Group level FDRs assume the same score type as on protein level.
For peptide hits, a hit is considered target also if it maps to both
a target and a decoy protein (i.e. "target+decoy") as value in the
"target_decoy" metavalue e.g. annotated by @ref TOPP_PeptideIndexer
@note The parameter add_decoy_proteins currently does not affect groups
@htmlinclude OpenMS_FalseDiscoveryRate.parameters
@ingroup Analysis_ID
*/
class OPENMS_DLLAPI FalseDiscoveryRate :
public DefaultParamHandler
{
public:
///Default constructor
FalseDiscoveryRate();
/**
@brief Calculates the FDR of two runs, a forward run and a decoy run on peptide level
@param[in,out] fwd_ids forward peptide identifications
@param[in,out] rev_ids reverse peptide identifications
*/
void apply(PeptideIdentificationList& fwd_ids, PeptideIdentificationList& rev_ids) const;
/**
@brief Calculates the FDR of one run from a concatenated sequence DB search.
@param[in,out] id peptide identifications, containing target and decoy hits
@param[in] annotate_peptide_fdr adds the peptide q-value or peptide fdr meta value to each PSM. Calculation uses best PSM per peptide.
*/
void apply(PeptideIdentificationList& id, bool annotate_peptide_fdr = false) const;
/**
@brief Calculates the FDR of two runs, a forward run and decoy run on protein level
@param[in,out] fwd_ids forward protein identifications
@param[in,out] rev_ids reverse protein identifications
*/
void apply(std::vector<ProteinIdentification>& fwd_ids, std::vector<ProteinIdentification>& rev_ids) const;
/**
@brief Calculate the FDR of one run from a concatenated sequence db search
@param[in,out] ids protein identifications, containing target and decoy hits
*/
void apply(std::vector<ProteinIdentification>& ids) const;
/**
@brief Calculate the FDR based on PEPs or PPs (if present) and modifies the IDs inplace
@param[in,out] ids protein identifications, containing PEP scores (not necessarily) annotated with target decoy.
*/
void applyEstimated(std::vector<ProteinIdentification>& ids) const;
/**
@brief Calculate a linear combination of the area of the difference in estimated vs. empirical (TD) FDR
and the ROC-N value (AUC up to first N false positives).
@param[in] ids protein identifications, containing PEP scores annotated with target decoy. Only first run will be evaluated.
@param[in] pepCutoff up to which PEP should the differences between the two FDRs be calculated
@param[in] fpCutoff up to which nr. of false positives should the target-decoy AUC be evaluated
@param[in] diffWeight which weight should the difference get. The ROC-N value gets 1 - this weight.
*/
double applyEvaluateProteinIDs(const std::vector<ProteinIdentification>& ids, double pepCutoff = 1.0, UInt fpCutoff = 50, double diffWeight = 0.2) const;
/**
@brief Calculate a linear combination of the area of the difference in estimated vs. empirical (TD) FDR
and the ROC-N value (AUC up to first N false positives).
@param[in] ids protein identifications, containing PEP scores annotated with target decoy.
@param[in] pepCutoff up to which PEP should the differences between the two FDRs be calculated
@param[in] fpCutoff up to which nr. of false positives should the target-decoy AUC be evaluated
@param[in] diffWeight which weight should the difference get. The ROC-N value gets 1 - this weight.
*/
double applyEvaluateProteinIDs(const ProteinIdentification& ids, double pepCutoff = 1.0, UInt fpCutoff = 50, double diffWeight = 0.2) const;
/**
@brief Calculate a linear combination of the area of the difference in estimated vs. empirical (TD) FDR
and the ROC-N value (AUC up to first N false positives).
@param[in,out] score_to_tgt_dec_fraction_pairs extracted scores of protein(group) identifications, containing PEP scores annotated with target decoy fractions. Simple case target=1, decoy=0.
@param[in] pepCutoff up to which PEP should the differences between the two FDRs be calculated
@param[in] fpCutoff up to which nr. of false positives should the target-decoy AUC be evaluated
@param[in] diffWeight which weight should the difference get. The ROC-N value gets 1 - this weight.
*/
double applyEvaluateProteinIDs(ScoreToTgtDecLabelPairs& score_to_tgt_dec_fraction_pairs, double pepCutoff = 1.0, UInt fpCutoff = 50, double diffWeight = 0.2) const;
/// simpler reimplementation of the apply function above for PSMs. With charge and identifier info from @p run_info
void applyBasic(const std::vector<ProteinIdentification> & run_info, PeptideIdentificationList & ids);
/// simpler reimplementation of the apply function above for PSMs or peptides.
void applyBasic(PeptideIdentificationList & ids, bool higher_score_better, int charge = 0, String identifier = "", bool only_best_per_pep = false);
/// like applyBasic with "only_best_per_peptide" but it assigns a score to EVERY PSM sharing the peptide sequence with the
/// best representative. Useful if all hits need to have a peptide score (e.g., for mzTab report). No support for specific charges, runs etc. yet
void applyBasicPeptideLevel(PeptideIdentificationList & ids);
/// like applyBasic with "only_best_per_peptide" but it assigns a score to EVERY PSM sharing the peptide sequence with the
/// best representative. Useful if all hits need to have a peptide score (e.g., for mzTab report). No support for specific charges, runs etc. yet
void applyBasicPeptideLevel(ConsensusMap & ids, bool use_unassigned_peptides = true);
/// simpler reimplementation of the apply function above for peptides in ConsensusMaps.
void applyBasic(ConsensusMap & cmap, bool use_unassigned_peptides = true);
/// simpler reimplementation of the apply function above for proteins.
void applyBasic(ProteinIdentification & id, bool groups_too = true);
/**
* @brief Applies a picked protein FDR.
* Behaves like a normal target-decoy FDR where only the score of the best protein per
* target-decoy pair is used. A pair is calculated by checking accession equality after removing the decoy string.
* If @p decoy_string is empty, we try to guess it. If you set @p decoy_string you should also set @p prefix and
* say if the string is a prefix (true) or suffix (false).
* @p groups_too decides if also a (indistinguishable) group-level FDR will be calculated. Here a group score
* will be taken if not ALL proteins in the group were picked already. Targets preferred.
*/
void applyPickedProteinFDR(ProteinIdentification& id, String decoy_string = "", bool prefix = true, bool groups_too = true);
/// calculates the AUC until the first fp_cutoff False positive pep IDs (currently only takes all runs together)
/// if fp_cutoff = 0, it will calculate the full AUC
double rocN(const PeptideIdentificationList& ids, Size fp_cutoff) const;
/// calculates the AUC until the first fp_cutoff False positive pep IDs (currently only takes all runs together)
/// if fp_cutoff = 0, it will calculate the full AUC. Restricted to IDs from a specific ID run.
double rocN(const PeptideIdentificationList& ids, Size fp_cutoff, const String& identifier) const;
/// calculates the AUC until the first @p fp_cutoff False positive pep IDs (takes all runs together)
/// if fp_cutoff = 0, it will calculate the full AUC
double rocN(const ConsensusMap& ids, Size fp_cutoff, bool include_unassigned_peptides = false) const;
/// calculates the AUC until the first @p fp_cutoff False positive pep IDs.
/// if fp_cutoff = 0, it will calculate the full AUC. Restricted to IDs from a specific ID run with @p identifier.
double rocN(const ConsensusMap& ids, Size fp_cutoff, const String& identifier, bool include_unassigned_peptides = false) const;
//TODO the next two methods could potentially be merged for speed (they iterate over the same structure)
//But since they have different cutoff types and it is more generic, I leave it like this.
/// calculates the area of the difference between estimated and empirical FDR on the fly. Does not store results.
double diffEstimatedEmpirical(const ScoreToTgtDecLabelPairs& scores_labels, double pepCutoff = 1.0) const;
/// calculates AUC of empirical FDR up to the first fpCutoff false positives on the fly. Does not store results.
/// use e.g. fpCutoff = scores_labels.size() for complete AUC
double rocN(const ScoreToTgtDecLabelPairs& scores_labels, Size fpCutoff = 50) const;
/**
@brief Calculate FDR on the level of observation matches (e.g. peptide-spectrum matches) for "general" identification data
@param[in,out] id_data Identification data
@param[in] score_ref Key of the score to use for FDR calculation
@return Key of the FDR score
*/
IdentificationData::ScoreTypeRef applyToObservationMatches(IdentificationData& id_data, IdentificationData::ScoreTypeRef score_ref) const;
/**
* @brief Finds decoy strings in ProteinIdentification runs
*/
class DecoyStringHelper
{
public:
/**
* A result of the findDecoyString function
*/
struct Result
{
bool success; ///< did more than 30% of proteins have the *same* prefix or suffix
String name; ///< on success, what was the decoy string?
bool is_prefix; ///< on success, was it a prefix or suffix
};
/**
* @brief Finds the most common decoy string in the accessions of @p proteins. Checks for suffix and prefix and
* some common decoy strings. Only successful if more than 30% had a common string.
* @param[in] proteins Input proteins with accessions
* @return A @struct Result
*/
static Result findDecoyString(const ProteinIdentification& proteins);
};
private:
/// Not implemented
FalseDiscoveryRate(const FalseDiscoveryRate&);
/// Not implemented
FalseDiscoveryRate& operator=(const FalseDiscoveryRate&);
/// calculates the FDR, given two vectors of scores
void calculateFDRs_(std::map<double, double>& score_to_fdr, std::vector<double>& target_scores, std::vector<double>& decoy_scores, bool q_value, bool higher_score_better) const;
/// Helper function for applyToObservationMatches()
void handleObservationMatch_(
IdentificationData::ObservationMatchRef match_ref,
IdentificationData::ScoreTypeRef score_ref,
std::vector<double>& target_scores,
std::vector<double>& decoy_scores,
std::map<IdentificationData::IdentifiedMolecule, bool>& molecule_to_decoy,
std::map<IdentificationData::ObservationMatchRef, double>& match_to_score) const;
/// calculates an estimated FDR (based on P(E)Ps) given a vector of score value pairs and fills a map for lookup
/// in scores_to_FDR
void calculateEstimatedQVal_(std::map<double, double> &scores_to_FDR,
ScoreToTgtDecLabelPairs &scores_labels,
bool higher_score_better) const;
/// calculates the FDR with a basic and faster algorithm
/// Just goes through the sorted scores and counts the number of decoys and targets and annotates the FDR for
/// this score as it goes. Q-values are optionally annotated by calculating the cumulative minimum in reversed
/// order afterwards. Since I never understood our other algorithm, I can not explain the difference.
/// @note Formula used depends on Param "conservative": false -> (D+1)/T, true (e.g. used in Fido) -> (D+1)/(T+D)
void calculateFDRBasic_(std::map<double,double>& scores_to_FDR, ScoreToTgtDecLabelPairs& scores_labels, bool qvalue, bool higher_score_better) const;
/// calculates the error area around the x=x line between two consecutive values of expected and actual
/// i.e. it assumes exp2 > exp1
double trapezoidal_area_xEqy(double exp1, double exp2, double act1, double act2) const;
/// calculates the trapezoidal area for a trapezoid with a flat horizontal base e.g. for an AUC
double trapezoidal_area(double x1, double x2, double y1, double y2) const;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/ID/ConsensusIDAlgorithmBest.h | .h | 1,281 | 43 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hendrik Weisser $
// $Authors: Andreas Bertsch, Marc Sturm, Sven Nahnsen, Hendrik Weisser $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/ANALYSIS/ID/ConsensusIDAlgorithmIdentity.h>
namespace OpenMS
{
/**
@brief Calculates a consensus from multiple ID runs by taking the best search score.
@htmlinclude OpenMS_ConsensusIDAlgorithmBest.parameters
@ingroup Analysis_ID
*/
class OPENMS_DLLAPI ConsensusIDAlgorithmBest :
public ConsensusIDAlgorithmIdentity
{
public:
/// Default constructor
ConsensusIDAlgorithmBest();
private:
/// Not implemented
ConsensusIDAlgorithmBest(const ConsensusIDAlgorithmBest&);
/// Not implemented
ConsensusIDAlgorithmBest& operator=(const ConsensusIDAlgorithmBest&);
/// Aggregate peptide scores into one final score (by taking the best score)
double getAggregateScore_(std::vector<double>& scores,
bool higher_better) override;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/ID/PeptideSearchEngineFIAlgorithm.h | .h | 8,311 | 206 | // Copyright (c) 2002-present, The OpenMS Team -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: $
// $Authors: Raphael Förster $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/CHEMISTRY/ModifiedPeptideGenerator.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/DATASTRUCTURES/StringView.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <vector>
namespace OpenMS
{
/**
@brief Fragment-index-based peptide database search algorithm (experimental).
Provides a self-contained search engine that matches MS/MS spectra against a protein
database using an FI (Fragment Index). Typical usage:
- Configure parameters via DefaultParamHandler (mass tolerances, enzyme, charges, etc.)
- Call search() with an input mzML file and a FASTA database to populate identification
outputs (ProteinIdentification and PeptideIdentificationList)
- Intended for educational/prototyping use and to demonstrate FI-backed searching
Notes:
- Used by the PeptideDataBaseSearchFI TOPP tool
- Experimental; interfaces and behavior may change
*/
/**
@brief Fragment-index-based peptide database search algorithm (experimental).
Provides a self-contained search engine that matches MS/MS spectra against a protein
database using an FI (Fragment Index). Typical usage:
- Configure parameters via DefaultParamHandler (mass tolerances, enzyme, charges, etc.)
- Call search() with an input mzML file and a FASTA database to populate identification
outputs (ProteinIdentification and PeptideIdentificationList)
- Intended for educational/prototyping use and to demonstrate FI-backed searching
Notes:
- Used by the PeptideDataBaseSearchFI TOPP tool
- Experimental; interfaces and behavior may change
*/
class OPENMS_DLLAPI PeptideSearchEngineFIAlgorithm :
public DefaultParamHandler,
public ProgressLogger
{
public:
PeptideSearchEngineFIAlgorithm();
/// Exit codes
enum class ExitCodes
{
EXECUTION_OK,
INPUT_FILE_EMPTY,
UNEXPECTED_RESULT,
UNKNOWN_ERROR,
ILLEGAL_PARAMETERS
};
/**
* @brief Search spectra in an mzML file against a protein database using an FI-backed workflow.
*
* Populates protein and peptide identifications, including search meta data, PSM hits,
* and search engine annotations. Parameters are taken from this instance (DefaultParamHandler).
*
* @param[in] in_mzML Input path to the mzML file containing MS/MS spectra to search.
* @param[in] in_db Input path to the protein sequence database in FASTA format.
* @param[out] prot_ids Output container receiving search meta data and protein-level information.
* @param[out] pep_ids Output container receiving spectrum-level peptide identifications (PSMs).
*
* @return ExitCodes indicating success (EXECUTION_OK) or the encountered error condition.
*
* Side effects:
* - Updates ProgressLogger during processing.
* - Assigns identifiers and sets search engine name/version in prot_ids/pep_ids.
*
* Errors:
* - May signal invalid parameters via ILLEGAL_PARAMETERS exit code.
* - May propagate OpenMS exceptions (e.g., I/O or parse errors) from underlying components.
*/
ExitCodes search(const String& in_mzML,
const String& in_db,
std::vector<ProteinIdentification>& prot_ids,
PeptideIdentificationList& pep_ids) const;
protected:
void updateMembers_() override;
/// Slimmer structure as storing all scored candidates in PeptideHit objects takes too much space
struct AnnotatedHit_
{
AASequence sequence;
/*
StringView sequence;
SignedSize peptide_mod_index; ///< enumeration index of the non-RNA peptide modification
*/
double score = 0; ///< main score
std::vector<PeptideHit::PeakAnnotation> fragment_annotations;
double prefix_fraction = 0; ///< fraction of annotated b-ions
double suffix_fraction = 0; ///< fraction of annotated y-ions
double mean_error = 0.0; ///< mean absolute fragment mass error
int isotope_error = 0; ///< isotope offset used for this PSM
uint16_t applied_charge = 0; ///< precursor charge used for this PSM
double delta_mass = 0.0; ///< mass difference for open search (Da)
static bool hasBetterScore(const AnnotatedHit_& a, const AnnotatedHit_& b)
{
if (a.score != b.score) return a.score > b.score;
return a.sequence < b.sequence;
}
};
/// @brief filter, deisotope, decharge spectra
static void preprocessSpectra_(PeakMap& exp, double fragment_mass_tolerance, bool fragment_mass_tolerance_unit_ppm);
/**
* @brief Filter and annotate search results.
*
* Trims per-spectrum candidate hits to the top N and converts them into
* PeptideIdentification objects, adding requested PSM annotations and
* populating protein-level search metadata.
*
* @param[in] exp Input MS experiment providing spectra/metadata for annotation.
* @param[in,out] annotated_hits Per-spectrum candidate hits (trimmed to @p top_hits in-place).
* @param[out] protein_ids Output container for protein-level identification and search metadata.
* @param[out] peptide_ids Output container for spectrum-level peptide identifications (PSMs).
* @param[in] top_hits Number of top-scoring hits to retain per spectrum (report_top_hits_).
* @param[in] modifications_fixed Fixed modifications (by name) used during the search.
* @param[in] modifications_variable Variable modifications (by name) used during the search.
* @param[in] peptide_missed_cleavages Allowed missed cleavages in digestion.
* @param[in] precursor_mass_tolerance Precursor mass tolerance value.
* @param[in] fragment_mass_tolerance Fragment mass tolerance value.
* @param[in] precursor_mass_tolerance_unit_ppm Precursor tolerance unit ("true"->ppm, "false"->Da).
* @param[in] fragment_mass_tolerance_unit_ppm Fragment tolerance unit ("true"->ppm, "false"->Da).
* @param[in] precursor_min_charge Minimum precursor charge considered.
* @param[in] precursor_max_charge Maximum precursor charge considered.
* @param[in] enzyme Digestion enzyme name.
* @param[out] database_name Database file name used for the search (stored in protein_ids).
*/
void postProcessHits_(const PeakMap& exp,
std::vector<std::vector<PeptideSearchEngineFIAlgorithm::AnnotatedHit_> >& annotated_hits,
std::vector<ProteinIdentification>& protein_ids,
PeptideIdentificationList& peptide_ids,
Size top_hits,
const StringList& modifications_fixed,
const StringList& modifications_variable,
Int peptide_missed_cleavages,
double precursor_mass_tolerance,
double fragment_mass_tolerance,
const String& precursor_mass_tolerance_unit_ppm,
const String& fragment_mass_tolerance_unit_ppm,
const Int precursor_min_charge,
const Int precursor_max_charge,
const String& enzyme,
const String& database_name) const;
double precursor_mass_tolerance_;
String precursor_mass_tolerance_unit_;
Size precursor_min_charge_;
Size precursor_max_charge_;
IntList precursor_isotopes_;
double fragment_mass_tolerance_;
String fragment_mass_tolerance_unit_;
StringList modifications_fixed_;
StringList modifications_variable_;
Size modifications_max_variable_mods_per_peptide_;
String enzyme_;
bool decoys_;
StringList annotate_psm_;
Size peptide_min_size_;
Size peptide_max_size_;
Size peptide_missed_cleavages_;
String peptide_motif_;
Size report_top_hits_;
/// Helper function to determine if open search should be used based on tolerance
bool isOpenSearchMode_() const
{
return precursor_mass_tolerance_unit_ == "ppm"
? (precursor_mass_tolerance_ > 1000.0)
: (precursor_mass_tolerance_ > 1.0);
}
};
} // namespace | Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/ID/AccurateMassSearchEngine.h | .h | 13,419 | 362 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Erhan Kenar, Chris Bielow $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/MassTrace.h>
#include <OpenMS/KERNEL/Feature.h>
#include <OpenMS/KERNEL/ConsensusFeature.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/KERNEL/ConsensusMap.h>
#include <OpenMS/FORMAT/MzTab.h>
#include <OpenMS/FORMAT/MzTabM.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/SYSTEM/File.h>
#include <OpenMS/CHEMISTRY/AdductInfo.h>
#include <iosfwd>
#include <vector>
namespace OpenMS
{
class OPENMS_DLLAPI AccurateMassSearchResult
{
public:
/// Default constructor
AccurateMassSearchResult();
/// Default destructor
~AccurateMassSearchResult();
/// copy constructor
AccurateMassSearchResult(const AccurateMassSearchResult&);
/// assignment operator
AccurateMassSearchResult& operator=(const AccurateMassSearchResult&);
/// get the m/z of the small molecule + adduct
double getObservedMZ() const;
/// set the m/z of the small molecule + adduct
void setObservedMZ(const double&);
/// get the theoretical m/z of the small molecule + adduct
double getCalculatedMZ() const;
/// set the theoretical m/z of the small molecule + adduct
void setCalculatedMZ(const double&);
/// get the mass used to query the database (uncharged small molecule)
double getQueryMass() const;
/// set the mass used to query the database (uncharged small molecule)
void setQueryMass(const double&);
/// get the mass returned by the query (uncharged small molecule)
double getFoundMass() const;
/// set the mass returned by the query (uncharged small molecule)
void setFoundMass(const double&);
/// get the charge
Int getCharge() const;
/// set the charge
void setCharge(const Int&);
/// get the error between observed and theoretical m/z in ppm
double getMZErrorPPM() const;
/// set the error between observed and theoretical m/z in ppm
void setMZErrorPPM(const double);
/// get the observed rt
double getObservedRT() const;
/// set the observed rt
void setObservedRT(const double& rt);
/// get the observed intensity
double getObservedIntensity() const;
/// set the observed intensity
void setObservedIntensity(const double&);
/// get the observed intensities
std::vector<double> getIndividualIntensities() const;
/// set the observed intensities
void setIndividualIntensities(const std::vector<double>&);
Size getMatchingIndex() const;
void setMatchingIndex(const Size&);
Size getSourceFeatureIndex() const;
void setSourceFeatureIndex(const Size&);
const String& getFoundAdduct() const;
void setFoundAdduct(const String&);
const String& getFormulaString() const;
void setEmpiricalFormula(const String&);
const std::vector<String>& getMatchingHMDBids() const;
void setMatchingHMDBids(const std::vector<String>&);
/// return trace intensities of the underlying feature;
const std::vector<double>& getMasstraceIntensities() const;
void setMasstraceIntensities(const std::vector<double>&);
double getIsotopesSimScore() const;
void setIsotopesSimScore(const double&);
// debug/output functions
friend OPENMS_DLLAPI std::ostream& operator<<(std::ostream& os, const AccurateMassSearchResult& amsr);
private:
/// Stored information/results of DB query
double observed_mz_;
double theoretical_mz_;
double searched_mass_;
double db_mass_;
Int charge_;
double mz_error_ppm_;
double observed_rt_;
double observed_intensity_;
std::vector<double> individual_intensities_;
Size matching_index_;
Size source_feature_index_;
String found_adduct_;
String empirical_formula_;
std::vector<String> matching_hmdb_ids_;
std::vector<double> mass_trace_intensities_;
double isotopes_sim_score_;
};
OPENMS_DLLAPI std::ostream& operator<<(std::ostream& os, const AccurateMassSearchResult& amsr);
/**
@brief An algorithm to search for exact mass matches from a spectrum against a database (e.g. HMDB).
For each peak, neutral masses are reconstructed from observed (spectrum) m/z values by enumerating all possible adducts with matching charge.
The resulting neutral masses (can be more than one, depending on list of possible adducts) are matched against masses from
a database within a certain mass error (Da or ppm).
Supports any database which contains an identifier, chemical sum formula and (optional) mass.
If masses in the database are not given (= set to 0), they are computed from sum formulas.
Both positive and negative ion mode is supported. Charge for (Consensus-)Features can be either positive or negative, but
only the absolute value is used since many FeatureFinders will only report positive charges even in negative ion mode.
Entities with charge=0 are treated as "unknown charge" and are tested with all potential adducts and subsequently matched against the database.
A file with a list of potential adducts can be given for each mode separately.
Each line contains a chemical formula (plus quantor) and a charge (separated by semicolon), e.g.
M+H;1+
The M can be preceded by a quantor (e.g.2M, 3M), implicitly assumed as 1.
The chemical formula can contain multiple segments, separated by + or - operators, e.g. M+H-H2O;+1 (water loss in positive mode).
Brackets are implicit per segment, i.e. M+H-H2O is parsed as M + (H) - (H2O).
Each segment can also be preceded by a quantor, e.g. M+H-H2O would parse as
M + (H) - 2x(H2O).
If debug mode is enabled, the masses of each segment are printed for verification.
In particular, typing H20 (twenty H) is different from H2O (water).
Ionization mode of the observed m/z values can be determined automatically if the input map (either FeatureMap or ConsensusMap) is annotated
with a meta value, as done by @ref TOPP_FeatureFinderMetabo.
@ingroup Analysis_ID
*/
class OPENMS_DLLAPI AccurateMassSearchEngine :
public DefaultParamHandler,
public ProgressLogger
{
public:
/// uses 'AccurateMassSearchEngine' as search engine id for protein and peptide ids which are generated by AMS
static constexpr char search_engine_identifier[] = "AccurateMassSearchEngine";
/// Default constructor
AccurateMassSearchEngine();
/// Default destructor
~AccurateMassSearchEngine() override;
/**
@brief search for a specific observed mass by enumerating all possible adducts and search M+X against database.
If use_feature_adducts is activated, queryByMZ uses annotated, observed adducts as EmpiricalFormulas, restricting M+X candidates.
*/
void queryByMZ(const double& observed_mz, const Int& observed_charge, const String& ion_mode, std::vector<AccurateMassSearchResult>& results, const EmpiricalFormula& observed_adduct = EmpiricalFormula()) const;
void queryByFeature(const Feature& feature, const Size& feature_index, const String& ion_mode, std::vector<AccurateMassSearchResult>& results) const;
void queryByConsensusFeature(const ConsensusFeature& cfeat, const Size& cf_index, const Size& number_of_maps, const String& ion_mode, std::vector<AccurateMassSearchResult>& results) const;
/// main method of AccurateMassSearchEngine
/// input map is not const, since it will get annotated with results
void run(FeatureMap&, MzTab&) const;
void run(FeatureMap&, MzTabM&) const;
/// main method of AccurateMassSearchEngine
/// input map is not const, since it will get annotated with results
/// @note Call init() before calling run!
void run(ConsensusMap&, MzTab&) const;
/// parse database and adduct files
void init();
protected:
void updateMembers_() override;
private:
/// private member functions
/// if ion-mode is auto, this will set the internal mode according to input data
/// @throw InvalidParameter if ion mode cannot be resolved
template <typename MAPTYPE> String resolveAutoMode_(const MAPTYPE& map) const
{
String ion_mode_internal;
String ion_mode_detect_msg = "";
if (map.size() > 0)
{
if (map[0].metaValueExists("scan_polarity"))
{
StringList pols = ListUtils::create<String>(String(map[0].getMetaValue("scan_polarity")), ';');
if (pols.size() == 1 && !pols[0].empty())
{
pols[0].toLower();
if (pols[0] == "positive" || pols[0] == "negative")
{
ion_mode_internal = pols[0];
OPENMS_LOG_INFO << "Setting auto ion-mode to '" << ion_mode_internal << "' for file " << File::basename(map.getLoadedFilePath()) << std::endl;
}
else ion_mode_detect_msg = String("Meta value 'scan_polarity' does not contain unknown ion mode") + String(map[0].getMetaValue("scan_polarity"));
}
else
{
ion_mode_detect_msg = String("ambiguous ion mode: ") + String(map[0].getMetaValue("scan_polarity"));
}
}
else
{
ion_mode_detect_msg = String("Meta value 'scan_polarity' not found in (Consensus-)Feature map");
}
}
else
{ // do nothing, since map is
OPENMS_LOG_INFO << "Meta value 'scan_polarity' cannot be determined since (Consensus-)Feature map is empty!" << std::endl;
}
if (!ion_mode_detect_msg.empty())
{
throw Exception::InvalidParameter(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Auto ionization mode could not resolve ion mode of data (") + ion_mode_detect_msg + "!");
}
return ion_mode_internal;
}
void parseMappingFile_(const StringList&);
void parseStructMappingFile_(const StringList&);
void parseAdductsFile_(const String& filename, std::vector<AdductInfo>& result);
void searchMass_(double neutral_query_mass, double diff_mass, std::pair<Size, Size>& hit_indices) const;
/// Add search results to a Consensus/Feature
void annotate_(const std::vector<AccurateMassSearchResult>&, BaseFeature&) const;
/// Extract query results from feature
std::vector<AccurateMassSearchResult> extractQueryResults_(const Feature& feature, const Size& feature_index, const String& ion_mode_internal, Size& dummy_count) const;
/// Add resulting matches to IdentificationData
void addMatchesToID_(
IdentificationData& id,
const std::vector<AccurateMassSearchResult>& amr,
const IdentificationData::InputFileRef& file_ref,
const IdentificationData::ScoreTypeRef& mass_error_ppm_score_ref,
const IdentificationData::ScoreTypeRef& mass_error_Da_score_ref,
const IdentificationData::ProcessingStepRef& step_ref,
BaseFeature& f) const;
/// For two vectors of identical length, compute the cosine of the angle between them.
/// Since we look at the angle, scaling of the vectors does not change the result (when ignoring numerical instability).
double computeCosineSim_(const std::vector<double>& x, const std::vector<double>& y) const;
double computeIsotopePatternSimilarity_(const Feature& feat, const EmpiricalFormula& form) const;
typedef std::vector<std::vector<AccurateMassSearchResult> > QueryResultsTable;
void exportMzTab_(const QueryResultsTable& overall_results, const Size number_of_maps, MzTab& mztab_out, const std::vector<String>& file_locations) const;
void exportMzTabM_(const FeatureMap& fmap, MzTabM& mztabm_out) const;
/// private member variables
typedef std::vector<std::vector<String> > MassIDMapping;
typedef std::map<String, std::vector<String> > HMDBPropsMapping;
struct MappingEntry_
{
double mass;
std::vector<String> massIDs;
String formula;
};
std::vector<MappingEntry_> mass_mappings_;
struct CompareEntryAndMass_ // defined here to allow for inlining by compiler
{
double asMass(const MappingEntry_& v) const
{
return v.mass;
}
double asMass(double t) const
{
return t;
}
template <typename T1, typename T2>
bool operator()(T1 const& t1, T2 const& t2) const
{
return asMass(t1) < asMass(t2);
}
};
HMDBPropsMapping hmdb_properties_mapping_;
bool is_initialized_; ///< true if init_() was called without any subsequent param changes
bool legacyID_ = true;
/// parameter stuff
double mass_error_value_;
String mass_error_unit_;
String ion_mode_;
bool iso_similarity_;
String pos_adducts_fname_;
String neg_adducts_fname_;
StringList db_mapping_file_;
StringList db_struct_file_;
std::vector<AdductInfo> pos_adducts_;
std::vector<AdductInfo> neg_adducts_;
String database_name_;
String database_version_;
String database_location_;
bool keep_unidentified_masses_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/ID/ConsensusIDAlgorithmSimilarity.h | .h | 2,496 | 66 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hendrik Weisser $
// $Authors: Andreas Bertsch, Marc Sturm, Sven Nahnsen, Hendrik Weisser $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/ANALYSIS/ID/ConsensusIDAlgorithm.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
namespace OpenMS
{
/**
@brief Abstract base class for ConsensusID algorithms that take peptide similarity into account.
Similarity-based algorithms require posterior error probabilities (PEPs) as peptide scores, in order to combine scores and similarities into a consensus score for each peptide. See the following publication for the formula governing this calculation:
Nahnsen <em>et al.</em>: <a href="https://doi.org/10.1021/pr2002879">Probabilistic consensus scoring improves tandem mass spectrometry peptide identification</a> (J. Proteome Res., 2011, PMID: 21644507).
Derived classes should implement getSimilarity_(), which defines how similarity of two peptide sequences is quantified.
@htmlinclude OpenMS_ConsensusIDAlgorithmSimilarity.parameters
@ingroup Analysis_ID
*/
class OPENMS_DLLAPI ConsensusIDAlgorithmSimilarity :
public ConsensusIDAlgorithm
{
protected:
/// Default constructor
ConsensusIDAlgorithmSimilarity();
/// Mapping: pair of peptide sequences -> sequence similarity
typedef std::map<std::pair<AASequence, AASequence>, double> SimilarityCache;
/// Cache for already computed sequence similarities
SimilarityCache similarities_;
/**
@brief Sequence similarity calculation (to be implemented by subclasses).
Implementations should use/update the cache of previously computed similarities.
@return Similarity between two sequences in the range [0, 1]
*/
virtual double getSimilarity_(AASequence seq1, AASequence seq2) = 0;
private:
/// Not implemented
ConsensusIDAlgorithmSimilarity(const ConsensusIDAlgorithmSimilarity&);
/// Not implemented
ConsensusIDAlgorithmSimilarity& operator=(const ConsensusIDAlgorithmSimilarity&);
/// Consensus scoring
void apply_(PeptideIdentificationList& ids,
const std::map<String, String>& se_info,
SequenceGrouping& results) override;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/ID/PrecursorPurity.h | .h | 6,688 | 111 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Eugen Netz $
// $Authors: Eugen Netz $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/CONCEPT/Types.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <vector>
namespace OpenMS
{
/**
@brief Precursor purity or noise estimation
This class computes metrics for precursor isolation window purity (or noise).
The function extracts the peaks from an isolation window targeted for fragmentation
and determines which peaks are isotopes of the target and which come from other sources.
The intensities of the assumed target peaks are summed up as the target intensity.
Using this information it calculates an intensity ratio for the relative intensity of the target
compared to other sources.
These metrics are combined over the previous and the next MS1 spectrum.
@note: If an MS1 spectrum does not contain the target peak within the given tolerance, all values are returned as 0.
@ingroup Analysis_ID
*/
class OPENMS_DLLAPI PrecursorPurity
{
public:
struct PurityScores
{
double total_intensity = 0.0;
double target_intensity = 0.0;
double signal_proportion = 0.0;
Size target_peak_count = 0;
Size interfering_peak_count = 0;
PeakSpectrum interfering_peaks; // peaks left after precursor (isotopic) peaks have been removed
};
/** @brief compute precursor purity metrics for each MS2 spectrum in a PeakMap
This is the main function of this class. See class description.
Note: Spectra annotated with charge 0 will be treated as charge 1.
* @param[in] spectra A PeakMap containing MS1 and MS2 spectra in order of acquisition or measurement. The first spectrum must be an MS1.
* @param[out] precursor_mass_tolerance The precursor tolerance. Is used for determining the targeted peak and deisotoping.
* @param[in] precursor_mass_tolerance_unit_ppm The unit of the precursor tolerance
* @param[in] ignore_missing_precursor_spectra Allow MS2 spectra without a MS1 precursor spectrum (PurityScores for these spectra will be 0).
*/
static std::map<String, PurityScores> computePrecursorPurities(const PeakMap& spectra, double precursor_mass_tolerance, bool precursor_mass_tolerance_unit_ppm, bool ignore_missing_precursor_spectra = false);
/** @brief compute precursor purity metrics for one MS2 precursor
@note This function is implemented in a general way and can also be used for e.g. MS3 precursor isolation windows in MS2 spectra.
Spectra annotated with charge 0 will be treated as charge 1.
@param[in] ms1 The Spectrum containing the isolation window
@param[in] pre The precursor containing the definition the isolation window
@param[out] precursor_mass_tolerance The precursor tolerance. Is used for determining the targeted peak and deisotoping.
@param[in] precursor_mass_tolerance_unit_ppm The unit of the precursor tolerance
*/
static PurityScores computePrecursorPurity(const PeakSpectrum& ms1, const Precursor& pre, const double precursor_mass_tolerance, const bool precursor_mass_tolerance_unit_ppm);
/**
* @brief Computes a simple purity score aggregate for all Precursors (and their windows) of spectrum at @p ms2_spec_idx in the precursor spectrum at @p precursor_spec_idx
*
* Extracts with fuzzy boundaries around expected isotopes where it only considers 50% of the intensity of the peak as belonging to the target.
* Warning: Does neither check if the relationship between those spectra make sense nor that all precursors windows in @p ms2_spec_idx even come from the same spectrum.
*
* @param[in] ms2_spec_idx index for the spectrum holding the precursor information
* @param[in] precursor_spec_idx index for the precursor spectrum to extract the intensities from
* @param[in] exp the MSExperiment holding the spectra to look them up
* @param[in] max_precursor_isotope_deviation the maximum allowed deviation for the precursor isotopes in ppm
* @return std::vector<double> precursor intensity vs. total intensity for every precursor window in @p ms2_spec_idx
*/
static std::vector<double> computeSingleScanPrecursorPurities(int ms2_spec_idx, int precursor_spec_idx, const MSExperiment & exp, double max_precursor_isotope_deviation);
/**
* @brief Computes a simple purity score aggregate for all Precursors (and their windows) of spectrum at @p ms2_spec_idx interpolated between
* precursor spectrum at @p precursor_spec_idx and the next parent type spectrum at @p next_ms1_spec_idx
*
* Interpolates by RT distances of ms2_spec_idx to the precursor_spec_idx and next_ms1_spec_idx.
* Extracts with fuzzy boundaries around expected isotopes where it only considers 50% of the intensity of the peak as belonging to the target.
* Warning: Does neither check if the relationship between those spectra make sense nor that all precursors windows in @p ms2_spec_idx even come from the same spectrum.
*
* @note If @p next_ms1_spec_idx is out of range, does not refer to an MS1 spectrum, or the RT denominator is zero/invalid,
* the function will fall back to returning the early scan purity (from @p precursor_spec_idx) without interpolation.
*
* @param[in] ms2_spec_idx index for the spectrum holding the precursor information
* @param[in] precursor_spec_idx index for the precursor spectrum to extract the intensities from
* @param[in] next_ms1_spec_idx index for the next parent type spectrum to extract the intensities from
* @param[in] exp the MSExperiment holding the spectra to look them up
* @param[in] max_precursor_isotope_deviation the maximum allowed deviation for the precursor isotopes in ppm
* @return std::vector<double> precursor intensity vs. total intensity for every precursor window in @p ms2_spec_idx
*/
static std::vector<double> computeInterpolatedPrecursorPurity(int ms2_spec_idx, int precursor_spec_idx, int next_ms1_spec_idx, const MSExperiment & exp, double max_precursor_isotope_deviation);
private:
// simple helper to combine the metrics contained in two PurityScores
static PurityScores combinePrecursorPurities(const PrecursorPurity::PurityScores& score1, const PrecursorPurity::PurityScores& score2);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/ID/IDMergerAlgorithm.h | .h | 11,740 | 279 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Julianus Pfeuffer $
// $Authors: Julianus Pfeuffer $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/KERNEL/ConsensusMap.h>
#include <OpenMS/METADATA/ExperimentalDesign.h>
#include <OpenMS/METADATA/ProteinIdentification.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <map>
#include <unordered_set>
namespace OpenMS
{
//TODO add params for checking consistency (i.e. how strict to check)
//TODO add another subclass that does score-aware merging? (i.e. only keep best per peptide[sequence])
/**
* @brief Algorithm for merging multiple protein and peptide identification runs.
*
* This class creates a new Protein ID run into which other runs can be inserted.
* It performs the following operations:
* - Creates a union of protein hits from all inserted runs
* - Concatenates Peptide-Spectrum Matches (PSMs) from all runs
* - Checks search engine consistency across all inserted runs
* - Maintains references between peptide IDs and their corresponding protein IDs
*
* The algorithm differs from the IDMerger tool in two key aspects:
* 1. It is implemented as an algorithm class rather than a tool
* 2. It allows inserting multiple peptide hits per peptide sequence (not only the first occurrence)
*
* The class handles the complexity of merging identification data from different sources
* while ensuring consistency and maintaining proper references between proteins and peptides.
* It can be used in workflows where identification results from multiple files or runs
* need to be combined into a single comprehensive result set.
*
* The algorithm can optionally annotate the origin of each identification to maintain
* traceability of the merged results back to their source files.
*
* @see IDMerger
*
* @todo Allow filtering for peptide sequence to supersede the IDMerger tool.
* Make it keep the best PSMs though.
*/
class OPENMS_DLLAPI IDMergerAlgorithm:
public DefaultParamHandler,
public ProgressLogger
{
public:
/**
* @brief Constructor for the IDMergerAlgorithm.
*
* Initializes a new merger with the specified run identifier.
*
* @param[in] runIdentifier Base identifier for the merged run (default: "merged")
* @param[in] addTimeStampToID Whether to append a timestamp to the run identifier for uniqueness (default: true)
*/
explicit IDMergerAlgorithm (const String& runIdentifier = "merged", bool addTimeStampToID = true);
/**
* @brief Insert runs using move semantics.
*
* Inserts (moves and clears) protein and peptide identifications into the internal
* merged data structures. This version uses move semantics for better performance
* when the source data is no longer needed.
* Note:
* - Only inserts PeptideIdentifications from existing runs in @p prots (noop if prots is empty)
* - Duplicates file origins if multiple (compatible) protein runs from the same spectrumfile
* are merged
*
* @param[in] prots Vector of protein identifications to be merged
* @param[in] peps Vector of peptide identifications to be merged
*/
void insertRuns(std::vector<ProteinIdentification>&& prots,
PeptideIdentificationList&& peps);
/**
* @brief Insert runs using copy semantics.
*
* Inserts (copies) protein and peptide identifications into the internal
* merged data structures. This version preserves the source data.
* Note:
* - Only inserts PeptideIdentifications from existing runs in @p prots (noop if prots is empty)
* - Duplicates file origins if multiple (compatible) protein runs from the same spectrumfile
* are merged
*
* @param[in] prots Vector of protein identifications to be merged
* @param[in] peps Vector of peptide identifications to be merged
*/
void insertRuns(const std::vector<ProteinIdentification>& prots,
const PeptideIdentificationList& peps);
//TODO add methods to just insert prots or just peps. Especially makes sense if you do re-indexing anyway,
// then you do not need the proteins. But then we need origin information. Either externally in form of a
// String or StringList (like the one from ProteinID.getPrimaryMSRunPath). Or by having the file annotated
// at the PeptideID (with getBasename maybe?)
// Current solution would be to clear the ProteinIdentification if you do not need the proteins and add all the
// necessary information about origin(s) to this ProteinIdentification.
/**
* @brief Return the merged results and reset internal state.
*
* Retrieves the merged protein and peptide identifications and clears all internal
* data structures, preparing the algorithm instance for potential reuse.
*
* This method should be called after all desired runs have been inserted to obtain
* the final merged result.
*
* @param[in] prots [out] The merged protein identification containing the union of all protein hits
* @param[in] peps [out] The merged peptide identifications containing all PSMs from the inserted runs
*
* @note After calling this method, the internal state is reset, and the algorithm
* can be reused for a new merging operation.
*/
void returnResultsAndClear(ProteinIdentification& prots,
PeptideIdentificationList& peps);
private:
/**
* @brief Generate a new identifier for the merged run.
*
* Creates a new identifier by combining the base identifier with a timestamp
* if requested.
*
* @param[in] addTimeStampToID Whether to append a timestamp to the identifier
* @return The generated identifier string
*/
String getNewIdentifier_(bool addTimeStampToID) const;
/**
* @brief Copy search parameters between protein identifications.
*
* Transfers search parameters from one protein identification to another.
*
* @param[in] from Source protein identification
* @param[out] to Destination protein identification
*/
static void copySearchParams_(const ProteinIdentification& from, ProteinIdentification& to);
/**
* @brief Check consistency of search engines and settings across runs.
*
* Verifies that all runs have compatible search engine settings before merging.
* Uses the first run as an implicit reference.
*
* @param[in] protRuns The runs to check (first = implicit reference)
* @param[in] experiment_type Experiment type to allow certain mismatches (e.g., "SILAC")
* @return True if all runs are consistent, false otherwise
* @throws BaseException for disagreeing settings
*
* @todo Return a merged RunDescription about what to put in the new runs (e.g., for SILAC)
*/
bool checkOldRunConsistency_(
const std::vector<ProteinIdentification>& protRuns,
const String& experiment_type) const;
/**
* @brief Check consistency of search engines and settings against a reference.
*
* Verifies that all runs have compatible search engine settings before merging,
* using an explicitly provided reference run.
*
* @param[in] protRuns The runs to check
* @param[in] ref An external protein run to use as reference
* @param[in] experiment_type Experiment type to allow certain mismatches (e.g., "SILAC")
* @return True if all runs are consistent with the reference, false otherwise
* @throws BaseException for disagreeing settings
*
* @todo Return a merged RunDescription about what to put in the new runs (e.g., for SILAC)
*/
bool checkOldRunConsistency_(
const std::vector<ProteinIdentification>& protRuns,
const ProteinIdentification& ref,
const String& experiment_type) const;
/**
* @brief Insert protein identifications into the merged result.
*
* Moves and inserts protein IDs if not yet present, then clears the input.
*
* @param[in] old_protRuns Vector of protein identifications to insert
*/
void insertProteinIDs_(
std::vector<ProteinIdentification>&& old_protRuns
);
/**
* @brief Update peptide ID references and move them to the result.
*
* Updates the references in peptide IDs to point to the new protein ID run,
* then moves the peptide IDs based on the provided mapping.
*
* @param[in] pepIDs Vector of peptide identifications to update and move
* @param[in] runID_to_runIdx Mapping from run IDs to run indices
* @param[in] originFiles List of origin files for each run
* @param[in] annotate_origin Whether to annotate peptide IDs with their origin
*/
void updateAndMovePepIDs_(
PeptideIdentificationList&& pepIDs,
const std::map<String, Size>& runID_to_runIdx,
const std::vector<StringList>& originFiles,
bool annotate_origin
);
/**
* @brief Optimized method to move peptide IDs and reference proteins to result.
*
* A faster implementation for moving peptide IDs and their referenced proteins
* to the result data structures.
*
* @param[in] pepIDs Vector of peptide identifications to move
* @param[in] old_protRuns Vector of protein identifications to reference
*/
void movePepIDsAndRefProteinsToResultFaster_(
PeptideIdentificationList&& pepIDs,
std::vector<ProteinIdentification>&& old_protRuns
);
/// The resulting merged protein identification
ProteinIdentification prot_result_;
/// The resulting merged peptide identifications
PeptideIdentificationList pep_result_;
/**
* @brief Hash function for protein hits based on accession.
*
* @param[in] p Protein hit to hash
* @return Hash value for the protein hit
*/
static size_t accessionHash_(const ProteinHit& p){
return std::hash<String>()(p.getAccession());
}
/**
* @brief Equality function for protein hits based on accession.
*
* @param[in] p1 First protein hit to compare
* @param[in] p2 Second protein hit to compare
* @return True if the accessions are equal, false otherwise
*/
static bool accessionEqual_(const ProteinHit& p1, const ProteinHit& p2){
return p1.getAccession() == p2.getAccession();
}
/// Type alias for the hash function
using hash_type = std::size_t (*)(const ProteinHit&);
/// Type alias for the equality function
using equal_type = bool (*)(const ProteinHit&, const ProteinHit&);
/// Set of collected protein hits using custom hash and equality functions
std::unordered_set<ProteinHit, hash_type, equal_type> collected_protein_hits_;
/// Flag indicating whether the resulting protein ID is already filled
bool filled_ = false;
/// Mapping to keep track of the mzML origins of spectra
std::map<String, Size> file_origin_to_idx_;
/// The new identifier string for the merged run
String id_;
/// Flag indicating whether the identifier should be fixed (i.e., not contain a timestamp)
bool fixed_identifier_;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/ID/ConsensusIDAlgorithmRanks.h | .h | 1,633 | 53 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hendrik Weisser $
// $Authors: Andreas Bertsch, Marc Sturm, Sven Nahnsen, Hendrik Weisser $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/ANALYSIS/ID/ConsensusIDAlgorithmIdentity.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
namespace OpenMS
{
/**
@brief Calculates a consensus from multiple ID runs based on the ranks of the search hits.
@htmlinclude OpenMS_ConsensusIDAlgorithmRanks.parameters
@ingroup Analysis_ID
*/
class OPENMS_DLLAPI ConsensusIDAlgorithmRanks :
public ConsensusIDAlgorithmIdentity
{
public:
/// Default constructor
ConsensusIDAlgorithmRanks();
private:
/// Number of ID runs for current analysis
Size current_number_of_runs_;
/// Number of considered hits for current analysis
Size current_considered_hits_;
/// Not implemented
ConsensusIDAlgorithmRanks(const ConsensusIDAlgorithmRanks&);
/// Not implemented
ConsensusIDAlgorithmRanks& operator=(const ConsensusIDAlgorithmRanks&);
/// Assign peptide scores based on search ranks
void preprocess_(PeptideIdentificationList& ids) override;
/// Aggregate peptide scores into one final score (by averaging ranks)
double getAggregateScore_(std::vector<double>& scores,
bool higher_better) override;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/ID/MessagePasserFactory.h | .h | 15,370 | 314 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Julianus Pfeuffer $
// $Authors: Julianus Pfeuffer $
// --------------------------------------------------------------------------
#pragma once
#include <cmath>
#include <Evergreen/evergreen.hpp>
typedef unsigned long int uiint;
namespace OpenMS
{
namespace Internal
{
/// Produces MessagePassers (nodes in a factor graph = bayesian network) for use with Evergreen library,
/// based on a parameterization of the Protein-Peptide Bayesian network.
/// Those MessagePassers can be tables or convolution trees. Labels are used to associate the variables they are
/// working on. They can be integers (for speed) or strings (for readability/debug)
template <typename Label>
class MessagePasserFactory {
private:
//const int minInputsPAF = 3; //@todo could be used to decide when brute force is better.
/// the model parameters
double alpha_, beta_, gamma_, p_, pepPrior_;
/// Likelihoods for the charge states given presence of the peptide sequence (@todo could be calculated from IDPEP
/// if we do per charge state fitting) or empirically estimated from the input PSMs
std::map<int, double> chgLLhoods = {{1, 0.7}, {2, 0.9}, {3, 0.7}, {4, 0.5}, {5, 0.5}};
/// to fill the noisy-OR table for a peptide given parent proteins
/// TODO pre-compute for like a hundred parent proteins
/// TODO introduce special case for alpha or beta = 1. The log formula does not work otherwise.
inline double notConditionalGivenSum(unsigned long summ) {
// use log for better precision
return std::pow(2., log2(1. - beta_) + summ * log2(1. - alpha_));
//return std::pow((1.0 - alpha_), summ) * (1.0 - beta_); // standard way
}
public:
/// Protein Factor initialized with model prior (missing peps are experimental)
evergreen::TableDependency<Label> createProteinFactor(Label id, int nrMissingPeps = 0);
/// Protein Factor initialized with user prior (missing peps are experimental)
evergreen::TableDependency<Label> createProteinFactor(Label id, double prior, int nrMissingPeps = 0);
/// Peptide Factor initialized with:
/// @param[in] id ID for the LabeledPMF
/// @param[in] prob peptide evidence probability
evergreen::TableDependency<Label> createPeptideEvidenceFactor(Label id, double prob);
/// Conditional probability table of peptide given number of parent proteins, based on model params.
/// Additionally regularizes on the amount of parent proteins.
/// @param[in] nr_parents (maximum) number of parent proteins
/// @param[in] id ID for the LabeledPMF
/// @param[in] pep_id ID for the LabeledPMF
evergreen::TableDependency<Label> createRegularizingSumEvidenceFactor(size_t nr_parents, Label id, Label pep_id);
/// Conditional probability table of peptide given number of parent proteins, based on model params.
/// @param[in] nr_parents (maximum) number of parent proteins
/// @param[in] id ID for the LabeledPMF
/// @param[in] pep_id ID for the LabeledPMF
evergreen::TableDependency<Label> createSumEvidenceFactor(size_t nr_parents, Label id, Label pep_id);
//For extended model. @todo currently unused
evergreen::TableDependency<Label> createSumFactor(size_t nr_parents, Label nId);
evergreen::TableDependency<Label> createReplicateFactor(Label seqId, Label repId);
evergreen::TableDependency<Label> createChargeFactor(Label repId, Label chargeId, int chg);
/// To sum up distributions for the number of parent proteins of a peptide with convolution trees
evergreen::AdditiveDependency<Label> createPeptideProbabilisticAdderFactor(const std::set<Label> & parentProteinIDs, Label nId);
/// To sum up distributions for the number of parent proteins of a peptide with convolution trees
evergreen::AdditiveDependency<Label> createPeptideProbabilisticAdderFactor(const std::vector<Label> & parentProteinIDs, Label nId);
/// To sum up distributions for the number of parent proteins of a peptide brute-force
evergreen::PseudoAdditiveDependency<Label> createBFPeptideProbabilisticAdderFactor(const std::set<Label> & parentProteinIDs, Label nId, const std::vector<evergreen::TableDependency <Label> > & deps);
/**
* @brief Constructor
* @param[in] alpha Peptide emission probability
* @param[in] beta Spurious peptide emission probability
* @param[in] gamma Protein prior
* @param[in] p Marginalization norm
* @param[in] pep_prior Peptide prior (defines at which evidence probability, additional evidence is beneficial)
*/
MessagePasserFactory(double alpha, double beta, double gamma, double p, double pep_prior);
/// Works on a vector of protein indices (potentially not consecutive)
// TODO we could recollect the protIDs from the union of parents.
void fillVectorsOfMessagePassers(const std::vector<Label> & protIDs,
const std::vector<std::vector<Label>> & parentsOfPeps,
const std::vector<double> & pepEvidences,
evergreen::InferenceGraphBuilder<Label> & igb);
//void fillVectorsOfMessagePassersBruteForce(const std::vector<Label> & protIDs,
// const std::vector<std::vector<Label>> & parentsOfPeps,
// const std::vector<double> & pepEvidences,
// evergreen::InferenceGraphBuilder<Label> & igb);
};
//IMPLEMENTATIONS:
template <typename Label>
MessagePasserFactory<Label>::MessagePasserFactory(double alpha, double beta, double gamma, double p, double pep_prior) {
assert(0. <= alpha && alpha <= 1.);
assert(0. <= beta && beta <= 1.);
assert(0. <= gamma && gamma <= 1.);
//Note: smaller than 1 might be possible but is untested right now.
assert(p >= 1.);
assert(0. < pep_prior && pep_prior < 1.);
alpha_ = alpha;
beta_ = beta;
gamma_ = gamma;
p_ = p;
pepPrior_ = pep_prior;
}
template <typename Label>
evergreen::TableDependency<Label> MessagePasserFactory<Label>::createProteinFactor(Label id, int nrMissingPeps) {
double prior = gamma_;
if (nrMissingPeps > 0)
{
double powFactor = std::pow(1.0 - alpha_, -nrMissingPeps);
prior = -prior/(prior * powFactor - prior - powFactor);
}
double table[] = {1.0 - prior, prior};
evergreen::LabeledPMF<Label> lpmf({id}, evergreen::PMF({0L}, evergreen::Tensor<double>::from_array(table)));
return evergreen::TableDependency<Label>(lpmf,p_);
}
template <typename Label>
evergreen::TableDependency<Label> MessagePasserFactory<Label>::createProteinFactor(Label id, double prior, int nrMissingPeps) {
if (nrMissingPeps > 0)
{
double powFactor = std::pow(1.0 - alpha_, -nrMissingPeps);
prior = -prior/(prior * powFactor - prior - powFactor);
}
double table[] = {1.0 - prior, prior};
evergreen::LabeledPMF<Label> lpmf({id}, evergreen::PMF({0L}, evergreen::Tensor<double>::from_array(table)));
return evergreen::TableDependency<Label>(lpmf,p_);
}
template <typename Label>
evergreen::TableDependency<Label> MessagePasserFactory<Label>::createPeptideEvidenceFactor(Label id, double prob) {
double table[] = {(1 - prob) * (1 - pepPrior_), prob * pepPrior_};
evergreen::LabeledPMF<Label> lpmf({id}, evergreen::PMF({0L}, evergreen::Tensor<double>::from_array(table)));
return evergreen::TableDependency<Label>(lpmf,p_);
}
template <typename Label>
evergreen::TableDependency<Label> MessagePasserFactory<Label>::createSumEvidenceFactor(size_t nrParents, Label nId, Label pepId) {
evergreen::Tensor<double> table({static_cast<unsigned long>(nrParents + 1) , 2});
for (unsigned long i=0; i <= nrParents; ++i) {
double notConditional = notConditionalGivenSum(i);
unsigned long indexArr[2] = {i,0ul};
table[indexArr] = notConditional;
unsigned long indexArr2[2] = {i,1ul};
table[indexArr2] = 1.0 - notConditional;
}
//std::cout << table << std::endl;
evergreen::LabeledPMF<Label> lpmf({nId, pepId}, evergreen::PMF({0L,0L}, table));
//std::cout << lpmf << std::endl;
return evergreen::TableDependency<Label>(lpmf,p_);
}
template <typename Label>
evergreen::TableDependency<Label> MessagePasserFactory<Label>::createRegularizingSumEvidenceFactor(size_t nrParents, Label nId, Label pepId) {
evergreen::Tensor<double> table({static_cast<unsigned long>(nrParents + 1) , 2});
unsigned long z[2]{0ul,0ul};
unsigned long z1[2]{0ul,1ul};
table[z] = 1. - beta_;
table[z1] = beta_;
for (unsigned long i=1; i <= nrParents; ++i) {
double notConditional = notConditionalGivenSum(i);
unsigned long indexArr[2] = {i,0ul};
table[indexArr] = notConditional / i;
unsigned long indexArr2[2] = {i,1ul};
table[indexArr2] = (1.0 - notConditional) / i;
}
//std::cout << table << std::endl;
evergreen::LabeledPMF<Label> lpmf({nId, pepId}, evergreen::PMF({0L,0L}, table));
//std::cout << lpmf << std::endl;
return evergreen::TableDependency<Label>(lpmf,p_);
}
template <typename Label>
evergreen::TableDependency<Label> MessagePasserFactory<Label>::createSumFactor(size_t nrParents, Label nId) {
evergreen::Tensor<double> table({nrParents+1});
for (unsigned long i=0; i <= nrParents; ++i) {
table[i] = 1.0/(nrParents+1.);
}
//std::cout << table << std::endl;
evergreen::LabeledPMF<Label> lpmf({nId}, evergreen::PMF({0L}, table));
//std::cout << lpmf << std::endl;
return evergreen::TableDependency<Label>(lpmf,p_);
}
template <typename Label>
evergreen::TableDependency<Label> MessagePasserFactory<Label>::createReplicateFactor(Label seqId, Label repId) {
using arr = unsigned long[2];
evergreen::Tensor<double> table({2,2});
table[arr{0,0}] = 0.999;
table[arr{0,1}] = 0.001;
table[arr{1,0}] = 0.1;
table[arr{1,1}] = 0.9;
//std::cout << table << std::endl;
evergreen::LabeledPMF<Label> lpmf({seqId,repId}, evergreen::PMF({0L,0L}, table));
//std::cout << lpmf << std::endl;
return evergreen::TableDependency<Label>(lpmf,p_);
}
template <typename Label>
evergreen::TableDependency<Label> MessagePasserFactory<Label>::createChargeFactor(Label repId, Label chgId, int chg) {
double chgPrior = chgLLhoods[chg];
using arr = unsigned long[2];
evergreen::Tensor<double> table({2,2});
table[arr{0,0}] = 0.999;
table[arr{0,1}] = 0.001;
table[arr{1,0}] = 0.1;
table[arr{1,1}] = chgPrior;
//std::cout << table << std::endl;
evergreen::LabeledPMF<Label> lpmf({repId,chgId}, evergreen::PMF({0L,0L}, table));
//std::cout << lpmf << std::endl;
return evergreen::TableDependency<Label>(lpmf,p_);
}
template <typename Label>
evergreen::AdditiveDependency<Label> MessagePasserFactory<Label>::createPeptideProbabilisticAdderFactor(const std::set<Label> & parentProteinIDs, Label nId) {
std::vector<std::vector<Label>> parents;
std::transform(parentProteinIDs.begin(), parentProteinIDs.end(), std::back_inserter(parents), [](const Label& l){return std::vector<Label>{l};});
return evergreen::AdditiveDependency<Label>(parents, {nId}, p_);
}
template <typename Label>
evergreen::AdditiveDependency<Label> MessagePasserFactory<Label>::createPeptideProbabilisticAdderFactor(const std::vector<Label> & parentProteinIDs, Label nId) {
std::vector<std::vector<Label>> parents;
std::transform(parentProteinIDs.begin(), parentProteinIDs.end(), std::back_inserter(parents), [](const Label& l){return std::vector<Label>{l};});
return evergreen::AdditiveDependency<Label>(parents, {nId}, p_);
}
template <typename Label>
evergreen::PseudoAdditiveDependency<Label> MessagePasserFactory<Label>::createBFPeptideProbabilisticAdderFactor(const std::set<Label> & parentProteinIDs, Label nId, const std::vector<evergreen::TableDependency<Label>> & deps) {
std::vector<std::vector<Label>> parents;
std::transform(parentProteinIDs.begin(), parentProteinIDs.end(), std::back_inserter(parents), [](const Label& l){return std::vector<Label>{l};});
return evergreen::PseudoAdditiveDependency<Label>(parents, {nId}, deps, p_);
}
/// Works on a vector of protein indices (potentially not consecutive)
// TODO we could recollect the protIDs from the union of parents.
template <typename Label>
void MessagePasserFactory<Label>::fillVectorsOfMessagePassers(const std::vector<Label>& protIDs,
const std::vector<std::vector<Label>>& parentsOfPeps,
const std::vector<double>& pepEvidences,
evergreen::InferenceGraphBuilder<Label>& igb)
{
//TODO asserts could be loosened
assert(parentsOfPeps.size() == pepEvidences.size());
for (const std::vector<uiint>& parents : parentsOfPeps)
for (Label parent : parents)
assert(std::find(protIDs.begin(), protIDs.end(), parent) != protIDs.end());
for (uiint pid : protIDs)
igb.insert_dependency(createProteinFactor(pid));
for (uiint j = 0; j < parentsOfPeps.size(); j++)
{
igb.insert_dependency(createPeptideEvidenceFactor(j,pepEvidences[j]));
igb.insert_dependency(createSumEvidenceFactor(parentsOfPeps[j],j,j));
igb.insert_dependency(createPeptideProbabilisticAdderFactor(parentsOfPeps[j],j));
}
}
/* unused but working
template <typename Label>
void MessagePasserFactory<Label>::fillVectorsOfMessagePassersBruteForce(const std::vector<Label> & protIDs,
const std::vector<std::vector<Label>> & parentsOfPeps,
const std::vector<double> & pepEvidences,
evergreen::InferenceGraphBuilder<Label> & igb)
{
assert(parentsOfPeps.size() == pepEvidences.size());
for (std::vector<uiint> parents : parentsOfPeps)
for (uiint parent : parents)
assert(std::find(protIDs.begin(), protIDs.end(), parent) != protIDs.end());
for (uiint pid : protIDs)
igb.insert_dependency(createProteinFactor(pid));
for (uiint j = 0; j < parentsOfPeps.size(); j++)
{
std::vector<evergreen::TableDependency<std::string> > deps;
auto pepdep = createSumEvidenceFactor(parentsOfPeps[j],j,j);
auto sumdep = createSumFactor(parentsOfPeps[j],j);
igb.insert_dependency(createPeptideEvidenceFactor(j,pepEvidences[j]));
igb.insert_dependency(pepdep);
deps.push_back(sumdep);
for (const auto& parent : parentsOfPeps[j]) {
deps.push_back(createProteinFactor(parent));
}
//igb.insert_dependency(createEmptyPeptideProbabilisticAdderFactor(parentsOfPeps[j],j));
igb.insert_dependency(createBFPeptideProbabilisticAdderFactor(parentsOfPeps[j],j,deps));
}
}
*/
} // namespace Internal
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/ID/NeighborSeq.h | .h | 8,077 | 162 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow, Philipp Wang $
// $Authors: Chris Bielow, Philipp Wang $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CHEMISTRY/TheoreticalSpectrumGenerator.h>
#include <OpenMS/KERNEL/MSSpectrum.h>
#include <vector>
#include <map>
namespace OpenMS
{
/**
@brief The Neighbor Peptide functionality is designed to find peptides (neighbors) in a given set of sequences (FASTA file) that are
similar to a target peptide (aka relevant peptide) based on mass and spectral characteristics. This provides more power
when searching complex samples, when only a subset of the peptides/proteins is of interest.
The paper on subset neighbor search is www.ncbi.nlm.nih.gov/pmc/articles/PMC8489664/
DOI: 10.1021/acs.jproteome.1c00483
*/
class OPENMS_DLLAPI NeighborSeq
{
public:
/// Constructor
/// @param[in] digested_relevant_peptides A vector of digested relevant peptides
NeighborSeq(std::vector<AASequence>&& digested_relevant_peptides);
/**
* @brief Generates a theoretical spectrum for a given peptide sequence with b/y ions at charge 1.
*
* Includes all b and y ions with charge 1 (even the prefix ions, e.g. b1), but no internal ions.
*
* @param[in] peptide_sequence The peptide sequence for which to generate the spectrum.
* @return The generated theoretical spectrum.
*/
MSSpectrum generateSpectrum(const AASequence& peptide_sequence);
/**
* @brief Compares two spectra to determine if they share a sufficient number of ions.
*
* All peaks are considered. Use generateSpectrum() to generate theoretical spectra with b/y ions.
*
* @param[in] spec1 The first theoretical spectrum.
* @param[in] spec2 The second theoretical spectrum.
* @param[in] min_shared_ion_fraction The minimal required proportion of shared ions in [0, 1]
* @param[in] mz_bin_size Bin size for the m/z values, which determines if two peaks are considered to be the same (typically, 0.05 for high resolution and 1.0005079 for low resolution).
* @return True if the spectra share a sufficient number of ions, false otherwise.
*/
static bool isNeighborSpectrum(const MSSpectrum& spec1, const MSSpectrum& spec2, const double min_shared_ion_fraction, const double mz_bin_size);
/**
* @brief Compute the number of shared ions between two spectra
*
* All peaks are considered. Use generateSpectrum() to generate theoretical spectra with b/y ions.
*
* @param[in] spec1 The first theoretical spectrum.
* @param[in] spec2 The second theoretical spectrum.
* @param[in] mz_bin_size Bin size for the m/z values, which determines if two peaks are considered to be the same.
* @return The number of shared ions
*/
static int computeSharedIonCount(const MSSpectrum& spec1, const MSSpectrum& spec2, const double& mz_bin_size);
/**
* @brief Is this peptide a neighbor to one of the relevant peptides?
*
* Also updates the internal statistics, which can be retrieved using getNeighborStats().
*
* @param[in] neighbor_candidate The peptide sequence (from a neighbor protein) to compare against the internal relevant peptides (see constructor).
* @param[in] mass_tolerance_pc Maximal precursor mass difference (in Da or ppm; see 'mass_tolerance_pc_ppm') between neighbor and relevant peptide.
* @param[in] mass_tolerance_pc_ppm Is 'mass_tolerance_pc' in Da or ppm?
* @param[in] min_shared_ion_fraction The ion tolerance for neighbor peptides.
* @param[in] mz_bin_size Bin size for spectra m/z comparison (the original study suggests 0.05 Th for high-res and 1.0005079 Th for low-res spectra).
* @return true if @p neighbor_candidate is neighbor to one or more relevant peptides, false otherwise.
*/
bool isNeighborPeptide(const AASequence& neighbor_candidate,
const double mass_tolerance_pc,
const bool mass_tolerance_pc_ppm,
const double min_shared_ion_fraction,
const double mz_bin_size);
/// Statistics of how many neighbors were found per reference peptide
struct NeighborStats
{
/** @name NeigborStats_members
* Mutually exclusive categories of how many neighbors were found per reference peptide
*/
///@{
int unfindable_peptides = 0; ///< how many ref-peptides contain an 'X' (unknown amino acid) and thus cannot be searched for neighbors
int findable_no_neighbors = 0; ///< how many peptides had no neighbors?
int findable_one_neighbor = 0; ///< how many peptides had exactly one neighbor?
int findable_multiple_neighbors = 0; ///< how many peptides had multiple neighbors?
///@}
/// Sum of all 4 categories
int total() const
{
return unfindable_peptides + findable_no_neighbors + findable_one_neighbor + findable_multiple_neighbors;
}
/// Number of reference peptides that contain an 'X' (unknown amino acid), formatted as 'X (Y%)'
String unfindable() const
{
return String(unfindable_peptides) + " (" + unfindable_peptides * 100 / total() + "%)";
}
/// Number of reference peptides that had no neighbors, formatted as 'X (Y%)'
String noNB() const
{
return String(findable_no_neighbors) + " (" + findable_no_neighbors * 100 / total() + "%)";
}
/// Number of reference peptides that had exactly one neighbor, formatted as 'X (Y%)'
String oneNB() const
{
return String(findable_one_neighbor) + " (" + findable_one_neighbor * 100 / total() + "%)";
}
/// Number of reference peptides that had multiple neighbors, formatted as 'X (Y%)'
String multiNB() const
{
return String(findable_multiple_neighbors) + " (" + findable_multiple_neighbors * 100 / total() + "%)";
}
};
/// after calling isNeighborPeptide() multiple times, this function returns the statistics of how many neighbors were found per reference peptide
NeighborStats getNeighborStats() const;
protected:
/**
* @brief Creates a map of masses to positions from the internal relevant peptides.
* @return A map where the key is the mass and the value is a vector of positions.
*/
std::map<double, std::vector<int>> createMassLookup_();
/**
* @brief Finds candidate positions based on a given mono-isotopic weight and mass tolerance.
* @param[in] mono_weight The mono-isotopic weight to find candidates for.
* @param[in] mass_tolerance The allowed tolerance for matching the mass.
* @param[in] mass_tolerance_pc_ppm Whether the mass tolerance is in ppm.
* @return A pair of begin/end iterators into mass_position_map_ for the candidate positions
*/
auto findCandidatePositions_(const double mono_weight, double mass_tolerance, const bool mass_tolerance_pc_ppm);
private:
const std::vector<AASequence>& digested_relevant_peptides_; ///< digested relevant peptides
std::map<double, std::vector<int>> mass_position_map_; ///< map of masses to positions in digested_relevant_peptides_
TheoreticalSpectrumGenerator spec_gen_; ///< for b/y ions with charge 1
const Residue* x_residue_; ///< residue for unknown amino acid
std::vector<int> neighbor_stats_; ///< how many neighbors per reference peptide searched using isNeighborPeptide()?
}; // class NeighborSeq
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/ID/IDBoostGraph.h | .h | 24,691 | 624 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Julianus Pfeuffer $
// $Authors: Julianus Pfeuffer $
// --------------------------------------------------------------------------
#pragma once
// define to get timings for connected components
//#define INFERENCE_BENCH
#include <OpenMS/ANALYSIS/ID/MessagePasserFactory.h> //included in BPI
#include <OpenMS/CONCEPT/Types.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/METADATA/ExperimentalDesign.h>
#include <OpenMS/METADATA/ProteinIdentification.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <vector>
#include <unordered_map>
#include <queue>
#include <boost/function.hpp>
#include <boost/blank.hpp>
#include <boost/serialization/strong_typedef.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/depth_first_search.hpp>
#include <boost/graph/filtered_graph.hpp>
#include <boost/graph/properties.hpp>
#include <boost/variant.hpp>
#include <boost/variant/detail/hash_variant.hpp>
#include <boost/variant/static_visitor.hpp>
namespace OpenMS
{
struct ScoreToTgtDecLabelPairs;
namespace Internal
{
/**
@brief Creates and maintains a boost graph based on the OpenMS ID datastructures
For finding connected components and applying functions to them.
Currently assumes that all PeptideIdentifications are from the ProteinID run that is given.
Please make sure this is right.
VERY IMPORTANT NOTE: If you add Visitors here, make sure they do not touch members of the
underlying ID objects that are responsible for the graph structure. E.g. the (protein/peptide)_hits vectors
or the lists in ProteinGroups. You can set information like scores or metavalues, though.
@ingroup Analysis_ID
*/
//TODO Add OPENMS_DLLAPI everywhere
class OPENMS_DLLAPI IDBoostGraph
{
public:
// boost has a weird extra semicolon in their strong typedef
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wextra-semi"
#endif
/// placeholder for peptides with the same parent proteins or protein groups
BOOST_STRONG_TYPEDEF(boost::blank, PeptideCluster);
/// indistinguishable protein groups (size, nr targets, score)
struct ProteinGroup
{
int size = 0;
int tgts = 0;
double score = 0.;
};
/// an (currently unmodified) peptide sequence
BOOST_STRONG_TYPEDEF(String, Peptide);
/// in which run a PSM was observed
BOOST_STRONG_TYPEDEF(Size, RunIndex);
/// in which charge state a PSM was observed
BOOST_STRONG_TYPEDEF(int, Charge);
#ifdef __clang__
#pragma clang diagnostic pop
#endif
//typedefs
//TODO rename ProteinGroup type since it collides with the actual OpenMS ProteinGroup
typedef boost::variant<ProteinHit*, ProteinGroup, PeptideCluster, Peptide, RunIndex, Charge, PeptideHit*> IDPointer;
typedef boost::variant<const ProteinHit*, const ProteinGroup*, const PeptideCluster*, const Peptide, const RunIndex, const Charge, const PeptideHit*> IDPointerConst;
//TODO check the impact of different data structures to store nodes/edges
// Directed graphs would make the internal computations much easier (less in/out edge checking) but boost
// does not allow computation of "non-strongly" connected components for directed graphs, which is what we would
// need. We can think about after/while copying to CCs, to insert it into a directed graph!
typedef boost::adjacency_list <boost::setS, boost::vecS, boost::undirectedS, IDPointer> Graph;
typedef std::vector<Graph> Graphs;
typedef boost::adjacency_list <boost::setS, boost::vecS, boost::undirectedS, IDPointer> GraphConst;
typedef boost::graph_traits<Graph>::vertex_descriptor vertex_t;
typedef boost::graph_traits<Graph>::edge_descriptor edge_t;
typedef std::set<IDBoostGraph::vertex_t> ProteinNodeSet;
typedef std::set<IDBoostGraph::vertex_t> PeptideNodeSet;
/// A boost dfs visitor that copies connected components into a vector of graphs
class dfs_ccsplit_visitor:
public boost::default_dfs_visitor
{
public:
dfs_ccsplit_visitor(Graphs& vgs)
: gs(vgs), curr_v(0), next_v(0), m()
{}
template < typename Vertex, typename Graph >
void start_vertex(Vertex u, const Graph & tg)
{
gs.emplace_back();
next_v = boost::add_vertex(tg[u], gs.back());
m[u] = next_v;
}
template < typename Vertex, typename Graph >
void discover_vertex(Vertex /*u*/, const Graph & /*tg*/)
{
curr_v = next_v;
}
template < typename Edge, typename Graph >
void examine_edge(Edge e, const Graph & tg)
{
if (m.find(e.m_target) == m.end())
{
next_v = boost::add_vertex(tg[e.m_target], gs.back());
m[e.m_target] = next_v;
}
else
{
next_v = m[e.m_target];
}
boost::add_edge(m[e.m_source], next_v, gs.back());
}
Graphs& gs;
vertex_t curr_v, next_v;
/// A mapping from old node id to new node id to not duplicate existing ones in the new graph
std::map<vertex_t, vertex_t> m;
};
///@brief Visits nodes in the boost graph (ptrs to an ID Object) and depending on their type creates a label
/// e.g. for printing to dot format
class LabelVisitor:
public boost::static_visitor<OpenMS::String>
{
public:
OpenMS::String operator()(const PeptideHit* pep) const
{
return pep->getSequence().toString() + "_" + pep->getCharge();
}
OpenMS::String operator()(const ProteinHit* prot) const
{
return prot->getAccession();
}
OpenMS::String operator()(const ProteinGroup& /*protgrp*/) const
{
return "PG";
}
OpenMS::String operator()(const PeptideCluster& /*pc*/) const
{
return "PepClust";
}
OpenMS::String operator()(const Peptide& peptide) const
{
return peptide;
}
OpenMS::String operator()(const RunIndex& ri) const
{
return "rep" + String(ri);
}
OpenMS::String operator()(const Charge& chg) const
{
return "chg" + String(chg);
}
};
/// @brief Visits nodes in the boost graph (ptrs to an ID Object) and depending on their type prints the address.
/// For debugging purposes only
template<class CharT>
class PrintAddressVisitor:
public boost::static_visitor<>
{
public:
explicit PrintAddressVisitor(std::basic_ostream<CharT> stream):
stream_(stream)
{}
void operator()(PeptideHit* pep) const
{
stream_ << pep->getSequence().toUnmodifiedString() << ": " << pep << std::endl;
}
void operator()(ProteinHit* prot) const
{
stream_ << prot->getAccession() << ": " << prot << std::endl;
}
void operator()(const ProteinGroup& /*protgrp*/) const
{
stream_ << "PG" << std::endl;
}
void operator()(const PeptideCluster& /*pc*/) const
{
stream_ << "PepClust" << std::endl;
}
void operator()(const Peptide& peptide) const
{
stream_ << peptide << std::endl;
}
void operator()(const RunIndex& ri) const
{
stream_ << "rep" << ri << std::endl;
}
void operator()(const Charge& chg) const
{
stream_ << "chg" << chg << std::endl;
}
std::basic_ostream<CharT> stream_;
};
/// @brief Visits nodes in the boost graph (either ptrs to an ID Object or some lightweight surrogates)
/// and depending on their type sets the posterior
/// Don't forget to set higherScoreBetter and score names in the parent ID objects.
class SetPosteriorVisitor:
public boost::static_visitor<>
{
public:
void operator()(PeptideHit* pep, double posterior) const
{
pep->setScore(posterior);
}
void operator()(ProteinHit* prot, double posterior) const
{
prot->setScore(posterior);
}
void operator()(ProteinGroup& pg, double posterior) const
{
pg.score = posterior;
}
// Everything else, do nothing for now
template <class T>
void operator()(T& /*any node type*/, double /*posterior*/) const
{
// do nothing
}
};
/// @brief Visits nodes in the boost graph (either ptrs to an ID Object or some lightweight surrogates)
/// and depending on their type gets the score (usually the posterior)
class GetPosteriorVisitor:
public boost::static_visitor<double>
{
public:
double operator()(PeptideHit* pep) const
{
return pep->getScore();
}
double operator()(ProteinHit* prot) const
{
return prot->getScore();
}
double operator()(ProteinGroup& pg) const
{
return pg.score;
}
// Everything else, do nothing for now
template <class T>
double operator()(T& /*any node type*/) const
{
return -1.0;
}
};
/// @brief Visits nodes in the boost graph (either ptrs to an ID Object or some lightweight surrogates)
/// and depending on their type gets the score (usually the posterior) plus if it is a decoy or a target.
/// If not known or not defined, returns (-1.0, false)
class GetScoreTgTVisitor:
public boost::static_visitor<std::pair<double,bool>>
{
public:
std::pair<double,bool> operator()(PeptideHit* pep) const
{
return {pep->getScore(), pep->getMetaValue("target_decoy").toString()[0] == 't'};
}
std::pair<double,bool> operator()(ProteinHit* prot) const
{
return {prot->getScore(), prot->getMetaValue("target_decoy").toString()[0] == 't'};
}
std::pair<double,bool> operator()(ProteinGroup& pg) const
{
return {pg.score, pg.tgts > 0};
}
// Everything else, do nothing for now
template <class T>
std::pair<double,bool> operator()(T& /*any node type*/) const
{
return {-1.0, false};
}
};
/// Constructors
IDBoostGraph(ProteinIdentification& proteins,
PeptideIdentificationList& idedSpectra,
Size use_top_psms,
bool use_run_info,
bool best_psms_annotated,
const std::optional<const ExperimentalDesign>& ed = std::optional<const ExperimentalDesign>());
IDBoostGraph(ProteinIdentification& proteins,
ConsensusMap& cmap,
Size use_top_psms,
bool use_run_info,
bool use_unassigned_ids,
bool best_psms_annotated,
const std::optional<const ExperimentalDesign>& ed = std::optional<const ExperimentalDesign>());
//TODO think about templating to avoid wrapping to std::function
// although we usually do long-running tasks per CC such that the extra virtual call does not matter much
// Instead we gain type erasure.
/// Do sth on connected components (your functor object has to inherit from std::function or be a lambda)
void applyFunctorOnCCs(const std::function<unsigned long(Graph&, unsigned int)>& functor);
/// Do sth on connected components single threaded (your functor object has to inherit from std::function or be a lambda)
void applyFunctorOnCCsST(const std::function<void(Graph&)>& functor);
/// Add intermediate nodes to the graph that represent indist. protein groups and peptides with the same parents
/// this will save computation time and oscillations later on.
void clusterIndistProteinsAndPeptides();
//TODO create a new class for an extended Graph and try to reuse as much as possible
// use inheritance or templates
/// (under development) As above but adds charge, replicate and sequence layer of nodes (untested)
/// @todo needs to be finished, updated with latest additions (i.e. check clusterIndistProteinsAndPeptides), and tested
void clusterIndistProteinsAndPeptidesAndExtendGraph();
/// Annotate indistinguishable proteins by adding the groups to the underlying
/// ProteinIdentification::ProteinGroups object.
/// This has no effect on the graph itself.
/// @pre Graph must contain ProteinGroup nodes (e.g. with clusterIndistProteinsAndPeptides).
/// Otherwise it does nothing and you should use calculateAndAnnotateIndistProteins instead.
/// @param[in] addSingletons if you want to annotate groups with just one protein entry
void annotateIndistProteins(bool addSingletons = true);
/// Annotate indistinguishable proteins by adding the groups to the underlying
/// ProteinIdentification::ProteinGroups object. This has no effect on the graph itself.
/// @param[in] addSingletons if you want to annotate groups with just one protein entry
void calculateAndAnnotateIndistProteins(bool addSingletons = true);
/// Splits the initialized graph into connected components and clears it.
void computeConnectedComponents();
/// @todo untested
/// Removes all edges from a peptide (and its PSMs) to its parent protein groups (and its proteins)
/// except for the best protein group.
/// @pre Graph must contain PeptideCluster nodes (e.g. with clusterIndistProteinsAndPeptides).
/// @param[in] removeAssociationsInData Also removes the corresponding PeptideEvidences in the underlying
/// ID data structure. Only deactivate if you know what you are doing.
void resolveGraphPeptideCentric(bool removeAssociationsInData = true);
/// Zero means the graph was not split yet
Size getNrConnectedComponents();
/// @brief Returns a specific connected component of the graph as a graph itself
/// @param[in] cc the index of the component
/// @return the component as graph
const Graph& getComponent(Size cc);
/// @brief Returns the underlying protein identifications for viewing
/// @return const ref to the protein ID run in this graph (can only be one)
const ProteinIdentification& getProteinIDs();
//TODO docu
//void buildExtendedGraph(bool use_all_psms, std::pair<int,int> chargeRange, unsigned int nrReplicates);
/// @brief Prints a graph (component or if not split, the full graph) in graphviz (i.e. dot) format
/// @param[in] out an ostream to print to
/// @param[in] fg the graph to print
static void printGraph(std::ostream& out, const Graph& fg);
/// @brief Searches for all upstream nodes from a (set of) start nodes that are lower
/// or equal than a given level. The ordering is the same as in the IDPointer variant typedef.
/// @param[in] q a queue of start nodes
/// @param[in] graph the graph to look in (q has to be part of it)
/// @param[in] lvl the level to start reporting from
/// @param[in] stop_at_first do you want to stop at the first node <= lvl or also report its
/// upstream "predecessors"
/// @param[in] result vector of reported nodes
void getUpstreamNodesNonRecursive(std::queue<vertex_t>& q, const Graph& graph, int lvl,
bool stop_at_first, std::vector<vertex_t>& result);
/// @brief Searches for all downstream nodes from a (set of) start nodes that are higher
/// or equal than a given level. The ordering is the same as in the IDPointer variant typedef.
/// @param[in] q a queue of start nodes
/// @param[in] graph the graph to look in (q has to be part of it)
/// @param[in] lvl the level to start reporting from
/// @param[in] stop_at_first do you want to stop at the first node >= lvl or also report its
/// upstream "predecessors"
/// @param[in] result vector of reported nodes
void getDownstreamNodesNonRecursive(std::queue<vertex_t>& q, const Graph& graph, int lvl,
bool stop_at_first, std::vector<vertex_t>& result);
/// Gets the scores from the proteins included in the graph.
/// The difference to querying the underlying ProteinIdentification structure is that not all
/// proteins might be included in the graph due to using only the best psm per peptide
void getProteinScores_(ScoreToTgtDecLabelPairs& scores_and_tgt);
/// Gets the scores and target decoy fraction from groups and score + binary values for singleton
/// proteins. This function is usually used to create input for FDR calculations
void getProteinGroupScoresAndTgtFraction(ScoreToTgtDecLabelPairs& scores_and_tgt_fraction);
void getProteinGroupScoresAndHitchhikingTgtFraction(ScoreToTgtDecLabelPairs& scores_and_tgt_fraction);
private:
ProteinIdentification& protIDs_;
struct SequenceToReplicateChargeVariantHierarchy;
//TODO introduce class hierarchy:
/*
* IDGraph<UnderlyingIDStruc>
*
* - BasicGraph<>
* - ExtendedGraphClustered<>
* - ExtendedGraphClusteredWithRunInfo<>
*
* in theory extending a basic one is desirable to create the extended one. But it means we have to
* copy/move the graph (node by node) because the nodes are of a broader boost::variant type. So we probably have to
* duplicate code and offer a from-scratch step-wise building for the extended graph, too.
* Note that there could be several levels of extension in the future. For now I keep everything in one
* class by having potential storage for the broadest extended type. Differences in the underlying ID structure
* e.g. ConsensusMap or PeptideIDs from idXML currently only have an effect during building, so I just overload
* the constructors. In theory it would be nice to generalize on that, too, especially when we adapt to the new
* ID data structure.
*/
/* ---------------- Either of them is used, preferably second --------------- */
/// the initial boost Graph (will be cleared when split into CCs)
Graph g;
/// the Graph split into connected components
Graphs ccs_;
/* ---------------------------------------------------------------------------- */
#ifdef INFERENCE_BENCH
/// nrNodes, nrEdges, nrMessages and times of last functor execution per connected component
std::vector<std::tuple<vertex_t, vertex_t, unsigned long, double>> sizes_and_times_{1};
#endif
/* ---- Only used when run information was available --------- */
//TODO think about preallocating it, but the number of peptide hits is not easily computed
// since they are inside the pepIDs
//TODO would multiple sets be better?
/// if a graph is built with run information, this will store the run, each peptide hit
/// vertex belongs to. Important for extending the graph.
std::unordered_map<vertex_t, Size> pepHitVtx_to_run_;
/// this basically stores the number of different values in the pepHitVtx_to_run
/// a Prefractionation group (previously called run) is a unique combination
/// of all non-fractionation related entries in the exp. design
/// i.e. one (sub-)experiment before fractionation
Size nrPrefractionationGroups_ = 0;
/* ----------------------------------------------------------- */
/// helper function to add a vertex if it is not present yet, otherwise return the present one
/// needs a temporary filled vertex_map that is modifiable
vertex_t addVertexWithLookup_(const IDPointer& ptr, std::unordered_map<IDPointer, vertex_t, boost::hash<IDPointer>>& vertex_map);
//vertex_t addVertexWithLookup_(IDPointerConst& ptr, std::unordered_map<IDPointerConst, vertex_t, boost::hash<IDPointerConst>>& vertex_map);
/// internal function to annotate the underlying ID structures based on the given Graph
void annotateIndistProteins_(const Graph& fg, bool addSingletons);
void calculateAndAnnotateIndistProteins_(const Graph& fg, bool addSingletons);
/// Initialize and store the graph
/// IMPORTANT: Once the graph is built, editing members like (protein/peptide)_hits_ will invalidate it!
/// @param[in] proteins ProteinIdentification object storing IDs and groups
/// @param[in] idedSpectra vector of ProteinIdentifications with links to the proteins and PSMs in its PeptideHits
/// @param[in] use_top_psms Nr of top PSMs used per spectrum (<= 0 means all)
/// @param[in] best_psms_annotated Are the PSMs annotated with the "best_per_peptide" meta value. Otherwise all are
/// taken into account.
/// @todo we could include building the graph in important "main" functions like inferPosteriors
/// to make the methods safer, but it is also nice to be able to reuse the graph
void buildGraph_(ProteinIdentification& proteins,
PeptideIdentificationList& idedSpectra,
Size use_top_psms,
bool best_psms_annotated = false);
void buildGraph_(ProteinIdentification& proteins,
ConsensusMap& cmap,
Size use_top_psms,
bool use_unassigned_ids,
bool best_psms_annotated = false);
/// Used during building
void addPeptideIDWithAssociatedProteins_(
PeptideIdentification& spectrum,
std::unordered_map<IDPointer, vertex_t, boost::hash<IDPointer>>& vertex_map,
const std::unordered_map<std::string, ProteinHit*>& accession_map,
Size use_top_psms,
bool best_psms_annotated);
void addPeptideAndAssociatedProteinsWithRunInfo_(
PeptideIdentification& spectrum,
std::unordered_map<unsigned, unsigned>& indexToPrefractionationGroup,
std::unordered_map<IDPointer, vertex_t, boost::hash<IDPointer>>& vertex_map,
std::unordered_map<std::string, ProteinHit*>& accession_map,
Size use_top_psms
);
/// Initialize and store the graph. Also stores run information to later group
/// peptides more efficiently.
/// IMPORTANT: Once the graph is built, editing members like (protein/peptide)_hits_ will invalidate it!
///
/// @p use_top_psms is the number of top PSMs used per spectrum (<= 0 means all)
/// @todo we could include building the graph in important "main" functions like inferPosteriors
/// to make the methods safer, but it is also nice to be able to reuse the graph
void buildGraphWithRunInfo_(ProteinIdentification& proteins,
ConsensusMap& cmap,
Size use_top_psms,
bool use_unassigned_ids,
const ExperimentalDesign& ed);
void buildGraphWithRunInfo_(ProteinIdentification& proteins,
PeptideIdentificationList& idedSpectra,
Size use_top_psms,
const ExperimentalDesign& ed);
/// see equivalent public method
void resolveGraphPeptideCentric_(Graph& fg, bool removeAssociationsInData);
template<class NodeType>
void getDownstreamNodes(const vertex_t& start, const Graph& graph, std::vector<NodeType>& result)
{
Graph::adjacency_iterator adjIt, adjIt_end;
boost::tie(adjIt, adjIt_end) = boost::adjacent_vertices(start, graph);
for (;adjIt != adjIt_end; ++adjIt)
{
if (graph[*adjIt].type() == typeid(NodeType))
{
result.emplace_back(boost::get<NodeType>(graph[*adjIt]));
}
else if (graph[*adjIt].which() > graph[start].which())
{
getDownstreamNodes(*adjIt, graph, result);
}
}
}
template<class NodeType>
void getUpstreamNodes(const vertex_t& start, const Graph graph, std::vector<NodeType>& result)
{
Graph::adjacency_iterator adjIt, adjIt_end;
boost::tie(adjIt, adjIt_end) = boost::adjacent_vertices(start, graph);
for (;adjIt != adjIt_end; ++adjIt)
{
if (graph[*adjIt].type() == typeid(NodeType))
{
result.emplace_back(boost::get<NodeType>(graph[*adjIt]));
}
else if (graph[*adjIt].which() < graph[start].which())
{
getUpstreamNodes(*adjIt, graph, result);
}
}
}
};
bool operator==(const IDBoostGraph::ProteinGroup& lhs, const IDBoostGraph::ProteinGroup& rhs);
} //namespace Internal
} //namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/ID/MorpheusScore.h | .h | 2,050 | 56 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/CONCEPT/Types.h>
#include <OpenMS/CONCEPT/Macros.h>
#include <OpenMS/METADATA/DataArrays.h>
namespace OpenMS
{
/**
* @brief An implementation of the Morpheus PSM scoring function
* Inspired by a C# implementation by C. Wenger released under MIT license
*/
struct OPENMS_DLLAPI MorpheusScore
{
/// score and subscores
struct OPENMS_DLLAPI Result
{
Size matches = 0; ///< matched theoretical peaks
Size n_peaks = 0; ///< number of theoretical peaks
float score = 0; ///< Morpheus score (matched peaks + matched ion current / TIC)
float MIC = 0; ///< ion current of matches (experimental peaks)
float TIC = 0; ///< total ion current (experimental peak)
float err = 0; ///< average absolute mass error of matched fragments (in Da)
float err_ppm = 0; ///< average absolute mass error of matched fragments (in ppm)
};
/// returns Morpheus Score, \#matched ions, \#total ions, \#matched intensities, \#total fragment intensities (TIC)
static Result compute(double fragment_mass_tolerance,
bool fragment_mass_tolerance_unit_ppm,
const PeakSpectrum& exp_spectrum,
const PeakSpectrum& theo_spectrum);
/// same as above but matches are only counted if charges match
static Result compute(double fragment_mass_tolerance,
bool fragment_mass_tolerance_unit_ppm,
const PeakSpectrum& exp_spectrum,
const DataArrays::IntegerDataArray& exp_charges,
const PeakSpectrum& theo_spectrum,
const DataArrays::IntegerDataArray& theo_charges);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/ID/ConsensusIDAlgorithmAverage.h | .h | 1,289 | 43 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hendrik Weisser $
// $Authors: Andreas Bertsch, Marc Sturm, Sven Nahnsen, Hendrik Weisser $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/ANALYSIS/ID/ConsensusIDAlgorithmIdentity.h>
namespace OpenMS
{
/**
@brief Calculates a consensus from multiple ID runs by averaging the search scores.
@htmlinclude OpenMS_ConsensusIDAlgorithmAverage.parameters
@ingroup Analysis_ID
*/
class OPENMS_DLLAPI ConsensusIDAlgorithmAverage :
public ConsensusIDAlgorithmIdentity
{
public:
/// Default constructor
ConsensusIDAlgorithmAverage();
private:
/// Not implemented
ConsensusIDAlgorithmAverage(const ConsensusIDAlgorithmAverage&);
/// Not implemented
ConsensusIDAlgorithmAverage& operator=(const ConsensusIDAlgorithmAverage&);
/// Aggregate peptide scores into one final score (by averaging)
double getAggregateScore_(std::vector<double>& scores,
bool higher_better) override;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/ID/FIAMSScheduler.h | .h | 3,356 | 87 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Svetlana Kutuzova, Douglas McCloskey $
// $Authors: Svetlana Kutuzova, Douglas McCloskey $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/FORMAT/CsvFile.h>
#include <map>
namespace OpenMS
{
class MzMLFile;
/*
@brief Scheduler for FIA-MS data batches. Works with FIAMSDataProcessor.
The class is initialised with the path to the csv file that must contain the following columns:
- *filename* - the mzML filename for the sample. Must not contains the extension and path. The results filenames follow the pattern @filename_@n_seconds.
- *dir_input* - the location of the subdirectory (relative to the `base_dir`) with the mzML file
- *dir_output* - the location of the subdirectory (relative to the `output_dir`) where the results will be stored
- *resolution* - the resolution of the instrument
- *polarity* - the charge of the instrument, accepts "positive" or "negative"
- *db:mapping* - database input file in `base_dir` containing three tab-separated columns of mass, formula, identifier for the accurate mass search
- *db:struct* - database input file in `base_dir` containing four tab-separated columns of identifier, name, SMILES, INCHI for the accurate mass search
- *positive_adducts* - file in `base_dir` containing the list of potential positive adducts for the accurate mass search
- *negative_adducts* - file in `base_dir` containing the list of potential negative adducts for the accurate mass search
- *time* - ";"-separated numbers of seconds to process, f.e. "30;60;90;180"
*/
class OPENMS_DLLAPI FIAMSScheduler
{
public:
FIAMSScheduler() = default;
/// Default constructor
FIAMSScheduler(
String filename, ///< full path to the csv file
String base_dir = "/", ///< base directory, where subdirectories within the CSV are located; must include a trailing slash at the end of the directory
String output_dir = "/", ///< output dir for results; must include a trailing slash at the end of the directory
bool load_cached_ = true ///< load the cached results if they exist
);
/// Default destructor
~FIAMSScheduler() = default;
/// Copy constructor
FIAMSScheduler(const FIAMSScheduler& cp) = default;
/// Assignment
FIAMSScheduler& operator=(const FIAMSScheduler& fdp) = default;
/**
@brief Run the FIA-MS data analysis for the batch defined in the @p filename_
*/
void run();
/**
@brief Get the batch
*/
const std::vector<std::map<String, String>>& getSamples();
/**
@brief Get the base directory for the relevant paths from the csv file
*/
const String& getBaseDir();
/**
@brief Get the output directory for the results
*/
const String& getOutputDir();
private:
/**
@brief Load the batch from the csv file and store as the vector of maps
*/
void loadSamples_();
String filename_;
String base_dir_;
String output_dir_;
bool load_cached_;
std::vector<std::map<String, String>> samples_;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/ID/FIAMSDataProcessor.h | .h | 5,705 | 155 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Svetlana Kutuzova, Douglas McCloskey $
// $Authors: Svetlana Kutuzova, Douglas McCloskey $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/PROCESSING/SMOOTHING/SavitzkyGolayFilter.h>
#include <OpenMS/PROCESSING/CENTROIDING/PeakPickerHiRes.h>
#include <OpenMS/FORMAT/MzTab.h>
#include <OpenMS/FORMAT/MzTabM.h>
#include <OpenMS/FORMAT/MzTabFile.h>
namespace OpenMS
{
/**
@brief Data processing for FIA-MS data
Flow injection analysis (FIA) omits the separation step by removal of the column.
It allows for much faster processing time with the cost of ambiguities in the data
interpretation. The compounds are identified through the accurate mass search.
Flow injection analysis class implements the basic FIA-MS data processing steps such as:
acquiring the data for the certain time interval, summing along the time axis, smoothing
the peaks, peak picking and accurate mass search. The batch runs are to be managed with
the FIAMSSchedule class that takes a simple csv file as an input.
The workflow is inspired by the data processing from Fuhrer et al https://pubs.acs.org/doi/10.1021/ac201267k
though it is not the exact implementation.
*/
class OPENMS_DLLAPI FIAMSDataProcessor :
public DefaultParamHandler
{
public:
/// Constructor
FIAMSDataProcessor();
/// Default destructor
~FIAMSDataProcessor() override = default;
/// Copy constructor
FIAMSDataProcessor(const FIAMSDataProcessor& cp) = default;
/// Assignment
FIAMSDataProcessor& operator=(const FIAMSDataProcessor& fdp) = default;
/**
@brief Run the full analysis for the experiment for the given time interval
The workflow steps are:
- the time axis of the experiment is cut to the interval from 0 to n_seconds
- the spectra are summed into one along the time axis with the bin size determined by mz and instrument resolution
- data is smoothed by applying the Savitzky-Golay filter
- peaks are picked
- the accurate mass search for all the picked peaks is performed
The intermediate summed spectra and picked peaks can be saved to the filesystem.
Also, the results of the accurate mass search and the signal-to-noise information
of the resulting spectrum is saved.
@param[in] experiment Input MSExperiment
@param[in] n_seconds Input number of seconds
@param[in] load_cached_spectrum Load the cached picked spectrum if exists
@param[out] output Output of the accurate mass search results
@return a boolean indicating if the picked spectrum was loaded from the cached file
*/
bool run(const MSExperiment& experiment, const float n_seconds, OpenMS::MzTab& output, const bool load_cached_spectrum = true);
/**
@brief Cut the time axis of the experiment from 0 to @p n_seconds
@param[in] experiment Input MSExperiment
@param[in] n_seconds Input number of seconds
@param[out] output Spectra with retention time less than @p n_seconds
*/
void cutForTime(const MSExperiment& experiment, const float n_seconds, std::vector<MSSpectrum>& output);
/**
@brief Sum the spectra with different retention times into one.
The bin size for summing the intensities is defined as mz / (resolution*4)
for all the mzs taken with the @p bin_step defined in the parameters.
Uses `SpectrumAddition::addUpSpectra` function with the sliding bin size parameter.
@param[in] input Input vector of spectra
@return a spectrum
*/
MSSpectrum mergeAlongTime(const std::vector<OpenMS::MSSpectrum>& input);
/**
@brief Pick peaks from the summed spectrum
@param[in] input Input vector of spectra
@return a spectrum with picked peaks
*/
MSSpectrum extractPeaks(const MSSpectrum& input);
/**
@brief Convert a spectrum to a feature map with the corresponding polarity
Applies `SavitzkyGolayFilter` and `PeakPickerHiRes`
@param[in] input Input a picked spectrum
@return a feature map with the peaks converted to features and polarity from the parameters
*/
FeatureMap convertToFeatureMap(const MSSpectrum& input);
/**
@brief Estimate noise for each peak
Uses `SignalToNoiseEstimatorMedianRapid`
@param[in] input Input a picked spectrum
@return a spectrum object storing logSN information
*/
MSSpectrum trackNoise(const MSSpectrum& input);
/**
@brief Perform accurate mass search
Uses `AccurateMassSearchEngine`
@param[in,out] input Input a feature map
@param[out] output mzTab file with the accurate mass search results
*/
void runAccurateMassSearch(FeatureMap& input, OpenMS::MzTab& output);
/**
@brief Get mass-to-charge ratios to base the summing the spectra along the time axis upon
*/
const std::vector<float>& getMZs();
/**
@brief Get the sliding bin sizes for summing the spectra along the time axis
*/
const std::vector<float>& getBinSizes();
protected:
void updateMembers_() override;
private:
/**
@brief Store the spectrum to the given filepath
*/
void storeSpectrum_(const MSSpectrum& input, const String& filename);
std::vector<float> mzs_;
std::vector<float> bin_sizes_;
SavitzkyGolayFilter sgfilter_;
PeakPickerHiRes picker_;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/ID/ConsensusIDAlgorithmPEPIons.h | .h | 1,439 | 52 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hendrik Weisser $
// $Authors: Andreas Bertsch, Marc Sturm, Sven Nahnsen, Hendrik Weisser $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/ANALYSIS/ID/ConsensusIDAlgorithmSimilarity.h>
namespace OpenMS
{
/**
@brief Calculates a consensus from multiple ID runs based on PEPs and shared ions.
@htmlinclude OpenMS_ConsensusIDAlgorithmPEPIons.parameters
@ingroup Analysis_ID
*/
class OPENMS_DLLAPI ConsensusIDAlgorithmPEPIons :
public ConsensusIDAlgorithmSimilarity
{
public:
/// Default constructor
ConsensusIDAlgorithmPEPIons();
private:
/// Fragment mass tolerance (for "PEPIons_")
double mass_tolerance_;
/// Min. number of shared fragments (for "PEPIons")
Size min_shared_;
/// Not implemented
ConsensusIDAlgorithmPEPIons(const ConsensusIDAlgorithmPEPIons&);
/// Not implemented
ConsensusIDAlgorithmPEPIons& operator=(const ConsensusIDAlgorithmPEPIons&);
/// Docu in base class
void updateMembers_() override;
/// Sequence similarity based on matching ions
double getSimilarity_(AASequence seq1, AASequence seq2) override;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/ID/SiriusExportAlgorithm.h | .h | 3,469 | 80 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Oliver Alka, Axel Walter $
// $Authors: Oliver Alka, Lukas Zimmermann $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/ANALYSIS/MAPMATCHING/FeatureMapping.h>
#include <OpenMS/SYSTEM/File.h>
#include <QtCore/QStringList>
namespace OpenMS
{
class OPENMS_DLLAPI SiriusExportAlgorithm : public DefaultParamHandler
{
public:
/// default constructor
SiriusExportAlgorithm();
// accessor for preprocessing parameters
bool isFeatureOnly() const { return param_.getValue("feature_only").toBool(); }
UInt getFilterByNumMassTraces() const { return param_.getValue("filter_by_num_masstraces"); }
double getPrecursorMzTolerance() const { return param_.getValue("precursor_mz_tolerance"); }
double getPrecursorRtTolerance() const { return param_.getValue("precursor_rt_tolerance"); }
bool precursorMzToleranceUnitIsPPM() const { return param_.getValue("precursor_mz_tolerance_unit") == "ppm"; }
bool isNoMasstraceInfoIsotopePattern() const { return param_.getValue("no_masstrace_info_isotope_pattern").toBool(); }
int getIsotopePatternIterations() const { return param_.getValue("isotope_pattern_iterations"); }
/**
@brief Preprocessing needed for SIRIUS and AssayGeneratorMetabo
Filter number of masstraces and perform feature mapping.
@param[in] featureinfo Path to featureXML
@param[in] spectra Input of MSExperiment with spectra information
@param[out] feature_mapping_info Emtpy - stores FeatureMaps and KDTreeMaps internally
@param[in] feature_ms2_indices Empty FeatureToMs2Indices
*/
void preprocessing(const String& featureinfo,
const MSExperiment& spectra,
FeatureMapping::FeatureMappingInfo& feature_mapping_info,
FeatureMapping::FeatureToMs2Indices& feature_ms2_indices) const;
/**
@brief logs number of features and spectra used
Prints the number of features and spectra used (OPENMS_LOG_INFO)
@param[in] featureinfo Path to featureXML
@param[in] feature_ms2_indices FeatureToMs2Indices with feature mapping
@param[in] spectra Input of MSExperiment with spectra information
*/
void logFeatureSpectraNumber(const String& featureinfo,
const FeatureMapping::FeatureToMs2Indices& feature_ms2_indices,
const MSExperiment& spectra) const;
/**
@brief exports SIRIUS .ms file
Runs SiriusExport with mzML and featureXML (optional) files as input.
Generates a SIRIUS .ms file and compound info table (optional).
@param[in] mzML_files List with paths to mzML files
@param[in] featureXML_files List with paths to featureXML files
@param[out] out_ms Output file name for SIRIUS .ms file
@param[out] out_compoundinfo Output file name for tsv file with compound info
*/
void run(const StringList& mzML_files,
const StringList& featureXML_files,
const String& out_ms,
const String& out_compoundinfo) const;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/ID/IDRipper.h | .h | 8,328 | 178 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg$
// $Authors: Immanuel Luhn, Leon Kuchenbecker$
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <OpenMS/METADATA/ProteinIdentification.h>
#include <unordered_map>
namespace OpenMS
{
/**
@brief Ripping protein/peptide identification according their file origin.
Helper class, which is used by @ref TOPP_ProteinQuantifier. See there for further documentation.
@htmlinclude OpenMS_IDRipper.parameters
@ingroup Analysis_ID
*/
class OPENMS_DLLAPI IDRipper :
public DefaultParamHandler
{
public:
/// Possible input file encodings for the origin as used by different versions of IDMerger
enum OriginAnnotationFormat { FILE_ORIGIN = 0, MAP_INDEX = 1, ID_MERGE_INDEX = 2, UNKNOWN_OAF = 3, SIZE_OF_ORIGIN_ANNOTATION_FORMAT = 4 };
/// String representations for the OriginAnnotationFormat enum
static const std::array<std::string, SIZE_OF_ORIGIN_ANNOTATION_FORMAT> names_of_OriginAnnotationFormat;
/// Represents a set of IdentificationRuns
struct OPENMS_DLLAPI IdentificationRuns
{
/// Maps a unique index to every IdentificationRun string representation (getIdentifier()).
std::map<String, UInt> index_map;
/// Maps the list of spectra data elements to every IdentificationRun index.
std::vector<StringList> spectra_data;
/// Generates a new IdentificationRuns object from a vector of ProteinIdentification objects.
IdentificationRuns(const std::vector<ProteinIdentification>& prot_ids);
};
/// Identifies an IDRipper output file
struct OPENMS_DLLAPI RipFileIdentifier
{
/// The numerical index of the source IdentificationRun
UInt ident_run_idx{};
/// The numerical index of the source file_origin / spectra_data element
UInt file_origin_idx{};
/// The output basename derived from the file_origin / spectra_data element
String out_basename;
/// The full length origin read from the file_origin / spectra_data element
String origin_fullname;
/// Constructs a new RipFileIdentifier object
RipFileIdentifier(const IDRipper::IdentificationRuns& id_runs,
const PeptideIdentification& pep_id,
const std::map<String, UInt>& file_origin_map,
const IDRipper::OriginAnnotationFormat origin_annotation_fmt,
bool split_ident_runs);
/// Get identification run index
UInt getIdentRunIdx() const;
/// Get file origin index
UInt getFileOriginIdx() const;
/// Get origin full name
const String & getOriginFullname() const;
/// Get output base name
const String & getOutputBasename() const;
};
/// Provides a 'less' operation for RipFileIdentifiers that ignores the out_basename and origin_fullname members
struct RipFileIdentifierIdxComparator
{
bool operator()(const RipFileIdentifier& left, const RipFileIdentifier& right) const;
};
/// Represents the content of an IDRipper output file
struct OPENMS_DLLAPI RipFileContent
{
/// Protein identifications
std::vector<ProteinIdentification> prot_idents;
/// Peptide identifications
PeptideIdentificationList pep_idents;
/// Constructs a new RipFileContent object
RipFileContent(const std::vector<ProteinIdentification>& prot_idents, const PeptideIdentificationList& pep_idents)
: prot_idents(prot_idents), pep_idents(pep_idents) {}
/// Get protein identifications
const std::vector<ProteinIdentification> & getProteinIdentifications();
/// Get peptide identifications
const PeptideIdentificationList & getPeptideIdentifications();
};
/// Represents the result of an IDRipper process, a map assigning file content to output file identifiers
typedef std::map<RipFileIdentifier, RipFileContent, RipFileIdentifierIdxComparator> RipFileMap;
/// Default constructor
IDRipper();
/// Destructor
~IDRipper() override;
/**
@brief Ripping protein/peptide identification according their file origin
Iteration over all @p peptides. For each annotated file origin create a map entry and store the
respective @p peptides and @p proteins.
@param[in] ripped Contains the protein identification and peptide identification for each file origin annotated in proteins and peptides
@param[in] proteins Protein identification
@param[in] peptides Peptide identification annotated with file origin
@param[out] numeric_filenames If false, deduce output files using basenames of origin annotations. Throws an exception if they are not unique. If true, assemble output files based on numerical IDs only.
@param[in] split_ident_runs Split identification runs into different files.
*/
void rip(
RipFileMap& ripped,
std::vector<ProteinIdentification>& proteins,
PeptideIdentificationList& peptides,
bool numeric_filenames,
bool split_ident_runs);
/**
@brief Ripping protein/peptide identification according their file origin
Iteration over all @p peptides. For each annotated file origin create a map entry and store the
respective @p peptides and @p proteins.
@param[out] rfis File info relating to @p rfcs
@param[out] rfcs Contains the protein identification and peptide identification for each file origin annotated in proteins and peptides
@param[in] proteins Protein identification
@param[in] peptides Peptide identification annotated with file origin
@param[out] numeric_filenames If false, deduce output files using basenames of origin annotations. Throws an exception if they are not unique. If true, assemble output files based on numerical IDs only.
@param[in] split_ident_runs Split identification runs into different files.
*/
// Autowrap compatible wrapper for rip(RipFileMap,...)
void rip(
std::vector<RipFileIdentifier>& rfis,
std::vector<RipFileContent>& rfcs,
std::vector<ProteinIdentification>& proteins,
PeptideIdentificationList& peptides,
bool numeric_filenames,
bool split_ident_runs);
private:
// Not implemented
/// Copy constructor
IDRipper(const IDRipper & rhs);
// Not implemented
/// Assignment
IDRipper & operator=(const IDRipper & rhs);
/// helper function, detects file origin annotation standard from collections of protein and peptide hits
OriginAnnotationFormat detectOriginAnnotationFormat_(std::map<String, UInt> & file_origin_map, const PeptideIdentificationList & peptide_idents);
/// helper function, extracts all protein hits that match the protein accession
void getProteinHits_(std::vector<ProteinHit> & result, const std::unordered_map<String, const ProteinHit*> & acc2protein_hits, const std::set<String> & protein_accessions);
/// helper function, returns the string representation of the peptide hit accession
std::set<String> getProteinAccessions_(const std::vector<PeptideHit> & peptide_hits);
/// helper function, returns the index of the protein identification for the given peptide identification based on the same identifier using id_runs as lookup
int getProteinIdentification_(const PeptideIdentification& pep_ident, const IdentificationRuns& id_runs);
/// helper function, register a potential output file basename to detect duplicate output basenames
bool registerBasename_(std::map<String, std::pair<UInt, UInt> >& basename_to_numeric, const IDRipper::RipFileIdentifier& rfi);
/// helper function, sets the value of mode to new_value and returns true if the old value was identical or unset (-1)
bool setOriginAnnotationMode_(short& mode, short const new_value);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/ID/ConsensusIDAlgorithmIdentity.h | .h | 2,497 | 71 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hendrik Weisser $
// $Authors: Andreas Bertsch, Marc Sturm, Sven Nahnsen, Hendrik Weisser $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/ANALYSIS/ID/ConsensusIDAlgorithm.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
namespace OpenMS
{
/**
@brief Abstract base class for ConsensusID algorithms that compare only identical sequences.
Search engine scores are grouped by peptide sequence in apply_(). For each sequence, getAggregateScore_() is called to produce a consensus score from the list of search engine scores.
All derived classes should implement getAggregateScore_(). They may re-implement preprocess_() if required.
@htmlinclude OpenMS_ConsensusIDAlgorithmIdentity.parameters
@ingroup Analysis_ID
*/
class OPENMS_DLLAPI ConsensusIDAlgorithmIdentity :
public ConsensusIDAlgorithm
{
protected:
/// Default constructor
ConsensusIDAlgorithmIdentity();
/**
@brief Preprocessing of peptide IDs (in the beginning of "apply_").
Checks whether the score types are the same (warns if not) and whether the score orientations agree (error if not).
@param[in,out] ids Input/output peptide identifications
@throw Exception::InvalidValue Score orientations do not agree
*/
virtual void preprocess_(PeptideIdentificationList& ids);
/**
@brief Aggregate peptide scores into one final score (to be implemented by subclasses).
@param[in,out] scores List of scores for the same peptide by different search engines
@param[in] higher_better Whether higher or lower scores are better
@return Final score for the respective peptide
*/
virtual double getAggregateScore_(std::vector<double>& scores,
bool higher_better) = 0;
private:
/// Not implemented
ConsensusIDAlgorithmIdentity(const ConsensusIDAlgorithmIdentity&);
/// Not implemented
ConsensusIDAlgorithmIdentity& operator=(const ConsensusIDAlgorithmIdentity&);
/// Consensus scoring
void apply_(PeptideIdentificationList& ids,
const std::map<String, String>& se_info,
SequenceGrouping& results) override;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/ID/PScore.h | .h | 5,124 | 100 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/CONCEPT/Types.h>
#include <vector>
#include <map>
namespace OpenMS
{
/**
@brief Implementation of the PScore PSM scoring algorithm
*/
struct OPENMS_DLLAPI PScore
{
/** @brief calculate local (windowed) peak ranks.
The peak rank is defined as the number of neighboring peaks in +/- (mz_window/2) that have higher intensity
The result can be used to efficiently filter spectra for top 1..n peaks in mass windows
@note ranks are zero based (highest intensity peak in window has rank 0)
@param[in] mz m/z positions of the peaks
@param[in] intensities of the peaks
@param[in] mz_window window in Thomson centered at each peak
*/
static std::vector<Size> calculateIntensityRankInMZWindow(const std::vector<double>& mz, const std::vector<double>& intensities, double mz_window);
/** @brief precalculated, windowed peak ranks for a whole experiment.
The peak rank is defined as the number of neighboring peaks in +/- (mz_window/2) that have higher intensity
-# Each spectrum is subdivided into windows of size \p mz_window.
-# For each window, peak ranks are assigned using calculateIntensityRankInMZWindow().
-# A rank map is returned
@note ranks are zero based (top element has rank 0)
@param[in] peak_map Fragment spectra used for rank calculation. Typically a peak map after removal of all MS1 spectra.
@param[in] mz_window window in Thomson centered at each peak
*/
static std::vector<std::vector<Size> > calculateRankMap(const PeakMap& peak_map, double mz_window = 100);
/** @brief Calculates spectra for peak level between min_level to max_level and stores them in the map
A spectrum of peak level n retains the (n+1) top intensity peaks in a sliding mz_window centered at each peak.
@note levels are zero based (level 0 has only the top intensity peaks for each window, level 1 the top and second most intensive one)
@note min and max level are taken from the Andromeda publication but are similar to the AScore publication
*/
static std::map<Size, PeakSpectrum > calculatePeakLevelSpectra(const PeakSpectrum& spec, const std::vector<Size>& ranks, Size min_level = 1, Size max_level = 9);
/** @brief Computes the PScore for a vector of theoretical spectra
Similar to Andromeda, a vector of theoretical spectra can be provided that e.g. contain loss spectra or higher charge spectra depending on the sequence.
The best score obtained by scoring all those theoretical spectra against the experimental ones is returned.
@param[in] fragment_mass_tolerance mass tolerance for matching peaks
@param[in] fragment_mass_tolerance_unit_ppm whether Thomson or ppm is used
@param[in] peak_level_spectra spectra for different peak levels (=filtered by maximum rank).
@param[in] theo_spectra theoretical spectra as obtained e.g. from TheoreticalSpectrumGenerator
@param[in] mz_window window in Thomson centered at each peak
*/
static double computePScore(double fragment_mass_tolerance, bool fragment_mass_tolerance_unit_ppm, const std::map<Size, PeakSpectrum>& peak_level_spectra, const std::vector<PeakSpectrum>& theo_spectra, double mz_window = 100.0);
/** @brief Computes the PScore for a single theoretical spectrum
@param[in] fragment_mass_tolerance mass tolerance for matching peaks
@param[in] fragment_mass_tolerance_unit_ppm whether Thomson or ppm is used
@param[in] peak_level_spectra spectra for different peak levels (=filtered by maximum rank).
@param[in] theo_spectrum Theoretical spectrum as obtained e.g. from TheoreticalSpectrumGenerator
@param[in] mz_window window in Thomson centered at each peak
*/
static double computePScore(double fragment_mass_tolerance, bool fragment_mass_tolerance_unit_ppm, const std::map<Size, PeakSpectrum>& peak_level_spectra, const PeakSpectrum& theo_spectrum, double mz_window = 100.0);
/// additive correction terms used by Andromeda (pscore + massC + cleaveC + modC - 100). For reference see the Andromeda source code.
/// @note constants used in the correction term might be instrument dependent
static double massCorrectionTerm(double mass);
/// correction term for type of cleavage. For reference see the Andromeda source code.
/// @note constants used in the correction term might be instrument dependent
static double cleavageCorrectionTerm(Size cleavages, bool consecutive_cleavage);
/// correction term for modification. For reference see the Andromeda source code.
/// @note constants used in the correction term might be instrument dependent
static double modificationCorrectionTerm(Size modifications);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/ID/ConsensusIDAlgorithmWorst.h | .h | 1,314 | 43 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hendrik Weisser $
// $Authors: Andreas Bertsch, Marc Sturm, Sven Nahnsen, Hendrik Weisser $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/ANALYSIS/ID/ConsensusIDAlgorithmIdentity.h>
namespace OpenMS
{
/**
@brief Calculates a consensus from multiple ID runs by taking the worst search score (conservative approach).
@htmlinclude OpenMS_ConsensusIDAlgorithmWorst.parameters
@ingroup Analysis_ID
*/
class OPENMS_DLLAPI ConsensusIDAlgorithmWorst :
public ConsensusIDAlgorithmIdentity
{
public:
/// Default constructor
ConsensusIDAlgorithmWorst();
private:
/// Not implemented
ConsensusIDAlgorithmWorst(const ConsensusIDAlgorithmWorst&);
/// Not implemented
ConsensusIDAlgorithmWorst& operator=(const ConsensusIDAlgorithmWorst&);
/// Aggregate peptide scores into one final score (by taking the worst score)
double getAggregateScore_(std::vector<double>& scores,
bool higher_better) override;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/ID/MetaboliteSpectralMatching.h | .h | 5,042 | 186 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Erhan Kenar $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/MassTrace.h>
#include <OpenMS/KERNEL/Feature.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/FORMAT/MzTab.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/KERNEL/MSSpectrum.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <vector>
namespace OpenMS
{
struct OPENMS_DLLAPI PrecursorMassComparator
{
bool operator() (const MSSpectrum& a, const MSSpectrum& b)
{
return a.getPrecursors()[0].getMZ() < b.getPrecursors()[0].getMZ();
}
} PrecursorMZLess;
class OPENMS_DLLAPI SpectralMatch
{
public:
/// Default constructor
SpectralMatch();
/// Default destructor
~SpectralMatch();
/// Copy constructor
SpectralMatch(const SpectralMatch&);
/// Assignment operator
SpectralMatch& operator=(const SpectralMatch&);
double getObservedPrecursorMass() const;
void setObservedPrecursorMass(const double&);
double getObservedPrecursorRT() const;
void setObservedPrecursorRT(const double&);
double getFoundPrecursorMass() const;
void setFoundPrecursorMass(const double&);
Int getFoundPrecursorCharge() const;
void setFoundPrecursorCharge(const Int&);
double getMatchingScore() const;
void setMatchingScore(const double&);
Size getObservedSpectrumIndex() const;
void setObservedSpectrumIndex(const Size&);
Size getMatchingSpectrumIndex() const;
void setMatchingSpectrumIndex(const Size&);
String getObservedSpectrumNativeID() const;
void setObservedSpectrumNativeID(const String&);
String getPrimaryIdentifier() const;
void setPrimaryIdentifier(const String&);
String getSecondaryIdentifier() const;
void setSecondaryIdentifier(const String&);
String getCommonName() const;
void setCommonName(const String&);
String getSumFormula() const;
void setSumFormula(const String&);
String getInchiString() const;
void setInchiString(const String&);
String getSMILESString() const;
void setSMILESString(const String&);
String getPrecursorAdduct() const;
void setPrecursorAdduct(const String&);
private:
double observed_precursor_mass_;
double observed_precursor_rt_;
double found_precursor_mass_;
Int found_precursor_charge_;
double matching_score_;
Size observed_spectrum_idx_;
Size matching_spectrum_idx_;
String observed_spectrum_native_id_;
// further meta information
String primary_id_;
String secondary_id_;
String common_name_;
String sum_formula_;
String inchi_string_;
String smiles_string_;
String precursor_adduct_;
};
struct OPENMS_DLLAPI SpectralMatchScoreComparator
{
bool operator() (const SpectralMatch& a, const SpectralMatch& b)
{
return a.getMatchingScore() > b.getMatchingScore();
}
} SpectralMatchScoreGreater;
class OPENMS_DLLAPI MetaboliteSpectralMatching :
public DefaultParamHandler,
public ProgressLogger
{
public:
/// Default constructor
MetaboliteSpectralMatching();
/// Default destructor
~MetaboliteSpectralMatching() override;
/// hyperscore computation
static double computeHyperScore(
double fragment_mass_error,
bool fragment_mass_tolerance_unit_ppm,
const MSSpectrum& exp_spectrum,
const MSSpectrum& db_spectrum,
double mz_lower_bound = 0.0);
/// hyperscore computation (with output of peak annotations)
static double computeHyperScore(
double fragment_mass_error,
bool fragment_mass_tolerance_unit_ppm,
const MSSpectrum& exp_spectrum,
const MSSpectrum& db_spectrum,
std::vector<PeptideHit::PeakAnnotation>& annotations,
double mz_lower_bound = 0.0);
/// main method of MetaboliteSpectralMatching
void run(PeakMap &, PeakMap &, MzTab &, String &);
protected:
void updateMembers_() override;
// we have to use a pointer for "annotations" because mutable
// references can't have temporary default values:
static double computeHyperScore_(
double fragment_mass_error,
bool fragment_mass_tolerance_unit_ppm,
const MSSpectrum& exp_spectrum,
const MSSpectrum& db_spectrum,
std::vector<PeptideHit::PeakAnnotation>* annotations = 0,
double mz_lower_bound = 0.0);
private:
/// private member functions
void exportMzTab_(const std::vector<SpectralMatch>&, MzTab&);
double precursor_mz_error_;
double fragment_mz_error_;
String mz_error_unit_;
String ion_mode_;
String report_mode_;
bool merge_spectra_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/ID/ConsensusMapMergerAlgorithm.h | .h | 4,905 | 91 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Julianus Pfeuffer $
// $Authors: Julianus Pfeuffer $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/KERNEL/ConsensusMap.h>
#include <OpenMS/METADATA/ExperimentalDesign.h>
#include <unordered_set>
namespace OpenMS
{
/**
* @brief Merges identification data in ConsensusMaps
* @todo This could be merged in the future with the general IDMergerAlgorithm since it shares a lot.
* IDMergerAlgorithm needs additional methods to have multiple runs as output. It also needs to store
* an extended mapping internally to distribute the PeptideIDs to the right output run according to origin and
* label.
* And should have non-copying/moving
* overloads for inserting PeptideIDs since we probably do not want to distribute the PeptideIDs to the features
* again. In general detaching IDs from features would be of great help here.
* @todo Untested for TMT/iTraq data where you usually have one Identification run per File but in one File you
* might have multiple conditions multiplexed, that you might want to split for inference. Problem:
* There is only one PeptideIdentification object per Feature that is representative for all "sub maps" (in this
* case the labels/reporter ions). -> A lookup is necessary if the reporter ion had non-zero intensity and if
* so, the peptide ID needs to be duplicated for every new (condition-based) IdentificationRun it is supposed
* to be used in, according to the mapping.
*/
class OPENMS_DLLAPI ConsensusMapMergerAlgorithm:
public DefaultParamHandler,
public ProgressLogger
{
public:
ConsensusMapMergerAlgorithm ();
/// Takes a ConsensusMap (with usually one IdentificationRun per column [= sub map]
/// and merges them to one IdentificationRun per Condition (unique entries in Sample section when removing
/// replicate columns) while reassociating the PeptideHits accordingly.
/// It just does not make sense to have every protein duplicated.
/// And IdentificationRuns are used to guide inference methods on what identifications to perform inference on
/// @note Constructs the mapping based on the exp. design and then uses mergeProteinIDRuns
/// @note Groups are not carried over during merging.
/// @throws MissingInformationException for e.g. missing map_indices in PeptideIDs
void mergeProteinsAcrossFractionsAndReplicates(ConsensusMap& cmap, const ExperimentalDesign& exp_design) const;
/// Similar to above, merges every ID Run into one big run. Proteins get only inserted once but Peptides stay unfiltered
/// i.e. might occur in several PeptideIdentifications afterwards
/// @note Groups are not carried over during merging.
/// @throws MissingInformationException for e.g. missing map_indices in PeptideIDs
void mergeAllIDRuns(ConsensusMap& cmap) const;
/// Takes a ConsensusMap and a mapping between ConsensusMap column index (sub map index in the map_index meta value)
/// and the new ProteinIdentification run index and merges them based on this.
/// @throws MissingInformationException for e.g. missing map_indices in PeptideIDs
/// @todo Do we need to consider the old IDRun identifier in addition to the sub map index
void mergeProteinIDRuns(ConsensusMap &cmap,
const std::map<unsigned, unsigned>& mapIdx_to_new_protIDRun) const;
private:
/// Checks consistency of search engines and settings across runs before merging.
/// Uses the first run as reference and compares all to it.
/// @return all same? TODO: return a merged RunDescription about what to put in the new runs (e.g. for SILAC)
/// @throws BaseException for disagreeing settings
bool checkOldRunConsistency_(const std::vector<ProteinIdentification>& protRuns, const String& experiment_type) const;
/// Same as above but with specific reference run
bool checkOldRunConsistency_(const std::vector<ProteinIdentification>& protRuns, const ProteinIdentification& ref, const String& experiment_type) const;
static size_t accessionHash_(const ProteinHit& p)
{
return std::hash<String>()(p.getAccession());
}
static bool accessionEqual_(const ProteinHit& p1, const ProteinHit& p2)
{
return p1.getAccession() == p2.getAccession();
}
using hash_type = std::size_t (*)(const ProteinHit&);
using equal_type = bool (*)(const ProteinHit&, const ProteinHit&);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/ID/IDMapper.h | .h | 11,536 | 253 | // 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, Hendrik Weisser, Chris Bielow $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/KERNEL/ConsensusMap.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <algorithm>
#include <limits>
namespace OpenMS
{
class AnnotatedMSRun;
/**
@brief Annotates an MSExperiment, FeatureMap or ConsensusMap with peptide identifications
ProteinIdentifications are assigned to the whole map.
The retention time and mass-to-charge ratio of the PeptideIdentification as the respective "MZ" and "RT" members.
m/z-matching on peptide side can be done either with the precursor m/z value of the peptide identification or with the theoretical masses of the peptide hits (see "mz_reference" parameter).
See the documentation of the individual @p annotate methods for more in-depth information.
@htmlinclude OpenMS_IDMapper.parameters
*/
class OPENMS_DLLAPI IDMapper :
public DefaultParamHandler
{
public:
enum Measure {MEASURE_PPM = 0, MEASURE_DA};
/// Default constructor
IDMapper();
/// Copy C'Tor
IDMapper(const IDMapper& cp);
/// Assignment
IDMapper& operator=(const IDMapper& rhs);
/**
@brief Mapping method for peak maps
The identifications stored in a PeptideIdentification instance can be added to the
corresponding spectrum.
Note that a PeptideIdentication is added to ALL spectra which are within the allowed RT and MZ boundaries.
@param[in,out] map MSExperiment to receive the identifications
@param[in] peptide_ids PeptideIdentification for the MSExperiment
@param[in] protein_ids ProteinIdentification for the MSExperiment
@param[in] clear_ids Reset peptide and protein identifications of each scan before annotating
@param[in] map_ms1 Attach Ids to MS1 spectra using RT mapping only (without precursor, without m/z)
@exception Exception::MissingInformation is thrown if entries of @p peptide_ids do not contain 'MZ' and 'RT' information.
*/
void annotate(AnnotatedMSRun& map, const PeptideIdentificationList& peptide_ids, const std::vector<ProteinIdentification>& protein_ids, const bool clear_ids = false, const bool map_ms1 = false);
/**
@brief Mapping method for peak maps
Add peptide identifications stored in a feature map to their
corresponding spectrum.
This function converts the feature map to a vector of peptide identifications (all peptide IDs from each feature are taken)
and calls the respective annotate() function.
RT and m/z are taken from the peptides, or (if missing) from the feature itself.
@param[in,out] map MSExperiment to receive the identifications
@param[in] fmap FeatureMap with PeptideIdentifications for the MSExperiment
@param[in] clear_ids Reset peptide and protein identifications of each scan before annotating
@param[in] map_ms1 attach Ids to MS1 spectra using RT mapping only (without precursor, without m/z)
*/
void annotate(AnnotatedMSRun& map, const FeatureMap& fmap, const bool clear_ids = false, const bool map_ms1 = false);
/**
@brief Mapping method for feature maps
If @em all features have at least one convex hull, peptide positions are matched against the bounding boxes of the convex hulls by default. If not, the positions of the feature centroids are used. The respective coordinates of the centroids are also used for matching (in place of the corresponding ranges from the bounding boxes) if @p use_centroid_rt or @p use_centroid_mz are true.
In any case, tolerance in RT and m/z dimension is applied according to the global parameters @p rt_tolerance and @p mz_tolerance. Tolerance is understood as "plus or minus x", so the matching range is actually increased by twice the tolerance value.
If several features (incl. tolerance) overlap the position of a peptide identification, the identification is annotated to all of them.
@param[in,out] map FeatureMap to receive the identifications
@param[in] ids PeptideIdentification for the ConsensusFeatures
@param[in] protein_ids ProteinIdentification for the ConsensusMap
@param[in] use_centroid_rt Whether to use the RT value of feature centroids even if convex hulls are present
@param[in] use_centroid_mz Whether to use the m/z value of feature centroids even if convex hulls are present
@param[in] spectra [Optional] Provide the underlying mass spectra, which allows adding an empty PeptideIdentification object containing the MS2 scan index
to each Feature that covers an MS/MS spectrum (irrespective if it already has an ID).
@exception Exception::MissingInformation is thrown if entries of @p ids do not contain 'MZ' and 'RT' information.
*/
void annotate(FeatureMap& map, const PeptideIdentificationList& ids, const std::vector<ProteinIdentification>& protein_ids, bool use_centroid_rt = false, bool use_centroid_mz = false, const PeakMap& spectra = PeakMap());
/**
@brief Mapping method for consensus maps
If several consensus features lie inside the allowed deviation, the peptide identifications
are mapped to all the consensus features.
@param[in,out] map ConsensusMap to receive the identifications
@param[in] ids PeptideIdentification for the ConsensusFeatures
@param[in] protein_ids ProteinIdentification for the ConsensusMap
@param[in] measure_from_subelements Do distance estimate from FeatureHandles instead of Centroid
@param[in] annotate_ids_with_subelements Store map index of FeatureHandle in peptide identification?
@param[in] spectra [Optional] Provide the underlying mass spectra, which allows adding an empty PeptideIdentification object containing the MS2 scan index
to each ConsensusFeature that covers an MS/MS spectrum (irrespective if it already has an ID).
@exception Exception::MissingInformation is thrown if the MetaInfoInterface of @p ids does not contain 'MZ' and 'RT'
*/
void annotate(ConsensusMap& map, const PeptideIdentificationList& ids,
const std::vector<ProteinIdentification>& protein_ids,
bool measure_from_subelements = false,
bool annotate_ids_with_subelements = false,
const PeakMap& spectra = PeakMap());
/**
@brief Result of a partitioning by identification state with mapPrecursorsToIdentifications().
*/
struct PeptideIdentificationListState
{
std::vector<Size> no_precursors;
std::vector<Size> identified;
std::vector<Size> unidentified;
};
/**
@brief Mapping of peptide identifications to spectra
This helper function partitions all spectra into those that had:
- no precursor (e.g. MS1 spectra),
- at least one identified precursor,
- or only unidentified precursor.
@param[in] spectra The mass spectra
@param[in] ids The peptide identifications
@param[in] mz_tol Tolerance used to map to precursor m/z
@param[in] rt_tol Tolerance used to map to spectrum retention time
Note: mz/tol and rt_tol should, in principle, be zero (or close to zero under numeric inaccuracies).
@return A struct of vectors holding spectra indices of the partitioning.
*/
static PeptideIdentificationListState mapPrecursorsToIdentifications(const PeakMap& spectra,
const PeptideIdentificationList& ids,
double mz_tol = 0.001,
double rt_tol = 0.001)
{
PeptideIdentificationListState ret;
for (Size spectrum_index = 0; spectrum_index < spectra.size(); ++spectrum_index)
{
const MSSpectrum& spectrum = spectra[spectrum_index];
if (!spectrum.getPrecursors().empty())
{
bool identified(false);
const std::vector<Precursor>& precursors = spectrum.getPrecursors();
// check if precursor has been identified
for (Size i_p = 0; i_p < precursors.size(); ++i_p)
{
// check by precursor mass and spectrum RT
double mz_p = precursors[i_p].getMZ();
double rt_s = spectrum.getRT();
for (Size i_id = 0; i_id != ids.size(); ++i_id)
{
const PeptideIdentification& pid = ids[i_id];
// do not count empty ids as identification of a spectrum
if (pid.getHits().empty()) continue;
double mz_id = pid.getMZ();
double rt_id = pid.getRT();
if ( fabs(mz_id - mz_p) < mz_tol && fabs(rt_s - rt_id) < rt_tol )
{
identified = true;
break;
}
}
}
if (!identified)
{
ret.unidentified.push_back(spectrum_index);
}
else
{
ret.identified.push_back(spectrum_index);
}
}
else
{
ret.no_precursors.push_back(spectrum_index);
}
}
return ret;
}
protected:
void updateMembers_() override;
/// Allowed RT deviation
double rt_tolerance_;
/// Allowed m/z deviation
double mz_tolerance_;
/// Measure used for m/z
Measure measure_;
/// Ignore charge states during matching?
bool ignore_charge_;
/// compute absolute Da tolerance, for a given m/z,
/// when @p measure is MEASURE_DA, the value is unchanged,
/// for MEASURE_PPM it is computed according to currently allowed ppm tolerance
double getAbsoluteMZTolerance_(const double mz) const;
/// check if distance constraint is fulfilled (using @p rt_tolerance_, @p mz_tolerance_ and @p measure_)
bool isMatch_(const double rt_distance, const double mz_theoretical, const double mz_observed) const;
/// helper function that checks if all peptide hits are annotated with RT and MZ meta values
void checkHits_(const PeptideIdentificationList& ids) const;
/// get RT, m/z and charge value(s) of a PeptideIdentification
/// - multiple m/z values are returned if "mz_reference" is set to "peptide" (one for each PeptideHit)
/// - one m/z value is returned if "mz_reference" is set to "precursor"
void getIDDetails_(const PeptideIdentification& id, double& rt_pep, DoubleList& mz_values, IntList& charges, bool use_avg_mass = false) const;
/// increase a bounding box by the given RT and m/z tolerances
void increaseBoundingBox_(DBoundingBox<2>& box);
/// try to determine the type of m/z value reported for features, return
/// whether average peptide masses should be used for matching
bool checkMassType_(const std::vector<DataProcessing>& processing) const;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/ID/OpenSearchModificationAnalysis.h | .h | 6,098 | 138 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <map>
#include <vector>
#include <unordered_map>
#include <unordered_set>
namespace OpenMS
{
/**
* @brief Utility class for analyzing modification patterns in open search results
*
* This class provides functionality to analyze delta mass patterns from open search
* peptide identifications, identify common modifications, and map them to known
* modifications from the ModificationsDB. Originally extracted from SageAdapter.
*/
class OPENMS_DLLAPI OpenSearchModificationAnalysis
{
public:
/// Stores details of a modification pattern found in the data
struct ModificationPattern
{
double count = 0.0; ///< Number of peptides with this modification
std::vector<double> masses; ///< Masses associated with the modification
int num_charge_states = 0; ///< Number of different charge states observed
};
/// Data structure for modification summary output
struct ModificationSummary
{
int count; ///< Modification rate (number of occurrences)
String name; ///< Modification name
int num_charge_states; ///< Number of charge states
std::vector<double> masses; ///< Masses associated with the modification
};
/// Comparator for approximate comparison of double values
struct FuzzyDoubleComparator
{
double epsilon;
FuzzyDoubleComparator(double eps = 1e-9) : epsilon(eps) {}
bool operator()(const double& a, const double& b) const
{
return std::fabs(a - b) >= epsilon && a < b;
}
};
/// Type definitions for delta mass analysis
using DeltaMassHistogram = std::map<double, double, FuzzyDoubleComparator>;
using DeltaMassToChargeCount = std::map<double, int, FuzzyDoubleComparator>;
/// Default constructor
OpenSearchModificationAnalysis() = default;
/// Destructor
~OpenSearchModificationAnalysis() = default;
/**
* @brief Analyze delta mass patterns from peptide identifications
*
* @param[in,out] peptide_ids List of peptide identifications containing delta mass information
* @param[in] use_smoothing Whether to apply smoothing to the delta mass histogram
* @param[out] debug Enable debug output
* @return Pair containing delta mass histogram and charge state counts
*/
std::pair<DeltaMassHistogram, DeltaMassToChargeCount>
analyzeDeltaMassPatterns(const PeptideIdentificationList& peptide_ids,
bool use_smoothing = false,
bool debug = false) const;
/**
* @brief Map delta masses to known modifications and annotate peptides
*
* @param[in] delta_mass_histogram Histogram of delta masses
* @param[in] charge_histogram Charge state counts for each delta mass
* @param[in,out] peptide_ids List of peptide identifications to annotate (modified in-place)
* @param[in] precursor_mass_tolerance Mass tolerance for mapping
* @param[in] precursor_mass_tolerance_unit_ppm Whether tolerance is in ppm (true) or Da (false)
* @param[in] output_file Optional file path for writing modification summary table
* @return List of modification summaries found
*/
std::vector<ModificationSummary>
mapDeltaMassesToModifications(const DeltaMassHistogram& delta_mass_histogram,
const DeltaMassToChargeCount& charge_histogram,
PeptideIdentificationList& peptide_ids,
double precursor_mass_tolerance = 5.0,
bool precursor_mass_tolerance_unit_ppm = true,
const String& output_file = "") const;
/**
* @brief Complete analysis workflow: analyze patterns and map to modifications
*
* @param[in] peptide_ids List of peptide identifications (modified in-place)
* @param[in] precursor_mass_tolerance Mass tolerance for mapping
* @param[in] precursor_mass_tolerance_unit_ppm Whether tolerance is in ppm (true) or Da (false)
* @param[in] use_smoothing Whether to apply smoothing to delta mass histogram
* @param[in] output_file Optional file path for writing modification summary table
* @return List of modification summaries found
*/
std::vector<ModificationSummary>
analyzeModifications(PeptideIdentificationList& peptide_ids,
double precursor_mass_tolerance = 5.0,
bool precursor_mass_tolerance_unit_ppm = true,
bool use_smoothing = false,
const String& output_file = "") const;
private:
/// Gaussian function for smoothing
static double gaussian_(double x, double sigma);
/// Smooth delta mass histogram using Gaussian kernel density estimation
static DeltaMassHistogram smoothDeltaMassHistogram_(const DeltaMassHistogram& histogram,
double sigma = 0.001);
/// Find peaks in delta mass histogram based on count threshold and signal-to-noise ratio
static DeltaMassHistogram findPeaksInHistogram_(const DeltaMassHistogram& histogram,
double count_threshold = 0.0,
double snr = 2.0);
/// Write modification summary table to file
void writeModificationSummary_(const std::vector<ModificationSummary>& modifications,
const String& output_file) const;
};
} // namespace OpenMS | Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/ID/AScore.h | .h | 7,723 | 181 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Petra Gutenbrunner $
// $Authors: David Wojnar, Timo Sachsenberg, Petra Gutenbrunner $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CONCEPT/Types.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/KERNEL/MSSpectrum.h>
#include <OpenMS/ANALYSIS/ID/PScore.h>
#include <limits>
#include <vector>
namespace OpenMS
{
class PeptideHit;
class AASequence;
class ProbablePhosphoSites
{
public:
Size first;
Size second;
Size seq_1; ///< index of best permutation with site in phosphorylated state
Size seq_2; ///< index of permutation with site in unphosphorylated state
Size peak_depth; ///< filtering level that gave rise to maximum discriminatory score
Size AScore;
};
/**
@brief Implementation of the Ascore
For a given peptide sequence and its MS/MS spectrum it identifies the most probable phosphorylation-site(s).
For each phosphorylation site a probability score is calculated.
The algorithm is implemented according to Beausoleil et al. (Nat. Biotechnol. 2006).
@htmlinclude OpenMS_AScore.parameters
*/
class OPENMS_DLLAPI AScore: public DefaultParamHandler
{
friend struct PScore;
public:
///Default constructor
AScore();
///Destructor
~AScore() override;
/**
@brief Computes the AScore and returns all computed phospho-sites. The saved sequences contain only phospho information. All other modifications are dropped due to simplicity.
@param[in] hit a PeptideHit
@param[in,out] real_spectrum spectrum mapped to hit
@note the original sequence is saved in the PeptideHits as MetaValue Search_engine_sequence.
*/
PeptideHit compute(const PeptideHit& hit, PeakSpectrum& real_spectrum);
protected:
int compareMZ_(double mz1, double mz2) const;
/// getSpectrumDifference_ works similar as the method std::set_difference (http://en.cppreference.com/w/cpp/algorithm/set_difference).
/// set_difference was reimplemented, because it was necessary to overwrite the compare operator to be able to compare the m/z values.
/// not implemented as "operator<", because using tolerances for comparison does not imply total ordering
template <class InputIterator1, class InputIterator2, class OutputIterator>
OutputIterator getSpectrumDifference_(InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, InputIterator2 last2, OutputIterator result) const
{
while (first1 != last1 && first2 != last2)
{
double mz1 = first1->getMZ();
double mz2 = first2->getMZ();
int val = compareMZ_(mz1, mz2);
if (val == -1)
{
*result = *first1;
++result;
++first1;
}
else if (val == 1)
{
++first2;
}
else // check if more ions are within the same tolerance. If so, these can not be site determining ions
{
//check mz2 until no match
++first2;
if (first2 != last2)
{
int ret = compareMZ_(mz1, first2->getMZ());
while (ret == 0 && first2 != last2)
{
++first2;
ret = compareMZ_(mz1, first2->getMZ());
}
}
//check mz1 until no match
++first1;
if (first1 != last1)
{
int ret = compareMZ_(first1->getMZ(), mz2);
while (ret == 0 && first1 != last1)
{
++first1;
ret = compareMZ_(first1->getMZ(), mz2);
}
}
}
}
return std::copy(first1, last1, result);
}
///Computes the site determining_ions for the given AS and sequences in candidates
void computeSiteDeterminingIons_(const std::vector<PeakSpectrum>& th_spectra, const ProbablePhosphoSites& candidates, std::vector<PeakSpectrum>& site_determining_ions) const;
/// return all phospho sites
std::vector<Size> getSites_(const String& unmodified_sequence) const;
/// calculate all n_phosphorylation_events sized sets of phospho sites (all versions of the peptides with exactly n_phosphorylation_events)
std::vector<std::vector<Size>> computePermutations_(const std::vector<Size>& sites, Int n_phosphorylation_events) const;
/// Computes number of matched ions between windows and the given spectrum. All spectra have to be sorted by position!
Size numberOfMatchedIons_(const PeakSpectrum& th, const PeakSpectrum& windows, Size depth) const;
/// Computes the peptide score according to Beausoleil et al. page 1291
double peptideScore_(const std::vector<double>& scores) const;
/**
@brief Finds the peptides with the highest PeptideScores and outputs all information for computing the AScore
@note This function assumes that there are more permutations than the assumed number of phosphorylations!
*/
void determineHighestScoringPermutations_(const std::vector<std::vector<double>>& peptide_site_scores, std::vector<ProbablePhosphoSites>& sites, const std::vector<std::vector<Size>>& permutations, std::multimap<double, Size>& ranking) const;
/// Computes probability for a peak depth of one given spectra and mass_tolerance variables
double computeBaseProbability_(double ppm_reference_mz) const;
/// Computes the cumulative binomial probabilities.
double computeCumulativeScore_(Size N, Size n, double p) const;
/// Computes number of phospho events in a sequence
Size numberOfPhosphoEvents_(const String& sequence) const;
/// Create variant of the peptide with all phosphorylations removed
AASequence removePhosphositesFromSequence_(const String& sequence) const;
/// Create theoretical spectra with all combinations with the number of phosphorylation events
std::vector<PeakSpectrum> createTheoreticalSpectra_(const std::vector<std::vector<Size>>& permutations, const AASequence& seq_without_phospho) const;
/// Pick top 10 intensity peaks for each 100 Da windows
std::vector<PeakSpectrum> peakPickingPerWindowsInSpectrum_(PeakSpectrum& real_spectrum) const;
/// Create 10 scores for each theoretical spectrum (permutation), according to Beausoleil et al. Figure 3 b
std::vector<std::vector<double>> calculatePermutationPeptideScores_(std::vector<PeakSpectrum>& th_spectra, const std::vector<PeakSpectrum>& windows_top10) const;
/// Rank weighted permutation scores ascending
std::multimap<double, Size> rankWeightedPermutationPeptideScores_(const std::vector<std::vector<double>>& peptide_site_scores) const;
/// Reimplemented from @ref DefaultParamHandler
void updateMembers_() override;
// variables:
double fragment_mass_tolerance_; ///< Fragment mass tolerance for spectrum comparisons
bool fragment_tolerance_ppm_; ///< Is fragment mass tolerance given in ppm (or Da)?
Size max_peptide_length_; ///< Limit for peptide lengths that can be analyzed
Size max_permutations_; ///< Limit for number of sequence permutations that can be handled
double unambiguous_score_; ///< Score for unambiguous assignments (all sites phosphorylated)
double base_match_probability_; ///< Probability of a match at a peak depth of 1
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/ID/ConsensusIDAlgorithmPEPMatrix.h | .h | 1,822 | 53 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hendrik Weisser $
// $Authors: Andreas Bertsch, Marc Sturm, Sven Nahnsen, Hendrik Weisser $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/ANALYSIS/ID/ConsensusIDAlgorithmSimilarity.h>
#include <OpenMS/ANALYSIS/SEQUENCE/NeedlemanWunsch.h>
namespace OpenMS
{
/**
@brief Calculates a consensus from multiple ID runs based on PEPs and sequence similarities.
@note The similarity scoring is based on an amino acid substitution matrix. Therefore only the raw amino acid sequences, without post-translational modifications (PTMs), can be considered for similarity scoring - PTMs are ignored during this step. However, PTMs on peptides are retained and separate results are produced for differently-modified peptides.
@htmlinclude OpenMS_ConsensusIDAlgorithmPEPMatrix.parameters
@ingroup Analysis_ID
*/
class OPENMS_DLLAPI ConsensusIDAlgorithmPEPMatrix :
public ConsensusIDAlgorithmSimilarity
{
public:
/// Default constructor
ConsensusIDAlgorithmPEPMatrix();
private:
/// object for alignment score calculation
NeedlemanWunsch alignment_;
/// Not implemented
ConsensusIDAlgorithmPEPMatrix(const ConsensusIDAlgorithmPEPMatrix&);
/// Not implemented
ConsensusIDAlgorithmPEPMatrix& operator=(const ConsensusIDAlgorithmPEPMatrix&);
/// Sequence similarity based on substitution matrix (ignores PTMs)
double getSimilarity_(AASequence seq1, AASequence seq2) override;
// Docu in base class
void updateMembers_() override;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/NUXL/NuXLConstants.h | .h | 897 | 32 | // Copyright (c) 2002-present, The OpenMS Team -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Timo Sachsenberg $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/CONCEPT/Constants.h>
#include <OpenMS/CHEMISTRY/ModifiedPeptideGenerator.h>
#include <OpenMS/ANALYSIS/NUXL/NuXLParameterParsing.h>
#include <OpenMS/ANALYSIS/NUXL/NuXLAnnotatedHit.h>
#include <set>
#include <map>
#include <vector>
#include <algorithm>
namespace OpenMS
{
class OPENMS_DLLAPI NuXLConstants
{
public:
static constexpr size_t IA_CHARGE_INDEX = 0;
static constexpr size_t IA_RANK_INDEX = 1;
static constexpr size_t IA_DENOVO_TAG_INDEX = 2;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/NUXL/NuXLModificationsGenerator.h | .h | 3,753 | 85 | // Copyright (c) 2002-present, The OpenMS Team -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Timo Sachsenberg $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
#include <OpenMS/CHEMISTRY/EmpiricalFormula.h>
#include <vector>
#include <map>
#include <set>
#include <iostream>
namespace OpenMS
{
class AASequence;
/*
formula2mass holds the map from empirical formula to mass
mod_combinations holds the map from empirical formula to (potentially ambigious) nucleotide formulae
e.g.,:
C10H14N5O7P -> {A}
C10H14N5O8P -> {G}
C18H22N4O16P2 -> { CU-H3N1, UU-H2O1 }
*/
struct OPENMS_DLLAPI NuXLModificationMassesResult
{
struct MyStringLengthCompare
{
bool operator () (const std::string & p_lhs, const std::string & p_rhs) const
{
const size_t lhsLength = p_lhs.length() ;
const size_t rhsLength = p_rhs.length() ;
if(lhsLength == rhsLength)
{
return (p_lhs < p_rhs) ; // when two strings have the same
// length, defaults to the normal
// string comparison
}
return (lhsLength < rhsLength) ; // compares with the length
}
};
std::map<String, double> formula2mass; ///< empirical formula -> mass
using NucleotideFormulas = std::set<String, MyStringLengthCompare>;
using MapSumFormulaToNucleotideFormulas = std::map<String, NucleotideFormulas>;
MapSumFormulaToNucleotideFormulas mod_combinations; ///< empirical formula -> nucleotide formula(s) (formulas if modifications lead to ambiguities)
};
class OPENMS_DLLAPI NuXLModificationsGenerator
{
public:
/* @brief generate all combinations of precursor adducts
@param[in] target_nucleotides the list of nucleotides: e.g., "U", "C", "G", "A" or "U", "T", "G", "A"
@param[in] can_xl the set of cross-linkable nucleotides
@param[in] mappings
@param[in] modifications additional losses associated with the precursor adduct: e.g., "-H2O"
@param[in] sequence_restriction only precursor adducts that are substrings of this NA sequence are generated
@param[in] cysteine_adduct special DTT adduct
@param[in] max_length maximum oligo length
*/
static NuXLModificationMassesResult initModificationMassesNA(const StringList& target_nucleotides,
const StringList& nt_groups,
const std::set<char>& can_xl,
const StringList& mappings,
const StringList& modifications,
String sequence_restriction = "",
bool cysteine_adduct = false,
Int max_length = 4);
private:
/// return true if qery is not in sequence
static bool notInSeq(const String& res_seq, const String& query);
static void generateTargetSequences(const String& res_seq, Size param_pos, const std::map<char, std::vector<char> >& map_source2target, StringList& target_sequences);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/NUXL/NuXLFragmentAdductDefinition.h | .h | 2,442 | 76 | // Copyright (c) 2002-present, The OpenMS Team -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Timo Sachsenberg $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
#include <OpenMS/CHEMISTRY/EmpiricalFormula.h>
#include <OpenMS/CONCEPT/HashUtils.h>
#include <functional>
#include <vector>
#include <map>
#include <set>
namespace OpenMS
{
struct OPENMS_DLLAPI NuXLFragmentAdductDefinition
{
EmpiricalFormula formula; // formula
String name; // name used in annotation
double mass = 0;
NuXLFragmentAdductDefinition() = default;
NuXLFragmentAdductDefinition(const NuXLFragmentAdductDefinition&) = default;
NuXLFragmentAdductDefinition(NuXLFragmentAdductDefinition&&) = default;
NuXLFragmentAdductDefinition(const EmpiricalFormula& f, const String& n, double m) : formula(f), name(n), mass(m) {}
NuXLFragmentAdductDefinition& operator=(const NuXLFragmentAdductDefinition&) = default;
NuXLFragmentAdductDefinition& operator=(NuXLFragmentAdductDefinition&&) = default;
bool operator<(const NuXLFragmentAdductDefinition& other) const;
bool operator==(const NuXLFragmentAdductDefinition& other) const;
};
} // namespace OpenMS
// Hash function specialization for NuXLFragmentAdductDefinition
// Placed in std namespace to allow use with std::unordered_map/set
namespace std
{
/**
* @brief Hash function for OpenMS::NuXLFragmentAdductDefinition.
*
* Computes a hash based on all fields used in operator==:
* formula (EmpiricalFormula) and name (String).
*
* @note Hash is consistent with operator==.
*/
template<>
struct hash<OpenMS::NuXLFragmentAdductDefinition>
{
std::size_t operator()(const OpenMS::NuXLFragmentAdductDefinition& fad) const noexcept
{
std::size_t seed = 0;
// Hash formula using EmpiricalFormula's std::hash specialization
OpenMS::hash_combine(seed, std::hash<OpenMS::EmpiricalFormula>{}(fad.formula));
// Hash name using fnv1a_hash_string (String inherits from std::string)
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(fad.name));
return seed;
}
};
} // namespace std
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/NUXL/NuXLPresets.h | .h | 2,403 | 65 | // Copyright (c) 2002-present, The OpenMS Team -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Timo Sachsenberg $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CHEMISTRY/ResidueDB.h>
#include <OpenMS/CHEMISTRY/Residue.h>
#include <OpenMS/DATASTRUCTURES/StringListUtils.h>
#include <OpenMS/CONCEPT/LogStream.h>
namespace OpenMS
{
// MS1 (modifications) and MS2 (fragments) for the different protocols
namespace NuXLPresets
{
/**
@brief Get all available presets names from JSON file
@param[in] custom_presets_file Optional path to a custom presets file
@return StringList containing all available preset names
*/
OPENMS_DLLAPI StringList getAllPresetsNames(const String& custom_presets_file = "");
/**
@brief Get preset parameters for a given preset name
@param[in] p The preset name
@param[in] custom_presets_file Optional path to a custom presets file
@param[out] nucleotides Output parameter for nucleotides
@param[out] mapping Output parameter for mapping
@param[out] modifications Output parameter for modifications
@param[out] fragment_adducts Output parameter for fragment adducts
@param[out] can_cross_link Output parameter for can_cross_link
*/
OPENMS_DLLAPI void getPresets(const String& p,
const String& custom_presets_file,
StringList& nucleotides,
StringList& mapping,
StringList& modifications,
StringList& fragment_adducts,
String& can_cross_link);
/**
@brief Get preset parameters for a given preset name (using default presets file)
@param[in] p The preset name
@param[out] nucleotides Output parameter for nucleotides
@param[out] mapping Output parameter for mapping
@param[out] modifications Output parameter for modifications
@param[out] fragment_adducts Output parameter for fragment adducts
@param[out] can_cross_link Output parameter for can_cross_link
*/
OPENMS_DLLAPI void getPresets(const String& p,
StringList& nucleotides,
StringList& mapping,
StringList& modifications,
StringList& fragment_adducts,
String& can_cross_link);
}
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/NUXL/NuXLFragmentAnnotationHelper.h | .h | 3,136 | 86 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/CONCEPT/Constants.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/METADATA/PeptideHit.h>
#include <set>
#include <map>
#include <vector>
#include <algorithm>
namespace OpenMS
{
/**
@brief Convenience functions to construct appealing fragment annotation strings
and store them as PeptideHit::PeakAnnotation
*/
class OPENMS_DLLAPI NuXLFragmentAnnotationHelper
{
public:
/// Single fragment annotation
struct OPENMS_DLLAPI FragmentAnnotationDetail_
{
FragmentAnnotationDetail_(String s, int z, double m, double i):
shift(s),
charge(z),
mz(m),
intensity(i)
{}
String shift;
int charge;
double mz;
double intensity;
bool operator<(const FragmentAnnotationDetail_& other) const
{
return std::tie(charge, shift, mz, intensity) <
std::tie(other.charge, other.shift, other.mz, other.intensity);
}
bool operator==(const FragmentAnnotationDetail_& other) const
{
double mz_diff = fabs(mz - other.mz);
double intensity_diff = fabs(intensity - other.intensity);
return (charge == other.charge && shift == other.shift && mz_diff < 1e-6 && intensity_diff < 1e-6); // mz and intensity difference comparison actually not needed but kept for completeness
}
};
static String getAnnotatedImmoniumIon(char c, const String& fragment_shift_name);
/// conversion of NuXL annotations to PeptideHit::PeakAnnotation
static std::vector<PeptideHit::PeakAnnotation> fragmentAnnotationDetailsToPHFA(
const String& ion_type,
const std::map<Size, std::vector<FragmentAnnotationDetail_> >& ion_annotation_details);
static std::vector<PeptideHit::PeakAnnotation> shiftedToPHFA(
const std::map<String,
std::set<std::pair<String, double> > >& shifted_ions);
static String shiftedIonsToString(const std::vector<PeptideHit::PeakAnnotation>& as);
static void addShiftedPeakFragmentAnnotation_(const std::map<Size, std::vector<FragmentAnnotationDetail_>>& shifted_b_ions,
const std::map<Size, std::vector<FragmentAnnotationDetail_>>& shifted_y_ions,
const std::map<Size, std::vector<FragmentAnnotationDetail_>>& shifted_a_ions,
const std::vector<PeptideHit::PeakAnnotation>& shifted_immonium_ions,
const std::vector<PeptideHit::PeakAnnotation>& annotated_marker_ions,
const std::vector<PeptideHit::PeakAnnotation>& annotated_precursor_ions,
std::vector<PeptideHit::PeakAnnotation>& fas);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/NUXL/NuXLAnnotatedHit.h | .h | 8,081 | 225 | // Copyright (c) 2002-present, The OpenMS Team -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Timo Sachsenberg $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/METADATA/PeptideHit.h> // for PeakAnnotation
#include <OpenMS/DATASTRUCTURES/StringView.h>
namespace OpenMS
{
/// Slimmer structure as storing all scored candidates in PeptideHit objects takes too much space
/// floats need to be initialized to zero as default
class NuXLAnnotatedHit
{
public:
/*
Slim indices/views to lookup the actual sequence
*/
StringView sequence;
SignedSize peptide_mod_index = 0; // enumeration index of the non-NA peptide modification
Size NA_mod_index = 0; // index of the NA modification
Size NA_adduct_amb_index = 0; // store index the entry in the set of ambiguous precursor adducts (e.g, C-NH3 vs. U-H2O)
int isotope_error = 0; // wheter the hit has been matched with isotopic misassignment
static constexpr const char UNKNOWN_NUCLEOTIDE = '?';
char cross_linked_nucleotide = UNKNOWN_NUCLEOTIDE;
/**
The main score (score) is a linear combination of (weighted) subscores
For the fast score (ignoring all shifted peaks) we calculate:
score = 1.0 * total_loss_score
+ 1.0 * total_MIC
+ 0.333 * mass_error_p;
For the all-ion score we calculate:
peptides:
score = -6.486416409280039
+ 4.059968526608637 * ah.total_MIC
+ 0.5842539236790404 * ah.modds
+ 0.21721652155697285 * ah.total_loss_score
+ 1.9988345415208777 * ah.mass_error_p;
XLs:
score = -6.648631037190969
+ 0.4688059636415974 * ah.Morph
+ 4.0386886051238 * ah.MIC
+ 0.5446999629799386 * ah.modds
+ 0.25318342707227187 * ah.total_loss_score
+ 0.12472562244230834 * ah.partial_loss_score
+ 1.2107674392113372 * ah.mass_error_p
+ 2.3319284783288805 * ah.pl_MIC;
*/
float score = 0;
/**
Normalized precursor mass error score.
Mass error is assumed normally distributed with:
- mean = 0
- sd = sqrt(precursor_mass_tolerance) => variance = precursor tolerance
*/
float mass_error_p = 0;
//
// Scores exclusively calculated from peaks without nucleotide shifts:
//
/**
The total loss score is the X!Tandem HyperScore calculated from b-,y-ions
without any nucleotide shift.
*/
float total_loss_score = 0;
/**
The matched ion current in immonium (immonium_score) and precursor ions (precursor_score)
without any nucleotide shift.
see DOI: 10.1021/pr3007045 A Systematic Investigation into the Nature of Tryptic HCD Spectra
imY = EmpiricalFormula("C8H10NO").getMonoWeight(); // 85%
imW = EmpiricalFormula("C10H11N2").getMonoWeight(); // 84%
imF = EmpiricalFormula("C8H10N").getMonoWeight(); // 84%
imL = EmpiricalFormula("C5H12N").getMonoWeight(); // I/L 76%
imH = EmpiricalFormula("C5H8N3").getMonoWeight(); // 70%
imC = EmpiricalFormula("C2H6NS").getMonoWeight(); // CaC 61%
imK1 = EmpiricalFormula("C5H13N2").getMonoWeight(); // 2%
imP = EmpiricalFormula("C4H8N").getMonoWeight(); //?
imQ = 101.0715; // 52%
imE = 102.0555; // 37%
imM = 104.0534; // 3%
*/
float immonium_score = 0;
float precursor_score = 0;
/**
The matched ion current (MIC), average fragment error (err), and morpheus score (Morph) are calculated
for b-,y-,a-ions without nucleotide shift. Morph is just the number of matched peaks + the fraction of MIC
*/
float MIC = 0;
float err = 0;
float Morph = 0;
/**
The match odds (-log10) of observing this number of b-,a-, and y-ions assuming a uniform distribution of noise peaks.
*/
float modds = 0;
//
// Scores exclusively calculated from nucleotide shifted peaks:
//
/**
The partial loss score is the X!Tandem HyperScore calculated from b-,a-, and y-ions
with nucleotide shifts. Matches from b- and a-ions are combined, i.e. a matching a_n-ion is counted as b_n-ion.
For a precursor with charge N, all fragment ion charges up to N-1 are considered.
Calculation of HyperScore:
yFact = logfactorial_(y_ion_count);
bFact = logfactorial_(b_ion_count);
hyperScore = log1p(dot_product) + yFact + bFact;
*/
float partial_loss_score = 0;
/**
The matched ion current (pl_MIC) of ladder ions, average fragment error (pl_err), and morpheus score (pl_Morph) are calculated
from b-,y-,a-ions with nucleotide shift.
Morph: number of matched peaks + the fraction of MIC
*/
float pl_MIC = 0;
float pl_err = 0.0;
float pl_Morph = 0;
/*
The match odds (-log10) of observing this number of b-,a-, and y-ions with nucleotide shifts assuming a uniform distribution of noise peaks.
*/
float pl_modds = 0;
/*
The MIC of precursor with all nucleotide shifts.
Three variants: No additional loss, loss of water, and loss ammonia.
Charge states considered: 1..N (precursor charge)
*/
float pl_pc_MIC = 0;
/**
The matched ion current calculated from immonium ions with nucleotide shifts.
Only singly charged immonium ions are considered.
imY = EmpiricalFormula("C8H10NO").getMonoWeight();
imW = EmpiricalFormula("C10H11N2").getMonoWeight();
imF = EmpiricalFormula("C8H10N").getMonoWeight();
imH = EmpiricalFormula("C5H8N3").getMonoWeight();
imC = EmpiricalFormula("C2H6NS").getMonoWeight();
imP = EmpiricalFormula("C4H8N").getMonoWeight();
imL = EmpiricalFormula("C5H12N").getMonoWeight();
imK1 = EmpiricalFormula("C5H13N2").getMonoWeight();
imK2 = EmpiricalFormula("C5H10N1").getMonoWeight();
imK3 = EmpiricalFormula("C6H13N2O").getMonoWeight();
imQ = 101.0715;
imE = 102.0555;
imM = 104.0534;
*/
float pl_im_MIC = 0;
//
// Scores calculated from peaks with AND without nucleotide shifts:
//
/**
The complete TIC fraction of explained peaks (total_MIC) (excludes marker ions)
For peptides: total_MIC = MIC + im_MIC + pc_MIC (b-,a-,y-ions, immonium ions, precursor ions)
For XLs: total_MIC = MIC + im_MIC + pc_MIC + pl_MIC + pl_pc_MIC + pl_im_MIC + marker_ions_sub_score
*/
float total_MIC = 0;
/**
The matched ion current in marker ions (marker_ions_score) is not considered in scoring.
*/
float marker_ions_score = 0;
/**
Coverage of peptide by prefix or suffix ions (fraction)
For example: PEPTIDER
01000100 (two of eight ions observed -> 2/8)
Shifted and non-shifted are combined to determine coverage.
*/
float ladder_score = 0;
/**
Longest sequence covered in peptide by prefix or suffix ions (fraction).
Coverage of peptide by prefix or suffix ions (fraction)
For example: PEPTIDER
01110001 (three ions form the longest sequence -> 3/8)
Shifted and non-shifted are combined to determine coverage.
*/
float sequence_score = 0;
float best_localization_score = 0;
String localization_scores = 0;
String best_localization;
int best_localization_position = -1; // UNKNOWN
std::vector<PeptideHit::PeakAnnotation> fragment_annotations;
size_t tag_unshifted = 0;
size_t tag_shifted = 0;
size_t tag_XLed = 0; // tag that contains the transition from unshifted to shifted
double explained_peak_fraction = 0;
double matched_theo_fraction = 0;
double wTop50 = 0;
size_t n_theoretical_peaks = 0;
static bool hasBetterScore(const NuXLAnnotatedHit& a, const NuXLAnnotatedHit& b)
{
return a.score > b.score;
}
};
}
| Unknown |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.