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/NUXL/NuXLFragmentIonGenerator.h | .h | 3,472 | 73 | // 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/ANALYSIS/NUXL/NuXLFragmentAdductDefinition.h>
#include <OpenMS/ANALYSIS/NUXL/NuXLFragmentAnnotationHelper.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/KERNEL/MSSpectrum.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
{
// helper class that adds special ions not covered by TheoreticalSpectrumGenerator
class OPENMS_DLLAPI NuXLFragmentIonGenerator
{
public:
// prefix used to denote marker ions in fragment annotations
static constexpr const char* ANNOTATIONS_MARKER_ION_PREFIX = "MI:";
// add RNA-marker ions of charge 1
// this includes the protonated nitrogenous base and all shifts (e.g., U-H2O, U'-H20, ...)
static void addMS2MarkerIons(
const std::vector<NuXLFragmentAdductDefinition>& marker_ions,
PeakSpectrum& spectrum,
PeakSpectrum::IntegerDataArray& spectrum_charge,
PeakSpectrum::StringDataArray& spectrum_annotation);
static void addShiftedImmoniumIons(
const String & unmodified_sequence,
const String & fragment_shift_name,
const double fragment_shift_mass,
PeakSpectrum & partial_loss_spectrum,
PeakSpectrum::IntegerDataArray& partial_loss_spectrum_charge,
PeakSpectrum::StringDataArray& partial_loss_spectrum_annotation);
static void generatePartialLossSpectrum(const String& unmodified_sequence,
const double& fixed_and_variable_modified_peptide_weight,
const String& precursor_rna_adduct,
const double& precursor_rna_mass,
const int& precursor_charge,
const std::vector<NuXLFragmentAdductDefinition>& partial_loss_modification,
const PeakSpectrum& patial_loss_template_z1,
const PeakSpectrum& patial_loss_template_z2,
const PeakSpectrum& patial_loss_template_z3,
PeakSpectrum& partial_loss_spectrum);
static void addPrecursorWithCompleteRNA_(const double fixed_and_variable_modified_peptide_weight,
const String & precursor_rna_adduct,
const double precursor_rna_mass,
const int charge,
PeakSpectrum & partial_loss_spectrum,
MSSpectrum::IntegerDataArray & partial_loss_spectrum_charge,
MSSpectrum::StringDataArray & partial_loss_spectrum_annotation);
static void addSpecialLysImmonumIons(const String& unmodified_sequence,
PeakSpectrum &spectrum,
PeakSpectrum::IntegerDataArray &spectrum_charge,
PeakSpectrum::StringDataArray &spectrum_annotation);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/NUXL/NuXLFDR.h | .h | 2,263 | 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/KERNEL/StandardTypes.h>
#include <OpenMS/DATASTRUCTURES/Param.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <OpenMS/METADATA/ProteinIdentification.h>
#include <OpenMS/ANALYSIS/NUXL/NuXLReport.h>
#include <vector>
namespace OpenMS
{
/// @brief adapted FDR calculation for NA cross-links
class OPENMS_DLLAPI NuXLFDR
{
public:
explicit NuXLFDR(size_t report_top_hits);
// split by meta value "NuXL:isXL" == 0
void splitIntoPeptidesAndXLs(const PeptideIdentificationList& peptide_ids,
PeptideIdentificationList& pep_pi,
PeptideIdentificationList& xl_pi) const;
void mergePeptidesAndXLs(const PeptideIdentificationList& pep_pi,
const PeptideIdentificationList& xl_pi,
PeptideIdentificationList& peptide_ids) const;
// calculate PSM-level q-values (irrespective of XL/non-XL class)
void QValueAtPSMLevel(PeptideIdentificationList& peptide_ids) const;
// calculate PSM-level q-values for XL and non-XL class separately.
void calculatePeptideAndXLQValueAtPSMLevel(const PeptideIdentificationList& peptide_ids,
PeptideIdentificationList& pep_pi,
PeptideIdentificationList& xl_pi) const;
// calculate separate FDRs, filter decoys, write PSM and protein reports
void calculatePeptideAndXLQValueAndFilterAtPSMLevel(
const std::vector<ProteinIdentification>& protein_ids,
const PeptideIdentificationList& peptide_ids,
PeptideIdentificationList& pep,
double peptide_PSM_qvalue_threshold,
double peptide_peptide_qvalue_threshold,
PeptideIdentificationList& xl_pi,
std::vector<double> xl_PSM_qvalue_thresholds,
std::vector<double> xl_peptidelevel_qvalue_thresholds,
const String& out_idxml,
int decoy_factor) const;
private:
size_t report_top_hits_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/NUXL/NuXLReport.h | .h | 2,718 | 93 | // 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/ANALYSIS/NUXL/NuXLMarkerIonExtractor.h>
#include <OpenMS/DATASTRUCTURES/ListUtilsIO.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <OpenMS/KERNEL/MSSpectrum.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/CONCEPT/Constants.h>
#include <OpenMS/FORMAT/TextFile.h>
#include <vector>
namespace OpenMS
{
/// @brief struct to hold a single report line
struct OPENMS_DLLAPI NuXLReportRow
{
bool no_id;
// columns
double rt;
double original_mz;
String accessions;
String peptide;
String NA;
Int charge;
double score;
int rank;
double best_localization_score;
String localization_scores;
String best_localization;
double peptide_weight;
double NA_weight;
double xl_weight;
StringList meta_values; // the actual values of exported metadata
NuXLMarkerIonExtractor::MarkerIonsType marker_ions;
double abs_prec_error;
double rel_prec_error;
double m_H;
double m_2H;
double m_3H;
double m_4H;
String fragment_annotation;
String getString(const String& separator) const;
};
/// create header line
struct OPENMS_DLLAPI NuXLReportRowHeader
{
static String getString(const String& separator, const StringList& meta_values_to_export);
};
/// create PSM report
struct OPENMS_DLLAPI NuXLReport
{
static std::vector<NuXLReportRow> annotate(
const PeakMap& spectra,
PeptideIdentificationList& peptide_ids,
const StringList& meta_values_to_export,
double marker_ions_tolerance);
};
/// protein report
struct OPENMS_DLLAPI NuXLProteinReport
{
static void annotateProteinModificationForTopHits(std::vector<ProteinIdentification>& prot_ids,
const PeptideIdentificationList& peps,
TextFile& tsv_file);
// crosslink efficiency = frequency of the crosslinked amino acid / frequency of the amino acid in all crosslink spectrum matches
static std::map<char, double> getCrossLinkEfficiency(const PeptideIdentificationList& peps);
// returns map of adduct to counts
static std::map<String, size_t> countAdducts(const PeptideIdentificationList& peps);
static void mapAccessionToTDProteins(ProteinIdentification& prot_id, std::map<String, ProteinHit*>& acc2protein_targets, std::map<String, ProteinHit*>& acc2protein_decoys);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/NUXL/NuXLMarkerIonExtractor.h | .h | 809 | 31 | // 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 <map>
#include <vector>
namespace OpenMS
{
class String;
struct OPENMS_DLLAPI NuXLMarkerIonExtractor
{
/// name to mass-intensity pair
typedef std::map<String, std::vector<std::pair<double, double> > > MarkerIonsType;
/// extract an annotate RNA marker ions
static MarkerIonsType extractMarkerIons(const PeakSpectrum& s, const double marker_tolerance);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/NUXL/NuXLAnnotateAndLocate.h | .h | 1,310 | 43 | // 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 NuXLAnnotateAndLocate
{
public:
static void annotateAndLocate_(
const PeakMap& exp,
std::vector<std::vector<NuXLAnnotatedHit>>& annotated_hits,
const NuXLModificationMassesResult& mm,
const ModifiedPeptideGenerator::MapToResidueType& fixed_modifications,
const ModifiedPeptideGenerator::MapToResidueType& variable_modifications,
Size max_variable_mods_per_peptide,
double fragment_mass_tolerance,
bool fragment_mass_tolerance_unit_ppm,
const NuXLParameterParsing::PrecursorsToMS2Adducts & all_feasible_adducts);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/NUXL/NuXLDeisotoper.h | .h | 5,552 | 95 | // 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/Constants.h>
#include <OpenMS/CONCEPT/Types.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <string.h>
namespace OpenMS
{
class MSSpectrum;
/** @brief Deisotoping of nucleotide cross-link mass spectra.
This class provides methods for deisotoping mass spectra. The algorithm
considers each peak (starting from the right of a spectrum) and, for each
peak
**/
class OPENMS_DLLAPI NuXLDeisotoper
{
public:
/** @brief Detect isotopic clusters in a mass spectrum.
Deisotoping is based on C13 abundance and will try to identify a simple
model based on the C12-C13 distance and charge state. This is often a good
approximation for peptide fragment ion spectra but may not work well for
other spectra. The algorithm will consider each peak (starting from the
right of a spectrum) and, for each peak, attempt to add isotopic peaks to
its envelope until either no peak is found, the maximum number of isotopic
peaks is reached or (only when using @p use_decreasing_model) the intensity
of the peak is higher than the previous peak.
Deisotoping is done in-place and if @p annotate_charge is true,
an additional IntegerDataArray "charge" will be appended. If
@p annotate_iso_peak_count is true, an additional IntegerDataArray
"iso_peak_count" containing the number of isotopic peaks will be
appended. If @p annotate_features is true, an addtional IntegerData Array
"feature_number" containing the feature index will be appended.
Existing DataArrays are kept and shrunken to the peaks which
remain in the spectrum.
* @param [spectrum] Input spectrum (sorted by m/z)
* @param [fragment_tolerance] The tolerance used to match isotopic peaks
* @param [fragment_unit_ppm] Whether ppm or m/z is used as tolerance
* @param [min_charge] The minimum charge considered
* @param [max_charge] The maximum charge considered
* @param [keep_only_deisotoped] Only monoisotopic peaks of fragments with isotopic pattern are retained
* @param [min_isopeaks] The minimum number of isotopic peaks (at least 2) required for an isotopic cluster
* @param [max_isopeaks] The maximum number of isotopic peaks (at least 2) considered for an isotopic cluster
* @param [make_single_charged] Convert deisotoped monoisotopic peak to single charge
* @param [annotate_charge] Annotate the charge to the peaks in the IntegerDataArray: "charge" (0 for unknown charge)
* @param [annotate_iso_peak_count] Annotate the number of isotopic peaks in a pattern for each monoisotopic peak in the IntegerDataArray: "iso_peak_count"
* @param [use_decreasing_model] Use a simple averagine model that expects heavier isotopes to have less intensity. If false, no intensity checks are applied.
* @param [start_intensity_check] Number of the isotopic peak from which the decreasing model should be applied. <= 1 will force the monoisotopic peak to be the most intense.
2 will allow the monoisotopic peak to be less intense than the second peak.
3 will allow the monoisotopic and the second peak to be less intense than the third, etc.
A number higher than max_isopeaks will effectively disable use_decreasing_model completely.
* @param [add_up_intensity] Sum up the total intensity of each isotopic pattern into the intensity of the reported monoisotopic peak
* @param [annotate_features] Annotates the feature index in the IntegerDataArray: "feature_number".
* @param [preserve_high_intensity_peaks] If true, the highest intensity peak of each isotopic pattern will never be filtered
* @param [preserve_low_mz_peaks_threshold] If preserve_high_intensity_peaks is set, all peaks with smaller m/z will never be filtered
*
* Note: If @p make_single_charged is selected, the original charge (>=1) gets annotated.
*/
static void deisotopeAndSingleCharge(MSSpectrum& spectrum,
double fragment_tolerance,
bool fragment_unit_ppm,
int min_charge = 1,
int max_charge = 3,
bool keep_only_deisotoped = false,
unsigned int min_isopeaks = 3,
unsigned int max_isopeaks = 10,
bool make_single_charged = true,
bool annotate_charge = false,
bool annotate_iso_peak_count = false,
bool use_decreasing_model = true,
unsigned int start_intensity_check = 2,
bool add_up_intensity = false,
bool annotate_features = false,
bool preserve_high_intensity_peaks = false,
double preserve_low_mz_peaks_threshold = -1e10);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/NUXL/NuXLParameterParsing.h | .h | 4,012 | 83 | // 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/ANALYSIS/NUXL/NuXLFragmentAdductDefinition.h>
#include <OpenMS/ANALYSIS/NUXL/NuXLModificationsGenerator.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
#include <OpenMS/CHEMISTRY/EmpiricalFormula.h>
#include <OpenMS/CHEMISTRY/ResidueModification.h>
#include <vector>
#include <map>
#include <set>
#include <iostream>
namespace OpenMS
{
// fast (flat) data structure to store feasible x-,y-,a-ion fragment adducts and observable marker ions
using NucleotideToFeasibleFragmentAdducts = std::pair<char, std::vector<NuXLFragmentAdductDefinition> >;
// stores the fragment adducts and marker ions for a given precursor adduct
struct OPENMS_DLLAPI MS2AdductsOfSinglePrecursorAdduct
{
std::vector<NucleotideToFeasibleFragmentAdducts> feasible_adducts;
std::vector<NuXLFragmentAdductDefinition> marker_ions;
};
// helper struct to facilitate parsing of parameters (modifications, nucleotide adducts, ...)
struct OPENMS_DLLAPI NuXLParameterParsing
{
/// Query ResidueModifications (given as strings) from ModificationsDB
static std::vector<ResidueModification> getModifications(StringList modNames);
// Map a nucleotide (e.g. U to all possible fragment adducts)
using NucleotideToFragmentAdductMap = std::map<char, std::set<NuXLFragmentAdductDefinition> >;
// @brief Parse tool parameter to create map from target nucleotide to all its fragment adducts
// It maps a single letter nucleotide (e.g., 'T', 'C', ...)
// to the maximum set of fragment adducts that may arise if the nucleotide is cross-linked.
// Losses, that might reduce this set, are not considered in this data structure and handled later
// when specific precursor adducts are considered.
static NucleotideToFragmentAdductMap getTargetNucleotideToFragmentAdducts(StringList fragment_adducts);
// @brief Determines the fragment adducts and marker ions for a given precursor.
// The precursor adduct (the oligo including losses, e.g.: "TC-H3PO4") is mapped to all contained nucleotides
// and their marker ions. In addition, each cross-linkable nucleotide is mapped to its chemically feasible fragment adducts.
// Chemical feasible means in this context, that the fragment or marker ion adduct is a subformula of the precursor adduct.
static MS2AdductsOfSinglePrecursorAdduct getFeasibleFragmentAdducts(
const String& exp_pc_adduct,
const String& exp_pc_formula,
const NucleotideToFragmentAdductMap& nucleotide_to_fragment_adducts,
const std::set<char>& can_xl,
const bool always_add_default_marker_ions,
const bool default_marker_ions_RNA
);
// Maps a precursor adduct (e.g.: "UU-H2O") to all chemically feasible fragment adducts.
using PrecursorsToMS2Adducts = std::map<std::string, MS2AdductsOfSinglePrecursorAdduct>;
// @brief extract all marker ions into a vector and make it unique according to mass. (e.g., used for matching agains all possible marker ions for MIC calculation)
static std::vector<NuXLFragmentAdductDefinition> getMarkerIonsMassSet(const PrecursorsToMS2Adducts& pc2adducts);
// @brief Calculate all chemically feasible fragment adducts for all possible precursor adducts
// Same as getFeasibleFragmentAdducts but calculated from all precursor adducts
static PrecursorsToMS2Adducts getAllFeasibleFragmentAdducts(
const NuXLModificationMassesResult& precursor_adducts,
const NucleotideToFragmentAdductMap& nucleotide_to_fragment_adducts,
const std::set<char>& can_xl,
const bool always_add_default_marker_ions,
const bool default_marker_ions_RNA
);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/OPENSWATH/MRMBatchFeatureSelector.h | .h | 3,124 | 87 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Douglas McCloskey, Pasquale Domenico Colaianni $
// $Authors: Douglas McCloskey, Pasquale Domenico Colaianni $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/config.h> // OPENMS_DLLAPI
#include <OpenMS/ANALYSIS/OPENSWATH/MRMFeatureSelector.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <vector>
namespace OpenMS
{
/**
@brief Batch processing wrapper for MRMFeatureSelector.
This class enables iterative refinement of feature selection by applying
MRMFeatureSelector multiple times with different parameter sets. Each iteration
uses the output of the previous iteration as input, allowing for progressive
filtering and optimization.
@section MRMBatchFeatureSelector_usage Usage
@code
FeatureMap features, selected;
std::vector<MRMFeatureSelector::SelectorParameters> params_list;
// First pass: relaxed parameters
params_list.push_back(MRMFeatureSelector::SelectorParameters());
// Second pass: stricter parameters
MRMFeatureSelector::SelectorParameters strict;
strict.optimal_threshold = 0.8;
params_list.push_back(strict);
MRMBatchFeatureSelector::batchMRMFeaturesScore(features, selected, params_list);
@endcode
@see MRMFeatureSelector for single-pass feature selection
@see MRMFeatureSelectorQMIP for QMIP-based selection
@see MRMFeatureSelectorScore for score-based selection
@ingroup TargetedQuantitation
*/
class OPENMS_DLLAPI MRMBatchFeatureSelector
{
public:
MRMBatchFeatureSelector() = delete;
~MRMBatchFeatureSelector() = delete;
/**
Calls `feature_selector.selectMRMFeature()` feeding it the parameters found in `parameters`.
It calls said method `parameters.size()` times, using the result of each cycle as input
for the next cycle.
@param[in] feature_selector Base class for the feature selector to use
@param[in] features Input features
@param[out] selected_features Selected features
@param[in] parameters Vector of parameters for the multiple calls to the selector
*/
static void batchMRMFeatures(
const MRMFeatureSelector& feature_selector,
const FeatureMap& features,
FeatureMap& selected_features,
const std::vector<MRMFeatureSelector::SelectorParameters>& parameters
);
/// Calls `batchMRMFeatures()` using a `MRMFeatureSelectorScore` selector
static void batchMRMFeaturesScore(
const FeatureMap& features,
FeatureMap& selected_features,
const std::vector<MRMFeatureSelector::SelectorParameters>& parameters
);
/// Calls `batchMRMFeatures()` using a `MRMFeatureSelectorQMIP` selector
static void batchMRMFeaturesQMIP(
const FeatureMap& features,
FeatureMap& selected_features,
const std::vector<MRMFeatureSelector::SelectorParameters>& parameters
);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/OPENSWATH/OpenSwathWorkflow.h | .h | 29,173 | 590 | // 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
// Interfaces
#include <OpenMS/OPENSWATHALGO/DATAACCESS/ISpectrumAccess.h>
#include <OpenMS/OPENSWATHALGO/DATAACCESS/DataStructures.h>
#include <OpenMS/OPENSWATHALGO/DATAACCESS/TransitionExperiment.h>
#include <OpenMS/INTERFACES/IMSDataConsumer.h>
#include <OpenMS/FORMAT/FileHandler.h> // debug file store only
// Kernel and implementations
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/SpectrumAccessOpenMS.h>
#include <OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/SpectrumAccessTransforming.h>
#include <OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/SpectrumAccessOpenMSInMemory.h>
#include <OpenMS/OPENSWATHALGO/DATAACCESS/SwathMap.h>
// Helpers
#include <OpenMS/ANALYSIS/OPENSWATH/OpenSwathHelper.h>
// #include <OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/DataAccessHelper.h>
#include <OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/SimpleOpenMSSpectraAccessFactory.h>
#include <OpenMS/ANALYSIS/OPENSWATH/OpenSwathOSWWriter.h>
// Algorithms
#include <OpenMS/ANALYSIS/OPENSWATH/MRMRTNormalizer.h>
#include <OpenMS/ANALYSIS/OPENSWATH/ChromatogramExtractor.h>
#include <OpenMS/ANALYSIS/OPENSWATH/MRMFeatureFinderScoring.h>
#include <OpenMS/ANALYSIS/OPENSWATH/MRMTransitionGroupPicker.h>
#include <OpenMS/ANALYSIS/OPENSWATH/SwathMapMassCorrection.h>
#include <OpenMS/PROCESSING/RESAMPLING/LinearResamplerAlign.h>
#include <cassert>
#include <limits>
// #define OPENSWATH_WORKFLOW_DEBUG
// The workflow class
namespace OpenMS
{
/** @brief ChromatogramExtractor parameters
*
* A small helper struct to pass the parameters for the chromatogram
* extraction through to the actual algorithm.
*
*/
struct ChromExtractParams
{
/// Whether to not extract anything closer than this (in Da) from the upper edge
double min_upper_edge_dist;
/// Extraction window in Da or ppm (e.g. 50ppm means extraction +/- 25ppm)
double mz_extraction_window;
/// Extraction window in ion mobility
double im_extraction_window;
/// Whether the extraction window is given in ppm or Da
bool ppm;
/// The extraction function in mass space
String extraction_function;
/// The retention time extraction window
double rt_extraction_window;
/// Whether to extract some extra in the retention time (can be useful if one wants to look at the chromatogram outside the window)
double extra_rt_extract;
};
class OPENMS_DLLAPI OpenSwathWorkflowBase :
public ProgressLogger
{
protected:
/** @brief Default constructor
*
* Will not use any ms1 traces and use all threads in the outer loop.
*
**/
OpenSwathWorkflowBase() :
use_ms1_traces_(false),
use_ms1_ion_mobility_(false),
prm_(false),
pasef_(false),
threads_outer_loop_(-1)
{
}
/** @brief Constructor
*
* @param[in] use_ms1_traces Use MS1 data?
* @param[in] use_ms1_ion_mobility Use ion mobility extraction on MS1 traces?
* @param[out] prm Is data acquired in targeted DIA (e.g. PRM mode) with potentially overlapping windows?
* @param[in] pasef Is this diaPASEF data?
* @param[in] threads_outer_loop How many threads should be used for the outer
* loop (-1 will use all threads in the outer loop)
*
* @note The total number of threads should be divisible by this number
* (e.g. use 8 in outer loop if you have 24 threads in total and 3 will be
* used for the inner loop).
*
*
**/
OpenSwathWorkflowBase(bool use_ms1_traces, bool use_ms1_ion_mobility, bool prm, bool pasef, int threads_outer_loop) :
use_ms1_traces_(use_ms1_traces),
use_ms1_ion_mobility_(use_ms1_ion_mobility),
prm_(prm),
pasef_(pasef),
threads_outer_loop_(threads_outer_loop)
{
}
/** @brief Perform MS1 extraction and store result in ms1_chromatograms
*
* @param[in] ms1_map Spectrum Access to the MS1 map
* @param[in] swath_maps The raw data (swath maps)
* @param[in] ms1_chromatograms Output vector for MS1 chromatograms
* @param[in] cp Parameter set for the chromatogram extraction
* @param[in] transition_exp The set of assays to be extracted and scored
* @param[in] trafo_inverse Inverse transformation function
* @param[in] ms1_only If true, will only score on MS1 level and ignore MS2 level
* @param[in] ms1_isotopes Number of MS1 isotopes to extract (zero means only monoisotopic peak)
*
*/
void MS1Extraction_(const OpenSwath::SpectrumAccessPtr& ms1_map,
const std::vector<OpenSwath::SwathMap>& swath_maps,
std::vector<MSChromatogram>& ms1_chromatograms,
const ChromExtractParams& cp,
const OpenSwath::LightTargetedExperiment& transition_exp,
const TransformationDescription& trafo_inverse,
bool ms1_only = false,
int ms1_isotopes = 0);
/** @brief Function to prepare extraction coordinates that also correctly handles RT transformations
*
* Creates a set of (empty) chromatograms and extraction coordinates with
* the correct ids, m/z and retention time start/end points to be extracted
* by the ChromatogramExtractor.
*
* Handles RT extraction windows by calculating the correct transformation
* for each coordinate.
*
* @param[out] chrom_list Output of chromatograms (will be filled with empty chromatogram ptrs)
* @param[out] coordinates Output of extraction coordinates (will be filled with matching extraction coordinates)
* @param[out] transition_exp_used The transition experiment used to create the coordinates
* @param[in] trafo_inverse Inverse transformation function
* @param[in] cp Parameter set for the chromatogram extraction
* @param[in] ms1 Whether to perform MS1 (precursor ion) or MS2 (fragment ion) extraction
* @param[in] ms1_isotopes Number of MS1 isotopes to extract (zero means only monoisotopic peak)
*
*/
void prepareExtractionCoordinates_(std::vector< OpenSwath::ChromatogramPtr > & chrom_list,
std::vector< ChromatogramExtractorAlgorithm::ExtractionCoordinates > & coordinates,
const OpenSwath::LightTargetedExperiment & transition_exp_used,
const TransformationDescription& trafo_inverse,
const ChromExtractParams & cp,
const bool ms1 = false,
const int ms1_isotopes = -1) const;
/**
* @brief Spectrum Access to the MS1 map (note that this is *not* threadsafe!)
*
* @note This pointer is not threadsafe, please use the lightClone() function to create a copy for each thread
* @note This pointer may be NULL if use_ms1_traces_ is set to false
*
*/
OpenSwath::SpectrumAccessPtr ms1_map_ = nullptr;
/// Whether to use the MS1 traces
bool use_ms1_traces_;
/// Whether to use ion mobility extraction on MS1 traces
bool use_ms1_ion_mobility_;
/** @brief Whether data is acquired in targeted DIA (e.g. PRM mode) with potentially overlapping windows
*
* If set to true, a precursor will only be extracted from a single window
* that matches in m/z and whose m/z center is *closest* to the library m/z
* of the precursor. This is required if windows overlap in m/z as is the
* case for SRM / PRM data where often multiple windows with similar (or
* overlaping) m/z are used to target different precursors at different RT.
*/
bool prm_;
/** @brief Whether data is diaPASEF data
*
* If set to true, a precursor will only be extracted from a single window
* that matches both in m/z and whose ion mobility (drift time) center is
* *closest* to the library ion mobility of the precursor. This is required
* if windows overlap in m/z or in ion mobility, as is the case for
* diaPASEF data.
*/
bool pasef_;
/** @brief How many threads should be used for the outer loop
*
* @note A value of -1 will use all threads in the outer loop
*
* @note The total number of threads should be divisible by this number
* (e.g. use 8 in outer loop if you have 24 threads in total and 3 will be
* used for the inner loop).
*
**/
int threads_outer_loop_;
};
/**
* @brief Execute all steps for retention time and m/z calibration of SWATH-MS data
*
* Uses a set of robust calibrant peptides (e.g. iRT peptides, common
* calibrants) perform RT and m/z correction in SWATH-MS data. Currently
* supports (non-)linear correction of RT against library RT as well
* as (non-)linear correction of m/z error as a function of m/z.
*
* @note The relevant algorithms are implemented in MRMRTNormalizer for RT
* calibration and SwathMapMassCorrection for m/z calibration.
*
* The overall execution flow in this class is as follows (see performRTNormalization() function):
* - Extract chromatograms across the whole RT range using simpleExtractChromatograms_()
* - Compute calibration functions for RT and m/z using doDataNormalization_()
*
*/
class OPENMS_DLLAPI OpenSwathCalibrationWorkflow :
public OpenSwathWorkflowBase
{
public:
OpenSwathCalibrationWorkflow() :
OpenSwathWorkflowBase()
{
}
explicit OpenSwathCalibrationWorkflow(bool use_ms1_traces) :
OpenSwathWorkflowBase(use_ms1_traces, false, false, false, -1)
{
}
/** @brief Perform RT and m/z correction of the input data using RT-normalization peptides.
*
* This function extracts the RT normalization chromatograms using
* simpleExtractChromatograms_() and then uses the chromatograms to find
* features (in doDataNormalization_()). If desired, also m/z correction
* is performed using the lock masses of the given peptides. The provided
* raw data (swath_maps) are therefore not constant but may be changed in
* this function.
*
* @param[in] irt_transitions A set of transitions used for the RT normalization peptides
* @param[in] swath_maps The raw data (swath maps)
* @param[out] im_trafo Ion mobility trafo values on the RT-normalization peptides
* @param[in] min_rsq Minimal R^2 value that is expected for the RT regression
* @param[in] min_coverage Minimal coverage of the chromatographic space that needs to be achieved
* @param[in] feature_finder_param Parameter set for the feature finding in chromatographic dimension
* @param[in] cp_irt Parameter set for the chromatogram extraction
* @param[in] irt_detection_param Parameter set for the detection of the iRTs (outlier detection, peptides per bin etc)
* @param[in] calibration_param Parameter for the m/z and im calibration (see SwathMapMassCorrection)
* @param[in] debug_level Debug level (writes out the RT normalization chromatograms if larger than 1)
* @param[out] irt_mzml_out Output Chromatogram mzML containing the iRT peptides (if not empty,
* iRT chromatograms will be stored in this file)
* @param[in] pasef whether the data is PASEF data (should match transitions by their IM)
* @param[in] load_into_memory Whether to cache the current SWATH map in memory
*
*/
TransformationDescription performRTNormalization(const OpenSwath::LightTargetedExperiment & irt_transitions,
std::vector< OpenSwath::SwathMap > & swath_maps,
TransformationDescription& im_trafo,
double min_rsq,
double min_coverage,
const Param & feature_finder_param,
const ChromExtractParams & cp_irt,
const Param& irt_detection_param,
const Param& calibration_param,
const String& irt_mzml_out,
Size debug_level,
bool pasef = false,
bool load_into_memory = false);
public:
/** @brief Perform retention time and m/z calibration
*
* Uses MRMRTNormalizer for RT calibration and SwathMapMassCorrection for m/z calibration.
*
* The overall execution flow is as follows:
* - Estimate the retention time range of the iRT peptides over all assays (see OpenSwathHelper::estimateRTRange())
* - Store the peptide retention times in an intermediate map
* - Pick input chromatograms to identify RT pairs from the input data
* using MRMFeatureFinderScoring, which will be used without the RT
* scoring enabled
* - Find most likely correct feature for each compound (see OpenSwathHelper::simpleFindBestFeature())
* - Perform the outlier detection (see MRMRTNormalizer)
* - Check whether the found peptides fulfill the binned coverage criteria set by the user.
* - Select the "correct" peaks for m/z correction (e.g. remove those not
* part of the linear regression)
* - Perform m/z and IM calibration (see SwathMapMassCorrection)
* - Store transformation, using the selected model
*
* @param[in] transition_exp_ The transitions for the normalization peptides
* @param[out] chromatograms The extracted chromatograms
* @param[out] im_trafo Ion mobility trafo values on the RT-normalization peptides
* @param[in] swath_maps The raw data (swath maps)
* @param[in] min_rsq Minimal R^2 value that is expected for the RT regression
* @param[in] min_coverage Minimal coverage of the chromatographic space that needs to be achieved
* @param[in] default_ffparam Parameter set for the feature finding in chromatographic dimension
* @param[in] irt_detection_param Parameter set for the detection of the iRTs (outlier detection, peptides per bin etc)
* @param[in] calibration_param Parameter for the m/z and im calibration (see SwathMapMassCorrection)
* @param[in] pasef whether this data is pasef data with potentially overlapping m/z windows (differing by IM)
*
* @note This function is based on the algorithm inside the OpenSwathRTNormalizer tool
*
*/
TransformationDescription doDataNormalization_(const OpenSwath::LightTargetedExperiment& transition_exp_,
const std::vector< OpenMS::MSChromatogram >& chromatograms,
TransformationDescription& im_trafo,
std::vector< OpenSwath::SwathMap > & swath_maps,
double min_rsq,
double min_coverage,
const Param& default_ffparam,
const Param& irt_detection_param,
const Param& calibration_param,
const bool pasef);
/** @brief Simple method to extract chromatograms (for the RT-normalization peptides)
*
* @param[in] swath_maps The raw data (swath maps)
* @param[in] irt_transitions A set of transitions used for the RT normalization peptides
* @param[in] chromatograms The extracted chromatograms (output)
* @param[in] trafo Transformation description for RT normalization
* @param[in] cp Parameter set for the chromatogram extraction
* @param[in] load_into_memory Whether to cache the current SWATH map in memory
* @param[in] pasef whether the data is PASEF data with possible overlapping m/z windows (with different ion mobility)
*
*/
void simpleExtractChromatograms_(const std::vector< OpenSwath::SwathMap > & swath_maps,
const OpenSwath::LightTargetedExperiment & irt_transitions,
std::vector< OpenMS::MSChromatogram > & chromatograms,
const TransformationDescription& trafo,
const ChromExtractParams & cp,
bool pasef,
bool load_into_memory);
/** @brief Add two chromatograms
*
* @param[in] base_chrom The base chromatogram to which we will add intensity
* @param[in] newchrom The chromatogram to be added
*
*/
static void addChromatograms(MSChromatogram& base_chrom, const MSChromatogram& newchrom);
/// Retrieve the estimated fragment m/z window (ppm)
double getEstimatedMzWindow() const;
/// Set the estimated fragment m/z window (ppm)
void setEstimatedMzWindow(double estimatedMzWindow);
/// Retrieve the estimated fragment ion mobility
double getEstimatedImWindow() const;
/// Set the estimated fragment ion mobility
void setEstimatedImWindow(double estimatedImWindow);
/// Retrieve the estimated MS1 m/z window (ppm)
double getEstimatedMs1MzWindow() const;
/// Set the estimated MS1 m/z window (ppm)
void setEstimatedMs1MzWindow(double estimatedMs1MzWindow);
/// Retrieve the estimated MS1 ion mobility window
double getEstimatedMs1ImWindow() const;
/// Set the estimated MS1 ion mobility window
void setEstimatedMs1ImWindow(double estimatedMs1ImWindow);
protected:
/// estimated extraction windows
double estimated_mz_window_ = -1;
double estimated_im_window_ = -1;
double estimated_ms1_mz_window_ = -1;
double estimated_ms1_im_window_ = -1;
};
/**
* @brief Execute all steps in an \ref TOPP_OpenSwathWorkflow "OpenSwath" analysis
*
* The workflow will perform a complete OpenSWATH analysis. Optionally,
* a calibration of m/z and retention time (mapping peptides to normalized
* space and correcting m/z error) can be performed beforehand using the
* OpenSwathCalibrationWorkflow class.
*
* For diaPASEF workflows where ion mobility windows are overlapping, precursors may be found in multiple SWATHs.
* In this case, precursors are only extracted from the SWATH in which they are most centered across ion mobility
* (Provided -pasef flag is set).
*
* The overall execution flow in this class is as follows (see performExtraction() function)
*
* - Obtain precursor ion chromatograms (if enabled) through MS1Extraction_()
* - Perform scoring of precursor ion chromatograms if no MS2 is given
* - Iterate through each SWATH-MS window:
* - Select which transitions to extract (proceed in batches) using OpenSwathHelper::selectSwathTransitions()
* - Iterate through each batch of transitions:
* - Extract current batch of transitions from current SWATH window:
* - Select transitions for current batch (see selectCompoundsForBatch_())
* - Prepare transition extraction (see prepareExtractionCoordinates_())
* - Extract transitions using ChromatogramExtractor::extractChromatograms()
* - Convert data to OpenMS format using ChromatogramExtractor::return_chromatogram()
* - Score extracted transitions (see scoreAllChromatograms_())
* - Write scored chromatograms and peak groups to disk (see writeOutFeaturesAndChroms_())
*
*/
class OPENMS_DLLAPI OpenSwathWorkflow :
public OpenSwathWorkflowBase
{
typedef OpenSwath::LightTransition TransitionType;
typedef MRMTransitionGroup< MSChromatogram, TransitionType> MRMTransitionGroupType;
public:
/** @brief Constructor
*
* @param[in] use_ms1_traces Whether to use MS1 data
* @param[in] use_ms1_ion_mobility Whether to use ion mobility extraction on MS1 traces
* @param[out] prm Whether data is acquired in targeted DIA (e.g. PRM mode) with potentially overlapping windows
* @param[in] pasef Is this diaPASEF data?
* @param[in] threads_outer_loop How many threads should be used for the outer
* loop (-1 will use all threads in the outer loop)
*
* @note The total number of threads should be divisible by this number
* (e.g. use 8 in outer loop if you have 24 threads in total and 3 will be
* used for the inner loop).
*
*
**/
OpenSwathWorkflow(bool use_ms1_traces, bool use_ms1_ion_mobility, bool prm, bool pasef, int threads_outer_loop) :
OpenSwathWorkflowBase(use_ms1_traces, use_ms1_ion_mobility, prm, pasef, threads_outer_loop)
{
}
/** @brief Execute OpenSWATH analysis on a set of SwathMaps and transitions.
*
* See OpenSwathWorkflow class for a detailed description of this function.
*
* @param[in] swath_maps The raw data (swath maps)
* @param[in] rt_trafo Retention time transformation description (translating this runs' RT to normalized RT space)
* @param[in] chromatogram_extraction_params Parameter set for the chromatogram extraction
* @param[in] ms1_chromatogram_extraction_params Parameter set for the chromatogram extraction of the MS1 data
* @param[in] feature_finder_param Parameter set for the feature finding in chromatographic dimension
* @param[in] assay_library The set of assays to be extracted and scored
* @param[out] result_featureFile Output feature map to store identified features
* @param[out] store_features_in_featureFile Whether features should be appended to the output feature map (if this is false, then out_featureFile will be empty)
* @param[out] result_osw OSW Writer object to store identified features in SQLite format (set store_features to false if using this option)
* @param[out] result_chromatograms Chromatogram consumer object to store the extracted chromatograms
* @param[in] batchSize Size of the batches which should be extracted and scored
* @param[in] ms1_isotopes Number of MS1 isotopes to extract (zero means only monoisotopic peak)
* @param[in] load_into_memory Whether to cache the current SWATH map in memory
*
* @note Speed and memory performance can be influenced by \p batchSize and
* \p load_into_memory where larger batch sizes increase memory and
* potentially decrease the utility of parallelization while loading data
* into memory will increase memory usage but decrease execution time.
*
*/
void performExtraction(const std::vector<OpenSwath::SwathMap>& swath_maps,
const TransformationDescription& rt_trafo,
const ChromExtractParams & chromatogram_extraction_params,
const ChromExtractParams & ms1_chromatogram_extraction_params,
const Param & feature_finder_param,
const OpenSwath::LightTargetedExperiment& assay_library,
FeatureMap& result_featureFile,
bool store_features_in_featureFile,
OpenSwathOSWWriter & result_osw,
Interfaces::IMSDataConsumer * result_chromatograms,
int batchSize,
int ms1_isotopes,
bool load_into_memory);
protected:
/** @brief Write output features and chromatograms
*
* Writes output chromatograms to the provided chromatogram consumer
* (presumably to disk) and output features to the provided FeatureMap.
*
* @param[in] chromatograms Output chromatograms to be passed to the consumer
* @param[in] ms1_chromatograms Output chromatograms (MS1 level) to be passed to the consumer
* @param[in] featureFile Features to be appended to the @p out_featureFile
* @param[out] out_featureFile Output FeatureMap to which the features will be appended
* @param[in] store_features Whether features should be appended to the output
* feature map (if this is false, then out_featureFile will be empty)
* @param[out] chromConsumer Chromatogram consumer object to store the extracted chromatograms
*
* @note This should be wrapped in an OpenMP critical block
*/
void writeOutFeaturesAndChroms_(std::vector< OpenMS::MSChromatogram > & chromatograms,
std::vector< MSChromatogram >& ms1_chromatograms,
const FeatureMap & featureFile,
FeatureMap& out_featureFile,
bool store_features,
Interfaces::IMSDataConsumer * chromConsumer);
/** @brief Perform scoring on a set of chromatograms
*
* This will generate a new object of type MRMTransitionGroup for each
* compound or peptide in the provided assay library and link the
* transition meta information with the extracted chromatograms. This will
* then be used to perform peak picking and peak scoring through
* MRMTransitionGroupPicker and MRMFeatureFinderScoring. The assay library
* is provided as transition_exp and the chromatograms in
* ms2_chromatograms.
*
* The overall execution flow is as follows:
*
* - Iterate over all assays (compounds / peptides) in the transition_exp
* - Create a new MRMTransitionGroup
* - Iterate over all transitions in an assay
* - Find the relevant chromatogram for the given transition, convert it and filter it by RT
* - Add the chromatogram and transition to the MRMTransitionGroup
* - Add a single MS1 chromatogram of the mono-isotopic precursor to the
* MRMTransitionGroup, if available (named "groupId_Precursor_i0")
* - Find peakgroups in the chromatogram set (see MRMTransitionGroupPicker::pickTransitionGroup)
* - Score peakgroups in the chromatogram set (see MRMFeatureFinderScoring::scorePeakgroups)
* - Add the identified peak groups to the SQL-based output format (osw_writer)
*
* @param[in] ms2_chromatograms Input chromatograms (MS2 level)
* @param[out] ms1_chromatograms Input chromatograms (MS1-level)
* @param[in] swath_maps Set of swath map(s) for the current swath window
* @param[in] transition_exp The transition experiment (assay library)
* @param[in] feature_finder_param Parameters for the MRMFeatureFinderScoring
* @param[in] trafo RT Transformation function
* @param[in] rt_extraction_window RT extraction window
* @param[out] output Output map
* @param[out] osw_writer OSW Writer object to store identified features in SQLite format
* @param[in] nr_ms1_isotopes Consider this many MS1 isotopes for precursor chromatograms
* @param[in] ms1only If true, will only score on MS1 level and ignore MS2 level
*
*/
void scoreAllChromatograms_(
const std::vector<OpenMS::MSChromatogram>& ms2_chromatograms,
const std::vector<OpenMS::MSChromatogram>& ms1_chromatograms,
const std::vector<OpenSwath::SwathMap>& swath_maps,
const OpenSwath::LightTargetedExperiment& transition_exp,
const Param& feature_finder_param,
const TransformationDescription& trafo,
const double rt_extraction_window,
FeatureMap& output,
OpenSwathOSWWriter& osw_writer,
int nr_ms1_isotopes = 0,
bool ms1only = false) const;
/** @brief Select which compounds to analyze in the next batch (and copy to output)
*
* This function will select which compounds or peptides should be analyzed
* in the current batch (with index "batch_idx"). The selected compounds
* will be copied into the output structure. The output will contain
* "batch_size" compounds or peptides.
*
* @param[in] transition_exp_used_all The full set of transitions (this will be used to select transitions from)
* @param[in] transition_exp_used The selected set of transitions (will contain only transitions for the next batch)
* @param[in] batch_size How many compounds or peptides should be used per batch
* @param[in] batch_idx Current batch index (only compounds or peptides from batch_idx*batch_size to batch_idx*batch_size+batch_size will be copied)
*
* @note The proteins will be copied completely without checking for a match
*
*/
void selectCompoundsForBatch_(const OpenSwath::LightTargetedExperiment& transition_exp_used_all,
OpenSwath::LightTargetedExperiment& transition_exp_used, int batch_size, size_t batch_idx);
/** @brief Helper function for selectCompoundsForBatch_()
*
* Copy all transitions matching to one of the compounds in the selected
* peptide vector from all_transitions to the output.
*
* @param[in] used_compounds Which peptides or metabolites to be used
* @param[in] all_transitions Transitions vector from which to select transitions
* @param[out] output Output vector containing matching transitions (taken from all_transitions)
*
*/
void copyBatchTransitions_(const std::vector<OpenSwath::LightCompound>& used_compounds,
const std::vector<OpenSwath::LightTransition>& all_transitions,
std::vector<OpenSwath::LightTransition>& output);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/OPENSWATH/ChromatogramExtractorAlgorithm.h | .h | 7,747 | 167 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hannes Roest $
// $Authors: Hannes Roest $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/OPENSWATHALGO/DATAACCESS/ISpectrumAccess.h>
namespace OpenMS
{
/**
* @brief The ChromatogramExtractorAlgorithm extracts chromatograms from a MS data.
*
* It will take as input a set of transitions coordinates and will extract
* the signal of the provided map at the product ion m/z and retention time
* (rt) values specified by the extraction coordinates. This interface only
* expects a set of coordinates which are up to the user to fill but a
* convenient prepare_coordinates function is provided (in the
* ChromatogramExtractor class) to create the coordinates for the most common
* case of an MS2 and MS1 extraction.
*
* In the case of MS2 extraction, the map is assumed to originate from a SWATH
* (data-independent acquisition or DIA) experiment.
*
*/
class OPENMS_DLLAPI ChromatogramExtractorAlgorithm :
public ProgressLogger
{
public:
struct ExtractionCoordinates
{
double mz = 0.0; ///< m/z value around which should be extracted
double ion_mobility = 0.0; ///< ion mobility value around which should be extracted
double mz_precursor = 0.0; ///< precursor m/z value (is currently ignored by the algorithm)
double rt_start = 0.0; ///< rt start of extraction (in seconds)
double rt_end = 0.0; ///< rt end of extraction (in seconds)
std::string id; ///< identifier
static bool SortExtractionCoordinatesByMZ(
const ChromatogramExtractorAlgorithm::ExtractionCoordinates& left,
const ChromatogramExtractorAlgorithm::ExtractionCoordinates& right)
{
return left.mz < right.mz;
}
static bool SortExtractionCoordinatesReverseByMZ(
const ChromatogramExtractorAlgorithm::ExtractionCoordinates& left,
const ChromatogramExtractorAlgorithm::ExtractionCoordinates& right)
{
return left.mz > right.mz;
}
};
/**
* @brief Extract chromatograms at the m/z and RT defined by the ExtractionCoordinates.
*
* @param[in] input Input spectral map
* @param[out] output Output chromatograms (XICs)
* @param[in] extraction_coordinates Extracts around these coordinates (from
* rt_start to rt_end in seconds - extracts the whole chromatogram if
* rt_end - rt_start < 0).
* @param[in] mz_extraction_window Extracts a window of this size in m/z
* dimension in Th or ppm (e.g. a window of 50 ppm means an extraction of
* 25 ppm on either side)
* @param[in] ppm Whether mz_extraction_window is in ppm or in Th
* @param[in] im_extraction_window Full window width (i.e. twice the tolerance) for IM extraction. Must be positive.
* @param[in] filter Which function to apply in m/z space (currently "tophat" only)
*
*/
void extractChromatograms(const OpenSwath::SpectrumAccessPtr& input,
std::vector< OpenSwath::ChromatogramPtr >& output,
const std::vector<ExtractionCoordinates>& extraction_coordinates,
double mz_extraction_window,
bool ppm,
double im_extraction_window,
const String& filter);
/**
* @brief Extract the next mz value and add the integrated intensity to integrated_intensity.
*
* This function will sum up all intensities within a window of
* mass-to-charge. It will extract around mz +/- mz_extract_window / 2.0
* and add the result to integrated_intensity.
*
* @param[out] mz_start Start of the spectrum (m/z coordinates)
* @param[in,out] mz_it Current m/z position (will be modified)
* @param[in] mz_end End of the spectrum (m/z coordinates)
* @param[in,out] int_it Current intensity position (will be modified)
* @param[out] mz Target m/z for the current ion
* @param[out] integrated_intensity Resulting intensity (will be overwritten)
* @param[in] mz_extraction_window Extracts a window of this size in m/z
* dimension (e.g. a window of 50 ppm means an extraction of 25 ppm on
* either side)
* @param[in] ppm Whether the parameter mz_extraction_window is given in ppm or Th
*
* @note This function will change the position of the iterators mz_it and
* int_it and it can *not* extract any data if the mz-iterator is already
* passed the mz value given. It is thus critically important to provide
* all mz values to be extracted in ascending order!
*
*/
void extract_value_tophat(const std::vector<double>::const_iterator& mz_start,
std::vector<double>::const_iterator& mz_it,
const std::vector<double>::const_iterator& mz_end,
std::vector<double>::const_iterator& int_it,
const double mz,
double& integrated_intensity,
const double mz_extraction_window,
const bool ppm);
/**
* @brief Extract the next m/z value and add the integrated intensity to integrated_intensity.
*
* This function will sum up all intensities within a two-dimensional
* window of mass-to-charge and ion mobility. It will extract around mz +/-
* mz_extract_window / 2.0 and im +/- im_extraction_window / 2.0 and add
* the result to integrated_intensity.
*
* @param[in] mz_start Start of the spectrum (m/z coordinates)
* @param[in,out] mz_it Current m/z position (will be modified)
* @param[in] mz_end End of the spectrum (m/z coordinates)
* @param[in,out] int_it Current intensity position (will be modified)
* @param[out] im_it Current ion mobility position (will be modified)
* @param[out] mz Target m/z for the current ion
* @param[out] im Target ion mobility for the current ion
* @param[out] integrated_intensity Resulting intensity (will be overwritten)
* @param[in] mz_extraction_window Extracts a window of this size in m/z
* dimension (e.g. a window of 50 ppm means an extraction of 25 ppm on
* either side)
* @param[in] im_extraction_window Extracts a window of this size in ion mobility dimension.
* @param[in] ppm Whether the parameter mz_extraction_window is given in ppm or Th
*
* @note This function will change the position of the iterators mz_it,
* int_it and im_it and it can *not* extract any data if the mz-iterator is
* already passed the mz value given. It is thus critically important to
* provide all mz values to be extracted in ascending order!
*
*/
void extract_value_tophat(const std::vector<double>::const_iterator& mz_start,
std::vector<double>::const_iterator& mz_it,
const std::vector<double>::const_iterator& mz_end,
std::vector<double>::const_iterator& int_it,
std::vector<double>::const_iterator& im_it,
const double mz,
const double im,
double& integrated_intensity,
const double mz_extraction_window,
const double im_extraction_window,
const bool ppm);
private:
int getFilterNr_(const String& filter);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/OPENSWATH/TargetedSpectraExtractor.h | .h | 24,850 | 621 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Douglas McCloskey, Pasquale Domenico Colaianni $
// $Authors: Douglas McCloskey, Pasquale Domenico Colaianni $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/config.h> // OPENMS_DLLAPI
#include <OpenMS/ANALYSIS/TARGETED/TargetedExperiment.h>
#include <OpenMS/COMPARISON/BinnedSpectralContrastAngle.h>
#include <OpenMS/KERNEL/BinnedSpectrum.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/KERNEL/FeatureMap.h>
namespace OpenMS
{
/**
@brief This class filters, annotates, picks, and scores spectra (e.g., taken
from a DDA experiment) based on a target list.
The input experiment is expected to be a standard .mzML file.
The input target list is expected to be a standard TraML formatted .csv file.
The class deals with filtering and annotating only those spectra that reflect
the characteristics described by the target list.
The filtering is done based on the transition_name, PrecursorMz and RetentionTime.
The spectra are smoothed and peaks are picked for each spectrum.
The spectra are then scored based on total TIC, FWHM and SNR.
One spectrum is chosen for each of those transitions for which at least one
valid spectrum was found and matched.
@section TargetedSpectraExtractor_workflow Workflow
The user can decide to use only extractSpectra() for the full pipeline, or run
the methods individually in the following order:
1. annotateSpectra() - Match spectra to targets by precursor MZ and RT
2. pickSpectrum() - Smooth and pick peaks (called for each spectrum)
3. scoreSpectra() - Score by TIC, FWHM, SNR with configurable weights
4. selectSpectra() - Choose the best spectrum per transition
@section TargetedSpectraExtractor_library Spectral Library Matching
The class also provides spectral library matching capabilities:
- matchSpectrum() - Compare against a spectral library
- targetedMatching() - Bulk library search for targeted spectra
- untargetedMatching() - Bulk library search for unprocessed spectra
@section TargetedSpectraExtractor_params Key Parameters
| Parameter | Description |
|-----------|-------------|
| rt_window | Retention time tolerance for matching |
| mz_tolerance | Precursor m/z tolerance |
| peak_height_min/max | Peak intensity bounds |
| fwhm_threshold | Minimum peak width |
| tic_weight, fwhm_weight, snr_weight | Scoring weights |
| min_select_score | Minimum score for selection |
@see MRMFeatureFilter for downstream QC filtering
@see AbsoluteQuantitation for downstream quantitation
@ingroup TargetedQuantitation
*/
class OPENMS_DLLAPI TargetedSpectraExtractor :
public DefaultParamHandler
{
public:
TargetedSpectraExtractor();
~TargetedSpectraExtractor() override = default;
/**
Structure for a match against a spectral library
TODO: Replace with MzTab once the final implementation is done
*/
struct Match
{
Match() = default;
Match(MSSpectrum a, double b) : spectrum(std::move(a)), score(b) {}
MSSpectrum spectrum;
double score = 0.0;
};
class OPENMS_DLLAPI Comparator
{
public:
virtual ~Comparator() = default;
virtual void generateScores(
const MSSpectrum& spec,
std::vector<std::pair<Size,double>>& scores,
double min_score
) const = 0;
virtual void init(
const std::vector<MSSpectrum>& library,
const std::map<String,DataValue>& options
) = 0;
const std::vector<MSSpectrum>& getLibrary() const
{
return library_;
}
protected:
std::vector<MSSpectrum> library_;
};
class OPENMS_DLLAPI BinnedSpectrumComparator : public Comparator
{
public:
~BinnedSpectrumComparator() override = default;
void generateScores (
const MSSpectrum& spec,
std::vector<std::pair<Size,double>>& scores,
double min_score
) const override
{
scores.clear();
const BinnedSpectrum in_bs(spec, bin_size_, false, peak_spread_, bin_offset_);
for (Size i = 0; i < bs_library_.size(); ++i)
{
const double cmp_score = cmp_bs_(in_bs, bs_library_[i]);
if (cmp_score >= min_score)
{
scores.emplace_back(i, cmp_score);
}
}
}
void init(const std::vector<MSSpectrum>& library, const std::map<String,DataValue>& options) override;
private:
BinnedSpectralContrastAngle cmp_bs_;
std::vector<BinnedSpectrum> bs_library_;
double bin_size_ = 0.02; // Default for nominal mass: 1.0;
UInt peak_spread_ = 0;
double bin_offset_ = 0.0; // Default for nominal mass resolution: 0.4;
};
void getDefaultParameters(Param& params) const;
/**
@brief Filters and annotates those spectra that could potentially match the
transitions of the target list.
The spectra taken into account are those that fall within the precursor RT
window and MZ tolerance set by the user through the parameters "rt_window"
and "mz_tolerance". Default values are provided for both parameters.
@warning The picked spectrum could be empty, meaning no peaks were found.
@param[in] spectra The spectra to filter
@param[in] targeted_exp The target list
@param[out] annotated_spectra The spectra annotated with the related transition's name
@param[out] features A FeatureMap which will contain informations about the name, precursor RT and precursor MZ of the matched transition
@param[in] compute_features If false, `features` will be ignored
*/
void annotateSpectra(
const std::vector<MSSpectrum>& spectra,
const TargetedExperiment& targeted_exp,
std::vector<MSSpectrum>& annotated_spectra,
FeatureMap& features,
bool compute_features = true
) const;
/**
@brief Filters and annotates those spectra that could potentially match the
transitions of the target list.
The spectra taken into account are those that fall within the precursor RT
window and MZ tolerance set by the user through the parameters "rt_window"
and "mz_tolerance". Default values are provided for both parameters.
@warning The picked spectrum could be empty, meaning no peaks were found.
@param[in] spectra The spectra to filter
@param[in] targeted_exp The target list
@param[out] annotated_spectra The spectra annotated with the related transition's name
*/
void annotateSpectra(
const std::vector<MSSpectrum>& spectra,
const TargetedExperiment& targeted_exp,
std::vector<MSSpectrum>& annotated_spectra
) const;
/**
@brief Annotates the MS2 spectra with the likely MS1 feature that it was derived from
Annotating based on MS1 feature results from AccurateMassSearch.
In this case, the input will be e.g., const FeatureMap& ms1_features and the RTs and names (i.e., PeptideRef),
defined in the FeatureMap.
@param[in] spectra The spectra to filter
@param[in] ms1_features The MS1 features
@param[out] ms2_features The MS2 features
@param[out] annotated_spectra The resulting annotated spectra
*/
void annotateSpectra(
const std::vector<MSSpectrum>& spectra,
const FeatureMap& ms1_features,
FeatureMap& ms2_features,
std::vector<MSSpectrum>& annotated_spectra) const;
/**
@brief Search accurate masses and add identification (peptide hits) as features/sub-features
@param[in] feat_map The feature map to search in
@param[out] feat_map_output The output feature map, with peptide identifaction as sub features
@param[in] add_unidentified_features Adds unidentified features to the feature map
*/
void searchSpectrum(
OpenMS::FeatureMap& feat_map,
OpenMS::FeatureMap& feat_map_output,
bool add_unidentified_features = false) const;
/**
@brief Picks a spectrum's peaks and saves them in picked_spectrum.
The spectrum is first smoothed with a Gaussian filter (default) or using the
Savitzky-Golay method. The parameter "use_gauss" handles this choice.
The peak picking is executed with PeakPickerHiRes.
Custom parameters provided with the prefix "GaussFilter:", "SavitzkyGolayFilter:"
and "PeakPickerHiRes:" are taken into account.
Peaks are then filtered by their heights and FWHM values.
It is possible to set the peaks' limits through the parameters: "peak_height_min",
"peak_height_max" and "fwhm_threshold".
@throw Exception::IllegalArgument If `spectrum` is not sorted by position (mz).
@param[in] spectrum The input spectrum
@param[out] picked_spectrum A spectrum containing only the picked peaks
*/
void pickSpectrum(const MSSpectrum& spectrum, MSSpectrum& picked_spectrum) const;
/**
@brief Assigns a score to the spectra given an input and saves them in scored_spectra.
Also add the informations to the FeatureMap first constructed in annotateSpectra().
The scores are based on total TIC, SNR and FWHM. It is possible to assign a
weight to these parameters using: "tic_weight", "fwhm_weight" and "snr_weight".
For each spectrum, the TIC and the SNR are computed on the entire spectrum.
The FWHMs are computed only on picked peaks. Both SNR and FWHM are averaged values.
The informations are added as FloatDataArray in scored_spectra and as MetaValue in features.
@throw Exception::InvalidSize If `features` and `annotated_spectra` sizes don't match.
@param[in] annotated_spectra The annotated spectra to score (for TIC and SNR)
@param[in] picked_spectra The picked peaks found on each of the annotated spectra (for FWHM)
@param[in,out] features The score informations are also added to this FeatureMap. Picked peaks' FWHMs are saved in features' subordinates.
@param[out] scored_spectra The scored spectra. Basically a copy of annotated_spectra with the added score informations
@param[in] compute_features If false, `features` will be ignored
*/
void scoreSpectra(
const std::vector<MSSpectrum>& annotated_spectra,
const std::vector<MSSpectrum>& picked_spectra,
FeatureMap& features,
std::vector<MSSpectrum>& scored_spectra,
bool compute_features = true
) const;
/**
@brief Assigns a score to the spectra given an input and saves them in scored_spectra.
Also add the informations to the FeatureMap first constructed in annotateSpectra().
The scores are based on total TIC, SNR and FWHM. It is possible to assign a
weight to these parameters using: "tic_weight", "fwhm_weight" and "snr_weight".
For each spectrum, the TIC and the SNR are computed on the entire spectrum.
The FWHMs are computed only on picked peaks. Both SNR and FWHM are averaged values.
@param[in] annotated_spectra The annotated spectra to score (for TIC and SNR)
@param[in] picked_spectra The picked peaks found on each of the annotated spectra (for FWHM)
@param[out] scored_spectra The scored spectra. Basically a copy of annotated_spectra with the added score informations
*/
void scoreSpectra(
const std::vector<MSSpectrum>& annotated_spectra,
const std::vector<MSSpectrum>& picked_spectra,
std::vector<MSSpectrum>& scored_spectra
) const;
/**
@brief The method selects the highest scoring spectrum for each possible
annotation (i.e., transition name)
@throw Exception::InvalidSize If `scored_spectra` and `features` sizes don't match.
@param[in] scored_spectra Input annotated and scored spectra
@param[in] features Input features
@param[out] selected_spectra Output selected spectra
@param[out] selected_features Output selected features
@param[in] compute_features If false, `selected_features` will be ignored
*/
void selectSpectra(
const std::vector<MSSpectrum>& scored_spectra,
const FeatureMap& features,
std::vector<MSSpectrum>& selected_spectra,
FeatureMap& selected_features,
bool compute_features = true
) const;
/**
@brief The method selects the highest scoring spectrum for each possible
annotation (i.e., transition name)
@param[in] scored_spectra Input annotated and scored spectra
@param[out] selected_spectra Output selected spectra
*/
void selectSpectra(
const std::vector<MSSpectrum>& scored_spectra,
std::vector<MSSpectrum>& selected_spectra
) const;
/**
@brief Combines the functionalities given by all the other methods implemented
in this class.
The method expects an experiment and a target list in input,
and constructs the extracted spectra and features.
For each transition of the target list, the method tries to find its best
spectrum match. A FeatureMap is also filled with informations about the
extracted spectra.
@param[in] experiment The input experiment
@param[in] targeted_exp The target list
@param[out] extracted_spectra The spectra related to the transitions
@param[out] extracted_features The features related to the output spectra
@param[in] compute_features If false, `extracted_features` will be ignored
*/
void extractSpectra(
const MSExperiment& experiment,
const TargetedExperiment& targeted_exp,
std::vector<MSSpectrum>& extracted_spectra,
FeatureMap& extracted_features,
bool compute_features = true
) const;
/**
@brief Combines the functionalities given by all the other methods implemented
in this class.
The method expects an experiment and a target list in input,
and constructs the extracted spectra.
For each transition of the target list, the method tries to find its best
spectrum match.
@param[in] experiment The input experiment
@param[in] targeted_exp The target list
@param[out] extracted_spectra The spectra related to the transitions
*/
void extractSpectra(
const MSExperiment& experiment,
const TargetedExperiment& targeted_exp,
std::vector<MSSpectrum>& extracted_spectra
) const;
/**
@brief Combines the functionalities given by all the other methods implemented
in this class.
The method expects an experiment and MS1 features in input,
and constructs the extracted spectra and features.
For each transition of the target list, the method tries to find its best
spectrum match. A FeatureMap is also filled with informations about the
extracted spectra.
@param[in] experiment The input experiment
@param[in] ms1_features The MS1 features map
@param[out] extracted_spectra The spectra related to the transitions
*/
void extractSpectra(
const MSExperiment& experiment,
const FeatureMap& ms1_features,
std::vector<MSSpectrum>& extracted_spectra
) const;
/**
@brief Combines the functionalities given by all the other methods implemented
in this class.
The method expects an experiment and MS1 features in input,
and constructs the extracted spectra and features.
For each transition of the target list, the method tries to find its best
spectrum match. A FeatureMap is also filled with informations about the
extracted spectra.
@param[in] experiment The input experiment
@param[in] ms1_features The MS1 features map
@param[out] extracted_spectra The spectra related to the transitions
@param[out] extracted_features The features related to the output spectra
*/
void extractSpectra(
const MSExperiment& experiment,
const FeatureMap& ms1_features,
std::vector<MSSpectrum>& extracted_spectra,
FeatureMap& extracted_features
) const;
/**
@brief Searches the spectral library for the top scoring candidates that
match the input spectrum.
@param[in] input_spectrum The input spectrum for which a match is desired
@param[in] cmp The comparator object containing the library and the logic for matching
@param[out] matches A vector of `Match`es, containing the matched spectra and their scores
*/
void matchSpectrum(
const MSSpectrum& input_spectrum,
const Comparator& cmp,
std::vector<Match>& matches
) const;
/**
@brief Compares a list of spectra against a spectral library and updates
the related features.
The metavalues added to each `Feature` within the `FeatureMap` are:
- spectral_library_name The name of the match's spectrum found in the library
- spectral_library_score The match score [0-1]
- spectral_library_comments The comments for the match's spectrum
If a match for a given input spectrum is not found, the metavalues will be
assigned a default value:
- spectral_library_name and spectral_library_comments: an empty string
- spectral_library_score: a value of 0.0
@note The input `spectra` (and related `features`) are assumed to be the
result of `extractSpectra()`, meaning they went (at least) through the process
of peak picking.
@param[in] spectra The input spectra
@param[in] cmp The `Comparator` object containing the spectral library
@param[in,out] features The `FeatureMap` to be updated with matching info
*/
void targetedMatching(
const std::vector<MSSpectrum>& spectra,
const Comparator& cmp,
FeatureMap& features
);
/**
@brief Compares a list of spectra against a spectral library and creates
a `FeatureMap` with the relevant information.
The metavalues added to each `Feature` within the `FeatureMap` are:
- spectral_library_name The name of the match's spectrum found in the library
- spectral_library_score The match score [0-1]
- spectral_library_comments The comments for the match's spectrum
If a match for a given input spectrum is not found, the metavalues will be
assigned a default value:
- spectral_library_name and spectral_library_comments: an empty string
- spectral_library_score: a value of 0.0
@note The input `spectra` (and related `features`) are assumed to be unprocessed,
therefore undergoing a process of peak picking during execution of this method.
@param[in] spectra The input spectra
@param[in] cmp The `Comparator` object containing the spectral library
@param[out] features The `FeatureMap` to be filled with matching info
*/
void untargetedMatching(
const std::vector<MSSpectrum>& spectra,
const Comparator& cmp,
FeatureMap& features
);
/**
@brief compute transitions list from MS1 and the associated MS2 features
@param[in] ms1_features the MS1 features
@param[in] ms2_features the MS2 features
@param[out] t_exp the targeted experiment, containing the transitions
*/
void constructTransitionsList(const OpenMS::FeatureMap& ms1_features, const OpenMS::FeatureMap& ms2_features, TargetedExperiment& t_exp) const;
/**
@brief store spectra in MSP format
@param[in] filename the filename of the file to write
@param[in] experiment the experiment to store
*/
void storeSpectraMSP(const String& filename, MSExperiment& experiment) const;
/**
@brief organize into a map by combining features and subordinates with the same `identifier`
@param[in] fmap_input input features map
@param[in] fmap_output output features map
*/
void mergeFeatures(const OpenMS::FeatureMap& fmap_input, OpenMS::FeatureMap& fmap_output) const;
protected:
/// Overridden function from DefaultParamHandler to keep members up to date, when a parameter is changed
void updateMembers_() override;
/// Deisotope MS2 spectra
void deisotopeMS2Spectra_(MSExperiment& experiment) const;
/// Remove peaks form MS2 which are at a higher mz than the precursor + 10 ppm
void removeMS2SpectraPeaks_(MSExperiment& experiment) const;
/// organize into a map by combining features and subordinates with the same `identifier`
void organizeMapWithSameIdentifier(const OpenMS::FeatureMap& fmap_input, std::map<OpenMS::String, std::vector<OpenMS::Feature>>& fmapmap) const;
private:
/**
@brief Combines the functionalities given by all the other methods implemented
in this class.
The method expects an experiment and MS1 features in input,
and constructs the extracted spectra and features.
For each transition of the target list, the method tries to find its best
spectrum match. A FeatureMap is also filled with informations about the
extracted spectra.
@param[in] experiment The input experiment
@param[in] ms1_features The MS1 features map
@param[out] extracted_spectra The spectra related to the transitions
@param[out] extracted_features The features related to the output spectra
@param[in] compute_features If false, `extracted_features` will be ignored
*/
void extractSpectra(
const MSExperiment& experiment,
const FeatureMap& ms1_features,
std::vector<MSSpectrum>& extracted_spectra,
FeatureMap& extracted_features,
const bool compute_features
) const;
private:
/**
Unit to use for mz_tolerance_ and fwhm_threshold_: true for Da, false for ppm.
*/
bool mz_unit_is_Da_;
/**
Precursor Retention Time window used during the annotation phase.
For each transition in the target list, annotateSpectra() looks for
the first spectrum whose RT time falls within the RT Window, whose
left and right limits are computed at each analyzed spectrum.
Also the spectrum's precursor MZ is checked against the transition MZ.
*/
double rt_window_;
/**
Precursor MZ tolerance used during the annotation phase.
For each transition in the target list, annotateSpectra() looks for
the first spectrum whose precursor MZ is close enough (+-mz_tolerance_)
to the transition's MZ.
Also the spectrum's precursor RT is checked against the transition RT.
*/
double mz_tolerance_;
/**
Used in pickSpectrum(), a peak's intensity needs to be >= peak_height_min_
for it to be picked.
*/
double peak_height_min_;
/**
Used in pickSpectrum(), a peak's intensity needs to be <= peak_height_max_
for it to be picked.
*/
double peak_height_max_;
/**
Used in pickSpectrum(), a peak's FWHM needs to be >= fwhm_threshold_
for it to be picked.
*/
double fwhm_threshold_;
double tic_weight_; /**< Total TIC's weight when computing a spectrum's score */
double fwhm_weight_; /**< FWHM's weight when computing a spectrum's score */
double snr_weight_; /**< SNR's weight when computing a spectrum's score */
/**
Used in selectSpectra(), after the spectra have been assigned a score.
Remained transitions will have at least one spectrum assigned.
Each spectrum needs to have a score >= min_select_score_ to be valid,
otherwise it gets filtered out.
*/
double min_select_score_;
/**
Used in pickSpectrum(), it selects which filtering method is used during
the smoothing phase.
By default the Gauss filter is selected. Set to false for the Savitzky-Golay method.
*/
bool use_gauss_;
/**
The number of matches to output from `matchSpectrum()`.
These will be the matches of highest scores, sorted in descending order.
*/
Size top_matches_to_report_;
/// Minimum score for a match to be considered valid in `matchSpectrum()`.
double min_match_score_;
double min_fragment_mz_;
double max_fragment_mz_;
double relative_allowable_product_mass_;
bool deisotoping_use_deisotoper_;
double deisotoping_fragment_tolerance_;
std::string deisotoping_fragment_unit_;
int deisotoping_min_charge_;
int deisotoping_max_charge_;
int deisotoping_min_isopeaks_;
int deisotoping_max_isopeaks_;
bool deisotoping_keep_only_deisotoped_;
bool deisotoping_annotate_charge_;
double max_precursor_mass_threashold_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/OPENSWATH/SwathQC.h | .h | 5,436 | 145 | // 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/OPENSWATHALGO/DATAACCESS/SwathMap.h>
#include <OpenMS/OpenMSConfig.h>
#include <functional>
#include <map>
#include <vector>
namespace OpenMS
{
class String;
class MSSpectrum;
class ExperimentalSettings;
}
namespace OpenSwath
{
/**
@brief Quality Control function for OpenSwath
The class is meant to collect information as a plugin of type IMSDataConsumer.
You can (if the relevant data is already available and you do not mind the overhead), call
static functions, which will do the same.
*/
class OPENMS_DLLAPI SwathQC
{
public:
typedef std::map<int,int> ChargeDistribution;
/// default C'tor (forbidden)
SwathQC() = delete;
/**
@brief CTor with arguments
@param[in] cd_spectra Number of MS spectra to inspect for charge distribution estimation
@param[in] decon_ms1_mz_tol m/z tolerance for isotope deconvolution
*/
SwathQC(const size_t cd_spectra, const double decon_ms1_mz_tol);
/**
@brief Returns a lambda function, which captures internal members and can be used in MSDataTransformingConsumer::setExperimentalSettingsFunc()
If @p es contains a metavalue 'nr_ms1_spectra' it will be used to set the internal number of expected MS1 spectra
*/
std::function<void(const OpenMS::ExperimentalSettings& es)> getExpSettingsFunc();
/// returns a lambda function, which captures internal members and can be used in MSDataTransformingConsumer::setExperimentalSettingsFunc()
/// PeakPicking is performed internally if the data is estimated to be profile data.
/// Uses the Deisotoper class for charge determination and updates the internal charge count.
std::function<void (const OpenMS::MSSpectrum&)> getSpectraProcessingFunc();
/**
@brief Sample the spectra in all MS1 Swath maps and determine all charge states.
Conveniently wraps internal functions and applies them to a whole set of data.
However, it might be more speed efficient to sample the spectra as they are loaded using member functions.
From all swath maps in @p swath_maps which are ms_level == 1 we extract @p nr_samples spectra (subsampling),
determine the charge states of all isotopic envelopes and return their total counts
using getSpectraProcessingFunc().
@param[in] swath_maps Swath maps of mixed ms-level
@param[in] nr_samples Number of spectra to sample per Swath map. To sample all spectra, set to -1
@param[in] mz_tol Error tolerance in Th in which an isotopic peak is expected (assuming C12-C13 distance)
@return Distribution of charge (key = charge, value = counts)
@throw Exception::Postcondition if Deisotoper did not return charge data
*/
static ChargeDistribution getChargeDistribution(const std::vector<SwathMap>& swath_maps, const size_t nr_samples, const double mz_tol);
/**
@brief Save all internally collected data to a JSON file.
*/
void storeJSON(const OpenMS::String& filename);
/**
@brief returns the charge distribution which was internally computed by applying getSpectraProcessingFunc() externally
*/
const ChargeDistribution& getChargeDistribution() const;
/**
@brief Explicitly set the number of expected MS1 spectra (for sampling charge distribution)
Computing the charge distribution using getSpectraProcessingFunc() requires knowing the total number of MS1 spectra.
Either use getExpSettingsFunc() externally, or use this method to set it explicitly (depending on workflow).
If @p nr is set to 0, all spectra passed into getSpectraProcessingFunc() will be inspected for their charge distribution.
*/
void setNrMS1Spectra(size_t nr);
protected:
/**
@brief Given a total spectrum count and a number of spectra to inspect, is the current index a candidate?
Allows to uniformly sample a range of spectra.
E.g. given 10 spectra exist, and we want to subsample 4 of them, the answer of this function for every
requested index from 0..9 is:
If the total number of spectra is unknown, pass 0 as first argument, which will return true for every query, i.e. sample everything.
@param[in] total_spec_count Total number of spectra expected
@param[in] subsample_count Number of spectra which should be sampled from @p total_spec_count
@param[in] idx Index of the spectrum under question
*/
static bool isSubsampledSpectrum_(const size_t total_spec_count, const size_t subsample_count, const size_t idx);
private:
/// internal ChargeDistribution which is augmented upon calling the corresponding member functions
ChargeDistribution cd_;
/// number of MS1 spectra expected
size_t nr_ms1_spectra_;
/// number of spectra to inspect for charge distribution
size_t cd_spectra_;
/// m/z tolerance for isotope deconvolution
double decon_ms1_mz_tol_;
/// keeps track of number of spectra passed to getSpectraProcessingFunc()
size_t ms1_spectra_seen_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/OPENSWATH/MRMRTNormalizer.h | .h | 7,837 | 166 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: George Rosenberger $
// $Authors: George Rosenberger, Hannes Roest $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/config.h>
#include <cstddef> // for size_t & ptrdiff_t
#include <vector>
#include <string>
namespace OpenMS
{
/**
@brief The MRMRTNormalizer will find retention time peptides in data.
This tool will take a description of RT peptides and their normalized
retention time to write out a transformation file on how to transform the
RT space into the normalized space.
The principle is adapted from the following publication:
Escher, C. et al. (2012), Using iRT, a normalized retention time for more
targeted measurement of peptides. Proteomics, 12: 1111-1121.
*/
class OPENMS_DLLAPI MRMRTNormalizer
{
protected:
/**
@brief This function computes a candidate outlier peptide by iteratively
leaving one peptide out to find the one which results in the maximum R^2
of a first order linear regression of the remaining ones. The data points
are submitted as two vectors of doubles (x- and y-coordinates).
@return The position of the candidate outlier peptide as supplied by the
vector is returned.
@exception Exception::UnableToFit is thrown if fitting cannot be performed
*/
static int jackknifeOutlierCandidate_(const std::vector<double>& x, const std::vector<double>& y);
/**
@brief This function computes a candidate outlier peptide by computing
the residuals of all points to the linear fit and selecting the one with
the largest deviation. The data points are submitted as two vectors of
doubles (x- and y-coordinates).
@return The position of the candidate outlier peptide as supplied by the
vector is returned.
@exception Exception::UnableToFit is thrown if fitting cannot be performed
*/
static int residualOutlierCandidate_(const std::vector<double>& x, const std::vector<double>& y);
public:
/**
@brief This function removes potential outliers in a linear regression dataset.
Two thresholds need to be defined, first a lower R^2 limit to accept the
regression for the RT normalization and second, the lower limit of peptide
coverage. The algorithms then selects candidate outlier peptides using the
RANSAC outlier detection algorithm and returns the corrected set of peptides
if the two thresholds are satisfied.
@param[in] pairs Input data (paired data of type <experimental_rt, theoretical_rt>)
@param[in] rsq_limit Minimal R^2 required
@param[in] coverage_limit Minimal coverage required (if the number of points
falls below this fraction, the algorithm aborts)
@param[in] max_iterations Maximum iterations for the RANSAC algorithm
@param[in] max_rt_threshold Maximum deviation from fit for the retention time.
This must be in the unit of the second dimension (e.g. theoretical_rt).
@param[in] sampling_size The number of data points to sample for the RANSAC algorithm.
@return A vector of pairs is returned if the R^2 limit was reached without
reaching the coverage limit. If the limits are reached, an exception is
thrown.
@exception Exception::UnableToFit is thrown if fitting cannot be
performed (rsq_limit and coverage_limit cannot be fulfilled)
*/
static std::vector<std::pair<double, double> > removeOutliersRANSAC(const std::vector<std::pair<double, double> >& pairs,
double rsq_limit,
double coverage_limit,
size_t max_iterations,
double max_rt_threshold,
size_t sampling_size);
/**
@brief This function removes potential outliers in a linear regression dataset.
Two thresholds need to be defined, first a lower R^2 limit to accept the
regression for the RT normalization and second, the lower limit of peptide
coverage. The algorithms then selects candidate outlier peptides and applies
the Chauvenet's criterion on the assumption that the residuals are normal
distributed to determine whether the peptides can be removed. This is done
iteratively until both limits are reached.
@param[in] pairs Input data (paired data of type <experimental_rt, theoretical_rt>)
@param[in] rsq_limit Minimal R^2 required
@param[in] coverage_limit Minimal coverage required (the number of points
falls below this fraction, the algorithm aborts)
@param[in] use_chauvenet Whether to only remove outliers that fulfill
Chauvenet's criterion for outliers (otherwise it will remove any outlier
candidate regardless of the criterion)
@param[in] method Outlier detection method ("iter_jackknife" or "iter_residual")
@return A vector of pairs is returned if the R^2 limit was reached without
reaching the coverage limit. If the limits are reached, an exception is
thrown.
@exception Exception::UnableToFit is thrown if fitting cannot be
performed (rsq_limit and coverage_limit cannot be fulfilled)
*/
static std::vector<std::pair<double, double> > removeOutliersIterative(const std::vector<std::pair<double, double> >& pairs,
double rsq_limit,
double coverage_limit,
bool use_chauvenet,
const std::string& method);
/**
@brief This function computes Chauvenet's criterion probability for a vector
and a value whose position is submitted.
@return Chauvenet's criterion probability
*/
static double chauvenet_probability(const std::vector<double>& residuals, int pos);
/**
@brief This function computes Chauvenet's criterion for a vector and a value
whose position is submitted.
@return TRUE, if Chauvenet's criterion is fulfilled and the outlier can be removed.
*/
static bool chauvenet(const std::vector<double>& residuals, int pos);
/**
* @brief Computes coverage of the RT normalization peptides over the whole RT range, ensuring that each bin has enough peptides
*
* @param[in] rtRange The (estimated) full RT range in iRT space (theoretical RT)
* @param[in] pairs The RT normalization peptide pairs (pair = experimental RT / theoretical RT)
* @param[in] nrBins The number of bins to be used
* @param[in] minPeptidesPerBin The minimal number of peptides per bin to be used to be considered full
* @param[in] minBinsFilled The minimal number of bins needed to be full
*
* @return Whether more than the minimal number of bins are covered
*
*/
static bool computeBinnedCoverage(const std::pair<double,double> & rtRange,
const std::vector<std::pair<double, double> > & pairs,
int nrBins,
int minPeptidesPerBin,
int minBinsFilled);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/OPENSWATH/PeakPickerChromatogram.h | .h | 4,722 | 153 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hannes Roest $
// $Authors: Hannes Roest $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/KERNEL/MSSpectrum.h>
#include <OpenMS/KERNEL/MSChromatogram.h>
#include <OpenMS/KERNEL/ChromatogramPeak.h>
#include <OpenMS/PROCESSING/NOISEESTIMATION/SignalToNoiseEstimatorMedian.h>
#include <OpenMS/PROCESSING/SMOOTHING/SavitzkyGolayFilter.h>
#include <OpenMS/PROCESSING/SMOOTHING/GaussFilter.h>
#include <OpenMS/PROCESSING/CENTROIDING/PeakPickerHiRes.h>
#ifdef WITH_CRAWDAD
#include <CrawdadWrapper.h>
#endif
namespace OpenMS
{
/**
@brief The PeakPickerChromatogram finds peaks a single chromatogram.
@htmlinclude OpenMS_PeakPickerChromatogram.parameters
It uses the PeakPickerHiRes internally to find interesting seed candidates.
These candidates are then expanded and a right/left border of the peak is
searched.
Additionally, overlapping peaks can be removed.
*/
class OPENMS_DLLAPI PeakPickerChromatogram :
public DefaultParamHandler
{
public:
//@{
/// Constructor
PeakPickerChromatogram();
/// Destructor
~PeakPickerChromatogram() override {}
//@}
/// indices into FloatDataArrays of resulting picked chromatograms
enum FLOATINDICES { IDX_FWHM = 0, IDX_ABUNDANCE = 1, IDX_LEFTBORDER = 2, IDX_RIGHTBORDER = 3, SIZE_OF_FLOATINDICES };
/**
@brief Finds peaks in a single chromatogram and annotates left/right borders
It uses a modified algorithm of the PeakPickerHiRes
This function will return a picked chromatogram
*/
void pickChromatogram(const MSChromatogram& chromatogram, MSChromatogram& picked_chrom);
/**
@brief Finds peaks in a single chromatogram and annotates left/right borders
It uses a modified algorithm of the PeakPickerHiRes
This function will return a picked chromatogram and a smoothed chromatogram
*/
void pickChromatogram(const MSChromatogram& chromatogram, MSChromatogram& picked_chrom, MSChromatogram& smoothed_chrom);
protected:
void pickChromatogramCrawdad_(const MSChromatogram& chromatogram, MSChromatogram& picked_chrom);
void pickChromatogram_(const MSChromatogram& chromatogram, MSChromatogram& picked_chrom);
/**
@brief Compute peak area (peak integration)
*/
void integratePeaks_(const MSChromatogram& chromatogram);
/**
@brief Helper function to find the closest peak in a chromatogram to "target_rt"
The search will start from the index current_peak, so the function is
assuming the closest peak is to the right of current_peak.
It will return the index of the closest peak in the chromatogram.
*/
Size findClosestPeak_(const MSChromatogram& chromatogram, double target_rt, Size current_peak = 0);
/**
@brief Helper function to remove overlapping peaks in a single Chromatogram
*/
void removeOverlappingPeaks_(const MSChromatogram& chromatogram, MSChromatogram& picked_chrom);
/// Synchronize members with param class
void updateMembers_() override;
/// Assignment operator is protected for algorithm
PeakPickerChromatogram& operator=(const PeakPickerChromatogram& rhs);
// Members
/// Frame length for the SGolay smoothing
UInt sgolay_frame_length_;
/// Polynomial order for the SGolay smoothing
UInt sgolay_polynomial_order_;
/// Width of the Gaussian smoothing
double gauss_width_;
/// Whether to use Gaussian smoothing
bool use_gauss_;
/// Whether to resolve overlapping peaks
bool remove_overlapping_;
/// Forced peak with
double peak_width_;
/// Signal to noise threshold
double signal_to_noise_;
/// Signal to noise window length
double sn_win_len_;
/// Signal to noise bin count
UInt sn_bin_count_;
/// Whether to write out log messages of the SN estimator
bool write_sn_log_messages_;
/// Peak picker method
String method_;
/// Temporary vector to hold the integrated intensities
std::vector<double> integrated_intensities_;
/// Temporary vector to hold the peak left widths
std::vector<int> left_width_;
/// Temporary vector to hold the peak right widths
std::vector<int> right_width_;
PeakPickerHiRes pp_;
SavitzkyGolayFilter sgolay_;
GaussFilter gauss_;
SignalToNoiseEstimatorMedian<MSChromatogram > snt_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/OPENSWATH/MRMFeatureSelector.h | .h | 11,706 | 320 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Douglas McCloskey, Pasquale Domenico Colaianni, Svetlana Kutuzova $
// $Authors: Douglas McCloskey, Pasquale Domenico Colaianni, Svetlana Kutuzova $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/config.h> // OPENMS_DLLAPI
#include <OpenMS/DATASTRUCTURES/LPWrapper.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/KERNEL/FeatureMap.h>
namespace OpenMS
{
/**
@brief A base class for selection of MRM Features through Linear Programming optimization.
This class provides the framework for optimal feature selection in MRM/SRM experiments
using Linear Programming (LP). The key idea is to select the best peak for each transition
while maintaining consistency with neighboring transitions based on retention time relationships.
Two derived implementations are provided:
- @ref MRMFeatureSelectorQMIP - Uses Quadratic Mixed Integer Programming based on relative RT
- @ref MRMFeatureSelectorScore - Uses score-weighted linear programming
@section MRMFeatureSelector_algorithm Algorithm Overview
1. Features are sorted by retention time
2. The RT range is divided into overlapping segments (sliding window)
3. For each segment, an LP problem is formulated and solved
4. Solutions from segments are merged to produce final selection
@section MRMFeatureSelector_params Key Parameters
- `nn_threshold`: Number of nearest neighbors to include in optimization
- `segment_window_length`: Size of sliding window
- `segment_step_length`: Step size between windows
- `variable_type`: INTEGER (exact) or CONTINUOUS (relaxed) LP
- `optimal_threshold`: Cutoff for considering a feature as selected (0-1)
- `score_weights`: Weights for different scoring functions (LINEAR, LOG, INVERSE, etc.)
@see MRMBatchFeatureSelector for iterative batch processing
@see LPWrapper for the underlying LP solver interface
@ingroup TargetedQuantitation
*/
class OPENMS_DLLAPI MRMFeatureSelector
{
public:
MRMFeatureSelector() = default;
virtual ~MRMFeatureSelector() = default;
enum class VariableType
{
INTEGER = 1,
CONTINUOUS
};
enum class LambdaScore
{
LINEAR = 1,
INVERSE,
LOG,
INVERSE_LOG,
INVERSE_LOG10
};
/// To test private and protected methods
friend class MRMFeatureSelector_test;
/**
Structure to easily feed the parameters to the `MRMFeatureSelector` derived classes
*/
struct SelectorParameters
{
SelectorParameters() = default;
SelectorParameters(
Int nn,
bool lw,
bool stg,
Int swl,
Int ssl,
MRMFeatureSelector::VariableType vt,
double ot,
std::map<String, MRMFeatureSelector::LambdaScore>& sw
) :
nn_threshold(nn),
locality_weight(lw),
select_transition_group(stg),
segment_window_length(swl),
segment_step_length(ssl),
variable_type(vt),
optimal_threshold(ot),
score_weights(sw) {}
Int nn_threshold = 4; ///< Nearest neighbor threshold: the number of components or component groups to the left and right to include in the optimization problem (i.e. number of nearest compounds by Tr to include in network)
bool locality_weight = false; ///< Weight compounds with a nearer Tr greater than compounds with a further Tr
bool select_transition_group = true; ///< Use components groups instead of components for retention time optimization
Int segment_window_length = 8; ///< Number of components or component groups to include in the network
Int segment_step_length = 4; ///< Number of of components or component groups to shift the `segment_window_length` at each loop
MRMFeatureSelector::VariableType variable_type = MRMFeatureSelector::VariableType::CONTINUOUS; ///< INTEGER or CONTINUOUS
double optimal_threshold = 0.5; ///< Value above which the transition group or transition is considered optimal (0 < x < 1)
std::map<String, MRMFeatureSelector::LambdaScore> score_weights; ///< Weights for the scores
};
/**
Derived classes implement this pure virtual method.
It sets up the linear programming problem and solves it.
@param[in] time_to_name Pairs representing a mapping of retention times to transition names
@param[in] feature_name_map Transitions' names to their features objects
@param[out] result Transitions' names filtered out of the LP problem
@param[in] parameters Parameters
*/
virtual void optimize(
const std::vector<std::pair<double, String>>& time_to_name,
const std::map<String, std::vector<Feature>>& feature_name_map,
std::vector<String>& result,
const SelectorParameters& parameters
) const = 0;
/**
The features are sorted by retention time and splitted into segments with
the given step and window length. The features are then selected based on
the results of `optimize()` method applied to each segment. The segments
may overlap.
@param[in] features Input features
@param[out] selected_filtered Output features
@param[in] parameters Parameters
*/
void selectMRMFeature(
const FeatureMap& features,
FeatureMap& selected_filtered,
const SelectorParameters& parameters
) const;
protected:
/**
Add variable to the LP problem instantiated in `optimize()`
@param[in,out] problem LPWrapper object
@param[in] name Column name
@param[in] bounded Double bounded if true, otherwise Unbounded.
@param[in] obj Objective value
@param[in] variableType Either integer or continuous
@return The variable's column index
*/
Int addVariable_(
LPWrapper& problem,
const String& name,
const bool bounded,
const double obj,
const VariableType variableType
) const;
/**
Scoring method used by the optimizer. Metavalues to use are decided by
the `score_weights` argument.
The returned value is used in the LP problems' variables and constraints.
@param[in] feature Input feature
@param[in] score_weights Score weights
@return Computed score
*/
double computeScore_(const Feature& feature, const std::map<String, LambdaScore>& score_weights) const;
/**
Add constraint to the LP problem instantiated in `optimize()`
@param[in,out] problem LPWrapper object
@param[in] indices LP matrix indices
@param[in] values LP matrix values
@param[in] name Row name
@param[in] lb Lower bound
@param[in] ub Upper bound
@param[in] param Row type
*/
void addConstraint_(
LPWrapper& problem,
const std::vector<Int>& indices,
const std::vector<double>& values,
const String& name,
const double lb,
const double ub,
const LPWrapper::Type param
) const;
private:
/**
Construct the target transition's or transition group's retention times that
will be used to score candidate features based on their deviation from the
relative distance between the target transition's or transition group's times
@param[in] features Input features
@param[out] time_to_name Pairs representing a mapping of retention times to transition names
@param[out] feature_name_map Transitions' names to their features objects
@param[in] select_transition_group Transition group selection
*/
void constructTargTransList_(
const FeatureMap& features,
std::vector<std::pair<double, String>>& time_to_name,
std::map<String, std::vector<Feature>>& feature_name_map,
const bool select_transition_group
) const;
/**
Transform the given score through the chosen lambda function
Possible values for `lambda_score` are:
- LambdaScore::LINEAR
- LambdaScore::INVERSE
- LambdaScore::LOG
- LambdaScore::INVERSE_LOG
- LambdaScore::INVERSE_LOG10
@throw Exception::IllegalArgument When an invalid `lambda_score` is passed
@param[in] score Value to transform
@param[in] lambda_score A string representing the desired transformation
@return The weighted value
*/
double weightScore_(const double score, const LambdaScore lambda_score) const;
/// Removes spaces from the given string, not-in-place.
String removeSpaces_(String str) const;
};
/**
Class used to select MRMFeatures based on relative retention time using a
quadratic mixed integer programming (QMIP) formulation.
The method is described in [TODO: update when published]
*/
class OPENMS_DLLAPI MRMFeatureSelectorQMIP : public MRMFeatureSelector
{
public:
/**
Set up the linear programming problem and solve it.
@param[in] time_to_name Pairs representing a mapping of retention times to transition names
@param[in] feature_name_map Transitions' names to their features objects
@param[out] result Transitions' names filtered out of the LP problem
@param[in] parameters Parameters
*/
void optimize(
const std::vector<std::pair<double, String>>& time_to_name,
const std::map<String, std::vector<Feature>>& feature_name_map,
std::vector<String>& result,
const SelectorParameters& parameters
) const override;
};
/**
Class used to select MRMFeatures based on a linear programming where each
possible transition is weighted by a user defined score (most often retention
time and peak intensity). The method is described in [TODO: update when published].
*/
class OPENMS_DLLAPI MRMFeatureSelectorScore : public MRMFeatureSelector
{
public:
/**
Set up the linear programming problem and solve it.
@param[in] time_to_name Pairs representing a mapping of retention times to transition names
@param[in] feature_name_map Transitions' names to their features objects
@param[out] result Transitions' names filtered out of the LP problem
@param[in] parameters Parameters
*/
void optimize(
const std::vector<std::pair<double, String>>& time_to_name,
const std::map<String, std::vector<Feature>>& feature_name_map,
std::vector<String>& result,
const SelectorParameters& parameters
) const override;
};
class MRMFeatureSelector_test : public MRMFeatureSelectorQMIP
{
public:
MRMFeatureSelector_test() = default;
~MRMFeatureSelector_test() override = default;
void constructTargTransList_(
const FeatureMap& features,
std::vector<std::pair<double, String>>& time_to_name,
std::map<String, std::vector<Feature>>& feature_name_map,
const bool select_transition_group
) const
{
selector_.constructTargTransList_(features, time_to_name, feature_name_map, select_transition_group);
}
double weightScore_(const double score, const LambdaScore lambda_score) const
{
return selector_.weightScore_(score, lambda_score);
}
double computeScore_(const Feature& feature, const std::map<String, LambdaScore>& score_weights) const
{
return selector_.computeScore_(feature, score_weights);
}
String removeSpaces_(String str) const
{
return selector_.removeSpaces_(str);
}
MRMFeatureSelectorQMIP selector_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/OPENSWATH/MRMAssay.h | .h | 28,436 | 569 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: George Rosenberger $
// $Authors: George Rosenberger $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/ANALYSIS/TARGETED/TargetedExperiment.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/ANALYSIS/OPENSWATH/MRMIonSeries.h>
#include <OpenMS/CHEMISTRY/ModificationsDB.h>
#include <OpenMS/OPENSWATHALGO/DATAACCESS/TransitionExperiment.h>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int.hpp>
#include <boost/random/variate_generator.hpp>
// #define DEBUG_MRMASSAY
namespace OpenMS
{
/**
@brief Generate assays from a TargetedExperiment
Will generate assays from a raw, unfiltered TargetedExperiment, as can be
generated by TargetedFileConverter.
Transitions can be selected according to a set of rules, as described in
Schubert et al., 2015 (PMID 25675208).
In addition, unique ion signature (UIS) (Sherman et al., 2009; PMID
19556279) transitions can be generated based on empirically observed or in
silico generated ion series. This is described in detail in the IPF paper
(Rosenberger et al. 2017; PMID 28604659).
*/
class OPENMS_DLLAPI MRMAssay :
public ProgressLogger
{
public:
//@{
/// Constructor
MRMAssay(); // empty, no members
/// Destructor
~MRMAssay() override;
//@}
typedef std::vector<OpenMS::TargetedExperiment::Protein> ProteinVectorType;
typedef std::vector<OpenMS::TargetedExperiment::Peptide> PeptideVectorType;
typedef std::vector<OpenMS::TargetedExperiment::Compound> CompoundVectorType;
typedef std::vector<OpenMS::ReactionMonitoringTransition> TransitionVectorType;
typedef std::map<String, std::vector<const ReactionMonitoringTransition*> > PeptideTransitionMapType;
typedef std::map<String, std::vector<const ReactionMonitoringTransition*> > CompoundTransitionMapType;
typedef std::map<String, std::set<std::string> > ModifiedSequenceMap; ///< Maps an unmodified sequence to all its modified sequences
typedef std::map<size_t, ModifiedSequenceMap> SequenceMapT; ///< Stores the ModifiedSequenceMap for all SWATH windows (uses std::map for deterministic iteration order)
typedef std::vector<std::pair<double, std::string> > FragmentSeqMap; ///< Describes a fragment sequence map of : "fragment m/z" -> "modified sequence"
typedef std::map<size_t, std::map<String, FragmentSeqMap > > IonMapT; ///< Stores a mapping : "unmodified sequence" -> FragmentSeqMap for all SWATH windows (uses std::map for deterministic iteration order)
typedef std::vector<std::pair<std::string, double> > IonSeries; ///< Describes an ion series: "ion_type" -> "fragment m/z"
typedef std::map<String, IonSeries > PeptideMapT; ///< Maps a peptide sequence to an ion series: "ion_type" -> "fragment m/z"
typedef std::map<String, TargetedExperiment::Peptide> TargetDecoyMapT; ///< Maps the peptide id (same for target and decoy) to the decoy peptide object
/**
@brief Annotates and filters transitions in a TargetedExperiment
@param[out] exp the input, unfiltered transitions
@param[in] precursor_mz_threshold the precursor m/z threshold in Th for annotation
@param[in] product_mz_threshold the product m/z threshold in Th for annotation
@param[in] fragment_types the fragment types to consider for annotation
@param[in] fragment_charges the fragment charges to consider for annotation
@param[in] enable_specific_losses whether specific neutral losses should be considered
@param[in] enable_unspecific_losses whether unspecific neutral losses (H2O1, H3N1, C1H2N2, C1H2N1O1) should be considered
@param[in] round_decPow round product m/z values to decimal power (default: -4)
*/
void reannotateTransitions(OpenMS::TargetedExperiment& exp,
double precursor_mz_threshold,
double product_mz_threshold,
const std::vector<String>& fragment_types,
const std::vector<size_t>& fragment_charges,
bool enable_specific_losses,
bool enable_unspecific_losses,
int round_decPow = -4);
/**
@brief Restrict and filter transitions in a TargetedExperiment
@param[in] exp the input, unfiltered transitions
@param[in] lower_mz_limit the lower product m/z limit in Th
@param[in] upper_mz_limit the upper product m/z limit in Th
@param[in] swathes the swath window settings (to exclude fragment ions falling
into the precursor isolation window)
*/
void restrictTransitions(OpenMS::TargetedExperiment& exp,
double lower_mz_limit, double upper_mz_limit,
const std::vector<std::pair<double, double> >& swathes);
/**
@brief Select detecting fragment ions
@param[in] exp the input, unfiltered transitions
@param[out] min_transitions the minimum number of transitions required per assay
@param[in] max_transitions the maximum number of transitions required per assay
*/
void detectingTransitions(OpenMS::TargetedExperiment& exp, int min_transitions, int max_transitions);
/**
@brief Annotate UIS / site-specific transitions
Performs the following actions:
- Step 1: For each peptide, compute all theoretical alternative peptidoforms; see transitions generateTargetInSilicoMap_()
- Step 2: Generate target identification transitions; see generateTargetAssays_()
- Step 3a: Generate decoy sequences that share peptidoform properties with targets; see generateDecoySequences_()
- Step 3b: Generate decoy in silico peptide map containing theoretical transition; see generateDecoyInSilicoMap_()
- Step 4: Generate decoy identification transitions; see generateDecoyAssays_()
The IPF algorithm uses the concept of "identification transitions" that
are used to discriminate different peptidoforms, these are generated in
this function. In brief, the algorithm takes the existing set of
peptides and transitions and then appends these "identification
transitions" for targets and decoys. The novel transitions are set to be
non-detecting and non-quantifying and are annotated with the set of
peptidoforms to which they map.
@param[in] exp the input, unfiltered transitions
@param[in] fragment_types the fragment types to consider for annotation
@param[in] fragment_charges the fragment charges to consider for annotation
@param[in] enable_specific_losses whether specific neutral losses should be considered
@param[in] enable_unspecific_losses whether unspecific neutral losses (H2O1, H3N1, C1H2N2, C1H2N1O1) should be considered
@param[in] enable_ms2_precursors whether MS2 precursors should be considered
@param[in] mz_threshold the product m/z threshold in Th for annotation
@param[in] swathes the swath window settings (to exclude fragment ions falling
@param[in] round_decPow round product m/z values to decimal power (default: -4)
@param[in] max_num_alternative_localizations maximum number of allowed peptide sequence permutations
@param[in] shuffle_seed set seed for shuffle (-1: select seed based on time)
@param[in] disable_decoy_transitions whether to disable generation of decoy UIS transitions
*/
void uisTransitions(OpenMS::TargetedExperiment& exp,
const std::vector<String>& fragment_types,
const std::vector<size_t>& fragment_charges,
bool enable_specific_losses,
bool enable_unspecific_losses,
bool enable_ms2_precursors,
double mz_threshold,
const std::vector<std::pair<double, double> >& swathes,
int round_decPow = -4,
size_t max_num_alternative_localizations = 20,
int shuffle_seed = -1,
bool disable_decoy_transitions = false);
/**
@brief Filters target and decoy transitions by intensity, only keeping the top N transitions
@param[in] exp the transition list which will be filtered
@param[in] min_transitions the minimum number of transitions required per assay (targets only)
@param[in] max_transitions the maximum number of transitions allowed per assay
*/
void filterMinMaxTransitionsCompound(OpenMS::TargetedExperiment& exp, int min_transitions, int max_transitions);
/**
@brief Filters decoy transitions, which do not have respective target transition
based on the transitionID.
References between targets and decoys will be constructed based on the transitionID
and the "_decoy_" string. For example:
target: 84_CompoundName_[M+H]+_88_22
decoy: 84_CompoundName_decoy_[M+H]+_88_22
@param[in] exp the transition list which will be filtered
*/
void filterUnreferencedDecoysCompound(OpenMS::TargetedExperiment &exp);
// =====================================================================
// Light (memory-efficient) versions of the above methods
// =====================================================================
/**
@brief Annotates and filters transitions in a LightTargetedExperiment
Light version of reannotateTransitions() for memory-efficient processing.
@param[out] exp the input, unfiltered transitions
@param[in] precursor_mz_threshold the precursor m/z threshold in Th for annotation
@param[in] product_mz_threshold the product m/z threshold in Th for annotation
@param[in] fragment_types the fragment types to consider for annotation
@param[in] fragment_charges the fragment charges to consider for annotation
@param[in] enable_specific_losses whether specific neutral losses should be considered
@param[in] enable_unspecific_losses whether unspecific neutral losses should be considered
@param[in] round_decPow round product m/z values to decimal power (default: -4)
*/
void reannotateTransitionsLight(OpenSwath::LightTargetedExperiment& exp,
double precursor_mz_threshold,
double product_mz_threshold,
const std::vector<String>& fragment_types,
const std::vector<size_t>& fragment_charges,
bool enable_specific_losses,
bool enable_unspecific_losses,
int round_decPow = -4);
/**
@brief Restrict and filter transitions in a LightTargetedExperiment
Light version of restrictTransitions() for memory-efficient processing.
@param[in] exp the input, unfiltered transitions
@param[in] lower_mz_limit the lower product m/z limit in Th
@param[in] upper_mz_limit the upper product m/z limit in Th
@param[in] swathes the swath window settings
*/
void restrictTransitionsLight(OpenSwath::LightTargetedExperiment& exp,
double lower_mz_limit,
double upper_mz_limit,
const std::vector<std::pair<double, double> >& swathes);
/**
@brief Select detecting fragment ions in a LightTargetedExperiment
Light version of detectingTransitions() for memory-efficient processing.
@param[in] exp the input, unfiltered transitions
@param[out] min_transitions the minimum number of transitions required per assay
@param[in] max_transitions the maximum number of transitions required per assay
*/
void detectingTransitionsLight(OpenSwath::LightTargetedExperiment& exp,
int min_transitions,
int max_transitions);
/**
@brief Annotate UIS / site-specific transitions (light version)
Light version of uisTransitions() for memory-efficient processing of large libraries.
Works with LightTargetedExperiment structures.
@param[in,out] exp The light targeted experiment to annotate
@param[in] fragment_types Fragment types to consider (e.g., "b", "y")
@param[in] fragment_charges Fragment charges to consider
@param[in] enable_specific_losses Enable specific neutral losses
@param[in] enable_unspecific_losses Enable unspecific neutral losses
@param[in] enable_ms2_precursors Enable MS2 precursor transitions
@param[in] mz_threshold m/z tolerance for matching
@param[in] swathes SWATH isolation windows as (lower, upper) pairs
@param[in] round_decPow Decimal power for m/z rounding (default -4)
@param[in] max_num_alternative_localizations Max peptidoform permutations (default 20)
@param[in] shuffle_seed Random seed for decoy generation (-1 = time-based)
@param[in] disable_decoy_transitions Skip decoy transition generation
*/
void uisTransitionsLight(OpenSwath::LightTargetedExperiment& exp,
const std::vector<String>& fragment_types,
const std::vector<size_t>& fragment_charges,
bool enable_specific_losses,
bool enable_unspecific_losses,
bool enable_ms2_precursors,
double mz_threshold,
const std::vector<std::pair<double, double> >& swathes,
int round_decPow = -4,
size_t max_num_alternative_localizations = 20,
int shuffle_seed = -1,
bool disable_decoy_transitions = false);
protected:
/**
@brief Check whether fragment ion are unique ion signatures in vector within threshold and return matching peptidoforms
@param[in] fragment_ion the queried fragment ion
@param[in] ions a vector of pairs of fragment ion m/z and peptide sequences which could interfere with fragment_ion.
MUST be sorted by m/z (first element) in ascending order for binary search.
@param[in] mz_threshold the threshold within which to search for interferences
@return a vector of strings containing all peptidoforms with which fragment_ion overlaps
*/
std::vector<std::string> getMatchingPeptidoforms_(const double fragment_ion,
const FragmentSeqMap& ions,
const double mz_threshold);
/**
@brief Get swath index (precursor isolation window ordinal) for a particular precursor
@param[in] swathes the swath window settings
@param[in] precursor_mz the query precursor m/z
@return index of swath where precursor_mz falls into
*/
int getSwath_(const std::vector<std::pair<double, double> >& swathes, const double precursor_mz);
/**
@brief Check whether the product m/z of a transition falls into the precursor isolation window
@param[in] swathes the swath window settings
@param[in] precursor_mz the query precursor m/z
@param[in] product_mz the query product m/z
@return whether product m/z falls into precursor isolation window
*/
bool isInSwath_(const std::vector<std::pair<double, double> >& swathes, const double precursor_mz, const double product_mz);
/**
@brief Generates random peptide sequence
@param[in] sequence_size length of peptide sequence
@param[in] pseudoRNG a Boost pseudo RNG
@return random peptide sequence
*/
std::string getRandomSequence_(size_t sequence_size, boost::variate_generator<boost::mt19937&, boost::uniform_int<> > pseudoRNG);
/**
@brief Computes all N choose K combinations
@param[in] n vector of N indices
@param[in] k number of K
@return a vector of all N index combinations
*/
std::vector<std::vector<size_t> > nchoosekcombinations_(const std::vector<size_t>& n, size_t k);
/**
@brief Generate modified peptide forms based on all possible combinations
@param[in] sequences template AASequences
@param[in] mods_combs all possible combinations (e.g. from nchoosekcombinations() )
@param[in] modification String of the modification
@return a vector of all modified peptides.
*/
std::vector<OpenMS::AASequence> addModificationsSequences_(const std::vector<OpenMS::AASequence>& sequences,
const std::vector<std::vector<size_t> >& mods_combs,
const OpenMS::String& modification);
/**
@brief Generate alternative modified peptide forms according to ModificationsDB
@details An input peptide sequence containing modifications is used as template to generate
all modification-carrying residue permutations (n choose k possibilities) that are
physicochemically possible according to ModificationsDB.
@param[in] sequence template AASequence
@return a vector of all alternative modified peptides.
*/
std::vector<OpenMS::AASequence> generateTheoreticalPeptidoforms_(const OpenMS::AASequence& sequence);
/**
@brief Generate alternative modified peptide forms according to ModificationsDB
@details An input peptide sequence containing modifications is used as template to generate
all modification-carrying residue permutations (n choose k possibilities) that are
physicochemically possible according to ModificationsDB. Instead of the target sequence, the
permutations are transferred to the decoy sequence that might contain additional modifiable
residues. E.g. target sequence SAS(Phospho)K could result in [SAS(Phospho)K, S(Phospho)ASK]
but the responding set of the decoy sequence SSS(Phospho)K would be [SSS(Phospho)K, S(Phospho)SSK].
@param[in] sequence template AASequence
@param[in] decoy_sequence template decoy AASequence
@return a vector of all alternative modified peptides.
*/
std::vector<OpenMS::AASequence> generateTheoreticalPeptidoformsDecoy_(const OpenMS::AASequence& sequence, const OpenMS::AASequence& decoy_sequence);
/**
@brief Generate target in silico map
For each peptide, compute all alternative peptidoforms using all
modification-carrying residue permutations (n choose k possibilities)
that are physicochemically possible according to ModificationsDB.
Then store the ion series for each of these theoretical fragment ions in
the provided maps TargetSequenceMap, TargetIonMap, TargetPeptideMap.
@details Used internally by the IPF algorithm, see MRMAssay::uisTransitions()
*/
void generateTargetInSilicoMap_(const OpenMS::TargetedExperiment& exp,
const std::vector<String>& fragment_types,
const std::vector<size_t>& fragment_charges,
bool enable_specific_losses,
bool enable_unspecific_losses,
bool enable_ms2_precursors,
const std::vector<std::pair<double, double> >& swathes,
int round_decPow,
size_t max_num_alternative_localizations,
SequenceMapT& TargetSequenceMap,
IonMapT& TargetIonMap,
PeptideMapT& TargetPeptideMap);
/**
@brief Generate decoy sequences
Generate decoy sequences for IPF algorithm which share peptidoform
properties with targets.
@details Used internally by the IPF algorithm, see MRMAssay::uisTransitions()
*/
void generateDecoySequences_(const SequenceMapT& TargetSequenceMap,
std::map<String, String>& DecoySequenceMap,
int shuffle_seed);
/**
@brief Generate decoy in silico map
For each decoy peptide sequence, compute all alternative peptidoforms
using all modification-carrying residue permutations (n choose k
possibilities) that are physicochemically possible according to
ModificationsDB.
@details Used internally by the IPF algorithm, see MRMAssay::uisTransitions()
*/
void generateDecoyInSilicoMap_(const OpenMS::TargetedExperiment& exp,
const std::vector<String>& fragment_types,
const std::vector<size_t>& fragment_charges,
bool enable_specific_losses,
bool enable_unspecific_losses,
bool enable_ms2_precursors,
const std::vector<std::pair<double, double> >& swathes,
int round_decPow,
TargetDecoyMapT& TargetDecoyMap,
PeptideMapT& TargetPeptideMap,
std::map<String, String>& DecoySequenceMap,
IonMapT& DecoyIonMap,
PeptideMapT& DecoyPeptideMap);
/**
@brief Generate target identification transitions
This function iterates over each (theoretical) transition of each target
peptide and records the identity of all peptidoforms that map to each
transition. The resulting transitions are stored in transitions.
@param[in] exp The input experiment with the target peptides
@param[out] transitions The output containing annotated transitions with potential interferences
@param[in] mz_threshold The threshold for annotating transitions as equal
@param[in] swathes The swath windows used
@param[in] round_decPow round product m/z values to decimal power (default: -4)
@param[in] TargetPeptideMap Theoretical transitions for each peptide generated before
@param[in] TargetIonMap Theoretical transitions for each peptide generated before
@details Used internally by the IPF algorithm, see MRMAssay::uisTransitions()
*/
void generateTargetAssays_(const OpenMS::TargetedExperiment& exp,
TransitionVectorType& transitions,
double mz_threshold,
const std::vector<std::pair<double, double> >& swathes,
int round_decPow,
const PeptideMapT& TargetPeptideMap,
const IonMapT& TargetIonMap);
/**
@brief Generate decoy assays
@details Used internally by the IPF algorithm, see MRMAssay::uisTransitions()
*/
void generateDecoyAssays_(const OpenMS::TargetedExperiment& exp,
TransitionVectorType& transitions,
double mz_threshold,
const std::vector<std::pair<double, double> >& swathes,
int round_decPow,
const PeptideMapT& DecoyPeptideMap,
TargetDecoyMapT& TargetDecoyMap,
const IonMapT& DecoyIonMap,
const IonMapT& TargetIonMap);
// =====================================================================
// Light (memory-efficient) versions of IPF helper methods
// =====================================================================
/// Light version of TargetDecoyMapT using LightCompound
typedef std::map<String, OpenSwath::LightCompound> TargetDecoyMapLightT;
/**
@brief Generate target in silico map (light version)
Light version of generateTargetInSilicoMap_() for memory-efficient processing.
@details Used internally by the IPF algorithm, see MRMAssay::uisTransitionsLight()
*/
void generateTargetInSilicoMapLight_(const OpenSwath::LightTargetedExperiment& exp,
const std::vector<String>& fragment_types,
const std::vector<size_t>& fragment_charges,
bool enable_specific_losses,
bool enable_unspecific_losses,
bool enable_ms2_precursors,
const std::vector<std::pair<double, double> >& swathes,
int round_decPow,
size_t max_num_alternative_localizations,
SequenceMapT& TargetSequenceMap,
IonMapT& TargetIonMap,
PeptideMapT& TargetPeptideMap);
/**
@brief Generate decoy in silico map (light version)
Light version of generateDecoyInSilicoMap_() for memory-efficient processing.
@details Used internally by the IPF algorithm, see MRMAssay::uisTransitionsLight()
*/
void generateDecoyInSilicoMapLight_(const OpenSwath::LightTargetedExperiment& exp,
const std::vector<String>& fragment_types,
const std::vector<size_t>& fragment_charges,
bool enable_specific_losses,
bool enable_unspecific_losses,
bool enable_ms2_precursors,
const std::vector<std::pair<double, double> >& swathes,
int round_decPow,
TargetDecoyMapLightT& TargetDecoyMap,
const PeptideMapT& TargetPeptideMap,
const std::map<String, String>& DecoySequenceMap,
IonMapT& DecoyIonMap,
PeptideMapT& DecoyPeptideMap);
/**
@brief Generate target identification transitions (light version)
Light version of generateTargetAssays_() for memory-efficient processing.
@details Used internally by the IPF algorithm, see MRMAssay::uisTransitionsLight()
*/
void generateTargetAssaysLight_(const OpenSwath::LightTargetedExperiment& exp,
std::vector<OpenSwath::LightTransition>& transitions,
double mz_threshold,
const std::vector<std::pair<double, double> >& swathes,
int round_decPow,
const PeptideMapT& TargetPeptideMap,
const IonMapT& TargetIonMap);
/**
@brief Generate decoy assays (light version)
Light version of generateDecoyAssays_() for memory-efficient processing.
@details Used internally by the IPF algorithm, see MRMAssay::uisTransitionsLight()
*/
void generateDecoyAssaysLight_(const OpenSwath::LightTargetedExperiment& exp,
std::vector<OpenSwath::LightTransition>& transitions,
double mz_threshold,
const std::vector<std::pair<double, double> >& swathes,
int round_decPow,
const PeptideMapT& DecoyPeptideMap,
const TargetDecoyMapLightT& TargetDecoyMap,
const IonMapT& DecoyIonMap,
const IonMapT& TargetIonMap);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/OPENSWATH/MRMFeatureQC.h | .h | 9,248 | 278 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Douglas McCloskey $
// $Authors: Douglas McCloskey $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/MRMFeature.h>
#include <OpenMS/KERNEL/Feature.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/DATASTRUCTURES/String.h>
namespace OpenMS
{
/**
@brief The MRMFeatureQC is a class to handle the parameters and options for MRMFeatureFilter.
The format is based loosely on the TraML format and can be stored and loaded to disk using MRMFeatureQCFile.
Quality control parameters are available on multiple levels:
- **Component level** (ComponentQCs): QC for individual transitions - RT, intensity, quality bounds, and custom meta-values
- **Component group level** (ComponentGroupQCs): QC for transition groups - includes label counts (heavy/light),
transition type counts (detecting/quantifying/identifying), and ion ratios
- **Component group pair level** (ComponentGroupPairQCs): QC for pairs of groups - resolution and RT difference bounds
@section MRMFeatureQC_example Example Usage
@code
MRMFeatureQC qc;
// Add component QC
MRMFeatureQC::ComponentQCs comp_qc;
comp_qc.component_name = "heavy_13C6_glucose";
comp_qc.retention_time_l = 5.0;
comp_qc.retention_time_u = 7.0;
comp_qc.intensity_l = 1000.0;
qc.component_qcs.push_back(comp_qc);
// Add component group QC with ion ratio
MRMFeatureQC::ComponentGroupQCs group_qc;
group_qc.component_group_name = "glucose";
group_qc.ion_ratio_pair_name_1 = "quantifier";
group_qc.ion_ratio_pair_name_2 = "qualifier";
group_qc.ion_ratio_l = 0.8;
group_qc.ion_ratio_u = 1.2;
qc.component_group_qcs.push_back(group_qc);
@endcode
@see MRMFeatureFilter for applying QC filtering
@see MRMFeatureQCFile for file I/O
@ingroup TargetedQuantitation
*/
class OPENMS_DLLAPI MRMFeatureQC
{
public:
//@{
/// Constructor
MRMFeatureQC() = default;
/// Destructor
~MRMFeatureQC() = default;
//@}
// Members
//
/**@brief Quality Controls (QCs) for individual components
A component is analogous to a transition or subfeature.
A component is a transition that corresponds to a single peptide or metabolite
*/
struct ComponentQCs
{
bool operator==(const ComponentQCs& other) const {
bool members_eq =
std::tie(
component_name,
retention_time_l,
retention_time_u,
intensity_l,
intensity_u,
overall_quality_l,
overall_quality_u
) == std::tie(
other.component_name,
other.retention_time_l,
other.retention_time_u,
other.intensity_l,
other.intensity_u,
other.overall_quality_l,
other.overall_quality_u
);
auto compare_maps = [](std::pair<String, std::pair<double, double>> lhs, std::pair<String, std::pair<double, double>> rhs) {return (lhs.first == rhs.first && lhs.second.first == rhs.second.first && lhs.second.second == rhs.second.second); };
bool meta_values_eq = std::equal(meta_value_qc.begin(), meta_value_qc.end(), other.meta_value_qc.begin(), compare_maps);
return members_eq && meta_values_eq;
}
bool operator!=(const ComponentQCs& other) const
{
return !(*this == other);
}
/// name of the component
String component_name;
// Feature members
/// retention time lower bound
double retention_time_l { 0.0 };
/// retention time upper bound
double retention_time_u { 1e12 };
/// intensity lower bound
double intensity_l { 0.0 };
/// intensity upper bound
double intensity_u { 1e12 };
/// overall quality lower bound
double overall_quality_l { 0.0 };
/// overall quality upper bound
double overall_quality_u { 1e12 };
/// Feature MetaValues
std::map<String,std::pair<double,double>> meta_value_qc;
};
/**@brief Quality Controls (QCs) within a component group
A component group is analogous to a transition group or feature.
A component group includes all transitions that correspond to a given component (i.e., peptide or metabolite)
*/
struct ComponentGroupQCs
{
bool operator==(const ComponentGroupQCs& other) const {
bool members_eq =
std::tie(
component_group_name,
retention_time_l,
retention_time_u,
intensity_l,
intensity_u,
overall_quality_l,
overall_quality_u,
n_heavy_l,
n_heavy_u,
n_light_l,
n_light_u,
n_detecting_l,
n_detecting_u,
n_quantifying_l,
n_quantifying_u,
n_identifying_l,
n_identifying_u,
n_transitions_l,
n_transitions_u,
ion_ratio_pair_name_1,
ion_ratio_pair_name_2,
ion_ratio_l,
ion_ratio_u,
ion_ratio_feature_name
) == std::tie(
other.component_group_name,
other.retention_time_l,
other.retention_time_u,
other.intensity_l,
other.intensity_u,
other.overall_quality_l,
other.overall_quality_u,
other.n_heavy_l,
other.n_heavy_u,
other.n_light_l,
other.n_light_u,
other.n_detecting_l,
other.n_detecting_u,
other.n_quantifying_l,
other.n_quantifying_u,
other.n_identifying_l,
other.n_identifying_u,
other.n_transitions_l,
other.n_transitions_u,
other.ion_ratio_pair_name_1,
other.ion_ratio_pair_name_2,
other.ion_ratio_l,
other.ion_ratio_u,
other.ion_ratio_feature_name
);
auto compare_maps = [](std::pair<String, std::pair<double, double>> lhs, std::pair<String, std::pair<double, double>> rhs) {return (lhs.first == rhs.first && lhs.second.first == rhs.second.first && lhs.second.second == rhs.second.second); };
bool meta_values_eq = std::equal(meta_value_qc.begin(), meta_value_qc.end(), other.meta_value_qc.begin(), compare_maps);
return members_eq && meta_values_eq;
}
bool operator!=(const ComponentGroupQCs& other) const
{
return !(*this == other);
}
/// name of the component group
String component_group_name;
/// retention time lower bound
double retention_time_l { 0.0 };
/// retention time upper bound
double retention_time_u { 1e12 };
/// intensity lower bound
double intensity_l { 0.0 };
/// intensity upper bound
double intensity_u { 1e12 };
/// overall quality lower bound
double overall_quality_l { 0.0 };
/// overall quality upper bound
double overall_quality_u { 1e12 };
// number of transitions and labels
/// number of heavy ion lower bound
Int n_heavy_l { 0 };
/// number of heavy ion upper bound
Int n_heavy_u { 100 };
Int n_light_l { 0 };
Int n_light_u { 100 };
Int n_detecting_l { 0 };
Int n_detecting_u { 100 };
Int n_quantifying_l { 0 };
Int n_quantifying_u { 100 };
Int n_identifying_l { 0 };
Int n_identifying_u { 100 };
Int n_transitions_l { 0 };
Int n_transitions_u { 100 };
// Ion Ratio QCs
String ion_ratio_pair_name_1;
String ion_ratio_pair_name_2;
double ion_ratio_l { 0.0 };
double ion_ratio_u { 1e12 };
String ion_ratio_feature_name;
std::map<String,std::pair<double,double>> meta_value_qc;
};
/**@brief Quality Controls (QCs) for multiple components (between or within component_groups)
This structure contains upper and lower bounds for parameters that involve two or more
component groups. For example, a quality control that is based on a minimum retention
time difference between two components would be suitable for this struct.
*/
struct ComponentGroupPairQCs
{
/// name of the component
String component_group_name;
/// name of the component to calculate the resolution or retention time
String resolution_pair_name;
/// resolution lower bound
double resolution_l;
/// resolution upper bound
double resolution_u;
/// retention time lower bound
double rt_diff_l;
/// retention time upper bound
double rt_diff_u;
};
//members
/// list of all component QCs
std::vector<ComponentQCs> component_qcs;
/// list of all component group QCs
std::vector<ComponentGroupQCs> component_group_qcs;
/// list of all component group pair QCs
std::vector<ComponentGroupPairQCs> component_group_pair_qcs;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/OPENSWATH/SwathMapMassCorrection.h | .h | 7,378 | 167 | // 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 <vector>
#include <OpenMS/OPENSWATHALGO/DATAACCESS/SwathMap.h>
#include <OpenMS/ANALYSIS/OPENSWATH/MRMFeatureFinderScoring.h>
namespace OpenMS
{
/**
* @brief A class containing correction functions for Swath MS maps
*
* This class can use a set of pre-determined points in a Swath-MS map to
* correct all maps according to the m/z shift found in those fixed points.
*
*/
class OPENMS_DLLAPI SwathMapMassCorrection :
public DefaultParamHandler
{
public:
//@{
/// Constructor
SwathMapMassCorrection();
/// Destructor
~SwathMapMassCorrection() override = default;
//@}
/// Synchronize members with param class
void updateMembers_() override;
/**
* @brief Correct the m/z values of a SWATH map based on the RT-normalization peptides
*
* This extracts the full spectra at the most likely elution time of the
* calibrant peptides and fits a regression curve to correct for a possible
* mass shift of the empirical masses vs the theoretically expected masses.
* Several types of regressions are available (see below corr_type parameter).
*
* The function will replace the pointers stored in swath_maps with a
* transforming map that will contain corrected m/z values.
*
* @param[out] transition_group_map A MRMFeatureFinderScoring result map
* @param[in] targeted_exp The corresponding spectral library (required for extraction coordinates)
* @param[in] swath_maps The raw swath maps from the current run, will be modified (replaced with a corrected version)
* @param[in] pasef Whether the data is PASEF data with possible overlapping m/z windows (with different ion mobility). In this case, the "best" SWATH window (with precursor cetntered around IM) is chosen.
*/
void correctMZ(const std::map<String, OpenMS::MRMFeatureFinderScoring::MRMTransitionGroupType *>& transition_group_map,
const OpenSwath::LightTargetedExperiment & targeted_exp,
std::vector< OpenSwath::SwathMap > & swath_maps, const bool pasef);
/**
* @brief Correct the ion mobility values of a SWATH map based on the RT-normalization peptides
*
* This extracts the full spectra at the most likely elution time of the
* calibrant peptides and fits a linear regression curve to correct for a
* possible ion mobility (drift time) shift of the empirical drift time vs
* the theoretically expected drift time. The resulting linear
* transformation is stored using a TransformationDescription object.
*
* @param[out] transition_group_map A MRMFeatureFinderScoring result map
* @param[in,out] swath_maps The raw swath maps from the current run
* @param[in] targeted_exp The corresponding spectral library (required for extraction coordinates)
* @param[in] pasef whether the data is PASEF data with possible overlapping m/z windows (with different ion mobility). In this case, the "best" SWATH window (with precursor cetntered around IM) is chosen.
* @param[out] im_trafo The resulting map containing the transformation
*/
void correctIM(const std::map<String, OpenMS::MRMFeatureFinderScoring::MRMTransitionGroupType *> & transition_group_map,
const OpenSwath::LightTargetedExperiment & targeted_exp,
const std::vector< OpenSwath::SwathMap > & swath_maps,
const bool pasef,
TransformationDescription & im_trafo);
/**
* @brief Computes the SwathMaps for PASEF data in which windows can have the same m/z but differ by ion mobility
*
* For each precursor, the SwathMap is chosen based on library m/z and ion mobility.
* If two or more SwathMaps isolate the same precursor the SwathMap in which the precursor is more centered across
* ion mobility is chosen.
*
* @param[in] transition_group A MRMTransitionGroup for which the SwathMap is assigned to
* @param[out] swath_maps A vector containing the a single entry, the swath map which the MRMFeature is assigned to
*/
std::vector<OpenSwath::SwathMap> findSwathMapsPasef(const OpenMS::MRMFeatureFinderScoring::MRMTransitionGroupType& transition_group,
const std::vector< OpenSwath::SwathMap > & swath_maps);
/**
@brief Estimate an extraction window from absolute residuals.
Treats the input @p residuals as absolute errors (e.g., |delta ppm| for m/z).
We compute an adaptive half-width using OpenMS::Math::adaptiveQuantile
(Tukey k=1.5; blend raw vs winsorized by tail density), and return
either the half-width or the full width (2×half).
Notes:
- Empty input yields 0.0.
- Ensure @p residuals contain absolute values; non-absolute inputs will be
converted via std::abs internally.
@param[in] residuals Absolute residuals (e.g., |delta ppm|).
@param[in] quantile Quantile of the half-width distribution to use (default 0.99).
@param[in] full_width If true, return 2×half-width; if false, return half-width.
@param[in] padding_factor A padding factor to add to the estimated window.
@return Estimated window (same units as @p residuals; 0.0 if empty).
*/
static double estimateWindow(
std::vector<double> residuals,
double quantile = 0.99,
bool full_width = true,
double padding_factor = 1.0
);
/// Retrieve the estimated fragment m/z extraction window (ppm)
double getFragmentMzWindow() const;
/// Set the estimated fragment m/z extraction window (ppm_
void setFragmentMzWindow(double fragmentMzWindow);
/// Retrieve the estimated fragment ion mobility extraction window
double getFragmentImWindow() const;
/// Set the estimated fragment ion mobility extraction window
void setFragmentImWindow(double fragmentImWindow);
/// Retrieve the estimated precursor m/z extraction window (ppm)
double getPrecursorMzWindow() const;
/// Set the estimated precursor m/z extraction window (ppm)
void setPrecursorMzWindow(double precursorMzWindow);
/// Retrieve the estimated precursor ion mobility extraction window
double getPrecursorImWindow() const;
/// Set the estimated precursor ion mobility extraction window
void setPrecursorImWindow(double precursorImWindow);
private:
double mz_extraction_window_;
bool mz_extraction_window_ppm_;
bool ms1_im_;
double im_extraction_window_;
String mz_correction_function_;
String im_correction_function_;
String debug_im_file_;
String debug_mz_file_;
/// fields for estimated mz and ion mobility windows
double mz_estimation_padding_factor_ = 1.0;
double im_estimation_padding_factor_ = 1.0;
double fragment_mz_window_ = -1;
double fragment_im_window_ = -1;
double precursor_mz_window_ = -1;
double precursor_im_window_ = -1;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/OPENSWATH/IonMobilityScoring.h | .h | 12,384 | 246 | // 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
// data access
#include <OpenMS/OPENSWATHALGO/DATAACCESS/DataStructures.h>
#include <OpenMS/OPENSWATHALGO/DATAACCESS/ISpectrumAccess.h>
#include <OpenMS/OPENSWATHALGO/DATAACCESS/ITransition.h>
#include <OpenMS/OPENSWATHALGO/DATAACCESS/TransitionExperiment.h>
#include <OpenMS/OPENSWATHALGO/DATAACCESS/SwathMap.h>
#include <OpenMS/ANALYSIS/OPENSWATH/OpenSwathScoring.h>
#include <OpenMS/KERNEL/Mobilogram.h>
// Kernel classes
#include <OpenMS/KERNEL/MRMTransitionGroup.h>
#include <OpenMS/KERNEL/MSChromatogram.h>
// scoring
#include <OpenMS/ANALYSIS/OPENSWATH/PeakPickerMobilogram.h>
#include <OpenMS/ANALYSIS/OPENSWATH/DIAScoring.h>
#include <vector>
namespace OpenMS
{
struct RangeMobility;
struct RangeMZ;
/** @brief A class that calls the ion mobility scoring routines
*
* Use this class to invoke the individual OpenSWATH ion mobility scoring
* routines. These scores use the ion mobilograms from individual peptides in
* one (or more) frames to compute additional scores.
*
* - driftScoring() performs scoring on fragment ion mobilograms extracted from a DIA frame
* - driftScoringMS1() performs scoring on precursor ion mobilograms extracted from a MS1 frame
* - driftScoringMS1Contrast() performs cross correlation (contrast) scoring between precursor and fragment ion mobilograms
*
*/
class OPENMS_DLLAPI IonMobilityScoring
{
typedef OpenSwath::LightCompound CompoundType;
typedef OpenSwath::LightTransition TransitionType;
typedef MRMTransitionGroup< MSChromatogram, TransitionType> MRMTransitionGroupType;
public:
/// Constructor
IonMobilityScoring();
/// Destructor
~IonMobilityScoring();
/**
@brief Performs scoring of the ion mobility dimension in MS2
Populates additional scores in the @p scores object
If @p apply_im_peak_picking is set to true, peak picking is performed on the Savitzky-Golay smoothed ion mobilogram. This is useful for minimizing interference from co-eluting analytes in the ion mobility dimension (IM) that fall within the current extraction window. This process improves the specificity of analyte detection by dynamically adjusting the IM extraction window to extract only over the IM elution of the highest intensity species. If multiple peaks are present in the IM dimension, lower intensity peaks get discarded.
@param[in] spectra Sequence of segments of the DIA MS2 spectrum found at (and around) the peak apex
@param[in] transitions The transitions used for scoring
@param[out] scores The output scores
@param[out] drift_target Ion Mobility extraction target
@param[in] im_range Ion Mobility extraction range
@param[in] dia_extraction_window_ m/z extraction width
@param[in] dia_extraction_ppm_ Whether m/z extraction width is in ppm
@param[in] drift_extra Extend the extraction window to gain a larger field of view beyond drift_upper - drift_lower (in percent)
@param[in] apply_im_peak_picking Apply peak picking on the ion mobilogram
*/
static void driftScoring(const SpectrumSequence& spectra,
const std::vector<TransitionType> & transitions,
OpenSwath_Scores & scores,
const double drift_target,
RangeMobility im_range,
const double dia_extraction_window_,
const bool dia_extraction_ppm_,
const double drift_extra,
const bool apply_im_peak_picking);
/**
@brief Performs scoring of the ion mobility dimension in MS1
Populates additional scores in the @p scores object
@param[in] spectra vector containing the DIA MS1 spectra found at (or around) the peak apex
@param[in] transitions The transitions used for scoring
@param[out] scores The output scores
@param[in] im_range Ion Mobility extraction range
@param[out] drift_target Ion Mobility extraction target
@param[in] dia_extraction_window_ m/z extraction width
@param[in] dia_extraction_ppm_ Whether m/z extraction width is in ppm
@param[in] drift_extra Extra extraction to use for drift time (in percent)
*/
static void driftScoringMS1(const SpectrumSequence& spectra,
const std::vector<TransitionType> & transitions,
OpenSwath_Scores & scores,
const double drift_target,
RangeMobility im_range,
const double dia_extraction_window_,
const bool dia_extraction_ppm_,
const double drift_extra);
/**
@brief Performs scoring of the ion mobility dimension in MS1 and MS2 (contrast)
Populates additional scores in the @p scores object
@param[in] spectra Vector of the DIA MS2 spectrum found in SpectrumSequence object (can contain 1 or multiple spectra centered around peak apex)
@param[in] ms1spectrum The DIA MS1 spectrum found in SpectrumSequence object (can contain 1 or multiple spectra centered around peak apex)
@param[in] transitions The transitions used for scoring
@param[out] scores The output scores
@param[in] im_range the ion mobility range
@param[in] dia_extraction_window_ m/z extraction width
@param[in] dia_extraction_ppm_ Whether m/z extraction width is in ppm
@param[in] drift_extra Extra extraction to use for drift time (in percent)
*/
static void driftScoringMS1Contrast(const SpectrumSequence& spectra, const SpectrumSequence& ms1spectrum,
const std::vector<TransitionType> & transitions,
OpenSwath_Scores & scores,
RangeMobility im_range,
const double dia_extraction_window_,
const bool dia_extraction_ppm_,
const double drift_extra);
/**
@brief Performs scoring of the ion mobility dimension for identification transitions against detection transitions
@param[in] spectra Vector of the DIA MS2 spectrum found in SpectrumSequence object (can contain 1 or multiple spectra centered around peak apex)
@param[in] transitions The transitions used for scoring
@param[in] transition_group_detection The detection transition group
@param[out] scores The output scores
@param[out] drift_target Ion Mobility extraction target
@param[in] im_range Ion Mobility extraction range
@param[in] dia_extract_window_ m/z extraction width
@param[in] dia_extraction_ppm_ Whether m/z extraction width is in ppm
@param[in] drift_extra Extra extraction to use for drift time (in percent)
@param[in] apply_im_peak_picking Apply peak pickng on the ion mobilogram
*/
static void driftIdScoring(const SpectrumSequence& spectra,
const std::vector<TransitionType> & transitions,
MRMTransitionGroupType& transition_group_detection,
OpenSwath_Scores & scores,
const double drift_target,
RangeMobility im_range,
const double dia_extract_window_,
const bool dia_extraction_ppm_,
const double drift_extra,
const bool apply_im_peak_picking);
/**
* @brief computes ion mobilogram to be used in scoring based on mz_range and im_range.
* Also integrates intensity in the resulting ion mobility mobilogram in mz_range and im_range across all the entire SpectrumSequence.
* @note If there is no signal, mz will be set to -1 and intensity to 0
* @param[in] spectra Raw data in a spectrumSequence object (can contain 1 or multiple spectra centered around peak apex)
* @param[in] mz_range the range across mz to extract
* @param[in] im_range the range across im to extract
* @param[out] im computed weighted average ion mobility
* @param[out] intensity intensity computed intensity
* @param[out] res outputted ion mobilogram
* @param[in] eps minimum distance to allow for two seperate points
*/
static void computeIonMobilogram(const SpectrumSequence& spectra,
const RangeMZ & mz_range,
const RangeMobility & im_range,
double & im,
double & intensity,
Mobilogram & res,
double eps);
private:
/**
* @brief helper function to computeIonMobilogram. Discretizes ion mobility values into a grid.
**/
static std::vector<double> computeGrid_(const std::vector< Mobilogram >& mobilograms, double eps);
/*
@brief Extracts ion mobility values projected onto a grid
For a given ion mobility profile and a grid, compute an ion mobilogram
across the grid for each ion mobility data point. Returns two data arrays
for the ion mobilogram: intensity (y) and ion mobility (x). Zero values are
inserted if no data point was found for a given grid value.
@param[in] profile The ion mobility data
@param[in] im_grid The grid to be used
@param[in] eps Epsilon used for computing the ion mobility grid
@param[in] max_peak_idx The grid position of the maximum
*/
static void alignToGrid_(const Mobilogram& profile,
const std::vector<double>& im_grid,
Mobilogram & aligned_profile,
double eps,
Size & max_peak_idx);
/*
@brief Extracts intensity values from a vector of Mobilogram objects
This function takes a vector of Mobilogram objects and extracts the intensity
values from each Mobilogram, storing them in a 2D vector of doubles. The
resulting vector of intensity values is stored in the provided output parameter.
@param[in] mobilograms A const reference to a vector of Mobilogram objects
from which to extract intensity values.
@param[out] int_values A reference to a vector of vector of doubles where
the extracted intensity values will be stored. This
vector will be cleared and resized as necessary.
*/
static void extractIntensities(const std::vector< Mobilogram >& mobilograms,
std::vector<std::vector<double>>& int_values);
/**
* @brief Extracts intensity values from a single Mobilogram object
*
* This function takes a single Mobilogram object and extracts the intensity
* values, returning them as a vector of doubles.
*
* @param[in] mobilogram [in] A const reference to a Mobilogram object from which to extract intensity values.
* @return A vector of doubles containing the extracted intensity values.
*/
static std::vector<double> extractIntensities(const Mobilogram& mobilogram);
};
/*
@brief Helper function to sum up aligned mobilograms
This function takes a vector of aligned mobilograms and sums them up to create a single Mobilogram object. The resulting Mobilogram object will contain the sum of the intensity values from all the input mobilograms.
@note the input vector of Mobilograms all need to have the same size, otherwise the function will throw a pre-condition exception.
@param[in] aligned_mobilograms A vector of aligned mobilograms
@return A Mobilogram object that is the sum of the input mobilograms
*/
OpenMS::Mobilogram sumAlignedMobilograms(const std::vector<OpenMS::Mobilogram>& aligned_mobilograms);
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/OPENSWATH/OpenSwathScoring.h | .h | 15,578 | 310 | // 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
// data access
#include <OpenMS/OPENSWATHALGO/DATAACCESS/DataStructures.h>
#include <OpenMS/OPENSWATHALGO/DATAACCESS/ISpectrumAccess.h>
#include <OpenMS/OPENSWATHALGO/DATAACCESS/ITransition.h>
#include <OpenMS/OPENSWATHALGO/DATAACCESS/TransitionExperiment.h>
#include <OpenMS/OPENSWATHALGO/DATAACCESS/SwathMap.h>
// Kernel classes
#include <OpenMS/KERNEL/MRMTransitionGroup.h>
#include <OpenMS/KERNEL/MSChromatogram.h>
// scoring
#include <OpenMS/ANALYSIS/OPENSWATH/OpenSwathScores.h>
#include <OpenMS/ANALYSIS/OPENSWATH/DIAScoring.h>
#include <vector>
#include <memory>
#include <boost/make_shared.hpp>
//logging
#include <OpenMS/CONCEPT/LogStream.h>
struct RangeMZ;
struct RangeMobility;
namespace OpenMS
{
/** @brief A class that calls the scoring routines
*
* Use this class to invoke the individual OpenSWATH scoring routines.
*
*/
class OPENMS_DLLAPI OpenSwathScoring
{
typedef OpenSwath::LightCompound CompoundType;
typedef OpenSwath::LightTransition TransitionType;
typedef MRMTransitionGroup< MSChromatogram, TransitionType> MRMTransitionGroupType;
enum class SpectrumAdditionMethod
{
ADDITION,
RESAMPLE
};
enum class SpectrumMergeMethodType
{
FIXED,
DYNAMIC
};
double rt_normalization_factor_;
double spacing_for_spectra_resampling_;
double merge_spectra_by_peak_width_fraction_;
int add_up_spectra_;
SpectrumAdditionMethod spectra_addition_method_;
SpectrumMergeMethodType spectra_merge_method_type_;
double im_drift_extra_pcnt_;
OpenSwath_Scores_Usage su_;
bool use_ms1_ion_mobility_; ///< whether to use MS1 ion mobility extraction in DIA scores
bool apply_im_peak_picking_; ///< whether to apply peak picking on ion mobilograms
public:
/// Constructor
OpenSwathScoring();
/// Destructor
~OpenSwathScoring();
/** @brief Initialize the scoring object
*
* Sets the parameters for the scoring.
*
* @param[in] rt_normalization_factor Specifies the range of the normalized retention time space
* @param[in] add_up_spectra How many spectra to add up (default 1)
* @param[in] spacing_for_spectra_resampling Spacing factor for spectra addition
* @param[in] merge_spectra_by_peak_width_fraction Fraction of peak width to construct the number of spectra to add
* @param[in] drift_extra Extend the extraction window to gain a larger field of view beyond drift_upper - drift_lower (in percent)
* @param[in] su Which scores to actually compute
* @param[in] spectrum_addition_method Method to use for spectrum addition (valid: "simple", "resample")
* @param[in] spectrum_merge_method_type Type of method to use for spectrum addition. (valid: "fixed", "dynamic")
* @param[in] use_ms1_ion_mobility Use MS1 ion mobility extraction in DIA scores
* @param[in] apply_im_peak_picking Apply peak picking on ion mobilograms
*
*/
void initialize(double rt_normalization_factor,
int add_up_spectra,
double spacing_for_spectra_resampling,
double merge_spectra_by_peak_width_fraction,
const double drift_extra,
const OpenSwath_Scores_Usage & su,
const std::string& spectrum_addition_method,
const std::string& spectrum_merge_method_type,
bool use_ms1_ion_mobility,
bool apply_im_peak_picking);
/** @brief Score a single peakgroup in a chromatogram using only chromatographic properties.
*
* This function only uses the chromatographic properties (coelution,
* signal to noise, etc.) of a peakgroup in a chromatogram to compute
* scores. If more information is available, also consider using the
* library based scoring and the full-spectrum based scoring.
*
* The scores are returned in the OpenSwath_Scores object. Only those
* scores specified in the OpenSwath_Scores_Usage object are computed.
*
* @param[in] imrmfeature The feature to be scored
* @param[in] native_ids The list of native ids (giving a canonical ordering of the transitions)
* @param[in] precursor_ids The list of precursor ids
* @param[in] normalized_library_intensity The weights to be used for each transition (e.g. normalized library intensities)
* @param[in] signal_noise_estimators The signal-to-noise estimators for each transition
* @param[out] scores The object to store the result
*
*/
void calculateChromatographicScores(OpenSwath::IMRMFeature* imrmfeature,
const std::vector<std::string>& native_ids,
const std::vector<std::string>& precursor_ids,
const std::vector<double>& normalized_library_intensity,
std::vector<OpenSwath::ISignalToNoisePtr>& signal_noise_estimators,
OpenSwath_Scores & scores) const;
/** @brief Score identification transitions against detection transitions of a single peakgroup
* in a chromatogram using only chromatographic properties.
*
* This function only uses the chromatographic properties (coelution,
* signal to noise, etc.) of a peakgroup in a chromatogram to compute
* scores. The scores are computed by scoring identification against detection
* transitions.
*
* The scores are returned in the OpenSwath_Scores object. Only those
* scores specified in the OpenSwath_Scores_Usage object are computed.
*
* @param[in] imrmfeature The feature to be scored
* @param[in] native_ids_identification The list of identification native ids (giving a canonical ordering of the transitions)
* @param[in] native_ids_detection The list of detection native ids (giving a canonical ordering of the transitions)
* @param[in] signal_noise_estimators The signal-to-noise estimators for each transition
* @param[out] scores The object to store the result
*
*/
void calculateChromatographicIdScores(OpenSwath::IMRMFeature* imrmfeature,
const std::vector<std::string>& native_ids_identification,
const std::vector<std::string>& native_ids_detection,
std::vector<OpenSwath::ISignalToNoisePtr>& signal_noise_estimators,
OpenSwath_Ind_Scores & scores) const;
/** @brief Score a single chromatographic feature against a spectral library
*
* The spectral library is provided in a set of transition objects and a
* peptide object. Both contain information about the expected elution time
* on the chromatography and the relative intensity of the transitions.
*
* The scores are returned in the OpenSwath_Scores object.
*
* @param[in] imrmfeature The feature to be scored
* @param[in] transitions The library transition to score the feature against
* @param[in] compound The compound corresponding to the library transitions
* @param[in] normalized_feature_rt The retention time of the feature in normalized space
* @param[out] scores The object to store the result
*
*/
void calculateLibraryScores(OpenSwath::IMRMFeature* imrmfeature,
const std::vector<TransitionType> & transitions,
const CompoundType& compound,
const double normalized_feature_rt,
OpenSwath_Scores & scores);
/** @brief Score a single chromatographic feature using DIA / SWATH scores.
*
* The scores are returned in the OpenSwath_Scores object.
*
* @param[in] imrmfeature The feature to be scored
* @param[in] transitions The library transition to score the feature against
* @param[in] swath_maps The SWATH-MS (DIA) maps from which to retrieve full MS/MS spectra at the chromatographic peak apices
* @param[in] ms1_map The corresponding MS1 (precursor ion map) from which the precursor spectra can be retrieved (optional, may be NULL)
* @param[in] diascoring DIA Scoring object to use for scoring
* @param[in] compound The compound corresponding to the library transitions
* @param[out] scores The object to store the result
* @param[in] mzerror_ppm m/z and mass error (in ppm) for all transitions
* @param[in] drift_target target drift value
* @param[in] range_im drift time lower and upper bounds
*
*/
void calculateDIAScores(OpenSwath::IMRMFeature* imrmfeature,
const std::vector<TransitionType>& transitions,
const std::vector<OpenSwath::SwathMap>& swath_maps,
const OpenSwath::SpectrumAccessPtr& ms1_map,
const OpenMS::DIAScoring& diascoring,
const CompoundType& compound,
OpenSwath_Scores& scores,
std::vector<double>& mzerror_ppm,
const double drift_target,
const RangeMobility& range_im);
/** @brief Score a single chromatographic feature using the precursor map.
*
* The scores are returned in the OpenSwath_Scores object.
*
* @param[in] ms1_map The MS1 (precursor ion map) from which the precursor spectra can be retrieved
* @param[in] diascoring DIA Scoring object to use for scoring
* @param[in] precursor_mz The m/z ratio of the precursor
* @param[in] rt The compound retention time
* @param[in] compound the compound sequence
* @param[in] im_range drift time lower and upper bounds
* @param[out] scores The object to store the result
*
*/
void calculatePrecursorDIAScores(const OpenSwath::SpectrumAccessPtr& ms1_map,
const OpenMS::DIAScoring& diascoring,
double precursor_mz,
double rt,
const CompoundType& compound,
RangeMobility im_range,
OpenSwath_Scores& scores);
/** @brief Score a single chromatographic feature using DIA / SWATH scores.
*
* The scores are returned in the OpenSwath_Scores object.
*
* @param[in] imrmfeature The feature to be scored
* @param[in] transition The library transition to score the feature against
* @param[in] transition_group_detection The detection transition group
* @param[in] swath_maps The SWATH-MS (DIA) maps from which to retrieve full MS/MS spectra at the chromatographic peak apices
* @param[in] range_im drift time lower and upper bounds
* @param[in] diascoring DIA Scoring object to use for scoring
* @param[out] scores The object to store the result
* @param[out] drift_target target drift value
*
*/
void calculateDIAIdScores(OpenSwath::IMRMFeature* imrmfeature,
const TransitionType & transition,
MRMTransitionGroupType& transition_group_detection,
const std::vector<OpenSwath::SwathMap>& swath_maps,
RangeMobility& range_im,
const OpenMS::DIAScoring & diascoring,
OpenSwath_Scores & scores,
const double drift_target);
/** @brief Computing the normalized library intensities from the transition objects
*
* The intensities are normalized such that the sum to one.
*
* @param[in] transitions The library transition to score the feature against
* @param[out] normalized_library_intensity The resulting normalized library intensities
*
*/
void getNormalized_library_intensities_(const std::vector<TransitionType> & transitions,
std::vector<double>& normalized_library_intensity);
/** @brief Prepares a spectrum for DIA analysis (single map)
*
* This function will fetch a vector of spectrum pointers to be used in DIA analysis.
* If nr_spectra_to_add == 1, then a vector of length 1 will be returned
*
* - Case \#1: "simple" addition selected - Array of length "nr_spectra_to_add" returned corresponding with "nr_spectra_to_add" spectra
* - Case \#2: "resampling addition selected - Array of length 1 of the resampled spectrum returned
*
* For case \#2 result is
* all spectra summed up (add) with the intensities of multiple spectra a single
* swath map (assuming these are regular SWATH / DIA maps) around the given
* retention time and return an "averaged" spectrum which may contain less noise.
*
* For case \#1 this processing is done downstream in DIA scores to speed up computation time
*
* @param[in] swath_maps The map containing the spectra
* @param[in] RT The target retention time
* @param[in] nr_spectra_to_add How many spectra to add up
* @param[in] im_range Drift time lower and upper bounds
* @return Vector of spectra to be used
*
*/
SpectrumSequence fetchSpectrumSwath(std::vector<OpenSwath::SwathMap> swath_maps, double RT, int nr_spectra_to_add, const RangeMobility& im_range);
/** @brief Prepares a spectrum for DIA analysis (multiple map)
*
* This function will fetch a SpectrumSequence to be used in DIA analysis.
* If nr_spectra_to_add == 1, then a vector of length 1 will be returned.
* Spectra are prepared differently based on the condition
* Case #1: "simple" addition selected - Array of length "nr_spectra_to_add" returned corresponding with "nr_spectra_to_add" spectra
* Case #2: "resampling addition selected - Array of length 1 of the resampled spectrum returned
*
* For case #2 result is
* all spectra summed up (add) with the intensities of multiple spectra a single
* swath map (assuming these are regular SWATH / DIA maps) around the given
* retention time and return an "averaged" spectrum which may contain less noise.
* Spectra are also filtered and summed across drift time to transform an ion mobility spectrum into a non ion mobility spectrum
*
* For case #1 this processing is done downstream in DIA scores to speed up computation time, furthermore drift time filtering is done downstream (these parameters are ignored)
*
* @param[in] swath_map The map containing the spectra
* @param[in] RT The target retention time
* @param[in] nr_spectra_to_add How many spectra to add up
* @param[in] im_range mobility range, only used if resampling spectrum addition chosen
*
* @return Vector of spectra to be used
*
*/
SpectrumSequence fetchSpectrumSwath(OpenSwath::SpectrumAccessPtr swath_map, double RT, int nr_spectra_to_add, const RangeMobility& im_range);
};
} | Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/OPENSWATH/MRMIonSeries.h | .h | 6,066 | 140 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: George Rosenberger $
// $Authors: George Rosenberger $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/ANALYSIS/TARGETED/TargetedExperiment.h>
#include <OpenMS/MATH/MathFunctions.h>
#include <map>
// #define DEBUG_MRMIONSERIES
namespace OpenMS
{
/**
@brief Generate theoretical fragment ion series for use in MRMAssay and MRMDecoy
Will generate theoretical fragment ionseries based on AASequence and parameters.
Neutral losses are supported according to a model similar to the one in SpectraST.
ReactionMonitoringTransition objects can be annotated with the corresponding CV
terms.
MRMIonSeries uses internally an annotation format that is compatible with SpectraST,
which is derived from Roepstoff and Fohlman (1984, PMID: 6525415). An annotation tag
starts with ion type (a, b, c, x, y, z) followed by the ordinal (number of amino acids).
The caret symbol follows "^" with a positive integer indicating the fragment ion charge.
If no caret symbol is present, a charge of 1 is assumed. In case of neutral loss, a
negative symbol "-" followed by the integer mass (e.g. 17 for ammonia) OR the molecular
composition, compatible with EmpiricalFormula (e.g. N1H3 for ammonia) is allowed.
Valid examples: y3, y3^1, y3^1-18, y3^1-H2O, y3-H2O
Limitations: Special SpectraST multi-assignments, immonium, precursors are not supported.
*/
class OPENMS_DLLAPI MRMIonSeries
{
private:
TargetedExperiment::Interpretation annotationToCVTermList_(const String& annotation);
void annotationToCV_(ReactionMonitoringTransition& tr);
public:
//@{
/// Constructor
MRMIonSeries();
/// Destructor
~MRMIonSeries();
//@}
typedef std::map<String, double> IonSeries; ///< An MRM ion series which maps: "ion_type" -> "fragment m/z"
/**
@brief Selects ion from IonSeries according to annotation string
@param[in,out] ionseries the IonSeries from which to choose
@param[in] ionid the annotation string of the query fragment ion
@return std::pair<String, double> the annotation and product m/z of
the queried fragment ion
*/
std::pair<String, double> getIon(IonSeries& ionseries, const String& ionid);
/**
@brief Selects ion from IonSeries according to product m/z
@param[in] ionseries the IonSeries from which to choose
@param[in] product_mz the product m/z of the queried fragment ion
@param[in] mz_threshold the m/z threshold for annotation of the fragment ion
@return std::pair<String, double> the annotation and product m/z of
the queried fragment ion
*/
std::pair<String, double> annotateIon(const IonSeries& ionseries, const double product_mz, const double mz_threshold);
/**
@brief Annotates transition with CV terms
@param[in,out] tr the transition to annotate
@param[in] annotation the fragment ion annotation.
*/
void annotateTransitionCV(ReactionMonitoringTransition& tr, const String& annotation);
/**
@brief Annotates transition
@param[in,out] tr the transition to annotate
@param[in] peptide the corresponding peptide
@param[in] precursor_mz_threshold the m/z threshold for annotation of the precursor ion
@param[in] product_mz_threshold the m/z threshold for annotation of the fragment ion
@param[in] enable_reannotation whether the original (e.g. SpectraST)
annotation should be used or reannotation should be conducted
@param[in] fragment_types the fragment ion types for reannotation
@param[in] fragment_charges the fragment ion charges for reannotation
@param[in] enable_specific_losses whether specific neutral losses should be considered
@param[in] enable_unspecific_losses whether unspecific neutral losses (H2O1, H3N1, C1H2N2, C1H2N1O1) should be considered
@param[in] round_decPow round precursor and product m/z values to decimal power (default: -4)
*/
void annotateTransition(ReactionMonitoringTransition& tr,
const TargetedExperiment::Peptide& peptide,
const double precursor_mz_threshold,
const double product_mz_threshold,
const bool enable_reannotation,
const std::vector<String>& fragment_types,
const std::vector<size_t>& fragment_charges,
const bool enable_specific_losses,
const bool enable_unspecific_losses,
const int round_decPow = -4);
/**
@brief Computed theoretical fragment ion series
@param[in] sequence the peptide amino acid sequence
@param[in] precursor_charge the charge of the peptide precursor
@param[in] fragment_types the fragment ion types for reannotation
@param[in] fragment_charges the fragment ion charges for reannotation
@param[in] enable_specific_losses whether specific neutral losses should be considered
@param[in] enable_unspecific_losses whether unspecific neutral losses (H2O1, H3N1, C1H2N2, C1H2N1O1) should be considered
@param[in] round_decPow round product m/z values to decimal power (default: -4)
@return IonSeries the theoretical fragment ion series
*/
IonSeries getIonSeries(const AASequence& sequence,
size_t precursor_charge,
const std::vector<String>& fragment_types,
const std::vector<size_t>& fragment_charges,
const bool enable_specific_losses,
const bool enable_unspecific_losses,
const int round_decPow = -4);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/OPENSWATH/MRMFeaturePicker.h | .h | 1,956 | 55 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Douglas McCloskey, Pasquale Domenico Colaianni $
// $Authors: Douglas McCloskey, Pasquale Domenico Colaianni $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/config.h> // OPENMS_DLLAPI
#include <OpenMS/DATASTRUCTURES/Param.h>
#include <OpenMS/DATASTRUCTURES/String.h>
namespace OpenMS
{
/**
@brief _MRMFeaturePicker_ defines the structures containing parameters to be used in
[MRMTransitionGroupPicker](@ref MRMTransitionGroupPicker) for components and components groups.
This data can be loaded from a file with [MRMFeaturePickerFile](@ref MRMFeaturePickerFile).
Examples of parameters are:
"TransitionGroupPicker:compute_peak_quality"
"TransitionGroupPicker:stop_after_feature"
"TransitionGroupPicker:PeakPickerChromatogram:signal_to_noise"
"TransitionGroupPicker:PeakPickerChromatogram:sn_bin_count"
*/
class OPENMS_DLLAPI MRMFeaturePicker
{
public:
/// Constructor
MRMFeaturePicker() = default;
/// Destructor
~MRMFeaturePicker() = default;
/// Structure to contain information about a single component with its parameters
struct ComponentParams
{
String component_name; ///< The component_name can't be an empty string
String component_group_name; ///< The component_group_name can't be an empty string
Param params; ///< The parameters pertaining a single component
};
/// Structure to contain information about a component group with its parameters
struct ComponentGroupParams
{
String component_group_name; ///< The component_group_name can't be an empty string
Param params; ///< The parameters pertaining a component group
};
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/OPENSWATH/TransitionPQPFile.h | .h | 16,076 | 298 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: George Rosenberger $
// $Authors: George Rosenberger, Hannes Roest $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/ANALYSIS/OPENSWATH/TransitionTSVFile.h>
// Forward declaration for SQLite
struct sqlite3;
namespace OpenMS
{
/**
@brief This class supports reading and writing of PQP files.
The PQP files are SQLite databases consisting of several tables
representing the data contained in TraML files. For another file format that stores transitions, see also
TransitionTSVFile.
This class can convert TraML and PQP files into each other
<h2> The file format has the following tables: </h2>
Genes and proteins are described by a primary key as well as a
human-readable gene name or protein accession key.
<table border="0"><tr><td>
<table>
<tr> <th BGCOLOR="#EBEBEB" colspan=3>GENE</th> </tr>
<tr> <td BGCOLOR="#EBEBEB">ID</td> <td>INT</td> <td> Primary Key (gene id)</td> </tr>
<tr> <td BGCOLOR="#EBEBEB">GENE_NAME</td> <td>TEXT</td> <td> Gene name </td> </tr>
<tr> <td BGCOLOR="#EBEBEB">DECOY</td> <td>INT (0 or 1)</td> <td> Whether this is a decoy gene (1: decoy, 0: target) </td> </tr>
</table>
</td><td valign="top">
<table>
<tr> <th BGCOLOR="#EBEBEB" colspan=3>PEPTIDE_GENE_MAPPING</th> </tr>
<tr> <td BGCOLOR="#EBEBEB">PEPTIDE_ID</td> <td>INT</td> <td> Foreign Key (PEPTIDE.ID)</td> </tr>
<tr> <td BGCOLOR="#EBEBEB">GENE_ID</td> <td>INT</td> <td> Foreign Key (GENE.ID)</td> </tr>
</table>
</td></table>
<table border="0"><tr><td>
<table>
<tr> <th BGCOLOR="#EBEBEB" colspan=3>PROTEIN</th> </tr>
<tr> <td BGCOLOR="#EBEBEB">ID</td> <td>INT</td> <td> Primary Key (protein id)</td> </tr>
<tr> <td BGCOLOR="#EBEBEB">PROTEIN_ACCESSION</td> <td>TEXT</td> <td> Protein accession </td> </tr>
<tr> <td BGCOLOR="#EBEBEB">DECOY</td> <td>INT (0 or 1)</td> <td> Whether this is a decoy protein (1: decoy, 0: target) </td> </tr>
</table>
</td><td valign="top">
<table>
<tr> <th BGCOLOR="#EBEBEB" colspan=3>PEPTIDE_PROTEIN_MAPPING</th> </tr>
<tr> <td BGCOLOR="#EBEBEB">PEPTIDE_ID</td> <td>INT</td> <td> Foreign Key (PEPTIDE.ID)</td> </tr>
<tr> <td BGCOLOR="#EBEBEB">PROTEIN_ID</td> <td>INT</td> <td> Foreign Key (PROTEIN.ID)</td> </tr>
</table>
</td></table>
Peptides are physical analytes that are present in the sample and can carry post-translational modifications (PTMs). They are described by their amino-acid sequence and the modifications they carry:
<table border="0"><tr><td>
<table>
<tr> <th BGCOLOR="#EBEBEB" colspan=3>PEPTIDE</th> </tr>
<tr> <td BGCOLOR="#EBEBEB">ID</td> <td>INT</td> <td> Primary Key (peptide id)</td> </tr>
<tr> <td BGCOLOR="#EBEBEB">UNMODIFIED_SEQUENCE</td> <td>TEXT</td> <td> Peptide sequence (unmodified) </td> </tr>
<tr> <td BGCOLOR="#EBEBEB">MODIFIED_SEQUENCE</td> <td>TEXT</td> <td> Peptide sequence (modified) <sup>1</sup></td> </tr>
<tr> <td BGCOLOR="#EBEBEB">DECOY</td> <td>INT (0 or 1)</td> <td> Whether this is a decoy peptide (1: decoy, 0: target) </td> </tr>
</table>
</td><td valign="top">
<table>
<tr> <th BGCOLOR="#EBEBEB" colspan=3>PRECURSOR_PEPTIDE_MAPPING</th> </tr>
<tr> <td BGCOLOR="#EBEBEB">PRECURSOR_ID</td> <td>INT</td> <td> Foreign Key (PRECURSOR.ID)</td> </tr>
<tr> <td BGCOLOR="#EBEBEB">PEPTIDE_ID</td> <td>INT</td> <td> Foreign Key (PEPTIDE.ID)</td> </tr>
</table>
</td></table>
Compounds are generic analytes that are present in the sample (but are not peptides). This is used for small molecules which are described by their molecular formula and the SMILES representation (structural representation):
<table border="0"><tr><td>
<table>
<tr> <th BGCOLOR="#EBEBEB" colspan=3>COMPOUND</th> </tr>
<tr> <td BGCOLOR="#EBEBEB">ID</td> <td>INT</td> <td> Primary Key (compound id)</td> </tr>
<tr> <td BGCOLOR="#EBEBEB">COMPOUND_NAME</td> <td>TEXT</td> <td> Compound name (common name of the analyte)</td> </tr>
<tr> <td BGCOLOR="#EBEBEB">SUM_FORMULA</td> <td>TEXT</td> <td> Molecular formula of the compound </td> </tr>
<tr> <td BGCOLOR="#EBEBEB">SMILES</td> <td>TEXT</td> <td> SMILES representation</td> </tr>
<tr> <td BGCOLOR="#EBEBEB">ADDUCTS</td> <td>TEXT</td> <td> List of adducts for the compound</td> </tr>
<tr> <td BGCOLOR="#EBEBEB">DECOY</td> <td>INT (0 or 1)</td> <td> Whether this is a decoy compound (1: decoy, 0: target) </td> </tr>
</table>
</td><td valign="top">
<table>
<tr> <th BGCOLOR="#EBEBEB" colspan=3>PRECURSOR_COMPOUND_MAPPING</th> </tr>
<tr> <td BGCOLOR="#EBEBEB">PRECURSOR_ID</td> <td>INT</td> <td> Foreign Key (PRECURSOR.ID)</td> </tr>
<tr> <td BGCOLOR="#EBEBEB">COMPOUND_ID</td> <td>INT</td> <td> Foreign Key (COMPOUND.ID)</td> </tr>
</table>
</td></table>
Precursors are generated upon ionization from peptides or small molecule analytes (compounds) and are described by their charge state, mass-to-charge ratio, retention time and ion mobility drift time:
<table border="0"><tr><td>
<table>
<tr> <th BGCOLOR="#EBEBEB" colspan=3>PRECURSOR</th> </tr>
<tr> <td BGCOLOR="#EBEBEB">ID</td> <td>INT</td> <td> Primary Key (precursor id)</td> </tr>
<tr> <td BGCOLOR="#EBEBEB">TRAML_ID</td> <td>TEXT</td> <td> TraML identifiers (maps to the "id=" attribute in TraML)</td> </tr>
<tr> <td BGCOLOR="#EBEBEB">GROUP_LABEL</td> <td>TEXT</td> <td> designates to which peptide label group (as defined in MS:1000893) the peptide belongs to<sup>2</sup></td> </tr>
<tr> <td BGCOLOR="#EBEBEB">PRECURSOR_MZ</td> <td>REAL</td> <td> %Precursor m/z </td> </tr>
<tr> <td BGCOLOR="#EBEBEB">CHARGE</td> <td>TEXT</td> <td> %Precursor charge state </td> </tr>
<tr> <td BGCOLOR="#EBEBEB">LIBRARY_INTENSITY</td> <td>TEXT</td> <td> %Precursor library intensity </td> </tr>
<tr> <td BGCOLOR="#EBEBEB">LIBRARY_RT</td> <td>TEXT</td> <td> Library retention time (RT) </td> </tr>
<tr> <td BGCOLOR="#EBEBEB">LIBRARY_DRIFT_TIME</td> <td>TEXT</td> <td> Library drift time (ion mobility drift time or collisional cross-section) </td> </tr>
<tr> <td BGCOLOR="#EBEBEB">DECOY</td> <td>INT (0 or 1)</td> <td> Whether this is a decoy precursor (1: decoy, 0: target) </td> </tr>
</table>
</td><td valign="top">
<table>
<tr> <th BGCOLOR="#EBEBEB" colspan=3>TRANSITION_PRECURSOR_MAPPING</th> </tr>
<tr> <td BGCOLOR="#EBEBEB">TRANSITION_ID</td> <td>INT</td> <td> Foreign Key (TRANSITION.ID)</td> </tr>
<tr> <td BGCOLOR="#EBEBEB">PRECURSOR_ID</td> <td>INT</td> <td> Foreign Key (PRECURSOR.ID)</td> </tr>
</table>
</td></table>
Transitions are generated upon fragmentation from precursors and are described by their charge state and (fragment) mass-to-charge ratio. For peptide fragments, an ion type (e.g. y for y-ions) and a ordinal (e.g. 6 for a y6 ion) can be recorded. Note that detecting transitions are used for precursor detection and will indicate whether a given precursor is present or not in the sample. Use detecting transitions for the top N transitions of a precursor to detect a set of transitions in the sample. Identifying transitions will be used to discriminate different peptidoforms of the same precursor (see <a href="http://openswath.org/en/latest/docs/ipf.html">IPF Workflow</a> for PTM inference).
<table border="0"><tr><td>
<table>
<tr> <th BGCOLOR="#EBEBEB" colspan=3>TRANSITION</th> </tr>
<tr> <td BGCOLOR="#EBEBEB">ID</td> <td>INT</td> <td> Primary Key (transition id)</td> </tr>
<tr> <td BGCOLOR="#EBEBEB">TRAML_ID</td> <td>TEXT</td> <td> TraML identifiers (maps to the "id=" attribute in TraML)</td> </tr>
<tr> <td BGCOLOR="#EBEBEB">PRODUCT_MZ</td> <td>TEXT</td> <td> Fragment ion m/z </td> </tr>
<tr> <td BGCOLOR="#EBEBEB">CHARGE</td> <td>TEXT</td> <td> Fragment ion charge </td> </tr>
<tr> <td BGCOLOR="#EBEBEB">TYPE</td> <td>CHAR</td> <td> Fragment ion type (e.g. "b" or "y")</td> </tr>
<tr> <td BGCOLOR="#EBEBEB">ANNOTATION</td> <td>TEXT</td> <td> Fragment ion annotation </td> </tr>
<tr> <td BGCOLOR="#EBEBEB">ORDINAL</td> <td>INT</td> <td> Fragment ion ordinal </td> </tr>
<tr> <td BGCOLOR="#EBEBEB">DETECTING</td> <td>INT (0 or 1)</td> <td>1: use transition to detect peak group, 0: don't use transition for detection</td> </tr>
<tr> <td BGCOLOR="#EBEBEB">IDENTIFYING</td> <td>INT (0 or 1)</td> <td> 1: use transition for peptidoform inference in the <a href="http://openswath.org/en/latest/docs/ipf.html">IPF Workflow</a>, 0: don't use transition for identification</td> </tr>
<tr> <td BGCOLOR="#EBEBEB">QUANTIFYING</td> <td>INT (0 or 1)</td> <td> 1: use transition to quantify peak group, 0: don't use transition for quantification</td> </tr>
<tr> <td BGCOLOR="#EBEBEB">LIBRARY_INTENSITY</td> <td>REAL</td> <td> Fragment ion library intensity </td> </tr>
<tr> <td BGCOLOR="#EBEBEB">DECOY</td> <td>INT (0 or 1)</td> <td> Whether this is a decoy transition (1: decoy, 0: target) </td> </tr>
</table>
</td>
</table>
</td></table>
There is one extra table directly mapping TRANSITION to PEPTIDE which is mainly used for the
<a href="http://openswath.org/en/latest/docs/ipf.html">IPF Workflow</a> for PTM inference. It directly maps transitions to peptidoforms
(one identification transition can map to multiple peptidoforms):
<table border="0"><tr><td>
</td><td>
<table>
<tr> <th BGCOLOR="#EBEBEB" colspan=3>TRANSITION_PEPTIDE_MAPPING</th> </tr>
<tr> <td BGCOLOR="#EBEBEB">TRANSITION_ID</td> <td>INT</td> <td> Foreign Key (TRANSITION.ID)</td> </tr>
<tr> <td BGCOLOR="#EBEBEB">PEPTIDE_ID</td> <td>INT</td> <td> Foreign Key (PEPTIDE.ID)</td> </tr>
</table>
</td></table>
</td></table>
Another extra table describes the file format version:
<table>
<tr> <th BGCOLOR="#EBEBEB" colspan=3>VERSION</th> </tr>
<tr> <td BGCOLOR="#EBEBEB">ID</td> <td>INT</td> <td> %File Format version </td> </tr>
</table>
<p>
Remarks:
</p>
<ul>
<li>
1. modifications should be supplied inside the sequence using UniMod
identifiers or freetext identifiers that are understood by %OpenMS. See also @ref OpenMS::AASequence for more information. For example:
<ul>
<li> PEPT(Phosphorylation)IDE(UniMod:27)A ) </li>
</ul>
</li>
<li>
2. peptide label groups designate groups of peptides that are isotopically
modified forms of the same peptide species. For example, the heavy and
light forms of the same peptide will both be assigned the same peptide
group label. For example:
<ul>
<li> PEPTIDEAK -> gets label "PEPTIDEAK_gr1" </li>
<li> PEPTIDEAK[+8] -> gets label "PEPTIDEAK_gr1" </li>
<li> PEPT(Phosphorylation)IDEAK -> gets label "PEPTIDEAK_gr2" </li>
<li> PEPT(Phosphorylation)IDEAK[+8] -> gets label "PEPTIDEAK_gr2" </li>
</ul>
</li>
</ul>
</p>
@htmlinclude OpenMS_TransitionPQPFile.parameters
*/
class OPENMS_DLLAPI TransitionPQPFile :
public TransitionTSVFile
{
private:
/// Holds information about a PQP SQL query and optional column availability
struct PQPSqlQueryInfo
{
std::string select_sql; ///< The complete SQL SELECT query
bool drift_time_exists; ///< Whether LIBRARY_DRIFT_TIME column exists
bool gene_exists; ///< Whether GENE table exists
};
/** @brief Build the SQL query for reading PQP transitions
*
* This helper builds the SQL query used by both readPQPInput_ and
* streamPQPToLightTargetedExperiment_ to avoid code duplication.
*
* @param[in] db The SQLite database connection
* @param[in] legacy_traml_id Whether to use legacy TraML IDs
* @return PQPSqlQueryInfo containing the query and column availability flags
*/
PQPSqlQueryInfo buildPQPSelectQuery_(sqlite3* db, bool legacy_traml_id) const;
/** @brief Read PQP SQLite file
*
* @param[in] filename The input file
* @param[out] transition_list The output list of transitions
* @param[in] legacy_traml_id Should legacy TraML IDs be used (boolean)?
*
*/
void readPQPInput_(const char* filename, std::vector<TSVTransition>& transition_list, bool legacy_traml_id = false);
/** @brief Stream PQP directly to LightTargetedExperiment (memory-efficient)
*
* This function reads the PQP file and directly populates the
* LightTargetedExperiment without creating an intermediate vector<TSVTransition>.
* This reduces peak memory usage by ~5x for large files.
*
* @param[in] filename The input file
* @param[out] exp The output LightTargetedExperiment
* @param[in] legacy_traml_id Should legacy TraML IDs be used (boolean)?
*
*/
void streamPQPToLightTargetedExperiment_(const char* filename, OpenSwath::LightTargetedExperiment& exp, bool legacy_traml_id = false);
/** @brief Write a TargetedExperiment to a file
*
* @param[in] filename Name of the output file
* @param[out] targeted_exp The data structure to be written to the file
*/
void writePQPOutput_(const char* filename, OpenMS::TargetedExperiment& targeted_exp);
public:
//@{
/// Constructor
TransitionPQPFile();
/// Destructor
~TransitionPQPFile() override;
//@}
/** @brief Write out a targeted experiment (TraML structure) into a PQP file
*
@param[in] filename The output file
@param[out] targeted_exp The targeted experiment
*
*/
void convertTargetedExperimentToPQP(const char* filename, OpenMS::TargetedExperiment& targeted_exp);
/** @brief Write out a targeted experiment (Light structure) into a PQP file
*
@param[in] filename The output file
@param[in] targeted_exp The targeted experiment (Light structure)
*
*/
void convertLightTargetedExperimentToPQP(const char* filename, const OpenSwath::LightTargetedExperiment& targeted_exp);
/** @brief Read in a PQP file and construct a targeted experiment (TraML structure)
*
@param[out] filename The input file
@param[out] targeted_exp The output targeted experiment
@param[in] legacy_traml_id Should legacy TraML IDs be used (boolean)?
*
*/
void convertPQPToTargetedExperiment(const char* filename, OpenMS::TargetedExperiment& targeted_exp, bool legacy_traml_id = false);
/** @brief Read in a PQP file and construct a targeted experiment (Light transition structure)
*
* @param[out] filename The input file
* @param[out] targeted_exp The output targeted experiment
* @param[in] legacy_traml_id Should legacy TraML IDs be used (boolean)?
*
*/
void convertPQPToTargetedExperiment(const char* filename, OpenSwath::LightTargetedExperiment& targeted_exp, bool legacy_traml_id = false);
/** @brief Creates an undordered map between the traml_id and the pqp id
*
* @param[in] filename The input file
* @param[in] tableName The name of the table (can be "PRECURSOR" or "TRANSITION" since theses are the only tables that have a TRAML_ID)
*/
std::unordered_map<std::string, std::string> getPQPIDToTraMLIDMap(const char* filename, std::string tableName);
};
} | Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/OPENSWATH/MRMFeatureFilter.h | .h | 15,987 | 346 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Douglas McCloskey, Pasquale Domenico Colaianni $
// $Authors: Douglas McCloskey, Pasquale Domenico Colaianni $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/ANALYSIS/OPENSWATH/MRMFeatureQC.h>
#include <OpenMS/ANALYSIS/TARGETED/TargetedExperiment.h>
#include <OpenMS/KERNEL/MRMFeature.h>
#include <OpenMS/KERNEL/Feature.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/DATASTRUCTURES/String.h>
namespace OpenMS
{
class AbsoluteQuantitationMethod;
/**
@brief The MRMFeatureFilter either flags components and/or transitions that do not pass the QC criteria or filters out
components and/or transitions that do not pass the QC criteria.
This class provides comprehensive quality control filtering for MRM/SRM features. It can:
- Filter based on retention time, intensity, and quality bounds
- Filter based on ion ratios between transitions
- Filter based on %RSD from pooled QC samples
- Filter based on background interference from blank samples
- Estimate default QC values from standard samples
@htmlinclude OpenMS_MRMFeatureFilter.parameters
@see MRMFeatureQC for QC parameter structure
@see AbsoluteQuantitation for downstream quantitation
@ingroup TargetedQuantitation
*/
class OPENMS_DLLAPI MRMFeatureFilter :
public DefaultParamHandler
{
public:
//@{
/// Constructor
MRMFeatureFilter();
/// Destructor
~MRMFeatureFilter() override;
//@}
/**
@brief Get the class' default parameters
@param[out] params Output parameters
*/
void getDefaultParameters(Param& params) const;
/// Synchronize members with param class
void updateMembers_() override;
/**
@brief Flags or filters features and subordinates in a FeatureMap
@param[in] features FeatureMap to flag or filter
@param[in] filter_criteria MRMFeatureQC class defining QC parameters
@param[out] transitions transitions from a TargetedExperiment
*/
void FilterFeatureMap(FeatureMap& features, const MRMFeatureQC& filter_criteria,
const TargetedExperiment& transitions);
/**
@brief Flags or filters features and subordinates in a FeatureMap based on a user
defined set of filter values derived from calling `EstimatePercRSD`. The user supplied
filter_criteria represents the bounds on acceptable PercentRSD values.
NOTE that flagging nor filtering will be done on the labels and transitions type counts.
@param[in] features FeatureMap to flag or filter
@param[in] filter_criteria MRMFeatureQC class defining QC parameters defining the acceptable limits of the PercentRSD
where PercentRSD = (value std dev)/(value mean)*100Percent
@param[out] filter_values MRMFeatureQC class filled with bounds representing the PercentRSD found in e.g., pooled QC samples or replicate Unknown samples
*/
void FilterFeatureMapPercRSD(FeatureMap& features, const MRMFeatureQC& filter_criteria, const MRMFeatureQC& filter_values);
/**
@brief Flags or filters features and subordinates in a FeatureMap based on a user
defined set of filter values derived from calling `EstimateBackgroundInterferences`. The user supplied
filter_criteria represents the bounds on acceptable PercentBackgroundInterference values.
NOTE that filtering is only done on the `Intensity` member.
@param[in] features FeatureMap to flag or filter
@param[in] filter_criteria MRMFeatureQC class defining QC parameters defining the acceptable limits of PercentBackgroundInterference
where PercentBackgroundInterference = (value Sample)/(value Blank)*100Percent
@param[out] filter_values MRMFeatureQC class filled with bounds representing the average values found in e.g., pooled QC samples or replicate Unknown samples
*/
void FilterFeatureMapBackgroundInterference(FeatureMap& features, const MRMFeatureQC& filter_criteria, const MRMFeatureQC& filter_values);
/**
@brief Estimate the lower and upper bound values for the MRMFeatureQC class based on a
user supplied template. The template can either be initialized from the first sample
(meaning all initial template values are over written) or not (meaning the initial template
values will be updated if the ranges are found to be too narrow)
@param[in] samples Samples (typically Standards) from which to estimate the lower and upper bound values for the MRMFeatureQC members
@param[in,out] filter_template A MRMFeatureQC class that will be used as a template to fill in the estimated lower and upper values.
A "template" is needed so that the MRMFeatureQC::meta_value_qc parameters that the FeatureMap::MetaValues that user would like estimated are known.
@param[in] transitions transitions from a TargetedExperiment
@param[in] init_template_values Boolean indicating whether to initialize the template values based on the first sample
*/
void EstimateDefaultMRMFeatureQCValues(const std::vector<FeatureMap>& samples, MRMFeatureQC& filter_template, const TargetedExperiment& transitions, const bool& init_template_values) const;
/**
@brief Transfer the lower and upper bound values for the calculated concentrations
based off of the AbsoluteQuantitationMethod
@param[in] quantitation_method The absolute quantitation methods that has been determined for each component
@param[in,out] filter_template A MRMFeatureQC class that will be used as a template to fill in the
MRMFeatureQC::ComponentQCs.calculated_concentration bounds based on the LLOQ and ULOQ values given in the quantitation_method.
*/
void TransferLLOQAndULOQToCalculatedConcentrationBounds(const std::vector<AbsoluteQuantitationMethod>& quantitation_method, MRMFeatureQC& filter_template);
/**
@brief Estimate the feature variability as measured by PercentRSD from multiple pooled QC samples
or replicate Unknown samples. The returned filter_template can then be used by
`FilterFeatureMapPercRSD` in order to filter based on the PercentRSD user defined limits.
@param[in] samples multiple pooled QC samples or replicate Unknown samples FeatureMaps
@param[in,out] filter_template A MRMFeatureQC class that will be used as a template to determine what FeatureMap values
to estimate the PercentRSD for. The PercentRSD values will be stored in the upper bound parameter of the filter_template
@param[in] transitions transitions from a TargetedExperiment
*/
void EstimatePercRSD(const std::vector<FeatureMap>& samples, MRMFeatureQC& filter_template, const TargetedExperiment& transitions) const;
/**
@brief Estimate the background interference level based on the average values from Blank samples.
The returned filter_template can then be used by `FilterFeatureMapBackgroundInterference`
in order to filter on the `Intensity` members of MRMFeatureQC::ComponentGroupQCs and MRMFeatureQC::ComponentQCs.
@param[in] samples multiple Blank samples to estimate the background intensity values FeatureMaps
@param[in,out] filter_template A MRMFeatureQC class that will be used as a template to determine what FeatureMap values
to estimate the PercentInterference. The average values will be stored in the upper bound parameter of the filter_template
@param[in] transitions transitions from a TargetedExperiment
*/
void EstimateBackgroundInterferences(const std::vector<FeatureMap>& samples, MRMFeatureQC& filter_template, const TargetedExperiment& transitions) const;
/**
@brief Calculates the ion ratio between two transitions
@param[in] component_1 component of the numerator
@param[in] component_2 component of the denominator
@param[in] feature_name name of the feature to calculate the ratio on
e.g., peak_apex, peak_area
@return The ratio.
*/
double calculateIonRatio(const Feature& component_1, const Feature& component_2, const String& feature_name) const;
/**
@brief Calculates the retention time difference between two features
@param[in] component_1 First eluting component
@param[in] component_2 Second eluting component
@return The difference.
*/
double calculateRTDifference(Feature& component_1, Feature& component_2) const;
/**
@brief Calculates the resolution between two features
@param[in] component_1 component 1
@param[in] component_2 component 2
@return The difference.
*/
double calculateResolution(Feature& component_1, Feature& component_2) const;
/**
@brief Checks if the metaValue is within the user specified range
@param[in] component component of the numerator
@param[in] meta_value_key Name of the metaValue
@param[in] meta_value_l Lower bound (inclusive) for the metaValue range
@param[in] meta_value_u Upper bound (inclusive) for the metaValue range
@param[out] key_exists true if the given key is found, false otherwise
@return True if the metaValue is within the bounds, and False otherwise.
*/
bool checkMetaValue(
const Feature& component,
const String& meta_value_key,
const double& meta_value_l,
const double& meta_value_u,
bool& key_exists
) const;
/**
@brief Updates the metaValue ranges based on the value given
@param[in] component component of the numerator
@param[in] meta_value_key Name of the metaValue
@param[in,out] meta_value_l Lower bound (inclusive) for the metaValue range
@param[in,out] meta_value_u Upper bound (inclusive) for the metaValue range
@param[out] key_exists true if the given key is found, false otherwise
*/
void updateMetaValue(
const Feature& component,
const String& meta_value_key,
double& meta_value_l,
double& meta_value_u,
bool& key_exists
) const;
/**
@brief Uses the supplied value to set the metaValue ranges
@param[in] component component of the numerator
@param[in] meta_value_key Name of the metaValue
@param[in,out] meta_value_l Lower bound (inclusive) for the metaValue range
@param[in,out] meta_value_u Upper bound (inclusive) for the metaValue range
@param[out] key_exists true if the given key is found, false otherwise
*/
void setMetaValue(
const Feature& component,
const String& meta_value_key,
double& meta_value_l,
double& meta_value_u,
bool& key_exists
) const;
/**
@brief Uses the supplied value to initialize the metaValue ranges to the same value
@param[in] component component of the numerator
@param[in] meta_value_key Name of the metaValue
@param[in,out] meta_value_l Lower bound (inclusive) for the metaValue range
@param[in,out] meta_value_u Upper bound (inclusive) for the metaValue range
@param[out] key_exists true if the given key is found, false otherwise
*/
void initMetaValue(
const Feature& component,
const String& meta_value_key,
double& meta_value_l,
double& meta_value_u,
bool& key_exists
) const;
/**
@brief Count the number of heavy/light labels and quantifying/detecting/identifying transitions
@param[in] component_group Component group with subordinates
@param[out] transitions Transitions from a TargetedExperiment
@return Map of labels/transition types and their corresponding number.
*/
std::map<String,int> countLabelsAndTransitionTypes(const Feature& component_group,
const TargetedExperiment& transitions) const;
/**
@brief Sorts the messages and returns a copy without duplicates
@param[in] messages A StringList containing the failure messages
@return A copy of the input, without duplicates
*/
StringList getUniqueSorted(const StringList& messages) const;
/**
@brief Accumulate feature values from a list of FeatureMaps
@param[out] filter_values A list of MRMFeatureQC objects filled with the values determined by the filter_template from the samples
@param[in] samples A list of feature maps
@param[in] filter_template A MRMFeatureQC object that will be used as a template to fill in values derived from the sample feature maps
@param[in] transitions transitions from a TargetedExperiment
*/
void accumulateFilterValues(std::vector<MRMFeatureQC>& filter_values, const std::vector<FeatureMap>& samples, const MRMFeatureQC& filter_template, const TargetedExperiment& transitions) const;
/**
@brief Set all members in MRMFeatureQC to zero
@param[out] filter_zeros A MRMFeatureQC object whose members have been set to 0
@param[in] filter_template A MRMFeatureQC object that will be used as a template to fill in values
*/
void zeroFilterValues(MRMFeatureQC& filter_zeros, const MRMFeatureQC& filter_template) const;
/**
@brief Calculate the mean of each MRMFeatureQC parameter from a list of MRMFeatureQC classes
@param[out] filter_mean A MRMFeatureQC object whose members will be replaced by the mean values
@param[in] filter_values A list of MRMFeatureQC objects
@param[in] filter_template A MRMFeatureQC object that will be used as a template to fill in values
*/
void calculateFilterValuesMean(MRMFeatureQC& filter_mean, const std::vector<MRMFeatureQC>& filter_values, const MRMFeatureQC& filter_template) const;
/**
@brief Calculate the var of each MRMFeatureQC parameter from a list of MRMFeatureQC classes
@param[out] filter_var A MRMFeatureQC object whose members will be replaced by the variance of the values
@param[in] filter_values A list of MRMFeatureQC objects
@param[in] filter_mean A MRMFeatureQC object with the mean values of the filter_values
@param[in] filter_template A MRMFeatureQC object that will be used as a template to fill in values
*/
void calculateFilterValuesVar(MRMFeatureQC& filter_var, const std::vector<MRMFeatureQC>& filter_values, const MRMFeatureQC& filter_mean, const MRMFeatureQC& filter_template) const;
/**
@brief Calculate the relative standard deviation (PercentRSD) of each MRMFeatureQC parameter from pre-computed mean and variance values
@param[out] filter_rsd A MRMFeatureQC object whose members will be replaced by PercentRSD
@param[in] filter_var A MRMFeatureQC object with the variance
@param[in] filter_mean A MRMFeatureQC object with the mean
*/
void calculateFilterValuesPercRSD(MRMFeatureQC& filter_rsd, const MRMFeatureQC& filter_mean, const MRMFeatureQC& filter_var) const;
/// Checks that the range of value is bracketed by value_l and value_u
template <typename T>
bool checkRange(const T& value, const T& value_l, const T& value_u) const;
/// Updates value_l and value_u according to whether value is greater than value_u or less than value_l
template <typename T>
void updateRange(const T& value, T& value_l, T& value_u) const;
/// Sets value_l and value_u to bracket the range 0 to value or value to 0 depending on if value is >0
template <typename T>
void setRange(const T& value, T& value_l, T& value_u) const;
/// Sets value_l and value_u to value
template <typename T>
void initRange(const T& value, T& value_l, T& value_u) const;
private:
// Members
/// flag or filter (i.e., remove) features that do not pass the QC
String flag_or_filter_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/OPENSWATH/MRMFeatureFinderScoring.h | .h | 13,783 | 307 | // 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
#define USE_SP_INTERFACE
// Actual scoring
#include <OpenMS/ANALYSIS/OPENSWATH/OpenSwathScoring.h>
#include <OpenMS/ANALYSIS/OPENSWATH/DIAScoring.h>
#include <OpenMS/FEATUREFINDER/EmgScoring.h>
// Kernel classes
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/ANALYSIS/MAPMATCHING/TransformationDescription.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/KERNEL/MRMTransitionGroup.h>
#include <OpenMS/KERNEL/MRMFeature.h>
#include <OpenMS/KERNEL/MSSpectrum.h>
#include <OpenMS/KERNEL/MSChromatogram.h>
#include <OpenMS/ANALYSIS/TARGETED/TargetedExperiment.h>
#include <OpenMS/OPENSWATHALGO/DATAACCESS/SwathMap.h>
#include <unordered_map>
#ifdef _OPENMP
#include <omp.h>
#endif
bool SortDoubleDoublePairFirst(const std::pair<double, double>& left, const std::pair<double, double>& right);
namespace OpenMS
{
/**
@brief The MRMFeatureFinder finds and scores peaks of transitions that co-elute.
It does so using an internal peakpicker for each chromatogram and then
creating consensus / meta-peaks (MRMFeatures) that contain the information of
all corresponding chromatograms at the peak-position. It then goes on to
score those MRMFeatures using different criteria described in the
MRMScoring class.
Internally, all peak group detection is performed in MRMTransitionGroupPicker
which segments the data and determines consensus peaks across traces
(MRMFeatures). All scoring is delegated to the OpenSwathScoring class which
implements i) chromatographic scores, ii) library based scores and iii) full
spectrum (DIA) scores. These scores are retrieved from the OpenSwathScoring
class and added to the MRMFeatures found in this algorithm. Note that the
OpenSwathScoring is a facade that can be used to communicate with the
underlying actual scoring engines and assembles the scores inside a scoring
object called OpenSwath_Scores where they are easy to retrieve.
@htmlinclude OpenMS_MRMFeatureFinderScoring.parameters
*/
class OPENMS_DLLAPI MRMFeatureFinderScoring :
public DefaultParamHandler,
public ProgressLogger
{
public:
///Type definitions
//@{
typedef OpenSwath::LightTransition TransitionType;
typedef OpenSwath::LightTargetedExperiment TargetedExpType;
typedef OpenSwath::LightCompound PeptideType;
typedef OpenSwath::LightProtein ProteinType;
typedef OpenSwath::LightModification ModificationType;
// a transition group holds the chromatographic data and peaks across
// multiple chromatograms from the same compound
typedef MRMTransitionGroup< MSChromatogram, TransitionType> MRMTransitionGroupType;
typedef std::map<String, MRMTransitionGroupType> TransitionGroupMapType;
//@}
/// Constructor
MRMFeatureFinderScoring();
/// Destructor
~MRMFeatureFinderScoring() override;
/// Picker and prepare functions
//@{
/** @brief Pick and score features in a single experiment from chromatograms
*
* Function for wrapping in Python, only uses OpenMS datastructures and
* does not return the map.
*
* @param[in] chromatograms The input chromatograms
* @param[out] output The output features with corresponding scores
* @param[in] transition_exp The transition list describing the experiment
* @param[in] trafo Optional transformation of the experimental retention time
* to the normalized retention time space used in the transition list
* @param[in] swath_map Optional SWATH-MS (DIA) map corresponding from which the chromatograms were extracted
*
*/
void pickExperiment(const PeakMap & chromatograms,
FeatureMap& output,
const TargetedExperiment& transition_exp,
const TransformationDescription& trafo,
const PeakMap& swath_map);
/** @brief Pick and score features in a single experiment from chromatograms
*
* @param[in] input The input chromatograms
* @param[out] output The output features with corresponding scores
* @param[in] transition_exp The transition list describing the experiment
* @param[in] trafo Optional transformation of the experimental retention time
* to the normalized retention time space used in the
* transition list.
* @param[in] swath_maps Optional SWATH-MS (DIA) map corresponding from which
* the chromatograms were extracted. Use empty map if no
* data is available.
* @param[in] transition_group_map Output mapping of transition groups
*
*/
void pickExperiment(const OpenSwath::SpectrumAccessPtr& input,
FeatureMap& output,
const OpenSwath::LightTargetedExperiment& transition_exp,
const TransformationDescription& trafo,
const std::vector<OpenSwath::SwathMap>& swath_maps,
TransitionGroupMapType& transition_group_map);
/** @brief Prepares the internal mappings of peptides and proteins.
*
* Calling this method _is_ required before calling scorePeakgroups.
*
* @param[in] transition_exp The transition list describing the experiment
*
*/
void prepareProteinPeptideMaps_(const OpenSwath::LightTargetedExperiment& transition_exp);
//@}
/** @brief Score all peak groups of a transition group
*
* Iterate through all features found along the chromatograms of the
* transition group and score each one individually.
*
* @param[in] transition_group The MRMTransitionGroup to be scored (input)
* @param[in] trafo Optional transformation of the experimental retention time
* to the normalized retention time space used in the
* transition list.
* @param[in] swath_maps Optional SWATH-MS (DIA) map corresponding from which
* the chromatograms were extracted. Use empty map if no
* data is available.
* @param[out] output The output features with corresponding scores (the found
* features will be added to this FeatureMap).
* @param[in] ms1only Whether to only do MS1 scoring and skip all MS2 scoring
*
*/
void scorePeakgroups(MRMTransitionGroupType& transition_group,
const TransformationDescription & trafo,
const std::vector<OpenSwath::SwathMap>& swath_maps,
FeatureMap& output,
bool ms1only = false) const;
/** @brief Set the flag for strict mapping
*/
void setStrictFlag(bool f)
{
strict_ = f;
}
/** @brief Add an MS1 map containing spectra
*
* For DIA (SWATH-MS), an optional MS1 map can be supplied which can be
* used to extract precursor ion signal and provides additional scores. If
* no MS1 map is provided, the respective scores are not calculated.
*
* @param[in] ms1_map The raw mass spectrometric MS1 data
*
*/
void setMS1Map(OpenSwath::SpectrumAccessPtr ms1_map)
{
ms1_map_ = ms1_map;
}
/** @brief Map the chromatograms to the transitions.
*
* Map an input chromatogram experiment (mzML) and transition list (TraML)
* onto each other when they share identifiers, e.g. if the transition id
* is the same as the chromatogram native id.
*
* @param[in] input The input chromatograms
* @param[in] transition_exp The transition list describing the experiment
* @param[in] transition_group_map Mapping of transition groups
* @param[in] trafo Optional transformation of the experimental retention time
* to the normalized retention time space used in the
* transition list.
* @param[in] rt_extraction_window The used retention time extraction window
*
*/
void mapExperimentToTransitionList(const OpenSwath::SpectrumAccessPtr& input,
const OpenSwath::LightTargetedExperiment& transition_exp,
TransitionGroupMapType& transition_group_map,
TransformationDescription trafo,
double rt_extraction_window);
private:
/** @brief Splits combined transition groups into detection transition groups
*
* For standard assays, transition_group_detection is identical to transition_group and the others are empty.
*
* @param[in] transition_group Containing all detecting, identifying transitions
* @param[in] transition_group_detection To be filled with detecting transitions
*/
void splitTransitionGroupsDetection_(const MRMTransitionGroupType& transition_group,
MRMTransitionGroupType& transition_group_detection) const;
/** @brief Splits combined transition groups into identification transition groups
*
* For standard assays, transition_group_identification is empty. When UIS scoring
* is enabled, it contains the corresponding identification transitions.
*
* @param[in] transition_group Containing all detecting, identifying transitions
* @param[in] transition_group_identification To be filled with identifying transitions
* @param[out] transition_group_identification_decoy To be filled with identifying decoy transitions
*/
void splitTransitionGroupsIdentification_(const MRMTransitionGroupType& transition_group,
MRMTransitionGroupType& transition_group_identification,
MRMTransitionGroupType& transition_group_identification_decoy) const;
/** @brief Provides scoring for target and decoy identification against detecting transitions
*
* The function is used twice, for target and decoy identification transitions. The results are
* reported analogously to the ones for detecting transitions but must be stored separately.
*
* @param[out] transition_group_identification Containing all detecting and identifying transitions
* @param[out] transition_group_detection Containing all detecting transitions
* @param[in] scorer An instance of OpenSwathScoring
* @param[in] feature_idx The index of the current feature
* @param[in] native_ids_detection The native IDs of the detecting transitions
* @param[in] det_intensity_ratio_score The intensity score of the detection transitions for normalization
* @param[in] det_mi_ratio_score The MI score of the detection transitions for normalization
* @param[in] swath_maps Optional SWATH-MS (DIA) map corresponding from which
* the chromatograms were extracted. Use empty map if no
* data is available.
* @param[out] drift_target The target drift value
* @param[in] im_range Ion mobility subrange to consider (used as filter); can be empty (i.e. no IM filtering). If scoring non-IMS data, this should be empty, otherwise a missing information exception is thrown when integrating spectra for scoring.
* @return a struct of type OpenSwath_Ind_Scores containing either target or decoy values
*/
OpenSwath_Ind_Scores scoreIdentification_(MRMTransitionGroupType& transition_group_identification,
MRMTransitionGroupType& transition_group_detection,
OpenSwathScoring& scorer,
const size_t feature_idx,
const std::vector<std::string> & native_ids_detection,
const double det_intensity_ratio_score,
const double det_mi_ratio_score,
const std::vector<OpenSwath::SwathMap>& swath_maps,
const double drift_target,
RangeMobility& im_range) const;
void prepareFeatureOutput_(OpenMS::MRMFeature& mrmfeature, bool ms1only, int charge) const;
/// Synchronize members with param class
void updateMembers_() override;
// parameters
double rt_extraction_window_;
double quantification_cutoff_;
int stop_report_after_feature_;
bool write_convex_hull_;
bool strict_;
bool use_ms1_ion_mobility_;
bool apply_im_peak_picking_;
String scoring_model_;
// scoring parameters
double rt_normalization_factor_;
int add_up_spectra_;
String spectrum_addition_method_ ;
String spectrum_merge_method_type_;
double spacing_for_spectra_resampling_;
double merge_spectra_by_peak_width_fraction_;
double uis_threshold_sn_;
double uis_threshold_peak_area_;
double sn_win_len_;
unsigned int sn_bin_count_;
bool write_log_messages_;
double im_extra_drift_;
// members (unordered_map for O(1) lookup performance)
std::unordered_map<OpenMS::String, const PeptideType*> PeptideRefMap_;
OpenSwath_Scores_Usage su_;
OpenMS::DIAScoring diascoring_;
OpenMS::EmgScoring emgscoring_;
// data
OpenSwath::SpectrumAccessPtr ms1_map_;
};
}
#undef run_identifier
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/OPENSWATH/ChromatogramExtractor.h | .h | 19,153 | 430 | // 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/ANALYSIS/OPENSWATH/ChromatogramExtractorAlgorithm.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/ANALYSIS/TARGETED/TargetedExperiment.h>
#include <OpenMS/ANALYSIS/MAPMATCHING/TransformationDescription.h>
#include <OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/DataAccessHelper.h>
#include <OpenMS/ANALYSIS/OPENSWATH/OpenSwathHelper.h>
namespace OpenMS
{
/**
* @brief The ChromatogramExtractor extracts chromatograms (intensity vs retention time) from mass spectrometry data.
*
* This class provides functionality to extract chromatographic traces from mass spectrometry data
* based on specified coordinates (m/z, retention time, and optionally ion mobility values).
*
* The extractor supports two main interfaces:
* 1. Legacy interface: Takes a TargetedExperiment object containing transitions and extracts
* chromatograms at the m/z values specified in those transitions.
* 2. Modern interface: Takes a set of ExtractionCoordinates that specify the exact coordinates
* for extraction. This provides more flexibility and control over the extraction process.
* The prepare_coordinates() helper function can generate these coordinates for common
* MS1 and MS2 extraction scenarios.
*
* Key features:
* - Supports both MS1 and MS2 level extractions
* - Configurable extraction window sizes in m/z dimension (absolute or ppm)
* - Multiple filter types available (Bartlett, tophat) for signal processing
* - Handles ion mobility data when available
* - Optimized for SWATH/DIA (Data Independent Acquisition) experiments
* - Progress logging capabilities through ProgressLogger base class
*
* For MS2 extractions, the input data is expected to come from a SWATH/DIA experiment
* where precursor ions are fragmented in wide isolation windows, allowing for extraction
* of fragment ion chromatograms.
*
* @see ChromatogramExtractorAlgorithm For the underlying extraction algorithm implementation
* @see ExtractionCoordinates For the coordinate specification format
*/
class OPENMS_DLLAPI ChromatogramExtractor :
public ProgressLogger
{
public:
typedef ChromatogramExtractorAlgorithm::ExtractionCoordinates ExtractionCoordinates;
/**
* @brief Extract chromatograms at the m/z and RT defined by the ExtractionCoordinates.
*
* @param[in] input The input spectra from which to extract chromatograms
* @param[out] output The output vector in which to store the chromatograms
* (needs to be of the same length as the extraction coordinates, use
* prepare_coordinates)
* @param[in] extraction_coordinates The extraction coordinates (m/z, RT, ion mobility)
* @param[in] mz_extraction_window Extracts a window of this size in m/z
* dimension (e.g. a window of 50 ppm means an extraction of 25 ppm on
* either side)
* @param[in] ppm Whether mz windows in in ppm
* @param[in] filter Which filter to use (bartlett or tophat)
*
*
*/
void extractChromatograms(const OpenSwath::SpectrumAccessPtr input,
std::vector< OpenSwath::ChromatogramPtr >& output,
const std::vector<ExtractionCoordinates>& extraction_coordinates,
double mz_extraction_window,
bool ppm,
const String& filter)
{
ChromatogramExtractorAlgorithm().extractChromatograms(input, output,
extraction_coordinates, mz_extraction_window, ppm, -1, filter);
}
/**
* @brief Extract chromatograms at the m/z and RT defined by the ExtractionCoordinates.
*
* @param[in] input The input spectra from which to extract chromatograms
* @param[out] output The output vector in which to store the chromatograms
* (needs to be of the same length as the extraction coordinates, use
* prepare_coordinates)
* @param[in] extraction_coordinates The extraction coordinates (m/z, RT, ion mobility)
* @param[in] mz_extraction_window Extracts a window of this size in m/z
* dimension (e.g. a window of 50 ppm means an extraction of 25 ppm on
* either side)
* @param[in] ppm Whether mz windows in in ppm
* @param[in] im_extraction_window Extracts a window of this size in ion mobility
* @param[in] filter Which filter to use (bartlett or tophat)
*
* @note: whenever possible, please use this ChromatogramExtractorAlgorithm implementation
*
*/
void extractChromatograms(const OpenSwath::SpectrumAccessPtr input,
std::vector< OpenSwath::ChromatogramPtr >& output,
const std::vector<ExtractionCoordinates>& extraction_coordinates,
double mz_extraction_window,
bool ppm,
double im_extraction_window,
const String& filter)
{
ChromatogramExtractorAlgorithm().extractChromatograms(input, output,
extraction_coordinates, mz_extraction_window, ppm, im_extraction_window, filter);
}
/**
* @brief Prepare the extraction coordinates from a TargetedExperiment
*
* Will fill the coordinates vector with the appropriate extraction
* coordinates (transitions for MS2 extraction, peptide m/z for MS1
* extraction). The output will be sorted by m/z.
*
* @param[in] output_chromatograms An empty vector which will be initialized correctly
* @param[out] coordinates An empty vector which will be filled with the
* appropriate extraction coordinates in m/z and rt and sorted by m/z (to
* be used as input to extractChromatograms)
* @param[in] transition_exp The transition experiment used as input (is constant)
* @param[in] rt_extraction_window If non-negative, full RT extraction window,
* centered on the first RT value (@p rt_end - @p rt_start will equal this
* window size). If negative, @p rt_end will be set to -1 and @p rt_start
* to 0 (i.e. full RT range). If NaN, exactly two RT entries are expected
* - the first is used as @p rt_start and the second as @p rt_end.
* @param[in] ms1 Whether to extract for MS1 (peptide level) or MS2 (transition level)
* @param[in] ms1_isotopes Number of isotopes to include in @p coordinates when in MS1 mode
*
* @throw Exception::IllegalArgument if RT values are expected (depending on @p rt_extraction_window) but not provided
*/
static void prepare_coordinates(std::vector< OpenSwath::ChromatogramPtr > & output_chromatograms,
std::vector< ExtractionCoordinates > & coordinates,
const OpenMS::TargetedExperiment & transition_exp,
const double rt_extraction_window,
const bool ms1 = false,
const int ms1_isotopes = 0);
static void prepare_coordinates(std::vector< OpenSwath::ChromatogramPtr > & output_chromatograms,
std::vector< ExtractionCoordinates > & coordinates,
const OpenSwath::LightTargetedExperiment & transition_exp_used,
const double rt_extraction_window,
const bool ms1 = false,
const int ms1_isotopes = 0);
/**
* @brief This converts the ChromatogramPtr to MSChromatogram and adds meta-information.
*
* It sets
* 1) the target m/z
* 2) the isolation window (upper/lower)
* 3) the peptide sequence
* 4) the fragment m/z
* 5) the meta-data, e.g. InstrumentSettings, AcquisitionInfo,
* sourceFile and DataProcessing
* 6) the native ID from the transition
* 7) ion mobility extraction target and window (lower/upper)
*
*/
template <typename TransitionExpT>
static void return_chromatogram(const std::vector< OpenSwath::ChromatogramPtr > & chromatograms,
const std::vector< ChromatogramExtractor::ExtractionCoordinates > & coordinates,
TransitionExpT& transition_exp_used,
SpectrumSettings settings,
std::vector<OpenMS::MSChromatogram > & output_chromatograms,
bool ms1,
double im_extraction_width = 0.0)
{
typedef std::map<String, const typename TransitionExpT::Transition* > TransitionMapType;
TransitionMapType trans_map;
for (Size i = 0; i < transition_exp_used.getTransitions().size(); i++)
{
trans_map[transition_exp_used.getTransitions()[i].getNativeID()] = &transition_exp_used.getTransitions()[i];
}
for (Size i = 0; i < chromatograms.size(); i++)
{
const OpenSwath::ChromatogramPtr & chromptr = chromatograms[i];
const ChromatogramExtractor::ExtractionCoordinates & coord = coordinates[i];
// copy data
OpenMS::MSChromatogram chrom;
OpenSwathDataAccessHelper::convertToOpenMSChromatogram(chromptr, chrom);
chrom.setNativeID(coord.id);
// Create precursor and set
// 1) the target m/z
// 2) the isolation window (upper/lower)
// 3) the peptide sequence
Precursor prec;
if (ms1)
{
prec.setMZ(coord.mz);
chrom.setChromatogramType(ChromatogramSettings::ChromatogramType::BASEPEAK_CHROMATOGRAM);
// extract compound / peptide id from transition and store in
// more-or-less default field
String transition_group_id = OpenSwathHelper::computeTransitionGroupId(coord.id);
if (!transition_group_id.empty())
{
int prec_charge = 0;
String r = extract_id_(transition_exp_used, transition_group_id, prec_charge);
prec.setCharge(prec_charge);
prec.setMetaValue("peptide_sequence", r);
}
}
else
{
typename TransitionExpT::Transition transition = (*trans_map[coord.id]);
prec.setMZ(transition.getPrecursorMZ());
if (!settings.getPrecursors().empty())
{
prec.setIsolationWindowLowerOffset(settings.getPrecursors()[0].getIsolationWindowLowerOffset());
prec.setIsolationWindowUpperOffset(settings.getPrecursors()[0].getIsolationWindowUpperOffset());
}
// Create product and set its m/z
Product prod;
prod.setMZ(transition.getProductMZ());
chrom.setProduct(prod);
chrom.setChromatogramType(ChromatogramSettings::ChromatogramType::SELECTED_REACTION_MONITORING_CHROMATOGRAM);
// extract compound / peptide id from transition and store in
// more-or-less default field
if (!transition.getPeptideRef().empty())
{
int prec_charge = 0;
String r = extract_id_(transition_exp_used, transition.getPeptideRef(), prec_charge);
prec.setCharge(prec_charge);
prec.setMetaValue("peptide_sequence", r);
}
else
{
int prec_charge = 0;
String r = extract_id_(transition_exp_used, transition.getCompoundRef(), prec_charge);
prec.setCharge(prec_charge);
prec.setMetaValue("peptide_sequence", r);
}
}
if (coord.ion_mobility >= 0 && im_extraction_width > 0.0)
{
prec.setDriftTime(coord.ion_mobility);
prec.setDriftTimeWindowLowerOffset(im_extraction_width / 2.0);
prec.setDriftTimeWindowUpperOffset(im_extraction_width / 2.0);
}
chrom.setPrecursor(prec);
// Set the rest of the meta-data
chrom.setInstrumentSettings(settings.getInstrumentSettings());
chrom.setAcquisitionInfo(settings.getAcquisitionInfo());
chrom.setSourceFile(settings.getSourceFile());
for (Size j = 0; j < settings.getDataProcessing().size(); ++j)
{
settings.getDataProcessing()[j]->setMetaValue("performed_on_spectra", "true");
chrom.getDataProcessing().push_back(settings.getDataProcessing()[j]);
}
output_chromatograms.push_back(chrom);
}
}
private:
/**
* @brief Extracts id (peptide sequence or compound name) for a compound
*
* @param[out] transition_exp_used The transition experiment used as input (is constant) and either of type LightTargetedExperiment or TargetedExperiment
* @param[in] id The identifier of the compound or peptide
* @param[in] prec_charge The charge state of the precursor
*
*/
template <typename TransitionExpT>
static String extract_id_(TransitionExpT& transition_exp_used, const String& id, int& prec_charge);
/**
* @brief This populates the chromatograms vector with empty chromatograms
* (but sets their meta-information)
*
* It extracts
* 1) the target m/z
* 2) the isolation window (upper/lower)
* 3) the peptide sequence
* 4) the fragment m/z
* 5) Copy the meta-data, e.g. InstrumentSettings, AcquisitionInfo,
* sourceFile and DataProcessing
* 6) the native ID from the transition
*
*/
template <class SpectrumSettingsT, class ChromatogramT>
void prepareSpectra_(SpectrumSettingsT& settings,
std::vector<ChromatogramT>& chromatograms,
OpenMS::TargetedExperiment& transition_exp)
{
// first prepare all the spectra (but leave them empty)
for (Size i = 0; i < transition_exp.getTransitions().size(); i++)
{
const ReactionMonitoringTransition* transition = &transition_exp.getTransitions()[i];
// 1) and 2) Extract precursor m/z and isolation window
ChromatogramT chrom;
Precursor prec;
prec.setMZ(transition->getPrecursorMZ());
if (settings.getPrecursors().size() > 0)
{
prec.setIsolationWindowLowerOffset(settings.getPrecursors()[0].getIsolationWindowLowerOffset());
prec.setIsolationWindowUpperOffset(settings.getPrecursors()[0].getIsolationWindowUpperOffset());
}
// 3) set precursor peptide sequence / compound id in more-or-less default field
String pepref = transition->getPeptideRef();
for (Size pep_idx = 0; pep_idx < transition_exp.getPeptides().size(); pep_idx++)
{
const OpenMS::TargetedExperiment::Peptide* pep = &transition_exp.getPeptides()[pep_idx];
if (pep->id == pepref)
{
prec.setMetaValue("peptide_sequence", pep->sequence);
break;
}
}
String compref = transition->getCompoundRef();
for (Size comp_idx = 0; comp_idx < transition_exp.getCompounds().size(); comp_idx++)
{
const OpenMS::TargetedExperiment::Compound* comp = &transition_exp.getCompounds()[comp_idx];
if (comp->id == compref)
{
prec.setMetaValue("peptide_sequence", String(comp->id) );
break;
}
}
// add precursor to spectrum
chrom.setPrecursor(prec);
// 4) Create product and set its m/z
Product prod;
prod.setMZ(transition->getProductMZ());
chrom.setProduct(prod);
// 5) Set the rest of the meta-data
chrom.setInstrumentSettings(settings.getInstrumentSettings());
chrom.setAcquisitionInfo(settings.getAcquisitionInfo());
chrom.setSourceFile(settings.getSourceFile());
for (Size j = 0; j < settings.getDataProcessing().size(); ++j)
{
settings.getDataProcessing()[j]->setMetaValue("performed_on_spectra", "true");
chrom.getDataProcessing().push_back(settings.getDataProcessing()[j]);
}
// Set the id of the chromatogram, using the id of the transition (this gives directly the mapping of the two)
chrom.setNativeID(transition->getNativeID());
chrom.setChromatogramType(ChromatogramSettings::ChromatogramType::SELECTED_REACTION_MONITORING_CHROMATOGRAM);
chromatograms.push_back(chrom);
}
}
/// @note: TODO deprecate this function (use ChromatogramExtractorAlgorithm instead)
bool outsideExtractionWindow_(const ReactionMonitoringTransition& transition,
double current_rt,
const TransformationDescription& trafo,
double rt_extraction_window);
/// @note: TODO deprecate this function (use ChromatogramExtractorAlgorithm instead)
int getFilterNr_(const String& filter);
/// @note: TODO deprecate this function (use ChromatogramExtractorAlgorithm instead)
void populatePeptideRTMap_(OpenMS::TargetedExperiment& transition_exp,
double rt_extraction_window);
std::map<OpenMS::String, double> PeptideRTMap_;
};
// Specialization for template (LightTargetedExperiment)
template<>
inline String ChromatogramExtractor::extract_id_<OpenSwath::LightTargetedExperiment>(OpenSwath::LightTargetedExperiment& transition_exp_used,
const String& id,
int & prec_charge)
{
const OpenSwath::LightCompound comp = transition_exp_used.getCompoundByRef(id);
prec_charge = comp.charge;
if (!comp.sequence.empty())
{
return comp.sequence;
}
else
{
return comp.compound_name;
}
}
// Specialization for template (TargetedExperiment)
template<>
inline String ChromatogramExtractor::extract_id_<OpenMS::TargetedExperiment>(OpenMS::TargetedExperiment& transition_exp_used,
const String& id,
int & prec_charge)
{
if (transition_exp_used.hasPeptide(id))
{
const TargetedExperiment::Peptide p = transition_exp_used.getPeptideByRef(id);
if (p.hasCharge()) {prec_charge = p.getChargeState();}
return p.sequence;
}
else if (transition_exp_used.hasCompound(id))
{
const TargetedExperiment::Compound c = transition_exp_used.getCompoundByRef(id);
if (c.hasCharge()) {prec_charge = c.getChargeState();}
return c.id;
}
else
{
return "";
}
}
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/OPENSWATH/MRMScoring.h | .h | 13,542 | 292 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hannes Roest $a
// $Authors: Hannes Roest $
// --------------------------------------------------------------------------
#pragma once
#include <string>
#include <OpenMS/DATASTRUCTURES/Matrix.h>
#include <OpenMS/OPENSWATHALGO/OpenSwathAlgoConfig.h>
#include <OpenMS/OPENSWATHALGO/DATAACCESS/ISpectrumAccess.h>
#include <OpenMS/OPENSWATHALGO/DATAACCESS/ITransition.h>
#include <OpenMS/OPENSWATHALGO/DATAACCESS/TransitionExperiment.h>
#include <OpenMS/OPENSWATHALGO/ALGO/StatsHelpers.h>
#include <OpenMS/OPENSWATHALGO/ALGO/Scoring.h>
namespace OpenSwath
{
/**
@brief This class implements different scores for peaks found in SRM/MRM.
It uses scores based on different parameters of the peaks from the
individual transitions and stores them individually. The idea and the
scores are based on the following paper:
Reiter L, Rinner O, Picotti P, Huettenhain R, Beck M, Brusniak MY,
Hengartner MO, Aebersold R. mProphet: automated data processing and
statistical validation for large-scale SRM experiments. Nat Methods.
2011 May;8(5):430-5. Epub 2011 Mar 20.
The currently implemented scores include:
- xcorr_coelution: Cross-correlation of the different transitions
- xcorr_shape: Cross-correlation shape score (whether the maximal
Cross-correlation coincides with the maximal intensity)
- library_rmsd: normalized RMSD of the measured intensities to the expected intensities
- library_correlation: correlation of the measured intensities to the expected intensities
- rt_score: deviation from the expected retention time
- elution_fit_score: how well the elution profile fits a theoretical elution profile
*/
class OPENMS_DLLAPI MRMScoring
{
public:
///Type definitions
//@{
/// Cross Correlation array
typedef OpenSwath::Scoring::XCorrArrayType XCorrArrayType;
/// Cross Correlation matrix
typedef OpenMS::Matrix<XCorrArrayType> XCorrMatrixType;
typedef OpenSwath::SpectrumPtr SpectrumType;
typedef OpenSwath::LightTransition TransitionType;
typedef OpenSwath::LightCompound PeptideType;
typedef OpenSwath::LightProtein ProteinType;
typedef std::shared_ptr<OpenSwath::IFeature> FeatureType;
//@}
/** @name Accessors */
//@{
/// non-mutable access to the cross-correlation matrix
const XCorrMatrixType& getXCorrMatrix() const;
//@}
/// non-mutable access to the cross-correlation contrast matrix
const XCorrMatrixType& getXCorrContrastMatrix() const;
//@}
/// non-mutable access to the cross-correlation precursor contrast matrix
const XCorrMatrixType& getXCorrPrecursorContrastMatrix() const;
//@}
/// non-mutable access to the cross-correlation precursor contrast matrix
const XCorrMatrixType& getXCorrPrecursorCombinedMatrix() const;
//@}
/** @name Scores */
//@{
/// Initialize the scoring object and building the cross-correlation matrix
void initializeXCorrMatrix(const std::vector< std::vector< double > >& data);
/// Initialize the scoring object and building the cross-correlation matrix
void initializeXCorrMatrix(OpenSwath::IMRMFeature* mrmfeature, const std::vector<std::string>& native_ids);
/// Initialize the scoring object and building the cross-correlation matrix of chromatograms of set1 (e.g. identification transitions) vs set2 (e.g. detection transitions)
void initializeXCorrContrastMatrix(OpenSwath::IMRMFeature* mrmfeature, const std::vector<std::string>& native_ids_set1, const std::vector<std::string>& native_ids_set2);
/// Initialize the scoring object and building the cross-correlation matrix
void initializeXCorrPrecursorMatrix(OpenSwath::IMRMFeature* mrmfeature, const std::vector<std::string>& precursor_ids);
/// Initialize the scoring object and building the cross-correlation matrix of chromatograms of precursor isotopes vs transitions
void initializeXCorrPrecursorContrastMatrix(OpenSwath::IMRMFeature* mrmfeature, const std::vector<std::string>& precursor_ids, const std::vector<std::string>& native_ids);
/// Initialize the scoring object and building the cross-correlation matrix of chromatograms of precursor isotopes vs transitions
void initializeXCorrPrecursorContrastMatrix(const std::vector< std::vector< double > >& data_precursor, const std::vector< std::vector< double > >& data_fragments);
/// Initialize the scoring object and building the cross-correlation matrix of chromatograms of precursor isotopes and transitions
void initializeXCorrPrecursorCombinedMatrix(OpenSwath::IMRMFeature* mrmfeature, const std::vector<std::string>& precursor_ids, const std::vector<std::string>& native_ids);
/**
@brief Calculate the cross-correlation coelution score
The score is a distance where zero indicates perfect coelution.
*/
double calcXcorrCoelutionScore();
/**
@brief Calculate the weighted cross-correlation coelution score
The score is a distance where zero indicates perfect coelution. The
score is weighted by the transition intensities, non-perfect coelution
in low-intensity transitions should thus become less important.
*/
double calcXcorrCoelutionWeightedScore(const std::vector<double>& normalized_library_intensity);
/// calculate the separate cross-correlation contrast score
std::vector<double> calcSeparateXcorrContrastCoelutionScore();
/// calculate the precursor cross-correlation contrast score
double calcXcorrPrecursorCoelutionScore();
/**
@brief Calculate the precursor cross-correlation contrast score against the transitions
The score is a distance where zero indicates perfect coelution.
*/
double calcXcorrPrecursorContrastCoelutionScore();
/**
@brief Calculate the precursor cross-correlation contrast score against the sum of transitions
implemented the same as calcXcorrPrecursorCoelutionScore(), however assertion is different.
The score is a distance where zero indicates perfect coelution.
*/
double calcXcorrPrecursorContrastSumFragCoelutionScore();
/// calculate the precursor cross-correlation coelution score including the transitions
double calcXcorrPrecursorCombinedCoelutionScore();
/**
@brief Calculate the cross-correlation shape score
The score is a correlation measure where 1 indicates perfect correlation
and 0 means no correlation.
*/
double calcXcorrShapeScore();
/**
@brief Calculate the weighted cross-correlation shape score
The score is a correlation measure where 1 indicates perfect correlation
and 0 means no correlation. The score is weighted by the transition
intensities, non-perfect coelution in low-intensity transitions should
thus become less important.
*/
double calcXcorrShapeWeightedScore(const std::vector<double>& normalized_library_intensity);
/// calculate the cross-correlation contrast shape score
double calcXcorrContrastShapeScore();
/// calculate the separate cross-correlation contrast shape score
std::vector<double> calcSeparateXcorrContrastShapeScore();
/// calculate the precursor cross-correlation shape score
double calcXcorrPrecursorShapeScore();
/// calculate the precursor cross-correlation shape score against the transitions
double calcXcorrPrecursorContrastShapeScore();
/**
@brief Calculate the precursor cross-correlation contrast score against the sum of transitions
implemented the same as calcXcorrPrecursorContrastShapeScore(), however assertion is different.
The score is a distance where zero indicates perfect coelution.
*/
double calcXcorrPrecursorContrastSumFragShapeScore();
/// calculate the precursor cross-correlation shape score including the transitions
double calcXcorrPrecursorCombinedShapeScore();
/// calculate the library correlation score
static void calcLibraryScore(OpenSwath::IMRMFeature* mrmfeature,
const std::vector<TransitionType>& transitions, double& correlation,
double& norm_manhattan, double& manhattan, double& dotprod,
double& spectral_angle, double& rmsd);
/// calculate the retention time correlation score
static double calcRTScore(const PeptideType& peptide, double normalized_experimental_rt);
/// calculate the Signal to Noise ratio
// using a vector of SignalToNoiseEstimatorMedian that were calculated for
// each chromatogram of the transition_group.
static double calcSNScore(OpenSwath::IMRMFeature* mrmfeature,
std::vector<OpenSwath::ISignalToNoisePtr>& signal_noise_estimators);
static std::vector<double> calcSeparateSNScore(OpenSwath::IMRMFeature* mrmfeature,
std::vector<OpenSwath::ISignalToNoisePtr>& signal_noise_estimators);
/// non-mutable access to the MI matrix
const OpenMS::Matrix<double> & getMIMatrix() const;
//@}
/// non-mutable access to the MI contrast matrix
const OpenMS::Matrix<double> & getMIContrastMatrix() const;
//@}
/// non-mutable access to the MI precursor contrast matrix
const OpenMS::Matrix<double> & getMIPrecursorContrastMatrix() const;
//@}
/// non-mutable access to the MI precursor combined matrix
const OpenMS::Matrix<double> & getMIPrecursorCombinedMatrix() const;
//@}
/// Initialize the scoring object and building the MI matrix
void initializeMIMatrix(OpenSwath::IMRMFeature* mrmfeature, const std::vector<std::string>& native_ids);
/// Initialize the scoring object and building the MI matrix of chromatograms of set1 (e.g. identification transitions) vs set2 (e.g. detection transitions)
void initializeMIContrastMatrix(OpenSwath::IMRMFeature* mrmfeature, const std::vector<std::string>& native_ids_set1, const std::vector<std::string>& native_ids_set2);
/// Initialize the scoring object and building the MI matrix
void initializeMIPrecursorMatrix(OpenSwath::IMRMFeature* mrmfeature, const std::vector<std::string>& precursor_ids);
/// Initialize the mutual information vector against the MS1 trace
void initializeMIPrecursorContrastMatrix(OpenSwath::IMRMFeature* mrmfeature, const std::vector<std::string>& precursor_ids, const std::vector<std::string>& native_ids);
/// Initialize the mutual information vector with the MS1 trace
void initializeMIPrecursorCombinedMatrix(OpenSwath::IMRMFeature* mrmfeature, const std::vector<std::string>& precursor_ids, const std::vector<std::string>& native_ids);
double calcMIScore();
double calcMIWeightedScore(const std::vector<double>& normalized_library_intensity);
double calcMIPrecursorScore();
double calcMIPrecursorContrastScore();
double calcMIPrecursorCombinedScore();
std::vector<double> calcSeparateMIContrastScore();
//@}
private:
/** @name Members */
//@{
/// the precomputed cross correlation matrix
XCorrMatrixType xcorr_matrix_;
/// contains max Peaks from xcorr_matrix_
OpenMS::Matrix<int> xcorr_matrix_max_peak_;
OpenMS::Matrix<double> xcorr_matrix_max_peak_sec_;
/// the precomputed contrast cross correlation
XCorrMatrixType xcorr_contrast_matrix_;
//@}
/// contains max Peaks from xcorr_contrast_matrix_
OpenMS::Matrix<double> xcorr_contrast_matrix_max_peak_sec_;
/// the precomputed cross correlation matrix of the MS1 trace
XCorrMatrixType xcorr_precursor_matrix_;
/// the precomputed cross correlation against the MS1 trace
XCorrMatrixType xcorr_precursor_contrast_matrix_;
//@}
/// the precomputed cross correlation with the MS1 trace
XCorrMatrixType xcorr_precursor_combined_matrix_;
//@}
/// the precomputed mutual information matrix
OpenMS::Matrix<double> mi_matrix_;
/// the precomputed contrast mutual information matrix
OpenMS::Matrix<double> mi_contrast_matrix_;
/// the precomputed mutual information matrix of the MS1 trace
OpenMS::Matrix<double> mi_precursor_matrix_;
/// the precomputed contrast mutual information matrix against the MS1 trace
OpenMS::Matrix<double> mi_precursor_contrast_matrix_;
//@}
/// the precomputed contrast mutual information matrix with the MS1 trace
OpenMS::Matrix<double> mi_precursor_combined_matrix_;
//@}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/OPENSWATH/DIAHelper.h | .h | 9,728 | 181 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hannes Roest $
// $Authors: Witold Wolski, Hannes Roest $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CHEMISTRY/AASequence.h>
#include <OpenMS/OPENSWATHALGO/DATAACCESS/DataStructures.h>
#include <OpenMS/OPENSWATHALGO/DATAACCESS/ISpectrumAccess.h>
#include <vector>
namespace OpenMS
{
struct RangeMZ;
struct RangeMobility;
class TheoreticalSpectrumGenerator;
namespace DIAHelpers
{
/**
@brief Helper functions for the DIA scoring of OpenSWATH
*/
///@{
/**
@brief Integrate intensity in a spectrum from in @p mz_range (and @p im_range if defined)
returning the intensity-weighted m/z and im values as well as the total intensity.
@note If there is no signal, @p mz and @p im will be set to -1 and intensity to 0
@return Returns true if a signal was found (and false if no signal was found)
*/
OPENMS_DLLAPI bool integrateWindow(const OpenSwath::SpectrumPtr& spectrum,
double& mz, double& im, double& intensity, const RangeMZ& mz_range, const RangeMobility& im_range, bool centroided = false);
/**
@brief Integrate intensity in SpectrumSequence in range @p mz_range (and @p im_range if defined)
returning the intensity-weighted m/z and im values as well as the total intensity.
@note If there is no signal, @p mz and @p im will be set to -1 and intensity to 0
@return Returns true if a signal was found (and false if no signal was found)
*/
OPENMS_DLLAPI bool integrateWindow(const SpectrumSequence& spectrum,
double& mz, double& im, double& intensity, const RangeMZ& mz_range, const RangeMobility& im_range, bool centroided = false);
/**
@brief Integrate intensities in a spectrum in range @p im_range (if defined) for multiple windows.
@param[in] spectrum Input spectrum
@param[in] windows_center Center locations of the windows.
@param[in] width Width of the windows across m/z
@param[out] integrated_windows_intensity Integrated intensity for each window
@param[out] integrated_windows_mz Integrated intensity-weighted m/z for each window
@param[out] integrated_windows_im Integrated intensity-weighted im for each window
@param[in] im_range is the range of the IM dimension (if defined)
@param[in] remove_zero Remove zero intensity windows?
*/
OPENMS_DLLAPI void integrateWindows(const OpenSwath::SpectrumPtr& spectrum,
const std::vector<double>& windows_center,
double width,
std::vector<double>& integrated_windows_intensity,
std::vector<double>& integrated_windows_mz,
std::vector<double>& integrated_windows_im,
const RangeMobility& im_range,
bool remove_zero = false);
/**
@brief Integrate intensities of a SpectrumSequence in range @p im_range (if defined) for multiple windows.
@param[in] spectrum Input spectrum
@param[in] windows_center Center locations of the windows.
@param[in] width Width of the windows across m/z
@param[out] integrated_windows_intensity Integrated intensity for each window
@param[out] integrated_windows_mz Integrated intensity-weighted m/z for each window
@param[out] integrated_windows_im Integrated intensity-weighted im for each window
@param[in] im_range is the range of the IM dimension (if defined)
@param[in] remove_zero Remove zero intensity windows?
*/
OPENMS_DLLAPI void integrateWindows(const SpectrumSequence& spectrum,
const std::vector<double>& windows_center,
double width,
std::vector<double>& integrated_windows_intensity,
std::vector<double>& integrated_windows_mz,
std::vector<double>& integrated_windows_im,
const RangeMobility& im_range,
bool remove_zero = false);
/**
@brief Adjust left/right window based on window and whether its ppm or not
*/
OPENMS_DLLAPI void adjustExtractionWindow(double& right, double& left, const double& mz_extract_window, const bool& mz_extraction_ppm);
/// compute the b and y series masses for a given AASequence
OPENMS_DLLAPI void getBYSeries(const AASequence& a,
std::vector<double>& bseries,
std::vector<double>& yseries,
TheoreticalSpectrumGenerator const * g,
int charge = 1);
/// for SWATH -- get the theoretical b and y series masses for a sequence
OPENMS_DLLAPI void getTheorMasses(const AASequence& a,
std::vector<double>& masses,
TheoreticalSpectrumGenerator const * g,
int charge = 1);
/// get averagine distribution given mass
OPENMS_DLLAPI void getAveragineIsotopeDistribution(const double product_mz,
std::vector<std::pair<double, double> >& isotopes_spec,
const int charge = 1,
const int nr_isotopes = 4,
const double mannmass = 1.00048);
/// simulate spectrum from AASequence
OPENMS_DLLAPI void simulateSpectrumFromAASequence(const AASequence& aa,
std::vector<double>& first_isotope_masses, //[out]
std::vector<std::pair<double, double> >& isotope_masses, //[out]
TheoreticalSpectrumGenerator const * g,
int charge = 1);
/// add (potentially negative) pre-isotope weights to spectrum
OPENMS_DLLAPI void addPreisotopeWeights(const std::vector<double>& first_isotope_masses,
std::vector<std::pair<double, double> >& isotope_spec, // output
UInt nr_peaks = 2, //nr of pre-isotope peaks
double pre_isotope_peaks_weight = -0.5, // weight of pre-isotope peaks
double mannmass = 1.000482, //
int charge = 1);
/// add negative pre-isotope weights to spectrum
OPENMS_DLLAPI void addPreisotopeWeights(double mz,
std::vector<std::pair<double, double> >& isotope_spec, // output
UInt nr_peaks = 2, //nr of pre-isotope peaks
double pre_isotope_peaks_weight = -0.5, // weight of pre-isotope peaks
double mannmass = 1.000482, //
int charge = 1);
/// given an experimental spectrum, add averagine isotope pattern for every peak. Old + new peaks are pushed to
/// @p isotopeMasses
OPENMS_DLLAPI void addIsotopes2Spec(const std::vector<std::pair<double, double> >& spec,
std::vector<std::pair<double, double> >& isotope_masses, //[out]
Size nr_isotopes, int charge = 1);
/// given a peak of experimental mz and intensity, add averagine isotope pattern to a "spectrum".
/// Old + new peaks are pushed to @p isotopeMasses
OPENMS_DLLAPI void addSinglePeakIsotopes2Spec(double mz, double ity,
std::vector<std::pair<double, double> >& isotope_masses, //[out]
Size nr_isotopes, int charge);
/// sorts vector of pairs by first
OPENMS_DLLAPI void sortByFirst(std::vector<std::pair<double, double> >& tmp);
/// extract first from vector of pairs
OPENMS_DLLAPI void extractFirst(const std::vector<std::pair<double, double> >& peaks, std::vector<double>& mass);
/// extract second from vector of pairs
OPENMS_DLLAPI void extractSecond(const std::vector<std::pair<double, double> >& peaks, std::vector<double>& mass);
/** @brief optionally convert a DIA extraction window from ppm to m/z
@param[in] mz_ref Extraction window center
@param[in] dia_extraction_window How wide the extraction window is total (can be in m/z or ppm)
@param[in] ppm Is extraction window is in ppm?
@return The extraction window in m/z
*/
OPENMS_DLLAPI RangeMZ createMZRangePPM(double mz_ref, double dia_extraction_window, const bool ppm);
/**
@brief Helper function for integrating a spectrum.
*/
OPENMS_DLLAPI void integrateWindow_(const OpenSwath::SpectrumPtr& spectrum,
double & mz,
double & im,
double & intensity,
const RangeMZ & mz_range,
const RangeMobility & im_range,
bool centroided);
}
///}@
} //namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/OPENSWATH/MRMDecoy.h | .h | 14,280 | 333 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: George Rosenberger $
// $Authors: George Rosenberger, Hannes Roest $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/ANALYSIS/OPENSWATH/MRMIonSeries.h>
#include <OpenMS/ANALYSIS/TARGETED/TargetedExperiment.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/OPENSWATHALGO/DATAACCESS/TransitionExperiment.h>
#include <string>
#include <utility> // for pair
#include <vector>
#include <map>
// #define DEBUG_MRMDECOY
namespace OpenMS
{
/**
@brief This class generates a TargetedExperiment object with decoys based on a TargetedExperiment object
There are multiple methods to create the decoy transitions, the simplest ones
are reverse and pseudo-reverse which reverse the sequence either completely or
leaving the last (tryptic) AA untouched respectively.
Another decoy generation method is "shuffle" which uses an algorithm similar
to the one described in Lam, Henry, et al. (2010). "Artificial decoy spectral
libraries for false discovery rate estimation in spectral library searching in
proteomics". Journal of Proteome Research 9, 605-610. It shuffles the amino
acid sequence and shuffles the fragment ion intensities accordingly, however
for this to work the fragment ions need to be matched to annotated before.
First, the algorithm goes through all peptides and applies the decoy method to
the target peptide sequence (pseudo-reverse, reverse or shuffle) in order to
produce the decoy sequence. Then, for each peptide, the fragment ions in the
target library are matched to their most likely origin (e.g. the ions are
annotated with their ion series (a,b,y) and the fragment number and optionally
a neutral loss (10 different neutral losses are currently implemented)). For
each fragment ion from the target peptide, an equivalent ion is created for the
decoy peptide with the same intensity (e.g. if the target peptide sequence has
a b5 ion with a normalized intensity of 200, an equivalent b5 ion for the
decoy sequence is created and assigned the intensity 200).
Optionally, the m/z values are corrected to reflect the theoretical value rather
than the experimental value in the library.
*/
class OPENMS_DLLAPI MRMDecoy :
public DefaultParamHandler,
public ProgressLogger
{
public:
typedef std::vector<size_t> IndexType;
MRMDecoy();
/**
@brief Generate decoys from a TargetedExperiment
Will generate decoy peptides for each target peptide provided in exp and
write them into the decoy experiment.
Valid methods: shuffle, reverse, pseudo-reverse
If theoretical is true, the target transitions will be returned but their
masses will be adjusted to match the theoretical value of the fragment ion
that is the most likely explanation for the product.
mz_threshold is used for the matching of theoretical ion series to the observed one
To generate decoys with different precursor mass, use the "switchKR" flag
which switches terminal K/R (switches K to R and R to K). This generates
different precursor m/z and ensures that the y ion series has a different
mass. For a description of the procedure, see (supplemental material)
Bruderer et al. Mol Cell Proteomics. 2017. 10.1074/mcp.RA117.000314.
*/
void generateDecoys(const OpenMS::TargetedExperiment& exp,
OpenMS::TargetedExperiment& dec,
const String& method,
const double aim_decoy_fraction,
const bool switchKR,
const String& decoy_tag,
const int max_attempts,
const double identity_threshold,
const double precursor_mz_shift,
const double product_mz_shift,
const double product_mz_threshold,
const std::vector<String>& fragment_types,
const std::vector<size_t>& fragment_charges,
const bool enable_specific_losses,
const bool enable_unspecific_losses,
const int round_decPow = -4) const;
/**
@brief Generate decoys from a LightTargetedExperiment (memory-efficient version)
Light version of generateDecoys() for memory-efficient processing of large libraries.
@param[in] exp The target experiment (Light structure)
@param[out] dec The decoy experiment (Light structure)
@param[in] method The decoy generation method: "shuffle", "reverse", or "pseudo-reverse"
@param[in] aim_decoy_fraction Fraction of decoys to generate (1.0 = 100%)
@param[in] switchKR Whether to switch terminal K/R
@param[in] decoy_tag Tag to prepend to decoy IDs
@param[in] max_attempts Maximum shuffle attempts
@param[in] identity_threshold Maximum sequence identity for shuffled decoys
@param[in] precursor_mz_shift Precursor m/z shift for decoys
@param[in] product_mz_shift Product m/z shift for decoys (for shift method)
@param[in] product_mz_threshold Product m/z threshold for annotation
@param[in] fragment_types Fragment types to consider
@param[in] fragment_charges Fragment charges to consider
@param[in] enable_specific_losses Enable specific neutral losses
@param[in] enable_unspecific_losses Enable unspecific neutral losses
@param[in] round_decPow Round product m/z values to decimal power
*/
void generateDecoysLight(const OpenSwath::LightTargetedExperiment& exp,
OpenSwath::LightTargetedExperiment& dec,
const String& method,
const double aim_decoy_fraction,
const bool switchKR,
const String& decoy_tag,
const int max_attempts,
const double identity_threshold,
const double precursor_mz_shift,
const double product_mz_shift,
const double product_mz_threshold,
const std::vector<String>& fragment_types,
const std::vector<size_t>& fragment_charges,
const bool enable_specific_losses,
const bool enable_unspecific_losses,
const int round_decPow = -4) const;
/**
@brief Switch the final Amino Acid of a tryptic peptide.
E.g. If the last Amino Acid is "K" switch to "R" (and vice versa).
@note If the last Amino Acid is neither "K" or "R", the last Amino Acid is changed to a random Amino Acid .
*/
void switchKR(OpenMS::TargetedExperiment::Peptide& peptide) const;
typedef std::vector<OpenMS::TargetedExperiment::Protein> ProteinVectorType;
typedef std::vector<OpenMS::TargetedExperiment::Peptide> PeptideVectorType;
typedef std::vector<OpenMS::ReactionMonitoringTransition> TransitionVectorType;
typedef std::map<String, std::vector<const ReactionMonitoringTransition*> > PeptideTransitionMapType;
/**
@brief Compute relative identity (relative number of matches of amino
acids at the same position) between two sequences.
*/
float AASequenceIdentity(const String& sequence, const String& decoy) const;
/**
@brief Shuffle a peptide (with its modifications) sequence
This function will shuffle the given peptide sequences and its
modifications such that the resulting relative sequence identity is below
identity_threshold.
*/
OpenMS::TargetedExperiment::Peptide shufflePeptide(
OpenMS::TargetedExperiment::Peptide peptide,
const double identity_threshold,
int seed = -1,
const int max_attempts = 100) const;
/**
@brief Reverse a peptide sequence (with its modifications)
@param[in] peptide The peptide sequence and modifications
@param[in] keepN Whether to keep N terminus in place
@param[in] keepC Whether to keep C terminus in place
@param[in] const_pattern A list of AA to leave in place
*/
static OpenMS::TargetedExperiment::Peptide reversePeptide(
const OpenMS::TargetedExperiment::Peptide& peptide,
const bool keepN,
const bool keepC,
const String& const_pattern = String());
/**
@brief Find all residues in a sequence that should not be reversed / shuffled
@param[in] sequence The amino acid sequence
@param[in] keepN Whether to keep N terminus constant
@param[in] keepC Whether to keep C terminus constant
@param[in] keep_const_pattern A string containing the AA to not change (e.g. 'KRP')
*/
static IndexType findFixedResidues(const std::string& sequence,
bool keepN, bool keepC, const OpenMS::String& keep_const_pattern);
/**
@brief Reverse a peptide sequence (light version operating on strings)
Light version of reversePeptide() for memory-efficient processing.
Operates directly on sequence string and LightModification vector.
@param[in] sequence The amino acid sequence
@param[in] modifications The modifications with locations
@param[in] keepN Whether to keep N terminus in place
@param[in] keepC Whether to keep C terminus in place
@param[in] const_pattern A list of AA to leave in place
@return Pair of reversed sequence and relocated modifications
*/
static std::pair<std::string, std::vector<OpenSwath::LightModification>> reversePeptideLight(
const std::string& sequence,
const std::vector<OpenSwath::LightModification>& modifications,
bool keepN,
bool keepC,
const String& const_pattern = String());
/**
@brief Shuffle a peptide sequence (light version operating on strings)
Light version of shufflePeptide() for memory-efficient processing.
Operates directly on sequence string and LightModification vector.
@param[in] sequence The amino acid sequence
@param[in] modifications The modifications with locations
@param[in] identity_threshold Maximum allowed sequence identity
@param[in] seed Random seed (-1 for time-based)
@param[in] max_attempts Maximum shuffle attempts
@return Pair of shuffled sequence and relocated modifications
*/
std::pair<std::string, std::vector<OpenSwath::LightModification>> shufflePeptideLight(
const std::string& sequence,
const std::vector<OpenSwath::LightModification>& modifications,
double identity_threshold,
int seed = -1,
int max_attempts = 100) const;
/**
@brief Switch the final amino acid of a tryptic peptide (light version)
Light version of switchKR() operating directly on a sequence string.
If last AA is K, switches to R (and vice versa). Otherwise randomizes.
@param[in,out] sequence The sequence to modify in place
*/
static void switchKRLight(std::string& sequence);
protected:
/**
@brief Check if a peptide has C or N terminal modifications
*/
bool hasCNterminalMods_(const OpenMS::TargetedExperiment::Peptide& peptide, bool checkCterminalAA) const;
/**
@brief Check if light modifications include C or N terminal modifications
Light version of hasCNterminalMods_() for LightModification vectors.
@param[in] modifications The modifications vector
@param[in] sequence_length Length of the peptide sequence
@param[in] checkCterminalAA Also check the C-terminal amino acid position
@return True if terminal modifications are present
*/
static bool hasCNterminalModsLight_(
const std::vector<OpenSwath::LightModification>& modifications,
size_t sequence_length,
bool checkCterminalAA);
/**
@brief Pseudo-reverse a peptide sequence (light version)
Light version that keeps C terminus in place.
@param[in] sequence The amino acid sequence
@param[in] modifications The modifications with locations
@return Pair of pseudo-reversed sequence and relocated modifications
*/
std::pair<std::string, std::vector<OpenSwath::LightModification>> pseudoreversePeptideLight_(
const std::string& sequence,
const std::vector<OpenSwath::LightModification>& modifications) const;
/**
@brief Find all K, R, P sites in a sequence to be set as fixed
This method was adapted from the SpectraST decoy generator
*/
IndexType findFixedResidues_(const std::string& sequence) const;
/**
@brief Find all K, R, P and C-/N-terminal sites in a sequence to be set as fixed
This method was adapted from the SpectraST decoy generator
*/
IndexType findFixedAndTermResidues_(const std::string& sequence) const;
/**
@brief Pseudo-reverse a peptide sequence (with its modifications)
@note Pseudo reverses a peptide sequence, leaving the C terminus (the
last AA constant)
*/
OpenMS::TargetedExperiment::Peptide pseudoreversePeptide_(
const OpenMS::TargetedExperiment::Peptide& peptide) const;
/**
@brief Reverse a peptide sequence (with its modifications)
@note Does not keep N / C terminus in place.
*/
OpenMS::TargetedExperiment::Peptide reversePeptide_(
const OpenMS::TargetedExperiment::Peptide& peptide) const;
/**
@brief Convert a peptide to a string which contains the peptide sequence and modifications
**/
String getModifiedPeptideSequence_(const OpenMS::TargetedExperiment::Peptide& pep) const;
/// Synchronize members with param class
void updateMembers_() override;
String keep_const_pattern_;
bool keepN_;
bool keepC_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/OPENSWATH/ConfidenceScoring.h | .h | 6,590 | 191 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hendrik Weisser $
// $Authors: Hannes Roest, Hendrik Weisser $
// --------------------------------------------------------------------------
#pragma once
#include <cmath> // for "exp"
#include <limits> // for "infinity"
#include <map>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/ANALYSIS/MAPMATCHING/TransformationDescription.h>
#include <OpenMS/ANALYSIS/TARGETED/TargetedExperiment.h>
#include <OpenMS/MATH/MathFunctions.h>
namespace OpenMS
{
class OPENMS_DLLAPI ConfidenceScoring :
public ProgressLogger
{
public:
/// Constructor
explicit ConfidenceScoring(bool test_mode_ = false);
~ConfidenceScoring() override {}
protected:
/// Binomial GLM
struct GLM_
{
double intercept;
double rt_coef;
double int_coef;
double operator()(double diff_rt, double dist_int) const
{
double lm = intercept + rt_coef * diff_rt * diff_rt +
int_coef * dist_int;
return 1.0 / (1.0 + exp(-lm));
}
} glm_;
/// Helper for RT normalization (range 0-100)
struct RTNorm_
{
double min_rt;
double max_rt;
double operator()(double rt) const
{
return (rt - min_rt) / (max_rt - min_rt) * 100;
}
} rt_norm_;
TargetedExperiment library_; ///< assay library
IntList decoy_index_; ///< indexes of assays to use as decoys
Size n_decoys_; ///< number of decoys to use (per feature/true assay)
std::map<String, IntList> transition_map_; ///< assay (ID) -> transitions (indexes)
Size n_transitions_; ///< number of transitions to consider
/// RT transformation to map measured RTs to assay RTs
TransformationDescription rt_trafo_;
Math::RandomShuffler shuffler_; ///< random shuffler for container
/// Randomize the list of decoy indexes
void chooseDecoys_();
/// Manhattan distance
double manhattanDist_(DoubleList x, DoubleList y);
/// Get the retention time of an assay
double getAssayRT_(const TargetedExperiment::Peptide& assay);
/// Score the assay @p assay against feature data (@p feature_rt,
/// @p feature_intensities), optionally using only the specified transitions
/// (@p transition_ids)
double scoreAssay_(const TargetedExperiment::Peptide& assay,
double feature_rt, DoubleList& feature_intensities,
const std::set<String>& transition_ids = std::set<String>());
/// Score a feature
void scoreFeature_(Feature& feature);
public:
void initialize(const TargetedExperiment& library, const Size n_decoys, const Size n_transitions, const TransformationDescription& rt_trafo)
{
library_ = library;
n_decoys_ = n_decoys;
n_transitions_ = n_transitions;
rt_trafo_ = rt_trafo;
}
void initializeGlm(double intercept, double rt_coef, double int_coef)
{
glm_.intercept = intercept;
glm_.rt_coef = rt_coef;
glm_.int_coef = int_coef;
}
/**
@brief Score a feature map -> make sure the class is properly initialized
both functions initializeGlm and initialize need to be called first.
The input to the program is
- a transition library which contains peptides with corresponding assays.
- a feature map where each feature corresponds to an assay (mapped with
MetaValue "PeptideRef") and each feature has as many subordinates as the
assay has transitions (mapped with MetaValue "native_id").
*/
void scoreMap(FeatureMap & features)
{
// are there enough assays in the library?
Size n_assays = library_.getPeptides().size();
if (n_assays < 2)
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"There need to be at least 2 assays in the library for ConfidenceScoring.");
}
if (n_assays - 1 < n_decoys_)
{
OPENMS_LOG_WARN << "Warning: Parameter 'decoys' (" << n_decoys_
<< ") is higher than the number of unrelated assays in the "
<< "library (" << n_assays - 1 << "). "
<< "Using all unrelated assays as decoys." << std::endl;
}
if (n_assays - 1 <= n_decoys_) n_decoys_ = 0; // use all available assays
decoy_index_.resize(n_assays);
for (Size i = 0; i < n_assays; ++i) decoy_index_[i] = boost::numeric_cast<Int>(i);
// build mapping between assays and transitions:
OPENMS_LOG_DEBUG << "Building transition map..." << std::endl;
for (Size i = 0; i < library_.getTransitions().size(); ++i)
{
const String& ref = library_.getTransitions()[i].getPeptideRef();
transition_map_[ref].push_back(boost::numeric_cast<Int>(i));
}
// find min./max. RT in the library:
OPENMS_LOG_DEBUG << "Determining retention time range..." << std::endl;
rt_norm_.min_rt = std::numeric_limits<double>::infinity();
rt_norm_.max_rt = -std::numeric_limits<double>::infinity();
for (std::vector<TargetedExperiment::Peptide>::const_iterator it =
library_.getPeptides().begin(); it != library_.getPeptides().end();
++it)
{
double current_rt = getAssayRT_(*it);
if (current_rt == -1.0) continue; // indicates a missing value
rt_norm_.min_rt = std::min(rt_norm_.min_rt, current_rt);
rt_norm_.max_rt = std::max(rt_norm_.max_rt, current_rt);
}
// log scoring progress:
OPENMS_LOG_DEBUG << "Scoring features..." << std::endl;
startProgress(0, features.size(), "scoring features");
for (FeatureMap::Iterator feat_it = features.begin();
feat_it != features.end(); ++feat_it)
{
OPENMS_LOG_DEBUG << "Feature " << feat_it - features.begin() + 1
<< " (ID '" << feat_it->getUniqueId() << "')"<< std::endl;
scoreFeature_(*feat_it);
setProgress(feat_it - features.begin());
}
endProgress();
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/OPENSWATH/TransitionTSVFile.h | .h | 18,077 | 363 | // 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/ANALYSIS/TARGETED/TargetedExperiment.h>
#include <OpenMS/OPENSWATHALGO/DATAACCESS/TransitionExperiment.h>
#include <OpenMS/FORMAT/FileTypes.h>
#include <OpenMS/CHEMISTRY/ResidueModification.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <fstream>
namespace OpenMS
{
/**
@brief This class supports reading and writing of OpenSWATH transition
lists.
The transition lists can be either comma- or tab-separated plain
text files (CSV or TSV format). Modifications should be provided in
UniMod format<sup>1</sup>, but can also be provided in TPP format.
For another file format that stores transitions, see also TransitionPQPFile.
The following columns are required:
<table>
<tr> <td BGCOLOR="#EBEBEB">PrecursorMz*</td> <td>float</td> <td>This describes the precursor ion \a m/z</td> </tr>
<tr> <td BGCOLOR="#EBEBEB">ProductMz*</td> <td>float; synonyms: FragmentMz</td> <td>This specifies the product ion \a m/z</td> </tr>
<tr> <td BGCOLOR="#EBEBEB">LibraryIntensity*</td> <td>float; synonyms: RelativeFragmentIntensity</td> <td>This specifies the relative intensity of the fragment ion</td></tr>
<tr> <td BGCOLOR="#EBEBEB">NormalizedRetentionTime*</td> <td>float; synonyms: RetentionTime, Tr_recalibrated, iRT, RetentionTimeCalculatorScore</td> <td>This specifies the expected retention time (normalized retention time) </td></tr>
</table>
For targeted proteomics files, the following additional columns should be provided:
<table>
<tr> <td BGCOLOR="#EBEBEB">GeneName**</td> <td>free text; </td><td> Gene name (unique gene identifier)</td></tr>
<tr> <td BGCOLOR="#EBEBEB">ProteinId**</td> <td>free text; synonyms: ProteinName</td><td> Protein identifier</td></tr>
<tr> <td BGCOLOR="#EBEBEB">PeptideSequence**</td> <td>free text</td> <td> sequence only (no modifications); synonyms: Sequence, StrippedSequence</td> </tr>
<tr> <td BGCOLOR="#EBEBEB">ModifiedPeptideSequence**</td> <td>free text</td> <td> should contain modifications<sup>1</sup>; synonyms: FullUniModPeptideName, FullPeptideName, ModifiedSequence</td> </tr>
<tr> <td BGCOLOR="#EBEBEB">PrecursorCharge**</td> <td>integer; synonyms: Charge</td> <td> contains the charge of the precursor ion</td> </tr>
<tr> <td BGCOLOR="#EBEBEB">ProductCharge**</td> <td>integer; synonyms: FragmentCharge</td> <td> contains the fragment charge</td> </tr>
<tr> <td BGCOLOR="#EBEBEB">FragmentType</td> <td>free text</td> <td> contains the type of the fragment, e.g. "b" or "y"</td> </tr>
<tr> <td BGCOLOR="#EBEBEB">FragmentSeriesNumber</td> <td>integer; synonyms: FragmentNumber</td> <td> e.g. for y7 use "7" here</td> </tr>
</table>
OpenSWATH uses grouped transitions to detect candidate analyte signals. These groups are by default generated based on the input, but can also be manually specified:
<table>
<tr> <td BGCOLOR="#EBEBEB">TransitionGroupId**</td> <td>free text; synomys: TransitionGroupName, transition_group_id</td><td> designates the transition group [e.g. peptide] to which this transition belongs</td> </tr>
<tr> <td BGCOLOR="#EBEBEB">TransitionId**</td> <td>free text; synonyms: TransitionName, transition_name </td> <td> needs to be unique for each transition [in this file]</td> </tr>
<tr> <td BGCOLOR="#EBEBEB">Decoy</td> <td>1: decoy, 0: target; synomys: decoy, IsDecoy </td> <td> determines whether the transition is a decoy transition or not</td> </tr>
<tr> <td BGCOLOR="#EBEBEB">PeptideGroupLabel</td> <td>free text </td> <td> designates to which peptide label group (as defined in MS:1000893) the peptide belongs to<sup>2</sup></td> </tr>
<tr> <td BGCOLOR="#EBEBEB">DetectingTransition</td> <td> 0 or 1; synonyms: detecting_transition</td> <td>1: use transition to detect peak group, 0: don't use transition for detection</td> </tr>
<tr> <td BGCOLOR="#EBEBEB">IdentifyingTransition</td> <td> 0 or 1; synonyms: identifying_transition</td> <td>1: use transition for peptidoform inference in the <a href="http://openswath.org/en/latest/docs/ipf.html">IPF Workflow</a>, 0: don't use transition for identification</td> </tr>
<tr> <td BGCOLOR="#EBEBEB">QuantifyingTransition</td> <td> 0 or 1; synonyms: quantifying_transition</td> <td>1: use transition to quantify peak group, 0: don't use transition for quantification</td> </tr>
</table>
Optionally, the following columns can be specified but they are not actively used by OpenSWATH:
<table>
<tr> <td BGCOLOR="#EBEBEB">CollisionEnergy </td><td>float; synonyms: CE</td><td>Collision energy </td></tr>
<tr> <td BGCOLOR="#EBEBEB">Annotation </td><td>free text</td><td>Transition-level annotation, e.g. y7</td> </tr>
<tr> <td BGCOLOR="#EBEBEB">UniprotId </td><td>free text; synonyms: UniprotID</td> <td>A Uniprot identifier </td></tr>
<tr> <td BGCOLOR="#EBEBEB">LabelType </td><td>free text</td><td>optional description of which label was used, e.g. heavy or light</td> </tr>
</table>
For targeted metabolomics files, the following fields are also supported:
<table>
<tr> <td BGCOLOR="#EBEBEB">CompoundName**</td> <td>free text; synonyms: CompoundId</td><td>Should be unique for the analyte, if present the file will be interpreted as a metabolomics file </td></tr>
<tr> <td BGCOLOR="#EBEBEB">SMILES</td><td>free text</td><td>SMILES identifier of the compound</td></tr>
<tr> <td BGCOLOR="#EBEBEB">SumFormula</td><td>free text</td><td>molecular formula of the compound (e.g. H2O)</td></tr>
</table>
Fields indicated with * are strictly required to create a TraML file. Fields
indicated with ** are recommended, but only required for a specific
application (such as using the transition list for an analysis tool such as
\ref TOPP_OpenSwathWorkflow) or in a specific context (proteomics or metabolomics).
<p>
Remarks:
</p>
<ul>
<li>
1. modifications should be supplied inside the sequence using UniMod
identifiers or freetext identifiers that are understood by %OpenMS. See also @ref OpenMS::AASequence for more information. For example:
<ul>
<li> PEPT(Phosphorylation)IDE(UniMod:27)A ) </li>
</ul>
</li>
<li>
2. peptide label groups designate groups of peptides that are isotopically
modified forms of the same peptide species. For example, the heavy and
light forms of the same peptide will both be assigned the same peptide
group label. For example:
<ul>
<li> PEPTIDEAK -> gets label "PEPTIDEAK_gr1" </li>
<li> PEPTIDEAK[+8] -> gets label "PEPTIDEAK_gr1" </li>
<li> PEPT(Phosphorylation)IDEAK -> gets label "PEPTIDEAK_gr2" </li>
<li> PEPT(Phosphorylation)IDEAK[+8] -> gets label "PEPTIDEAK_gr2" </li>
</ul>
</li>
</ul>
</p>
@htmlinclude OpenMS_TransitionTSVFile.parameters
*/
class OPENMS_DLLAPI TransitionTSVFile :
public ProgressLogger,
public DefaultParamHandler
{
protected:
/**
@brief Internal structure to represent a transition
Internal structure to represent a single line from a transition input
file (one transition).
*/
struct TSVTransition
{
double precursor = -1; ///< Precursor m/z
double product = -1; ///< Product m/z (fragment ion m/z)
double rt_calibrated = -1; ///< Normalized RT
String transition_name = ""; ///< Unique transition name
double CE = -1; ///< Collision Energy
double library_intensity = -1; ///< Library intensity of fragment ion (relative)
String group_id = ""; ///< Transition group identifier (grouping transitions of the same analyte)
bool decoy = false; ///< Whether the transition is a decoy transition
String PeptideSequence; ///< Peptide sequence (only AA sequence)
std::vector<String> ProteinName; ///< List of protein identifiers
String GeneName; ///< Gene identifier
String Annotation; ///< Fragment ion annotation
String FullPeptideName; ///< Full peptide sequence with UniMod modifications
String CompoundName; ///< Compound name (for metabolomics)
String SMILES; ///< SMILES identifier (for metabolomics)
String SumFormula; ///< Molecular formula (for metabolomics)
String Adducts; ///< Adducts (for metabolomics)
String precursor_charge; ///< Precursor charge state
String peptide_group_label; ///< Peptide group identifier (grouping isotopically labelled peptides)
String label_type; ///< Type of label that was used (e.g. "heavy" or "light")
String fragment_charge = "NA"; ///< Fragment ion charge state
int fragment_nr = -1; ///< Fragment number (e.g. "7" for a y7 ion)
double fragment_mzdelta = -1; ///< Fragment m/z delta to theoretical ion
double drift_time = -1; ///< Ion mobility drift time
int fragment_modification = 0; ///< Fragment modification
String fragment_type; ///< Fragment type (e.g. "y" for a y7 ion)
std::vector<String> uniprot_id; ///< List of UniProt identifiers of associated proteins
bool detecting_transition = true; ///< Whether to use transition to detect peak group,
bool identifying_transition = false; ///< Whether to use transition for peptidoform inference using IPF
bool quantifying_transition = true; ///< Whether to use transition to quantify peak group
std::vector<String> peptidoforms; ///< List of peptidoforms
/// Whether the transition represents a peptide (by convention, if the
/// (metabolic) compound name field is empty, it is a peptide.)
bool isPeptide() const
{
return CompoundName.empty() || CompoundName == "NA";
}
};
/** @name Conversion functions from TSVTransition objects to OpenMS datastructures
*
* These functions convert the relevant data from a TSVTransition to the
* datastructures used by the TraML handler or by the internal LightTargetedExperiment.
*
*/
//@{
/** @brief Convert a list of TSVTransition to a TargetedExperiment
*
* Converts the list (read from csv/mrm) file into a object model using the
* TargetedExperiment with proper hierarchical structure from Transition to
* Peptide to Protein.
*
*/
void TSVToTargetedExperiment_(std::vector<TSVTransition>& transition_list, OpenMS::TargetedExperiment& exp);
/// Convert an OpenMS transition to a TSVTransition for output writing
TransitionTSVFile::TSVTransition convertTransition_(const ReactionMonitoringTransition* it, OpenMS::TargetedExperiment& targeted_exp);
//@}
/// Synchronize members with param class
void updateMembers_() override;
private:
// Members
String retentionTimeInterpretation_;
bool override_group_label_check_;
bool force_invalid_mods_;
// Typedefs
typedef std::vector<OpenMS::TargetedExperiment::Protein> ProteinVectorType;
typedef std::vector<OpenMS::TargetedExperiment::Peptide> PeptideVectorType;
typedef std::vector<OpenMS::ReactionMonitoringTransition> TransitionVectorType;
static const char* strarray_[];
static const std::vector<std::string> header_names_;
/** @name Reader helper functions
*
*/
//@{
/** @brief Determine separator in a CSV file and check for correct headers
*
* @param[in] line The header to be parsed
* @param[in] delimiter The delimiter which will be determined from the input
* @param[in] header_dict The map which maps the fields in the header to their position
*
*/
void getTSVHeader_(const std::string& line, char& delimiter, std::map<std::string, int>& header_dict) const;
/** @brief Read tab or comma separated input with columns defined by their column headers only
*
* @param[in] filename The input file
* @param[in] filetype The type of file ("mrm" or "tsv")
* @param[in] transition_list The output list of transitions
*
*/
void readUnstructuredTSVInput_(const char* filename, FileTypes::Type filetype, std::vector<TSVTransition>& transition_list);
/// Extract retention time from a SpectraST comment string
void spectrastRTExtract(const String& str_inp, double & value, bool & spectrast_legacy);
/// Extract annotation from a SpectraST comment string
bool spectrastAnnotationExtract(const String& str_inp, TSVTransition & mytransition);
/** @brief Cleanup of the read fields (removing quotes etc.)
*/
void cleanupTransitions_(TSVTransition& mytransition);
/** @brief Stream TSV directly to LightTargetedExperiment (memory-efficient)
*
* This function reads the TSV file line by line and directly populates
* the LightTargetedExperiment without creating an intermediate
* vector<TSVTransition>. This reduces peak memory usage by ~5x for large files.
*
* Mixed sequence group detection is performed inline during streaming.
*
* @param[in] filename The input file
* @param[in] filetype The type of file ("mrm" or "tsv")
* @param[out] exp The output LightTargetedExperiment
*
*/
void streamTSVToLightTargetedExperiment_(const char* filename, FileTypes::Type filetype, OpenSwath::LightTargetedExperiment& exp);
//@}
/** @name Conversion helper functions
*
*/
//@{
/** @brief Resolve cases where the same peptide label group has different sequences.
*
* Since members in a peptide label group (MS:1000893) should only be
* isotopically modified forms of the same peptide, having different
* peptide sequences (different AA sequences) within the same group most likely
* constitutes an error. This function will fix the error by erasing the
* provided "peptide group label" for a peptide and replace it with the
* peptide identifier (transition group id).
*
* @param[out] transition_list The list of transitions to be fixed.
*
*/
void resolveMixedSequenceGroups_(std::vector<TSVTransition>& transition_list) const;
/// Populate a new ReactionMonitoringTransition object from a row in the csv
void createTransition_(std::vector<TSVTransition>::iterator& tr_it,
OpenMS::ReactionMonitoringTransition& rm_trans);
/// Populate a new TargetedExperiment::Protein object from a row in the csv
void createProtein_(String protein_name, const String& uniprot_id,
OpenMS::TargetedExperiment::Protein& protein);
/// Helper function to assign retention times to compounds and peptides
void interpretRetentionTime_(std::vector<TargetedExperiment::RetentionTime>& retention_times,
const OpenMS::DataValue& rt_value);
/// Populate a new TargetedExperiment::Peptide object from a row in the csv
void createPeptide_(std::vector<TSVTransition>::const_iterator tr_it,
OpenMS::TargetedExperiment::Peptide& peptide);
/// Populate a new TargetedExperiment::Compound object (a metabolite) from a row in the csv
void createCompound_(std::vector<TSVTransition>::const_iterator tr_it,
OpenMS::TargetedExperiment::Compound& compound);
/// Add a modification at the specified location
void addModification_(std::vector<TargetedExperiment::Peptide::Modification>& mods,
int location,
const ResidueModification& rmod);
//@}
/** @brief Write a TargetedExperiment to a file
*
* @param[in] filename Name of the output file
* @param[out] targeted_exp The data structure to be written to the file
*/
void writeTSVOutput_(const char* filename, OpenMS::TargetedExperiment& targeted_exp);
public:
//@{
/// Constructor
TransitionTSVFile();
/// Destructor
~TransitionTSVFile() override;
//@}
/** @brief Write out a targeted experiment (TraML structure) into a tsv file
*
* @param[out] filename The output file
* @param[out] targeted_exp The targeted experiment
*
*/
void convertTargetedExperimentToTSV(const char* filename, OpenMS::TargetedExperiment& targeted_exp);
/** @brief Write out a targeted experiment (Light structure) into a tsv file
*
* @param[in] filename The output file
* @param[in] targeted_exp The targeted experiment (Light structure)
*
*/
void convertLightTargetedExperimentToTSV(const char* filename, const OpenSwath::LightTargetedExperiment& targeted_exp);
/** @brief Read in a tsv/mrm file and construct a targeted experiment (TraML structure)
*
* @param[out] filename The input file
* @param[in] filetype The type of file ("mrm" or "tsv")
* @param[out] targeted_exp The output targeted experiment
*
*/
void convertTSVToTargetedExperiment(const char* filename, FileTypes::Type filetype, OpenMS::TargetedExperiment& targeted_exp);
/** @brief Read in a tsv file and construct a targeted experiment (Light transition structure)
*
* @param[in] filename The input file
* @param[in] filetype The type of file ("mrm" or "tsv")
* @param[out] targeted_exp The output targeted experiment
*
*/
void convertTSVToTargetedExperiment(const char* filename, FileTypes::Type filetype, OpenSwath::LightTargetedExperiment& targeted_exp);
/// Validate a TargetedExperiment (check that all ids are unique)
void validateTargetedExperiment(const OpenMS::TargetedExperiment& targeted_exp);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/OPENSWATH/OpenSwathOSWWriter.h | .h | 8,078 | 175 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: George Rosenberger $
// $Authors: George Rosenberger $
// --------------------------------------------------------------------------
#pragma once
// Interfaces
#include <OpenMS/OPENSWATHALGO/DATAACCESS/TransitionExperiment.h>
#include <OpenMS/CONCEPT/UniqueIdGenerator.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <fstream>
namespace OpenMS
{
/**
@brief Class to write out an OpenSwath OSW SQLite output (PyProphet input).
The class can take a FeatureMap and create a set of string from it
suitable for output to OSW using the prepareLine function. The SQL data is
directly linked to the PQP file format described in the TransitionPQPFile class.
See also OpenSwathTSVWriter for another output format.
The file format has the following tables:
<table>
<tr> <th BGCOLOR="#EBEBEB" colspan=3>RUN</th> </tr>
<tr> <td BGCOLOR="#EBEBEB">ID</td> <td>INT</td> <td> Primary Key (run id)</td> </tr>
<tr> <td BGCOLOR="#EBEBEB">FILENAME</td> <td>TEXT</td> <td> Original filename associated with the run </td> </tr>
</table>
<table>
<tr> <th BGCOLOR="#EBEBEB" colspan=3>FEATURE</th> </tr>
<tr> <td BGCOLOR="#EBEBEB">ID</td> <td>INT</td> <td> Primary Key (feature id)</td> </tr>
<tr> <td BGCOLOR="#EBEBEB">RUN_ID</td> <td>INT</td> <td> Foreign Key (RUN.ID)</td> </tr>
<tr> <td BGCOLOR="#EBEBEB">PRECURSOR_ID</td> <td>INT</td> <td> Foreign Key (TransitionPQPFile PRECURSOR.ID) </td> </tr>
<tr> <td BGCOLOR="#EBEBEB">EXP_RT</td> <td>REAL</td> <td>Experimental RT (retention time) of the feature </td> </tr>
<tr> <td BGCOLOR="#EBEBEB">NORM_RT</td> <td>REAL</td> <td>Normalized RT (retention time) of the feature. The position of the peak group in the normalized retention time space (e.g. fx(RT) where fx describes the transformation fx)</td> </tr>
<tr> <td BGCOLOR="#EBEBEB">DELTA_RT</td> <td>REAL</td> <td>The difference in retention between expected retention time of the assay and the measured feature retention time (EXP_RT) </td> </tr>
<tr> <td BGCOLOR="#EBEBEB">LEFT_WIDTH</td> <td>REAL</td> <td>Retention time start of the peak (left width) in seconds</td> </tr>
<tr> <td BGCOLOR="#EBEBEB">RIGHT_WIDTH</td> <td>REAL</td> <td>Retention time end of the peak (right width) in seconds</td> </tr>
</table>
<table>
<tr> <th BGCOLOR="#EBEBEB" colspan=3>FEATURE_MS1</th> </tr>
<tr> <td BGCOLOR="#EBEBEB">FEATURE_ID</td> <td>INT</td> <td>Foreign Key (FEATURE.ID)</td> </tr>
<tr> <td BGCOLOR="#EBEBEB">AREA_INTENSITY</td> <td>REAL</td> <td>%Precursor intensity (area) </td> </tr>
<tr> <td BGCOLOR="#EBEBEB">APEX_INTENSITY</td> <td>REAL</td> <td>%Precursor intensity (apex) </td> </tr>
<tr> <td BGCOLOR="#EBEBEB">VAR_...</td> <td>REAL</td> <td>%Precursor score used in pyProphet </td> </tr>
</table>
<table>
<tr> <th BGCOLOR="#EBEBEB" colspan=3>FEATURE_MS2</th> </tr>
<tr> <td BGCOLOR="#EBEBEB">FEATURE_ID</td> <td>INT</td> <td> Foreign Key (FEATURE.ID)</td> </tr>
<tr> <td BGCOLOR="#EBEBEB">AREA_INTENSITY</td> <td>REAL</td> <td>Summed fragment ion intensity (area) </td> </tr>
<tr> <td BGCOLOR="#EBEBEB">TOTAL_AREA_INTENSITY </td> <td>REAL</td> <td>Summed total XIC of the whole chromatogram </td> </tr>
<tr> <td BGCOLOR="#EBEBEB">APEX_INTENSITY</td> <td>REAL</td> <td>Summed fragment ion intensity (apex) </td> </tr>
<tr> <td BGCOLOR="#EBEBEB">TOTAL_MI</td> <td>REAL</td> <td>Total mutual information (MI) </td> </tr>
<tr> <td BGCOLOR="#EBEBEB">VAR_...</td> <td>REAL</td> <td>Fragment ion score used in pyProphet </td> </tr>
</table>
<table>
<tr> <th BGCOLOR="#EBEBEB" colspan=3>FEATURE_PRECURSOR</th> </tr>
<tr> <td BGCOLOR="#EBEBEB">FEATURE_ID</td> <td>INT</td> <td> Foreign Key (FEATURE.ID)</td> </tr>
<tr> <td BGCOLOR="#EBEBEB">ISOTOPE</td> <td>INT</td> <td>Isotope identifier </td> </tr>
<tr> <td BGCOLOR="#EBEBEB">AREA_INTENSITY</td> <td>REAL</td> <td>%Precursor isotope ion intensity (area) </td> </tr>
<tr> <td BGCOLOR="#EBEBEB">APEX_INTENSITY</td> <td>REAL</td> <td>%Precursor isotope ion intensity (apex) </td> </tr>
</table>
<table>
<tr> <th BGCOLOR="#EBEBEB" colspan=3>FEATURE_TRANSITION</th> </tr>
<tr> <td BGCOLOR="#EBEBEB">FEATURE_ID</td> <td>INT</td> <td> Foreign Key (FEATURE.ID)</td> </tr>
<tr> <td BGCOLOR="#EBEBEB">TRANSITION_ID</td> <td>INT</td> <td> Foreign Key (transition identifier)</td> </tr>
<tr> <td BGCOLOR="#EBEBEB">AREA_INTENSITY</td> <td>REAL</td> <td>Fragment ion intensity (area) </td> </tr>
<tr> <td BGCOLOR="#EBEBEB">TOTAL_AREA_INTENSITY </td> <td>REAL</td> <td>Total XIC of the whole chromatogram </td> </tr>
<tr> <td BGCOLOR="#EBEBEB">APEX_INTENSITY</td> <td>REAL</td> <td>Fragment ion intensity (apex) </td> </tr>
<tr> <td BGCOLOR="#EBEBEB">TOTAL_MI</td> <td>REAL</td> <td>Total mutual information (MI) </td> </tr>
<tr> <td BGCOLOR="#EBEBEB">VAR_...</td> <td>REAL</td> <td>Fragment ion score used in pyProphet </td> </tr>
</table>
*/
class OPENMS_DLLAPI OpenSwathOSWWriter
{
String output_filename_;
String input_filename_;
OpenMS::UInt64 run_id_;
bool doWrite_;
bool enable_uis_scoring_;
public:
OpenSwathOSWWriter(const String& output_filename,
const UInt64 run_id,
const String& input_filename = "inputfile",
bool uis_scores = false);
bool isActive() const;
/**
* @brief Initializes file by generating SQLite tables
*
*/
void writeHeader();
/**
* @brief Prepare scores for SQLite insertion
*
* Some scores might not be defined, those are reported as NULL
*
* @param[in] feature The feature being evaluated
* @param[in] score_name The name of the queried score
*
* @returns A string with the queried score
*
*/
String getScore(const Feature& feature, const std::string& score_name) const;
/**
* @brief Prepare concatenated scores for SQLite insertion
*
* Some scores might not be defined, those are reported as NULL
*
* @param[in] feature The feature being evaluated
* @param[in] score_name The name of the queried score
*
* @returns A vector of strings with the queried scores
*
*/
std::vector<String> getSeparateScore(const Feature& feature, const std::string& score_name) const;
/**
* @brief Prepare a single line (feature) for output
*
* The result can be flushed to disk using writeLines (either line by line
* or after collecting several lines).
*
* @param[in] pep The compound (peptide/metabolite) used for extraction
* @param[in] transition The transition used for extraction
* @param[in] output The feature map containing all features (each feature will generate one entry in the output)
* @param[in] id The transition group identifier (peptide/metabolite id)
*
* @returns A string to be written using writeLines
*
*/
String prepareLine(const OpenSwath::LightCompound& pep,
const OpenSwath::LightTransition* transition,
const FeatureMap& output, const String& id) const;
/**
* @brief Write data to disk
*
* Takes a set of pre-prepared data statements from prepareLine and flushes them to disk
*
* @param[in] to_osw_output Statements generated by prepareLine
*
* @note Try to call this function as little as possible (it opens a new
* database connection each time)
*
* @note Only call inside an OpenMP critical section
*
*/
void writeLines(const std::vector<String>& to_osw_output);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/OPENSWATH/OpenSwathScores.h | .h | 8,093 | 236 | // 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/OpenMSConfig.h>
#include <OpenMS/CONCEPT/Types.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <vector>
namespace OpenMS
{
/** @brief A structure to store which scores should be used by the OpenSWATH Algorithm
*
* This can be used to turn on/off individual scores.
*/
struct OPENMS_DLLAPI OpenSwath_Scores_Usage
{
bool use_coelution_score_ = true;
bool use_shape_score_ = true;
bool use_rt_score_ = true;
bool use_library_score_ = true;
bool use_elution_model_score_ = true;
bool use_intensity_score_ = true;
bool use_total_xic_score_ = true;
bool use_total_mi_score_ = true;
bool use_nr_peaks_score_ = true;
bool use_sn_score_ = true;
bool use_mi_score_ = true;
bool use_dia_scores_ = true;
bool use_im_scores = true;
bool use_ms1_correlation = true;
bool use_ms1_fullscan = true;
bool use_ms1_mi = true;
bool use_uis_scores = true;
bool use_ionseries_scores = true;
bool use_ms2_isotope_scores = true;
bool use_peak_shape_metrics = false;
};
/** @brief A structure to hold the different scores computed by OpenSWATH
*
* This struct is used to store the individual OpenSWATH (sub-)scores. It
* also allows to compute some preliminary quality score for a feature by
* using a predefined combination of the individual scores determined using
* LDA.
*
*/
struct OPENMS_DLLAPI OpenSwath_Scores
{
double elution_model_fit_score = 0;
double library_corr = 0;
double library_norm_manhattan = 0;
double library_rootmeansquare = 0;
double library_sangle = 0;
double norm_rt_score = 0;
double isotope_correlation = 0;
double isotope_overlap = 0;
double massdev_score = 0;
double xcorr_coelution_score = 0;
double xcorr_shape_score = 0;
double yseries_score = 0;
double bseries_score = 0;
double log_sn_score = 0;
double weighted_coelution_score = 0;
double weighted_xcorr_shape = 0;
double weighted_massdev_score = 0;
double ms1_xcorr_coelution_score = -1;
double ms1_xcorr_coelution_contrast_score = 0;
double ms1_xcorr_coelution_combined_score = 0;
double ms1_xcorr_shape_score = -1;
double ms1_xcorr_shape_contrast_score = 0;
double ms1_xcorr_shape_combined_score = 0;
double ms1_ppm_score = 0;
double ms1_isotope_correlation = 0;
double ms1_isotope_overlap = 0;
double ms1_mi_score = -1;
double ms1_mi_contrast_score = 0;
double ms1_mi_combined_score = 0;
double im_xcorr_coelution_score = 0;
double im_xcorr_shape_score = 0;
double im_delta_score = 0;
double im_ms1_delta_score = 0;
double im_drift = 0;
double im_drift_left = 0;
double im_drift_right = 0;
double im_drift_weighted = 0;
double im_delta = -1;
double im_log_intensity = 0;
double im_ms1_contrast_coelution = 0;
double im_ms1_contrast_shape = 0;
double im_ms1_sum_contrast_coelution = 0;
double im_ms1_sum_contrast_shape = 0;
double im_ms1_drift = 0;
double im_ms1_delta = -1;
// additional ion mobility IPF identifying against detecting transition scores
double im_ind_contrast_coelution = 0;
double im_ind_contrast_shape = 0;
double im_ind_sum_contrast_coelution = 0;
double im_ind_sum_contrast_shape = 0;
double library_manhattan = 0;
double library_dotprod = 0;
double intensity = 0;
double total_xic = 0;
double nr_peaks = 0;
double sn_ratio = 0;
double mi_score = 0;
double weighted_mi_score = 0;
double rt_difference = 0;
double normalized_experimental_rt = 0;
double raw_rt_score = 0;
double dotprod_score_dia = 0;
double manhatt_score_dia = 0;
OpenSwath_Scores() = default;
double get_quick_lda_score(double library_corr_,
double library_norm_manhattan_,
double norm_rt_score_,
double xcorr_coelution_score_,
double xcorr_shape_score_,
double log_sn_score_) const;
/** @brief A quick LDA model based non-DIA scores
*
* A quick model LDA average model on which uses only non-DIA scores
* (library_corr, library_norm_manhattan, norm_rt_score,
* xcorr_coelution_score, xcorr_shape_score, log_sn_score and
* elution_model_fit_score).
*
* @returns A score which is better when more negative
*
*/
double calculate_lda_prescore(const OpenSwath_Scores& scores) const;
/** @brief A scoring model for peak groups with a single transition
*
* Manually derived scoring model for single transition peakgroups, only
* uses norm_rt_score, log_sn_score, and elution_model_fit_score.
*
* @returns A score which is better when more negative
*
*/
double calculate_lda_single_transition(const OpenSwath_Scores& scores) const;
/** @brief A full LDA model using DIA and non-DIA scores
*
* A LDA average model which uses all available scores.
*
* @returns A score which is better when more negative
*
*/
double calculate_swath_lda_prescore(const OpenSwath_Scores& scores) const;
};
/**
* @brief A structure to hold the individual scores computed for unique ion signatures (UIS) scores for the Inference of Peptidoforms (IPF) workflow
*
* Most of the scores are computed for each individual identifying transition (theoretical transitions) against the peak-group detection transitions.
*
* This struct also holds peak shape metrics for each individual transition.
*
*/
struct OPENMS_DLLAPI OpenSwath_Ind_Scores
{
int ind_num_transitions = 0;
std::vector<OpenMS::String> ind_transition_names;
std::vector<double> ind_isotope_correlation;
std::vector<double> ind_isotope_overlap;
std::vector<double> ind_massdev_score;
std::vector<double> ind_xcorr_coelution_score;
std::vector<double> ind_xcorr_shape_score;
std::vector<double> ind_log_sn_score;
std::vector<double> ind_area_intensity;
std::vector<double> ind_total_area_intensity;
std::vector<double> ind_intensity_score;
std::vector<double> ind_apex_intensity;
std::vector<double> ind_apex_position;
std::vector<double> ind_fwhm;
std::vector<double> ind_total_mi;
std::vector<double> ind_log_intensity;
std::vector<double> ind_intensity_ratio;
std::vector<double> ind_mi_ratio;
std::vector<double> ind_mi_score;
// ion mobility scores
std::vector<double> ind_im_drift;
std::vector<double> ind_im_drift_left;
std::vector<double> ind_im_drift_right;
std::vector<double> ind_im_delta;
std::vector<double> ind_im_delta_score;
std::vector<double> ind_im_log_intensity;
std::vector<double> ind_im_contrast_coelution;
std::vector<double> ind_im_contrast_shape;
std::vector<double> ind_im_sum_contrast_coelution;
std::vector<double> ind_im_sum_contrast_shape;
// peak shape metrics
std::vector<double> ind_start_position_at_5;
std::vector<double> ind_end_position_at_5;
std::vector<double> ind_start_position_at_10;
std::vector<double> ind_end_position_at_10;
std::vector<double> ind_start_position_at_50;
std::vector<double> ind_end_position_at_50;
std::vector<double> ind_total_width;
std::vector<double> ind_tailing_factor;
std::vector<double> ind_asymmetry_factor;
std::vector<double> ind_slope_of_baseline;
std::vector<double> ind_baseline_delta_2_height;
std::vector<double> ind_points_across_baseline;
std::vector<double> ind_points_across_half_height;
OpenSwath_Ind_Scores() = default;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/OPENSWATH/MasstraceCorrelator.h | .h | 5,831 | 138 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hannes Roest $
// $Authors: Hannes Roest $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/KERNEL/ConsensusMap.h>
#include <OpenMS/KERNEL/MSExperiment.h>
namespace OpenMS
{
/**
@brief Correlates individual masstraces found in mass spectrometric maps
The MasstraceCorrelator offers several functions to correlate individual
mass traces using the normalized Cross-Correlation and pearson scoring of
the OpenSWATH module.
*/
class OPENMS_DLLAPI MasstraceCorrelator :
public DefaultParamHandler,
public ProgressLogger
{
public:
MasstraceCorrelator();
~MasstraceCorrelator() override;
// a mass trace is a vector of pairs in (RT, Intensity)
typedef std::vector<std::pair<double, double> > MasstracePointsType;
/** Compute pseudo-spectra from a set of (MS2) masstraces
*
* This function will take a set of masstraces (consensus map) as input and
* produce a vector of pseudo spectra as output (pseudo_spectra result
* vector).
*
* It basically makes an all-vs-all comparison of all masstraces against
* each other and scores them on how similar they are in their mass traces.
*
* This assumes that the consensus feature is only from one (SWATH) map
* This assumes that the consensus map is sorted by intensity
*
*/
void createPseudoSpectra(const ConsensusMap& map, MSExperiment& pseudo_spectra,
Size min_peak_nr, double min_correlation, int max_lag,
double max_rt_apex_difference);
/* Score two mass traces against each other
*
* This function scores two mass traces (vector of <RT,Intensity>) against each other:
*
* - The algorithm first creates 2 arrays that contain matched intensities
* in RT-space (accounting for missing data points and unequal length)
* - Next, these arrays are scored using cross-correlation scores and
* pearson coefficients.
*
* @note The pairs need to be sorted by the first entry (RT)
*
* @param[in] hull_points1 The first input masstrace
* @param[in] hull_points2 The second input masstrace
* @param[out] lag The computed lag (output coelution score)
* @param[out] lag_intensity The computed intensity at the lag (output shape score)
* @param[out] pearson_score The computed pearson score (output)
* @param[in] min_corr Minimal correlation needed to proceed computing the cross-correlations
* @param[in] max_lag Currently unused
* @param[in] mindiff Minimal differences for matching up the two mass traces
*
*/
void scoreHullpoints(const MasstracePointsType& hull_points1,
const MasstracePointsType& hull_points2,
int& lag,
double& lag_intensity,
double& pearson_score,
const double min_corr,
const int max_lag,
const double mindiff = 0.1);
/* Create a cache of the features in a consensus map
*
* This creates a cache of the input consensus map by creating the
* following data structures:
* - a vector of mass traces (each mass trace is simply a vector of <RT,Intensity>
* - a vector of maximal intensities (max_rt, max_int)
* - a vector of retention times of the feature
*
* @param[in] map The input consensus map
* @param[in] feature_points The list of all mass traces
* @param[in] max_intensities The list of maximal intensities
* @param[in] rt_cache The list of retention times of all features
*/
void createConsensusMapCache(const ConsensusMap& map,
std::vector<MasstracePointsType>& feature_points,
std::vector<std::pair<double, double> >& max_intensities,
std::vector<double>& rt_cache);
protected:
/** @brief Match up two mass traces with potentially missing values
*
* To compute correlations on masstraces, they need to have the same length
* and matching points. This function matches two masstraces by RT and
* identifies points that are the same in retention time (see mindiff
* parameter) and matches them. If no match is found, a missing value is
* assumed and they are filled with zeros. Thus, if the two retention times
* are less than mindiff apart, the two entries are considered to be equal,
* otherwise one is assumed to be zero).
*
* This is useful for matching mass traces that are not of the exact same
* length and/or have missing values.
*
* @param[in] hull_points1 The first input mass trace
* @param[in] hull_points2 The second input mass trace
* @param[in] vec1 The intensities of the first mass trace with matched-up points
* @param[in] vec2 The intensities of the second mass trace with matched-up points
* @param[in] mindiff The minimal difference in RT for points to match up
* @param[in] padEnds Whether to pad ends with zeros
*
*/
void matchMassTraces_(const MasstracePointsType& hull_points1,
const MasstracePointsType& hull_points2,
std::vector<double>& vec1,
std::vector<double>& vec2,
double mindiff,
double padEnds = true);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/OPENSWATH/PeakIntegrator.h | .h | 39,570 | 948 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Douglas McCloskey, Pasquale Domenico Colaianni $
// $Authors: Douglas McCloskey, Pasquale Domenico Colaianni $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/config.h> // OPENMS_DLLAPI
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/DATASTRUCTURES/ConvexHull2D.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/KERNEL/MSChromatogram.h>
#include <OpenMS/KERNEL/MSSpectrum.h>
#include <OpenMS/MATH/MISC/EmgGradientDescent.h>
namespace OpenMS
{
/**
@brief Compute the area, background and shape metrics of a peak.
The area computation is performed in integratePeak() and it supports
integration by simple sum of the intensity, integration by Simpson's rule
implementations for an odd number of unequally spaced points or integration
by the trapezoid rule.
The background computation is performed in estimateBackground() and it
supports three different approaches to baseline correction, namely
computing a rectangular shape under the peak based on the minimum value of
the peak borders (vertical_division_min), a rectangular shape based on the
maximum value of the beak borders (vertical_division_max) or a trapezoidal
shape based on a straight line between the peak borders (base_to_base).
Peak shape metrics are computed in calculatePeakShapeMetrics() and multiple
metrics are supported.
The containers supported by the methods are MSChromatogram and MSSpectrum.
@section PeakIntegrator_integration Integration Methods
| Method | Description | Use Case |
|--------|-------------|----------|
| `intensity_sum` | Simple sum of intensities | Fast, profile data |
| `trapezoid` | Trapezoidal rule | General purpose, accurate |
| `simpson` | Simpson's rule (unequally spaced) | High accuracy for smooth peaks |
@section PeakIntegrator_baseline Baseline Methods
| Method | Description |
|--------|-------------|
| `base_to_base` | Trapezoidal baseline between peak borders |
| `vertical_division_min` | Rectangular baseline at minimum border intensity |
| `vertical_division_max` | Rectangular baseline at maximum border intensity |
@section PeakIntegrator_metrics Peak Shape Metrics
The calculatePeakShapeMetrics() method computes:
- Width at 5%, 10%, 50% of peak height
- Tailing factor (USP definition): W0.05 / 2a
- Asymmetry factor: b/a at 10% height
- Slope of baseline
- Points across baseline and half-height
@section PeakIntegrator_emg EMG Peak Fitting
When enabled via the `fit_EMG` parameter, peaks are first fitted to an
Exponentially Modified Gaussian model using EmgGradientDescent. This is
particularly useful for:
- Saturated peaks (detector saturation)
- Cutoff peaks (incomplete acquisition)
- Tailing peaks
@warning integratePeak() using Simpson's rule can result in negative areas despite
strictly positive intensities in the input dataset. An example is given in
the class test (see area = -665788.77).
@see EmgGradientDescent for EMG peak fitting
@see MRMTransitionGroupPicker for usage in MRM workflows
@ingroup TargetedQuantitation
*/
class OPENMS_DLLAPI PeakIntegrator :
public DefaultParamHandler
{
public:
/// Constructor
PeakIntegrator();
/// Destructor
~PeakIntegrator() override;
/** @name integratePeak() output
The integratePeak() method uses this struct to save its results.
*/
///@{
struct PeakArea
{
/**
The peak's computed area
*/
double area = 0.0;
/**
The peak's highest intensity
*/
double height = 0.0;
/**
The position of the point with highest intensity
*/
double apex_pos = 0.0;
/**
The peak's hull points
*/
ConvexHull2D::PointArrayType hull_points;
};
///@}
/** @name estimateBackground() output
The estimateBackground() method uses this struct to save its results.
*/
///@{
struct PeakBackground
{
/**
The background area estimation
*/
double area = 0.0;
/**
The background height
*/
double height = 0.0;
};
///@}
/** @name calculatePeakShapeMetrics() output
The calculatePeakShapeMetrics() method uses this struct to save its results.
*/
///@{
struct PeakShapeMetrics
{
/**
The width of the peak at 5% the peak's height.
*/
double width_at_5 = 0.0;
/**
The width of the peak at 10% the peak's height.
*/
double width_at_10 = 0.0;
/**
The width of the peak at 50% the peak's height.
*/
double width_at_50 = 0.0;
/**
The start position at which the intensity is 5% the peak's height.
*/
double start_position_at_5 = 0.0;
/**
The start position at which the intensity is 10% the peak's height.
*/
double start_position_at_10 = 0.0;
/**
The start position at which the intensity is 50% the peak's height.
*/
double start_position_at_50 = 0.0;
/**
The end position at which the intensity is 5% the peak's height.
*/
double end_position_at_5 = 0.0;
/**
The end position at which the intensity is 10% the peak's height.
*/
double end_position_at_10 = 0.0;
/**
The end position at which the intensity is 50% the peak's height.
*/
double end_position_at_50 = 0.0;
/**
The peak's total width.
*/
double total_width = 0.0;
/**
The tailing factor is a measure of peak tailing.
It is defined as the distance from the front slope of the peak to the back slope
divided by twice the distance from the center line of the peak to the front slope,
with all measurements made at 5% of the maximum peak height.
tailing_factor = Tf = W0.05/2a
where W0.05 is peak width at 5% max peak height
a = min width to peak maximum at 5% max peak height
b = max width to peak maximum at 5% max peak height
0.9 < Tf < 1.2
front Tf < 0.9
tailing Tf > 1.2
*/
double tailing_factor = 0.0;
/**
The asymmetry factor is a measure of peak tailing.
It is defined as the distance from the center line of the peak to the back slope
divided by the distance from the center line of the peak to the front slope,
with all measurements made at 10% of the maximum peak height.
asymmetry_factor = As = b/a
where a is min width to peak maximum at 10% max peak height
b is max width to peak maximum at 10% max peak height
*/
double asymmetry_factor = 0.0;
/**
The slope of the baseline is a measure of slope change.
It is approximated as the difference in baselines between the peak start and peak end.
*/
double slope_of_baseline = 0.0;
/**
The change in baseline divided by the height is
a way of comparing the influence of the change of baseline on the peak height.
*/
double baseline_delta_2_height = 0.0;
/**
The number of points across the baseline.
*/
Int points_across_baseline = 0;
/**
The number of points across half the peak's height.
*/
Int points_across_half_height = 0;
};
///@}
/** @name Constant expressions for parameters
Constants expressions used throughout the code and tests to set
the integration and baseline types.
*/
///@{
/// Integration type: intensity sum
static constexpr const char* INTEGRATION_TYPE_INTENSITYSUM = "intensity_sum";
/// Integration type: trapezoid
static constexpr const char* INTEGRATION_TYPE_TRAPEZOID = "trapezoid";
/// Integration type: simpson
static constexpr const char* INTEGRATION_TYPE_SIMPSON = "simpson";
/// Baseline type: base to base
static constexpr const char* BASELINE_TYPE_BASETOBASE = "base_to_base";
/// Baseline type: vertical division (min of end points; only for backwards compatibility)
static constexpr const char* BASELINE_TYPE_VERTICALDIVISION = "vertical_division";
/// Baseline type: vertical division (min of end points)
static constexpr const char* BASELINE_TYPE_VERTICALDIVISION_MIN = "vertical_division_min";
/// Baseline type: vertical division (max of end points)
static constexpr const char* BASELINE_TYPE_VERTICALDIVISION_MAX = "vertical_division_max";
///@}
/**
@brief Compute the area of a peak contained in a MSChromatogram.
The value of integration_type_ decides which integration technique to use:
- "trapezoid" for the trapezoidal rule
- "simpson" for the Simpson's rule (for unequally spaced points, Shklov, 1960)
- "intensity_sum" for the simple sum of the intensities
@note Make sure the chromatogram is sorted with respect to retention time.
@throw Exception::InvalidParameter for class parameter `integration_type`.
@param[in] chromatogram The chromatogram which contains the peak
@param[in] left The left retention time boundary
@param[in] right The right retention time boundary
@return A struct containing the informations about the peak's area, height and position
*/
PeakArea integratePeak(
const MSChromatogram& chromatogram, const double left, const double right
) const;
/**
@brief Compute the area of a peak contained in a MSChromatogram.
The value of integration_type_ decides which integration technique to use:
- "trapezoid" for the trapezoidal rule
- "simpson" for the Simpson's rule (for unequally spaced points, Shklov, 1960)
- "intensity_sum" for the simple sum of the intensities
@note Make sure the chromatogram is sorted with respect to retention time.
@throw Exception::InvalidParameter for class parameter `integration_type`.
@param[in] chromatogram The chromatogram which contains the peak
@param[in] left The iterator to the first point
@param[in] right The iterator to the last point
@return A struct containing the informations about the peak's area, height and position
*/
PeakArea integratePeak(
const MSChromatogram& chromatogram, MSChromatogram::ConstIterator& left, MSChromatogram::ConstIterator& right
) const;
/**
@brief Compute the area of a peak contained in a MSSpectrum.
The value of integration_type_ decides which integration technique to use:
- "trapezoid" for the trapezoidal rule
- "simpson" for the Simpson's rule (for unequally spaced points, Shklov, 1960)
- "intensity_sum" for the simple sum of the intensities
@note Make sure the spectrum is sorted with respect to mass-to-charge ratio.
@throw Exception::InvalidParameter for class parameter `integration_type`.
@param[in] spectrum The spectrum which contains the peak
@param[in] left The left mass-to-charge ratio boundary
@param[in] right The right mass-to-charge ratio boundary
@return A struct containing the informations about the peak's area, height and position
*/
PeakArea integratePeak(
const MSSpectrum& spectrum, const double left, const double right
) const;
/**
@brief Compute the area of a peak contained in a MSSpectrum.
The value of integration_type_ decides which integration technique to use:
- "trapezoid" for the trapezoidal rule
- "simpson" for the Simpson's rule (for unequally spaced points, Shklov, 1960)
- "intensity_sum" for the simple sum of the intensities
@note Make sure the spectrum is sorted with respect to mass-to-charge ratio.
@throw Exception::InvalidParameter for class parameter `integration_type`.
@param[in] spectrum The spectrum which contains the peak
@param[in] left The iterator to the first point
@param[in] right The iterator to the last point
@return A struct containing the informations about the peak's area, height and position
*/
PeakArea integratePeak(
const MSSpectrum& spectrum, MSSpectrum::ConstIterator& left, MSSpectrum::ConstIterator& right
) const;
/**
@brief Estimate the background of a peak contained in a MSChromatogram.
The user can choose to compute one of two background types: "vertical_sum" and "base_to_base".
For the former case, the area is computed as a rectangle with delta RT being the base and
the minimum intensity on boundaries as the height.
For the latter case, the area is computed as a rectangle trapezoid. Similar to the "vertical_sum"
solution, this technique also takes into account the area between the intensities on boundaries.
For both cases, the parameter integration_type_ decides which formula to use to compute the area.
The user should make sure to use the same integration_type between calls of estimateBackground() and
integratePeak().
@note Make sure the chromatogram is sorted with respect to retention time.
@throw Exception::InvalidParameter for class parameter `baseline_type`.
@param[in] chromatogram The chromatogram which contains the peak
@param[in] left The left retention time boundary
@param[in] right The right retention time boundary
@param[in] peak_apex_pos The position of the point with highest intensity
@return A struct containing the informations about the peak's background area and height
*/
PeakBackground estimateBackground(
const MSChromatogram& chromatogram, const double left, const double right,
const double peak_apex_pos
) const;
/**
@brief Estimate the background of a peak contained in a MSChromatogram.
The user can choose to compute one of two background types: "vertical_sum" and "base_to_base".
For the former case, the area is computed as a rectangle with delta RT being the base and
the minimum intensity on boundaries as the height.
For the latter case, the area is computed as a rectangle trapezoid. Similar to the "vertical_sum"
solution, this technique also takes into account the area between the intensities on boundaries.
For both cases, the parameter integration_type_ decides which formula to use to compute the area.
The user should make sure to use the same integration_type between calls of estimateBackground() and
integratePeak().
@note Make sure the chromatogram is sorted with respect to retention time.
@throw Exception::InvalidParameter for class parameter `baseline_type`.
@param[in] chromatogram The chromatogram which contains the peak
@param[in] left The iterator to the first point
@param[in] right The iterator to the last point
@param[in] peak_apex_pos The position of the point with highest intensity
@return A struct containing the informations about the peak's background area and height
*/
PeakBackground estimateBackground(
const MSChromatogram& chromatogram, MSChromatogram::ConstIterator& left, MSChromatogram::ConstIterator& right,
const double peak_apex_pos
) const;
/**
@brief Estimate the background of a peak contained in a MSSpectrum.
The user can choose to compute one of two background types: "vertical_sum" and "base_to_base".
For the former case, the area is computed as a rectangle with delta MZ being the base and
the minimum intensity on boundaries as the height.
For the latter case, the area is computed as a rectangle trapezoid. Similar to the "vertical_sum"
solution, this technique also takes into account the area between the intensities on boundaries.
For both cases, the parameter integration_type_ decides which formula to use to compute the area.
The user should make sure to use the same integration_type between calls of estimateBackground() and
integratePeak().
@note Make sure the spectrum is sorted with respect to mass-to-charge ratio.
@throw Exception::InvalidParameter for class parameter `baseline_type`.
@param[in] spectrum The spectrum which contains the peak
@param[in] left The left mass-to-charge ratio boundary
@param[in] right The right mass-to-charge ratio boundary
@param[in] peak_apex_pos The position of the point with highest intensity
@return A struct containing the informations about the peak's background area and height
*/
PeakBackground estimateBackground(
const MSSpectrum& spectrum, const double left, const double right,
const double peak_apex_pos
) const;
/**
@brief Estimate the background of a peak contained in a MSSpectrum.
The user can choose to compute one of two background types: "vertical_sum" and "base_to_base".
For the former case, the area is computed as a rectangle with delta MZ being the base and
the minimum intensity on boundaries as the height.
For the latter case, the area is computed as a rectangle trapezoid. Similar to the "vertical_sum"
solution, this technique also takes into account the area between the intensities on boundaries.
For both cases, the parameter integration_type_ decides which formula to use to compute the area.
The user should make sure to use the same integration_type between calls of estimateBackground() and
integratePeak().
@note Make sure the spectrum is sorted with respect to mass-to-charge ratio.
@throw Exception::InvalidParameter for class parameter `baseline_type`.
@param[in] spectrum The spectrum which contains the peak
@param[in] left The iterator to the first point
@param[in] right The iterator to the last point
@param[in] peak_apex_pos The position of the point with highest intensity
@return A struct containing the informations about the peak's background area and height
*/
PeakBackground estimateBackground(
const MSSpectrum& spectrum, MSSpectrum::ConstIterator& left, MSSpectrum::ConstIterator& right,
const double peak_apex_pos
) const;
/**
@brief Calculate peak's shape metrics.
The calculated characteristics are the start and end times at 0.05, 0.10 and
0.5 the peak's height. Also the widths at those positions are calculated.
Other values: the peak's total width, its tailing factor, asymmetry factor,
baseline delta to height and the slope of the baseline.
The number of points across the baseline and also at half height are saved.
@note Make sure the chromatogram is sorted with respect to retention time.
@param[in] chromatogram The chromatogram which contains the peak
@param[in] left The left retention time boundary
@param[in] right The right retention time boundary
@param[in] peak_height The peak's highest intensity
@param[in] peak_apex_pos The position of the point with highest intensity
@return A struct containing the calculated peak shape metrics
*/
PeakShapeMetrics calculatePeakShapeMetrics(
const MSChromatogram& chromatogram, const double left, const double right,
const double peak_height, const double peak_apex_pos
) const;
/**
@brief Calculate peak's shape metrics.
The calculated characteristics are the start and end times at 0.05, 0.10 and
0.5 the peak's height. Also the widths at those positions are calculated.
Other values: the peak's total width, its tailing factor, asymmetry factor,
baseline delta to height and the slope of the baseline.
The number of points across the baseline and also at half height are saved.
@note Make sure the chromatogram is sorted with respect to retention time.
@param[in] chromatogram The chromatogram which contains the peak
@param[in] left The iterator to the first point
@param[in] right The iterator to the last point
@param[in] peak_height The peak's highest intensity
@param[in] peak_apex_pos The position of the point with highest intensity
@return A struct containing the calculated peak shape metrics
*/
PeakShapeMetrics calculatePeakShapeMetrics(
const MSChromatogram& chromatogram, MSChromatogram::ConstIterator& left, MSChromatogram::ConstIterator& right,
const double peak_height, const double peak_apex_pos
) const;
/**
@brief Calculate peak's shape metrics.
The calculated characteristics are the start and end positions at 0.05, 0.10 and
0.5 the peak's height. Also the widths at those positions are calculated.
Other values: the peak's total width, its tailing factor, asymmetry factor,
baseline delta to height and the slope of the baseline.
The number of points across the baseline and also at half height are saved.
@note Make sure the spectrum is sorted with respect to mass-to-charge ratio.
@param[in] spectrum The spectrum which contains the peak
@param[in] left The left mass-to-charge ratio boundary
@param[in] right The right mass-to-charge ratio boundary
@param[in] peak_height The peak's highest intensity
@param[in] peak_apex_pos The position of the point with highest intensity
@return A struct containing the calculated peak shape metrics
*/
PeakShapeMetrics calculatePeakShapeMetrics(
const MSSpectrum& spectrum, const double left, const double right,
const double peak_height, const double peak_apex_pos
) const;
/**
@brief Calculate peak's shape metrics.
The calculated characteristics are the start and end positions at 0.05, 0.10 and
0.5 the peak's height. Also the widths at those positions are calculated.
Other values: the peak's total width, its tailing factor, asymmetry factor,
baseline delta to height and the slope of the baseline.
The number of points across the baseline and also at half height are saved.
@note Make sure the spectrum is sorted with respect to mass-to-charge ratio.
@param[in] spectrum The spectrum which contains the peak
@param[in] left The iterator to the first point
@param[in] right The iterator to the last point
@param[in] peak_height The peak's highest intensity
@param[in] peak_apex_pos The position of the point with highest intensity
@return A struct containing the calculated peak shape metrics
*/
PeakShapeMetrics calculatePeakShapeMetrics(
const MSSpectrum& spectrum, MSSpectrum::ConstIterator& left, MSSpectrum::ConstIterator& right,
const double peak_height, const double peak_apex_pos
) const;
void getDefaultParameters(Param& params);
protected:
void updateMembers_() override;
template <typename PeakContainerT>
PeakArea integratePeak_(const PeakContainerT& pc, double left, double right) const
{
OPENMS_PRECONDITION(left <= right, "Left peak boundary must be smaller than right boundary!") // otherwise the code below will segfault (due to PosBegin/PosEnd)
PeakContainerT emg_pc;
const PeakContainerT& p = EMGPreProcess_(pc, emg_pc, left, right);
std::function<double(const double, const double)>
compute_peak_area_trapezoid = [&p](const double left, const double right)
{
double peak_area { 0.0 };
for (typename PeakContainerT::ConstIterator it = p.PosBegin(left); it != p.PosEnd(right) - 1; ++it)
{
peak_area += ((it + 1)->getPos() - it->getPos()) * ((it->getIntensity() + (it + 1)->getIntensity()) / 2.0);
}
return peak_area;
};
std::function<double(const double, const double)>
compute_peak_area_intensity_sum = [&p](const double left, const double right)
{
// OPENMS_LOG_WARN << "WARNING: intensity_sum method is being used." << std::endl;
double peak_area { 0.0 };
for (typename PeakContainerT::ConstIterator it = p.PosBegin(left); it != p.PosEnd(right); ++it)
{
peak_area += it->getIntensity();
}
return peak_area;
};
PeakArea pa;
pa.apex_pos = (left + right) / 2; // initial estimate, to avoid apex being outside of [left,right]
UInt n_points = std::distance(p.PosBegin(left), p.PosEnd(right));
for (auto it = p.PosBegin(left); it != p.PosEnd(right); ++it) //OMS_CODING_TEST_EXCLUDE
{
pa.hull_points.push_back(DPosition<2>(it->getPos(), it->getIntensity()));
if (pa.height < it->getIntensity())
{
pa.height = it->getIntensity();
pa.apex_pos = it->getPos();
}
}
if (integration_type_ == INTEGRATION_TYPE_TRAPEZOID)
{
if (n_points >= 2)
{
pa.area = compute_peak_area_trapezoid(left, right);
}
}
else if (integration_type_ == INTEGRATION_TYPE_SIMPSON)
{
if (n_points == 2)
{
OPENMS_LOG_WARN << std::endl << "PeakIntegrator::integratePeak:"
"number of points is 2, falling back to `trapezoid`." << std::endl;
pa.area = compute_peak_area_trapezoid(left, right);
}
else if (n_points > 2)
{
if (n_points % 2)
{
pa.area = simpson_(p.PosBegin(left), p.PosEnd(right));
}
else
{
double areas[4] = {-1.0, -1.0, -1.0, -1.0};
areas[0] = simpson_(p.PosBegin(left), p.PosEnd(right) - 1); // without last point
areas[1] = simpson_(p.PosBegin(left) + 1, p.PosEnd(right)); // without first point
if (p.begin() <= p.PosBegin(left) - 1)
{
areas[2] = simpson_(p.PosBegin(left) - 1, p.PosEnd(right)); // with one more point on the left
}
if (p.PosEnd(right) < p.end())
{
areas[3] = simpson_(p.PosBegin(left), p.PosEnd(right) + 1); // with one more point on the right
}
UInt valids = 0;
for (const auto& area : areas)
{
if (area != -1.0)
{
pa.area += area;
++valids;
}
}
pa.area /= valids;
}
}
}
else if (integration_type_ == INTEGRATION_TYPE_INTENSITYSUM)
{
pa.area = compute_peak_area_intensity_sum(left, right);
}
else
{
throw Exception::InvalidParameter(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Please set a valid value for the parameter \"integration_type\".");
}
return pa;
}
template <typename PeakContainerT>
PeakBackground estimateBackground_(
const PeakContainerT& pc, double left, double right,
const double peak_apex_pos
) const
{
PeakContainerT emg_pc;
const PeakContainerT& p = EMGPreProcess_(pc, emg_pc, left, right);
const double int_l = p.PosBegin(left)->getIntensity();
const double int_r = (p.PosEnd(right) - 1)->getIntensity();
const double delta_int = int_r - int_l;
const double delta_pos = (p.PosEnd(right) - 1)->getPos() - p.PosBegin(left)->getPos();
const double min_int_pos = int_r <= int_l ? (p.PosEnd(right) - 1)->getPos() : p.PosBegin(left)->getPos();
const double delta_int_apex = std::fabs(delta_int) * std::fabs(min_int_pos - peak_apex_pos) / delta_pos;
double area {0.0};
double height {0.0};
if (baseline_type_ == BASELINE_TYPE_BASETOBASE)
{
height = std::min(int_r, int_l) + delta_int_apex;
if (integration_type_ == INTEGRATION_TYPE_TRAPEZOID || integration_type_ == INTEGRATION_TYPE_SIMPSON)
{
// formula for calculating the background using the trapezoidal rule
// area = intensity_min*delta_pos + 0.5*delta_int*delta_pos;
area = delta_pos * (std::min(int_r, int_l) + 0.5 * std::fabs(delta_int));
}
else if (integration_type_ == INTEGRATION_TYPE_INTENSITYSUM)
{
// calculate the background using an estimator of the form
// y = mx + b
// where x = rt or mz, m = slope, b = left intensity
// sign of delta_int will determine line direction
// area += delta_int / delta_pos * (it->getPos() - left) + int_l;
double pos_sum = 0.0; // rt or mz
for (auto it = p.PosBegin(left); it != p.PosEnd(right); ++it) //OMS_CODING_TEST_EXCLUDE
{
pos_sum += it->getPos();
}
UInt n_points = std::distance(p.PosBegin(left), p.PosEnd(right));
// We construct the background area as the sum of a rectangular part
// and a triangle on top. The triangle is constructed as the sum of the
// line's y value at each sampled point: \sum_{i=0}^{n} (x_i - x_0) * m
const double rectangle_area = n_points * int_l;
const double slope = delta_int / delta_pos;
const double triangle_area = (pos_sum - n_points * p.PosBegin(left)->getPos()) * slope;
area = triangle_area + rectangle_area;
}
}
else if (baseline_type_ == BASELINE_TYPE_VERTICALDIVISION || baseline_type_ == BASELINE_TYPE_VERTICALDIVISION_MIN)
{
height = std::min(int_r, int_l);
if (integration_type_ == INTEGRATION_TYPE_TRAPEZOID || integration_type_ == INTEGRATION_TYPE_SIMPSON)
{
area = delta_pos * std::min(int_r, int_l);
}
else if (integration_type_ == INTEGRATION_TYPE_INTENSITYSUM)
{
area = std::min(int_r, int_l) * std::distance(p.PosBegin(left), p.PosEnd(right));;
}
}
else if (baseline_type_ == BASELINE_TYPE_VERTICALDIVISION_MAX)
{
height = std::max(int_r, int_l);
if (integration_type_ == INTEGRATION_TYPE_TRAPEZOID || integration_type_ == INTEGRATION_TYPE_SIMPSON)
{
area = delta_pos * std::max(int_r, int_l);
}
else if (integration_type_ == INTEGRATION_TYPE_INTENSITYSUM)
{
area = std::max(int_r, int_l) * std::distance(p.PosBegin(left), p.PosEnd(right));
}
}
else
{
throw Exception::InvalidParameter(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Please set a valid value for the parameter \"baseline_type\".");
}
PeakBackground pb;
pb.area = area;
pb.height = height;
return pb;
}
/**
@brief Simpson's rule algorithm
This implementation expects an odd number of points. The formula used supports
unequally spaced points.
@note Make sure the container (chromatogram or spectrum) is sorted with respect to position (RT or m/z).
@warning An odd number of points is expected!
@param[in] it_begin The iterator to the first point
@param[in] it_end The iterator to the past-the-last point
@return The computed area
*/
template <typename PeakContainerConstIteratorT>
double simpson_(PeakContainerConstIteratorT it_begin, PeakContainerConstIteratorT it_end) const
{
double integral = 0.0;
for (auto it = it_begin + 1; it < it_end - 1; it = it + 2) //OMS_CODING_TEST_EXCLUDE
{
const double h = it->getPos() - (it - 1)->getPos();
const double k = (it + 1)->getPos() - it->getPos();
const double y_h = (it - 1)->getIntensity();
const double y_0 = it->getIntensity();
const double y_k = (it + 1)->getIntensity();
integral += (1.0 / 6.0) * (h + k) * ((2.0 - k / h) * y_h + (pow(h + k, 2) / (h * k)) * y_0 + (2.0 - h / k) * y_k);
}
return integral;
}
template <typename PeakContainerT>
PeakShapeMetrics calculatePeakShapeMetrics_(
const PeakContainerT& pc, double left, double right,
const double peak_height, const double peak_apex_pos
) const
{
PeakShapeMetrics psm;
if (pc.empty()) return psm; // return all '0'
// enforce order: left <= peakapex <= right
if (!(left <= peak_apex_pos && peak_apex_pos <= right)) throw Exception::InvalidRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
PeakContainerT emg_pc;
const PeakContainerT& p = EMGPreProcess_(pc, emg_pc, left, right);
typename PeakContainerT::ConstIterator it_PosBegin_l = p.PosBegin(left);
typename PeakContainerT::ConstIterator it_PosEnd_apex = p.PosBegin(peak_apex_pos); // if peak_apex_pos is correct, this will get the underlying iterator
typename PeakContainerT::ConstIterator it_PosEnd_r = p.PosEnd(right); // past the end. Do not dereference (might be the true .end())
for (auto it = it_PosBegin_l; it != it_PosEnd_r; ++it) //OMS_CODING_TEST_EXCLUDE
{
// points across the peak
++(psm.points_across_baseline);
if (it->getIntensity() >= 0.5 * peak_height)
{
++(psm.points_across_half_height);
}
}
// positions at peak heights
psm.start_position_at_5 = findPosAtPeakHeightPercent_(it_PosBegin_l, it_PosEnd_apex, p.end(), peak_height, 0.05, true);
psm.start_position_at_10 = findPosAtPeakHeightPercent_(it_PosBegin_l, it_PosEnd_apex, p.end(), peak_height, 0.1, true);
psm.start_position_at_50 = findPosAtPeakHeightPercent_(it_PosBegin_l, it_PosEnd_apex, p.end(), peak_height, 0.5, true);
psm.end_position_at_5 = findPosAtPeakHeightPercent_(it_PosEnd_apex, it_PosEnd_r, p.end(), peak_height, 0.05, false);
psm.end_position_at_10 = findPosAtPeakHeightPercent_(it_PosEnd_apex, it_PosEnd_r, p.end(), peak_height, 0.1, false);
psm.end_position_at_50 = findPosAtPeakHeightPercent_(it_PosEnd_apex, it_PosEnd_r, p.end(), peak_height, 0.5, false);
// peak widths
psm.width_at_5 = psm.end_position_at_5 - psm.start_position_at_5;
psm.width_at_10 = psm.end_position_at_10 - psm.start_position_at_10;
psm.width_at_50 = psm.end_position_at_50 - psm.start_position_at_50;
psm.total_width = (p.PosEnd(right) - 1)->getPos() - p.PosBegin(left)->getPos();
psm.slope_of_baseline = (p.PosEnd(right) - 1)->getIntensity() - p.PosBegin(left)->getIntensity();
if (peak_height != 0.0) // avoid division by zero
{
psm.baseline_delta_2_height = psm.slope_of_baseline / peak_height;
}
// Source of tailing_factor and asymmetry_factor formulas:
// USP 40 - NF 35 The United States Pharmacopeia and National Formulary - Supplementary
// Can only compute if start and peak apex are different
if (psm.start_position_at_5 != peak_apex_pos)
{
psm.tailing_factor = psm.width_at_5 / (2*(peak_apex_pos - psm.start_position_at_5));
}
if (psm.start_position_at_10 != peak_apex_pos)
{
psm.asymmetry_factor = (psm.end_position_at_10 - peak_apex_pos) / (peak_apex_pos - psm.start_position_at_10);
}
return psm;
}
/**
@brief Find the position (RT/MZ) at a given percentage of peak's height
@note The method expects that the iterators span half of the peak's width.
Examples:
- Left half case: the range would be [leftMostPt, peakApexPos)
- Right half case: the range would be [peakApexPos + 1, rightMostPt + 1)
@note The method assumes a convex peak. If 5%, 10%, or 50% peak heights are not found on either side of the peak,
the closest left (for left peak height percentages) and closest right (for right peak height percentages) will be used.
@param[in] it_left The iterator to the first point (must not be past the end)
@param[in] it_right The iterator to the last point (might be past the end)
@param[in] it_end The end-iterator of the container
@param[in] peak_height The peak's height
@param[in] percent At which percentage of the peak height we want to find the position (common values: 0.05, 0.1, 0.5)
@param[in] is_left_half According to which half of the peak, the algorithm proceeds to the correct direction
@return The position found
*/
template <typename PeakContainerConstIteratorT>
double findPosAtPeakHeightPercent_(
PeakContainerConstIteratorT it_left, // must not be past the end
PeakContainerConstIteratorT it_right, // might be past the end
PeakContainerConstIteratorT it_end, // definitely past-the-end
const double peak_height,
const double percent,
const bool is_left_half) const
{
// no points in range
if (it_left == it_end) throw Exception::InvalidRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
// only one point in range
if (it_left == it_right) return it_left->getPos();
const double percent_intensity = peak_height * percent;
PeakContainerConstIteratorT closest;
if (is_left_half)
{
closest = it_left;
for (
PeakContainerConstIteratorT it = it_left;
it < it_right && it->getIntensity() <= percent_intensity;
closest = it++
) {}
}
else // right half; search from right to left
{
closest = it_right - 1; // make sure we can deference it
for (
PeakContainerConstIteratorT it = it_right - 1;
it >= it_left && it->getIntensity() <= percent_intensity;
closest = it--
) {}
}
return closest->getPos();
}
private:
/** @name Parameters
The user is supposed to select a value for these parameters.
By default, the integration_type_ is "intensity_sum" and the baseline_type_ is "base_to_base".
*/
///@{
/**
The integration technique to use in integratePeak() and estimateBackground().
Possible values are: "trapezoid", "simpson", "intensity_sum".
*/
String integration_type_ = INTEGRATION_TYPE_INTENSITYSUM;
/**
The baseline type to use in estimateBackground().
Possible values are: "vertical_division_max", "vertical_division_min", "base_to_base".
*/
String baseline_type_ = BASELINE_TYPE_BASETOBASE;
///@}
/// Enable/disable EMG peak model fitting
bool fit_EMG_;
EmgGradientDescent emg_;
/**
@brief Fit the peak to the EMG model
The fitting process happens only if `fit_EMG_` is true. `left` and `right`
are updated accordingly.
@tparam PeakContainerT Either a MSChromatogram or a MSSpectrum
@param[in] pc Input peak
@param[out] emg_pc Will possibly contain the processed peak
@param[in] left RT or MZ value of the first point of interest
@param[in] right RT or MZ value of the first point of interest
@return A const reference to `emg_pc` if the fitting is executed, `pc` otherwise.
*/
template <typename PeakContainerT>
const PeakContainerT& EMGPreProcess_(
const PeakContainerT& pc,
PeakContainerT& emg_pc,
double& left,
double& right
) const
{
if (fit_EMG_)
{
emg_.fitEMGPeakModel(pc, emg_pc, left, right);
left = emg_pc.front().getPos();
right = emg_pc.back().getPos();
return emg_pc;
}
return pc;
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/OPENSWATH/DIAPrescoring.h | .h | 2,517 | 75 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Witold Wolski $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/OPENSWATHALGO/DATAACCESS/DataFrameWriter.h>
#include <OpenMS/OPENSWATHALGO/DATAACCESS/ISpectrumAccess.h>
#include <OpenMS/OPENSWATHALGO/DATAACCESS/TransitionExperiment.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/ANALYSIS/OPENSWATH/DIAHelper.h>
namespace OpenMS
{
/**
@brief Scoring of an spectrum given library intensities of a transition group.
In DIA (data independent acquisition) / SWATH analysis, at each
chromatographic point a full MS2 spectrum is recorded. This class allows to
compute a number of scores based on the full MS2 spectrum available. The scores are the following:
See also class DIAScoring.
Simulate theoretical spectrum from library intensities of transition group
and compute manhattan distance and dotprod score between spectrum intensities
and simulated spectrum.
*/
class OPENMS_DLLAPI DiaPrescore :
public DefaultParamHandler
{
double dia_extract_window_; //done
int nr_isotopes_;
int nr_charges_;
public:
DiaPrescore();
DiaPrescore(double dia_extract_window, int nr_isotopes = 4, int nr_charges = 4);
void defineDefaults();
void updateMembers_() override;
/**
@brief Score a spectrum given a transition group.
Simulate theoretical spectrum from library intensities of transition group
and compute manhattan distance and dotprod score between spectrum intensities
and simulated spectrum.
*/
void score(const SpectrumSequence& spec,
const std::vector<OpenSwath::LightTransition>& lt,
const RangeMobility& im_range,
double& dotprod,
double& manhattan) const;
/**
@brief Compute manhattan and dotprod score for all spectra which can be accessed by
the SpectrumAccessPtr for all transitions groups in the LightTargetedExperiment.
*/
void operator()(const OpenSwath::SpectrumAccessPtr& swath_ptr,
OpenSwath::LightTargetedExperiment& transition_exp_used, const RangeMobility& range_im,
OpenSwath::IDataFrameWriter* ivw) const;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/OPENSWATH/DIAScoring.h | .h | 10,896 | 230 | // 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, Witold Wolski $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CHEMISTRY/AASequence.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/OPENSWATHALGO/DATAACCESS/ISpectrumAccess.h>
#include <OpenMS/OPENSWATHALGO/DATAACCESS/DataStructures.h>
#include <OpenMS/OPENSWATHALGO/DATAACCESS/ITransition.h>
#include <OpenMS/OPENSWATHALGO/DATAACCESS/TransitionExperiment.h>
#include <OpenMS/KERNEL/RangeManager.h>
namespace OpenMS
{
class TheoreticalSpectrumGenerator;
/**
@brief Scoring of an spectrum at the peak apex of an chromatographic elution peak.
In DIA (data independent acquisition) / SWATH analysis, at each
chromatographic point a full MS2 spectrum is recorded. This class allows to
compute a number of scores based on the full MS2 spectrum available. The scores are the following:
- isotope scores:
- isotope_corr: computes the correlation of each fragment ion with the
theoretical isotope distribution. This is the pearson correlation to
the theoretical isotope pattern weighted by the relative intensity of
the transition (more is better).
- isotope_overlap: checks whether a signal at position (mz - 1) / charge
exists and how strong it is. This would be an indication that the current
peak is an isotopic signal of another peak. This simply counts how
often a peak was observed that is higher than the current peak, thus
number is then weighted by the relative intensity of the transition
(thus less is better here).
- massdiff score: computes the difference in ppm of the experimental signal to the expected signal (thus less is better).
- Equation: sum(ppm_difference) / # transitions
- Notes:
- Divide by the total number of transitions and is thus quite punishing if a transition is missing
- Also outputs a list of all the ppm differences, if signal is not found output -1.0
- b/y ion score: checks for the presence of b/y ions of the peptide in question
- theoretical spectrum: a dotproduct and a manhattan score with a theoretical spectrum
This class expects spectra objects that implement the OpenSWATH Spectrum
interface. Transitions are expected to be in the light transition format
(defined in OPENSWATHALGO/DATAACCESS/TransitionExperiment.h).
@htmlinclude OpenMS_DIAScoring.parameters
*/
class OPENMS_DLLAPI DIAScoring :
public DefaultParamHandler
{
///Type definitions
//@{
/// Spectrum type, see Spectrum interface
typedef OpenSwath::SpectrumPtr SpectrumPtrType;
/// Transition interface (Transition, Peptide, Protein)
typedef OpenSwath::LightTransition TransitionType;
//@}
public:
///@name Constructors and Destructor
//@{
/// Default constructor
DIAScoring();
/// Destructor
~DIAScoring() override;
//@}
///////////////////////////////////////////////////////////////////////////
// DIA / SWATH scoring
///@name DIA Scores
//@{
/// Isotope scores, see class description
void dia_isotope_scores(const std::vector<TransitionType>& transitions,
SpectrumSequence& spectrum,
OpenSwath::IMRMFeature* mrmfeature,
const RangeMobility& im_range,
double& isotope_corr,
double& isotope_overlap) const;
/// Massdiff scores, see class description
void dia_massdiff_score(const std::vector<TransitionType>& transitions,
const SpectrumSequence& spectrum,
const std::vector<double>& normalized_library_intensity,
const RangeMobility& im_range,
double& ppm_score,
double& ppm_score_weighted,
std::vector<double>& diff_ppm) const;
/**
Precursor massdifference score
@param[in] precursor_mz Exact m/z of the precursor to be evaluated
@param[in] spectrum MS1 spectrum to be evaluated
@param[in] im_range Ion mobility range to keep (filter data); can be empty
@param[out] ppm_score Resulting score
@return False if no signal was found (and no sensible score calculated), true otherwise
*/
bool dia_ms1_massdiff_score(double precursor_mz, const SpectrumSequence& spectrum, const RangeMobility& im_range,
double& ppm_score) const;
/// Precursor isotope scores for precursors (peptides and metabolites)
void dia_ms1_isotope_scores_averagine(double precursor_mz, const SpectrumSequence& spectrum, int charge_state, RangeMobility& im_range,
double& isotope_corr, double& isotope_overlap) const;
void dia_ms1_isotope_scores(double precursor_mz, const std::vector<SpectrumPtrType>& spectrum, RangeMobility& im_range,
double& isotope_corr, double& isotope_overlap, const EmpiricalFormula& sum_formula) const;
/// b/y ion scores
void dia_by_ion_score(const SpectrumSequence& spectrum, AASequence& sequence,
int charge, const RangeMobility& im_range, double& bseries_score, double& yseries_score) const;
/// Dotproduct / Manhattan score with theoretical spectrum
void score_with_isotopes(SpectrumSequence& spectrum,
const std::vector<TransitionType>& transitions,
const RangeMobility& im_range,
double& dotprod,
double& manhattan) const;
//@}
private:
/// Copy constructor (algorithm class)
DIAScoring(const DIAScoring& rhs);
/// Assignment operator (algorithm class)
DIAScoring& operator=(const DIAScoring& rhs);
/// Synchronize members with param class
void updateMembers_() override;
/// Subfunction of dia_isotope_scores
void diaIsotopeScoresSub_(const std::vector<TransitionType>& transitions,
const SpectrumSequence& spectrum,
std::map<std::string, double>& intensities,
const RangeMobility& im_range,
double& isotope_corr,
double& isotope_overlap) const;
/// retrieves intensities from MRMFeature
/// computes a vector of relative intensities for each feature (output to intensities)
void getFirstIsotopeRelativeIntensities_(const std::vector<TransitionType>& transitions,
OpenSwath::IMRMFeature* mrmfeature,
std::map<std::string, double>& intensities //experimental intensities of transitions
) const;
private:
/**
@brief Determine whether the current m/z value is a monoisotopic peak
This function will try to determine whether the current peak is a
monoisotopic peak or not. It will do so by searching for an intense peak
at a lower m/z that could explain the current peak as part of a isotope
pattern.
@param[in] spectrum The spectrum (MS1 or MS2)
@param[in] mono_mz The m/z value where a monoisotopic is expected
@param[in] mono_int The intensity of the monoisotopic peak (peak at mono_mz)
@param[out] nr_occurrences Will contain the count of how often a peak is found at lower m/z than mono_mz with an intensity higher than mono_int. Multiple charge states are tested, see class parameter dia_nr_charges_
@param[out] max_ratio Will contain the maximum ratio of a peaks intensity compared to the monoisotopic peak intensity how often a peak is found at lower m/z than mono_mz with an intensity higher than mono_int. Multiple charge states are tested, see class parameter dia_nr_charges_
@param[in] im_range Ion mobility subrange to consider (used as filter); can be empty (i.e. no IM filtering)
*/
void largePeaksBeforeFirstIsotope_(const SpectrumSequence& spectrum, double mono_mz, double mono_int, int& nr_occurrences, double& max_ratio, const RangeMobility& im_range) const;
/**
@brief Compare an experimental isotope pattern to a theoretical one
This function will take an array of isotope intensities @p isotopes_int and compare them
(by order only; no m/z matching) to the theoretically expected ones for the given @p product_mz using an averagine
model. The returned value is a Pearson correlation between the
experimental and theoretical pattern.
*/
double scoreIsotopePattern_(const std::vector<double>& isotopes_int,
double product_mz,
int putative_fragment_charge) const;
/**
@brief Compare an experimental isotope pattern to a theoretical one
This function will take an array of isotope intensities and compare them
(by order only; no m/z matching) to the theoretically expected ones for the given @p sum_formula.
The returned value is a Pearson correlation between the experimental and theoretical pattern.
*/
double scoreIsotopePattern_(const std::vector<double>& isotopes_int,
const EmpiricalFormula& sum_formula) const;
/**
@brief Compare an experimental isotope pattern to a theoretical one
This function will take an array of isotope intensities and compare them
(by order only; no m/z matching) to the theoretically expected ones given by @p isotope_dist.
The returned value is a Pearson correlation between the experimental and theoretical pattern.
*/
double scoreIsotopePattern_(const std::vector<double>& isotopes_int,
const IsotopeDistribution& isotope_dist) const;
/// Get the intensities of isotopes around @p precursor_mz in experimental @p spectrum
/// and fill @p isotopes_int.
void getIsotopeIntysFromExpSpec_(double precursor_mz, const SpectrumSequence& spectrum, int charge_state, const RangeMobility& im_range,
std::vector<double>& isotopes_int) const;
// Parameters
double dia_extract_window_;
double dia_byseries_intensity_min_;
double dia_byseries_ppm_diff_;
double dia_nr_isotopes_;
double dia_nr_charges_;
double peak_before_mono_max_ppm_diff_;
bool dia_extraction_ppm_;
bool dia_centroided_;
TheoreticalSpectrumGenerator * generator;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/OPENSWATH/SpectrumAddition.h | .h | 2,282 | 58 | // 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> // OPENMS_DLLAPI
#include <OpenMS/OPENSWATHALGO/DATAACCESS/ISpectrumAccess.h>
#include <OpenMS/KERNEL/MSSpectrum.h>
namespace OpenMS
{
/**
@brief The SpectrumAddition is used to add up individual spectra
It uses the given sampling rate to resample the spectra in m/z domain and
then add them up. This may lead to a certain inaccuracy, especially if a
inappropriate resampling rate is chosen.
*/
class OPENMS_DLLAPI SpectrumAddition
{
public:
/// adds up a list of Spectra by resampling them and then addition of intensities
static OpenSwath::SpectrumPtr addUpSpectra(const SpectrumSequence& all_spectra,
double sampling_rate,
bool filter_zeros);
/// adds up a list of ion mobility enhacned Spectra by resampling them and then addition of intensities. Currently this involves filtering to the desired IM extracion window and then performing addition across m/z and intensity.
static OpenSwath::SpectrumPtr addUpSpectra(const SpectrumSequence& all_spectra,
const RangeMobility& im_range,
double sampling_rate,
bool filter_zeros);
/// Concatenates a spectrum sequence into a single spectrum. Values are sorted by m/z
static OpenSwath::SpectrumPtr concatenateSpectra(const SpectrumSequence& all_spectra);
/// adds up a list of Spectra by resampling them and then addition of intensities
static OpenMS::MSSpectrum addUpSpectra(const std::vector<MSSpectrum>& all_spectra,
double sampling_rate,
bool filter_zeros);
// sorts a spectrumPtr object by mz
static void sortSpectrumByMZ(OpenSwath::Spectrum&);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/OPENSWATH/OpenSwathHelper.h | .h | 10,806 | 235 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hannes Roest $
// $Authors: Hannes Roest $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/ANALYSIS/TARGETED/TargetedExperiment.h>
#include <OpenMS/OPENSWATHALGO/DATAACCESS/TransitionExperiment.h>
#include <OpenMS/ANALYSIS/OPENSWATH/MRMFeatureFinderScoring.h>
#include <OpenMS/CONCEPT/LogStream.h>
namespace OpenMS
{
/**
@brief A helper class that is used by several OpenSWATH tools
*/
class OPENMS_DLLAPI OpenSwathHelper
{
public:
/**
@brief Compute unique precursor identifier
Uses transition_group_id and isotope number to compute a unique precursor
id of the form "groupID_Precursor_ix" where x is the isotope number, e.g.
the monoisotopic precursor would become "groupID_Precursor_i0".
@param[in] transition_group_id Unique id of the transition group (peptide/compound)
@param[in] isotope Precursor isotope number
@return Unique precursor identifier
*/
static String computePrecursorId(const String& transition_group_id, int isotope)
{
return transition_group_id + "_Precursor_i" + String(isotope);
}
/**
@brief Compute transition group id
Uses the unique precursor identifier to compute the transition group id
(peptide/compound identifier), reversing the operation performed by
computePrecursorId().
@param[in] precursor_id Precursor identifier as computed by computePrecursorId()
@return Original transition group id
*/
static String computeTransitionGroupId(const String& precursor_id)
{
std::vector<String> substrings;
precursor_id.split("_", substrings);
if (substrings.size() == 3) return substrings[0];
else if (substrings.size() > 3)
{
String r;
for (Size k = 0; k < substrings.size() - 2; k++) r += substrings[k] + "_";
return r.prefix(r.size() - 1);
}
return "";
}
/**
@brief Select transitions between lower and upper and write them into the new TargetedExperiment
Version for the OpenMS TargetedExperiment
@param[in] targeted_exp Transition list for selection
@param[out] selected_transitions Selected transitions for SWATH window
@param[in] min_upper_edge_dist Distance in Th to the upper edge
@param[in] lower Lower edge of SWATH window (in Th)
@param[in] upper Upper edge of SWATH window (in Th)
*/
static void selectSwathTransitions(const OpenMS::TargetedExperiment& targeted_exp,
OpenMS::TargetedExperiment& selected_transitions,
double min_upper_edge_dist,
double lower, double upper);
/**
@brief Select transitions between lower and upper and write them into the new TargetedExperiment
Version for the LightTargetedExperiment
@param[in] targeted_exp Transition list for selection
@param[out] selected_transitions Selected transitions for SWATH window
@param[in] min_upper_edge_dist Distance in Th to the upper edge
@param[in] lower Lower edge of SWATH window (in Th)
@param[in] upper Upper edge of SWATH window (in Th)
*/
static void selectSwathTransitions(const OpenSwath::LightTargetedExperiment& targeted_exp,
OpenSwath::LightTargetedExperiment& selected_transitions,
double min_upper_edge_dist,
double lower, double upper);
/**
@brief Match transitions with their "best" window across m/z and ion mobility, save results in a vector.
@param[in] transition_exp Transition list for selection
@param[out] tr_win_map Mapping from transition (index) to the best matching entry in @p swath_maps
@param[in] min_upper_edge_dist Distance in Th to the upper edge
@param[in] swath_maps vector of SwathMap objects defining mz and im bounds
*/
static void selectSwathTransitionsPasef(const OpenSwath::LightTargetedExperiment& transition_exp, std::vector<int>& tr_win_map,
double min_upper_edge_dist, const std::vector< OpenSwath::SwathMap > & swath_maps);
/**
@brief Get the lower / upper offset for this SWATH map and do some sanity checks
Sanity check for the whole map:
- all scans need to have exactly one precursor
- all scans need to have the same MS levels (otherwise extracting an XIC
from them makes no sense)
- all scans need to have the same precursor isolation window (otherwise
extracting an XIC from them makes no sense)
@param[in] swath_map Input SWATH map to check
@param[out] lower Lower edge of SWATH window (in Th)
@param[out] upper Upper edge of SWATH window (in Th)
@param[out] center Center of SWATH window (in Th)
@throw IllegalArgument exception if the sanity checks fail.
*/
static void checkSwathMap(const OpenMS::PeakMap& swath_map,
double& lower, double& upper, double& center);
/**
@brief Check the map and select transition in one function
Computes lower and upper offset for the SWATH map and performs some
sanity checks (see checkSwathMap()). Then selects transitions.
@param[in] exp Input SWATH map to check
@param[in] targeted_exp Transition list for selection
@param[out] selected_transitions Selected transitions for SWATH window
@param[in] min_upper_edge_dist Distance in Th to the upper edge
*/
template <class TargetedExperimentT>
static bool checkSwathMapAndSelectTransitions(const OpenMS::PeakMap& exp,
const TargetedExperimentT& targeted_exp,
TargetedExperimentT& selected_transitions,
double min_upper_edge_dist)
{
if (exp.empty() || exp[0].getPrecursors().empty())
{
std::cerr << "WARNING: File " << exp.getLoadedFilePath()
<< " does not have any experiments or any precursors. Is it a SWATH map? "
<< "I will move to the next map."
<< std::endl;
return false;
}
double upper, lower, center;
OpenSwathHelper::checkSwathMap(exp, lower, upper, center);
OpenSwathHelper::selectSwathTransitions(targeted_exp, selected_transitions, min_upper_edge_dist, lower, upper);
if (selected_transitions.getTransitions().size() == 0)
{
std::cerr << "WARNING: For File " << exp.getLoadedFilePath()
<< " no transition were within the precursor window of " << lower << " to " << upper
<< std::endl;
return false;
}
return true;
}
/**
@brief Computes the min and max retention time value
Estimate the retention time span of a targeted experiment by returning
the min/max values in retention time as a pair.
@return A std::pair that contains (min,max)
*/
static std::pair<double,double> estimateRTRange(const OpenSwath::LightTargetedExperiment & exp);
/**
* @brief Sample a subset of peptides uniformly across the RT range.
*
* Splits the RT span (min→max) into @p bins and randomly picks up to
* @p peptides_per_bin compounds from each bin. Useful for on-the-fly
* iRT calibration without external .irt files.
*
* @param[in] exp Full LightTargetedExperiment (the input peptide query parameter assay list for targeted extraction)
* @param[in] bins Number of retention‐time bins (i.e. 10 bins across the RT range for linear iRT, 500-1000 bins across the RT for nonlinear iRT)
* @param[in] peptides_per_bin How many peptides to draw per bin (i.e. 5 peptides for linear iRT, 25 - 50 for non-linear iRT)
* @param[in] seed If non‐zero, used to seed the RNG (deterministic).
* If zero, will use std::random_device for non-deterministic.
* @param[in] sort_by_intensity Whether to sort the assays by the highest cumulative intense transitions. This is useful for sampling the most intense peptides for iRTs.
* @param[in] top_fraction Only sample from the top N fraction of sorted assays to narrow down on only really intense peptides. This is useful for selecting a few "high quality" peptides to use for linear iRTs.
* @param[in] priority_peptides Optional set of peptide sequences to prioritize during sampling. If provided, these peptides
* will be sampled first if found in @p exp, before the remaining quota is filled with regular sampling.
* Useful for ensuring common iRT peptides (e.g., from irtkit or cirtkit) are included when present.
*
* @return A new LightTargetedExperiment containing only the sampled
* compounds, their transitions, and associated proteins.
*/
static OpenSwath::LightTargetedExperiment sampleExperiment(
const OpenSwath::LightTargetedExperiment & exp,
Size bins,
Size peptides_per_bin,
unsigned int seed = 0,
bool sort_by_intensity = false,
double top_fraction = 1.0,
const std::unordered_set<std::string> & priority_peptides = std::unordered_set<std::string>());
/**
@brief Returns the feature with the highest score for each transition group.
Simple method to extract the best feature for each transition group (e.g.
for RT alignment). A quality cutoff can be used to skip some low-quality
features altogether.
@param[in] transition_group_map Input data containing the picked and scored map
@param[in] useQualCutoff Whether to apply a quality cutoff to the data
@param[in] qualCutoff What quality cutoff should be applied (all data above the cutoff will be kept)
@return Result of the best scoring peaks (stored as map of peptide id and RT)
*/
static std::map<std::string, double> simpleFindBestFeature(const OpenMS::MRMFeatureFinderScoring::TransitionGroupMapType & transition_group_map,
bool useQualCutoff = false,
double qualCutoff = 0.0);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/OPENSWATH/MRMTransitionGroupPicker.h | .h | 51,068 | 1,149 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hannes Roest $
// $Authors: Hannes Roest $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/MRMTransitionGroup.h>
#include <OpenMS/KERNEL/MRMFeature.h>
#include <OpenMS/KERNEL/MSSpectrum.h>
#include <OpenMS/KERNEL/MSChromatogram.h>
#include <OpenMS/KERNEL/ChromatogramPeak.h>
#include <OpenMS/ANALYSIS/OPENSWATH/PeakIntegrator.h>
#include <OpenMS/ANALYSIS/OPENSWATH/PeakPickerChromatogram.h>
#include <OpenMS/PROCESSING/RESAMPLING/LinearResamplerAlign.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/CONCEPT/LogStream.h>
// Cross-correlation
#include <OpenMS/OPENSWATHALGO/ALGO/Scoring.h>
#include <OpenMS/OPENSWATHALGO/ALGO/StatsHelpers.h>
#include <numeric>
//#define DEBUG_TRANSITIONGROUPPICKER
namespace OpenMS
{
/**
@brief The MRMTransitionGroupPicker finds peaks in chromatograms that belong to the same precursors.
@htmlinclude OpenMS_MRMTransitionGroupPicker.parameters
It is called through pickTransitionGroup which will accept an
MRMTransitionGroup filled with n chromatograms and perform the following steps:
- Step 1: find features (peaks) in individual chromatograms
- Step 2: merge these features to consensus features that span multiple chromatograms
Step 1 is performed by smoothing the individual chromatogram and applying the
PeakPickerHiRes.
Step 2 is performed by finding the largest peak overall and use this to
create a feature, propagating this through all chromatograms.
*/
class OPENMS_DLLAPI MRMTransitionGroupPicker :
public DefaultParamHandler
{
public:
//@{
/// Constructor
MRMTransitionGroupPicker();
/// Destructor
~MRMTransitionGroupPicker() override;
//@}
/**
@brief Pick a group of chromatograms belonging to the same peptide
Will identify peaks in a set of chromatograms that belong to the same
peptide. The chromatograms are given in the MRMTransitionGroup container
which also contains the mapping of the chromatograms to their metadata.
Only chromatograms from detecting transitions are used for peak picking.
Identifying transitions will be processed alongside but do not contribute
to the meta-data, e.g. total_xic or peak_apices_sum.
The resulting features are added to the MRMTransitionGroup. Each feature contains the following meta-data:
- PeptideRef
- leftWidth
- rightWidth
- total_xic (fragment trace XIC sum)
- peak_apices_sum
*/
template <typename SpectrumT, typename TransitionT>
void pickTransitionGroup(MRMTransitionGroup<SpectrumT, TransitionT>& transition_group)
{
OPENMS_PRECONDITION(transition_group.isInternallyConsistent(), "Consistent state required")
OPENMS_PRECONDITION(transition_group.chromatogramIdsMatch(), "Chromatogram native IDs need to match keys in transition group")
std::vector<MSChromatogram > picked_chroms;
std::vector<MSChromatogram > smoothed_chroms;
// Pick fragment ion chromatograms
for (Size k = 0; k < transition_group.getChromatograms().size(); k++)
{
MSChromatogram& chromatogram = transition_group.getChromatograms()[k];
String native_id = chromatogram.getNativeID();
// only pick detecting transitions (skip all others)
if (transition_group.getTransitions().size() > 0 &&
transition_group.hasTransition(native_id) &&
!transition_group.getTransition(native_id).isDetectingTransition() )
{
continue;
}
MSChromatogram picked_chrom, smoothed_chrom;
smoothed_chrom.setNativeID(native_id);
picker_.pickChromatogram(chromatogram, picked_chrom, smoothed_chrom);
picked_chrom.sortByIntensity();
picked_chroms.push_back(std::move(picked_chrom));
smoothed_chroms.push_back(std::move(smoothed_chrom));
}
// Pick precursor chromatograms
if (use_precursors_)
{
for (Size k = 0; k < transition_group.getPrecursorChromatograms().size(); k++)
{
SpectrumT picked_chrom, smoothed_chrom;
SpectrumT& chromatogram = transition_group.getPrecursorChromatograms()[k];
picker_.pickChromatogram(chromatogram, picked_chrom, smoothed_chrom);
picked_chrom.sortByIntensity();
picked_chroms.push_back(picked_chrom);
smoothed_chroms.push_back(smoothed_chrom);
}
}
// Find features (peak groups) in this group of transitions.
// While there are still peaks left, one will be picked and used to create
// a feature. Whenever we run out of peaks, we will get -1 back as index
// and terminate.
int chr_idx, peak_idx, cnt = 0;
std::vector<MRMFeature> features;
while (true)
{
chr_idx = -1; peak_idx = -1;
if (boundary_selection_method_ == "largest")
{
findLargestPeak(picked_chroms, chr_idx, peak_idx);
}
else if (boundary_selection_method_ == "widest")
{
findWidestPeakIndices(picked_chroms, chr_idx, peak_idx);
}
if (chr_idx == -1 && peak_idx == -1)
{
OPENMS_LOG_DEBUG << "**** No more peaks left. Nr. chroms: " << picked_chroms.size() << std::endl;
break;
}
// Compute a feature from the individual chromatograms and add non-zero features
MRMFeature mrm_feature = createMRMFeature(transition_group, picked_chroms, smoothed_chroms, chr_idx, peak_idx);
double total_xic = 0;
double intensity = mrm_feature.getIntensity();
if (intensity > 0)
{
total_xic = mrm_feature.getMetaValue("total_xic");
features.push_back(std::move(mrm_feature));
cnt++;
}
if (stop_after_feature_ > 0 && cnt > stop_after_feature_) {
// If you set this, you only expect one feature anyway. No logging necessary why it stopped.
break;
}
if (intensity > 0 && intensity / total_xic < stop_after_intensity_ratio_)
{
OPENMS_LOG_DEBUG << "**** Minimum intensity ratio reached. Nr. chroms: " << picked_chroms.size() << std::endl;
break;
}
}
// Check for completely overlapping features
for (Size i = 0; i < features.size(); i++)
{
MRMFeature& mrm_feature = features[i];
bool skip = false;
for (Size j = 0; j < i; j++)
{
if ((double)mrm_feature.getMetaValue("leftWidth") >= (double)features[j].getMetaValue("leftWidth") &&
(double)mrm_feature.getMetaValue("rightWidth") <= (double)features[j].getMetaValue("rightWidth") )
{ skip = true; }
}
if (mrm_feature.getIntensity() > 0 && !skip)
{
transition_group.addFeature(mrm_feature);
}
}
}
/// Create feature from a vector of chromatograms and a specified peak
template <typename SpectrumT, typename TransitionT>
MRMFeature createMRMFeature(const MRMTransitionGroup<SpectrumT, TransitionT>& transition_group,
std::vector<SpectrumT>& picked_chroms,
const std::vector<SpectrumT>& smoothed_chroms,
const int chr_idx,
const int peak_idx)
{
OPENMS_PRECONDITION(transition_group.isInternallyConsistent(), "Consistent state required")
OPENMS_PRECONDITION(transition_group.chromatogramIdsMatch(), "Chromatogram native IDs need to match keys in transition group")
MRMFeature mrmFeature;
mrmFeature.setIntensity(0.0);
double best_left = picked_chroms[chr_idx].getFloatDataArrays()[PeakPickerChromatogram::IDX_LEFTBORDER][peak_idx];
double best_right = picked_chroms[chr_idx].getFloatDataArrays()[PeakPickerChromatogram::IDX_RIGHTBORDER][peak_idx];
double peak_apex = picked_chroms[chr_idx][peak_idx].getRT();
OPENMS_LOG_DEBUG << "**** Creating MRMFeature for peak " << peak_idx << " in chrom. " << chr_idx << " with " <<
picked_chroms[chr_idx][peak_idx] << " and borders " << best_left << " " <<
best_right << " (" << best_right - best_left << ")" << std::endl;
if (use_consensus_ && recalculate_peaks_)
{
// This may change best_left / best_right
recalculatePeakBorders_(picked_chroms, best_left, best_right, recalculate_peaks_max_z_);
if (peak_apex < best_left || peak_apex > best_right)
{
// apex fell out of range, lets correct it
peak_apex = (best_left + best_right) / 2.0;
}
}
std::vector< double > left_edges;
std::vector< double > right_edges;
double min_left = best_left;
double max_right = best_right;
if (use_consensus_)
{
// Remove other, overlapping, picked peaks (in this and other
// chromatograms) and then ensure that at least one peak is set to zero
// (the currently best peak).
remove_overlapping_features(picked_chroms, best_left, best_right);
}
else
{
pickApex(picked_chroms, best_left, best_right, peak_apex,
min_left, max_right, left_edges, right_edges);
} // end !use_consensus_
picked_chroms[chr_idx][peak_idx].setIntensity(0.0); // ensure that we set at least one peak to zero
// Check for minimal peak width -> return empty feature (Intensity zero)
if (use_consensus_)
{
if (min_peak_width_ > 0.0 && std::fabs(best_right - best_left) < min_peak_width_)
{
return mrmFeature;
}
if (compute_peak_quality_)
{
String outlier = "none";
double qual = computeQuality_(transition_group, picked_chroms, chr_idx, best_left, best_right, outlier);
if (qual < min_qual_)
{
return mrmFeature;
}
mrmFeature.setMetaValue("potentialOutlier", outlier);
mrmFeature.setMetaValue("initialPeakQuality", qual);
mrmFeature.setOverallQuality(qual);
}
}
// Prepare linear resampling of all the chromatograms, here creating the
// empty master_peak_container with the same RT (m/z) values as the
// reference chromatogram. We use the overall minimal left boundary and
// maximal right boundary to prepare the container.
SpectrumT master_peak_container;
const SpectrumT& ref_chromatogram = selectChromHelper_(transition_group, picked_chroms[chr_idx].getNativeID());
prepareMasterContainer_(ref_chromatogram, master_peak_container, min_left, max_right);
// Iterate over initial transitions / chromatograms (note that we may
// have a different number of picked chromatograms than total transitions
// as not all are detecting transitions).
double total_intensity = 0; double total_peak_apices = 0; double total_xic = 0; double total_mi = 0;
pickFragmentChromatograms(transition_group, picked_chroms, mrmFeature, smoothed_chroms,
best_left, best_right, use_consensus_,
total_intensity, total_xic, total_mi, total_peak_apices,
master_peak_container, left_edges, right_edges,
chr_idx, peak_idx);
// Also pick the precursor chromatogram(s); note total_xic is not
// extracted here, only for fragment traces
pickPrecursorChromatograms(transition_group,
picked_chroms, mrmFeature, smoothed_chroms,
best_left, best_right, use_consensus_,
total_intensity, master_peak_container, left_edges, right_edges,
chr_idx, peak_idx);
mrmFeature.setRT(peak_apex);
mrmFeature.setIntensity(total_intensity);
mrmFeature.setMetaValue("PeptideRef", transition_group.getTransitionGroupID());
mrmFeature.setMetaValue("leftWidth", best_left);
mrmFeature.setMetaValue("rightWidth", best_right);
mrmFeature.setMetaValue("total_xic", total_xic);
if (compute_total_mi_)
{
mrmFeature.setMetaValue("total_mi", total_mi);
}
mrmFeature.setMetaValue("peak_apices_sum", total_peak_apices);
mrmFeature.ensureUniqueId();
return mrmFeature;
}
/**
@brief Apex-based peak picking
Pick the peak with the closest apex to the consensus apex for each
chromatogram. Use the closest peak for the current peak.
Note that we will only set the closest peak per chromatogram to zero, so
if there are two peaks for some transitions, we will have to get to them
later. If there is no peak, then we transfer transition boundaries from
"master" peak.
*/
template <typename SpectrumT>
void pickApex(std::vector<SpectrumT>& picked_chroms,
const double best_left, const double best_right, const double peak_apex,
double &min_left, double &max_right,
std::vector< double > & left_edges, std::vector< double > & right_edges)
{
for (Size k = 0; k < picked_chroms.size(); k++)
{
double peak_apex_dist_min = std::numeric_limits<double>::max();
int min_dist = -1;
for (Size i = 0; i < picked_chroms[k].size(); i++)
{
PeakIntegrator::PeakArea pa_tmp = pi_.integratePeak( // get the peak apex
picked_chroms[k],
picked_chroms[k].getFloatDataArrays()[PeakPickerChromatogram::IDX_LEFTBORDER][i],
picked_chroms[k].getFloatDataArrays()[PeakPickerChromatogram::IDX_RIGHTBORDER][i]);
if (pa_tmp.apex_pos > 1e-11 && std::fabs(pa_tmp.apex_pos - peak_apex) < peak_apex_dist_min)
{ // update best candidate
peak_apex_dist_min = std::fabs(pa_tmp.apex_pos - peak_apex);
min_dist = (int)i;
}
}
// Select master peak boundaries, or in the case we found at least one peak, the local peak boundaries
double l = best_left;
double r = best_right;
if (min_dist >= 0)
{
l = picked_chroms[k].getFloatDataArrays()[PeakPickerChromatogram::IDX_LEFTBORDER][min_dist];
r = picked_chroms[k].getFloatDataArrays()[PeakPickerChromatogram::IDX_RIGHTBORDER][min_dist];
picked_chroms[k][min_dist].setIntensity(0.0); // only remove one peak per transition
}
left_edges.push_back(l);
right_edges.push_back(r);
// ensure we remember the overall maxima / minima
if (l < min_left) {min_left = l;}
if (r > max_right) {max_right = r;}
}
}
template <typename SpectrumT, typename TransitionT>
void pickFragmentChromatograms(const MRMTransitionGroup<SpectrumT, TransitionT>& transition_group,
const std::vector<SpectrumT>& picked_chroms,
MRMFeature& mrmFeature,
const std::vector<SpectrumT>& smoothed_chroms,
const double best_left, const double best_right,
const bool use_consensus_,
double & total_intensity,
double & total_xic,
double & total_mi,
double & total_peak_apices,
const SpectrumT & master_peak_container,
const std::vector< double > & left_edges,
const std::vector< double > & right_edges,
const int chr_idx,
const int peak_idx)
{
for (Size k = 0; k < transition_group.getTransitions().size(); k++)
{
double local_left = best_left;
double local_right = best_right;
if (!use_consensus_)
{
// We cannot have any non-detecting transitions (otherwise we have
// too few left / right edges) as we skipped those when doing peak
// picking and smoothing.
if (!transition_group.getTransitions()[k].isDetectingTransition())
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"When using non-consensus peak picker, all transitions need to be detecting transitions.");
}
local_left = left_edges[k];
local_right = right_edges[k];
}
const SpectrumT& chromatogram = selectChromHelper_(transition_group, transition_group.getTransitions()[k].getNativeID());
if (transition_group.getTransitions()[k].isDetectingTransition())
{
for (typename SpectrumT::const_iterator it = chromatogram.begin(); it != chromatogram.end(); it++)
{
total_xic += it->getIntensity();
}
}
// Compute total intensity on transition-level
double transition_total_xic = 0;
for (typename SpectrumT::const_iterator it = chromatogram.begin(); it != chromatogram.end(); it++)
{
transition_total_xic += it->getIntensity();
}
// Compute total mutual information on transition-level.
double transition_total_mi = 0;
if (compute_total_mi_)
{
std::vector<unsigned int> chrom_vect_id_ranked, chrom_vect_det_ranked;
std::vector<double> chrom_vect_id, chrom_vect_det;
for (typename SpectrumT::const_iterator it = chromatogram.begin(); it != chromatogram.end(); it++)
{
chrom_vect_id.push_back(it->getIntensity());
}
unsigned int max_rank_det = OpenSwath::Scoring::computeAndAppendRank(chrom_vect_id, chrom_vect_det_ranked);
// compute baseline mutual information
int transition_total_mi_norm = 0;
for (Size m = 0; m < transition_group.getTransitions().size(); m++)
{
if (transition_group.getTransitions()[m].isDetectingTransition())
{
const SpectrumT& chromatogram_det = selectChromHelper_(transition_group, transition_group.getTransitions()[m].getNativeID());
chrom_vect_det.clear();
for (typename SpectrumT::const_iterator it = chromatogram_det.begin(); it != chromatogram_det.end(); it++)
{
chrom_vect_det.push_back(it->getIntensity());
}
unsigned int max_rank_id = OpenSwath::Scoring::computeAndAppendRank(chrom_vect_det, chrom_vect_id_ranked);
transition_total_mi += OpenSwath::Scoring::rankedMutualInformation(chrom_vect_id_ranked, chrom_vect_det_ranked, max_rank_id, max_rank_det);
transition_total_mi_norm++;
}
}
if (transition_total_mi_norm > 0) { transition_total_mi /= transition_total_mi_norm; }
if (transition_group.getTransitions()[k].isDetectingTransition())
{
// sum up all transition-level total MI and divide by the number of detection transitions to have peak group level total MI
total_mi += transition_total_mi / transition_total_mi_norm;
}
}
SpectrumT used_chromatogram;
// resample the current chromatogram
if (peak_integration_ == "original")
{
used_chromatogram = resampleChromatogram_(chromatogram, master_peak_container, local_left, local_right);
}
else if (peak_integration_ == "smoothed")
{
if (smoothed_chroms.size() <= k)
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Tried to calculate peak area and height without any smoothed chromatograms");
}
used_chromatogram = resampleChromatogram_(smoothed_chroms[k], master_peak_container, local_left, local_right);
}
else
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
String("Peak integration chromatogram ") + peak_integration_ + " is not a valid method for MRMTransitionGroupPicker");
}
Feature f;
double quality = 0;
f.setQuality(0, quality);
f.setOverallQuality(quality);
PeakIntegrator::PeakArea pa = pi_.integratePeak(used_chromatogram, local_left, local_right);
double peak_integral = pa.area;
double peak_apex_int = pa.height;
f.setMetaValue("peak_apex_position", pa.apex_pos);
if (background_subtraction_ != "none")
{
double background{0};
double avg_noise_level{0};
if (background_subtraction_ == "original")
{
const double intensity_left = chromatogram.PosBegin(local_left)->getIntensity();
const double intensity_right = (chromatogram.PosEnd(local_right) - 1)->getIntensity();
const UInt n_points = std::distance(chromatogram.PosBegin(local_left), chromatogram.PosEnd(local_right));
avg_noise_level = (intensity_right + intensity_left) / 2;
background = avg_noise_level * n_points;
}
else if (background_subtraction_ == "exact")
{
PeakIntegrator::PeakBackground pb = pi_.estimateBackground(used_chromatogram, local_left, local_right, pa.apex_pos);
background = pb.area;
avg_noise_level = pb.height;
}
peak_integral -= background;
peak_apex_int -= avg_noise_level;
if (peak_integral < 0) {peak_integral = 0;}
if (peak_apex_int < 0) {peak_apex_int = 0;}
f.setMetaValue("area_background_level", background);
f.setMetaValue("noise_background_level", avg_noise_level);
} // end background
f.setRT(picked_chroms[chr_idx][peak_idx].getPos());
f.setIntensity(peak_integral);
ConvexHull2D hull;
hull.setHullPoints(pa.hull_points);
f.getConvexHulls().push_back(hull);
f.setMZ(chromatogram.getProduct().getMZ());
mrmFeature.setMZ(chromatogram.getPrecursor().getMZ());
if (chromatogram.metaValueExists("product_mz")) // legacy code (ensures that old tests still work)
{
f.setMetaValue("MZ", chromatogram.getMetaValue("product_mz"));
f.setMZ(chromatogram.getMetaValue("product_mz"));
}
f.setMetaValue("native_id", chromatogram.getNativeID());
f.setMetaValue("peak_apex_int", peak_apex_int);
f.setMetaValue("total_xic", transition_total_xic);
if (compute_total_mi_)
{
f.setMetaValue("total_mi", transition_total_mi);
}
if (transition_group.getTransitions()[k].isQuantifyingTransition())
{
total_intensity += peak_integral;
total_peak_apices += peak_apex_int;
}
// for backwards compatibility with TOPP tests
// Calculate peak shape metrics that will be used for later QC
PeakIntegrator::PeakShapeMetrics psm = pi_.calculatePeakShapeMetrics(used_chromatogram, local_left, local_right, peak_apex_int, pa.apex_pos);
f.setMetaValue("width_at_50", psm.width_at_50);
if (compute_peak_shape_metrics_)
{
f.setMetaValue("width_at_5", psm.width_at_5);
f.setMetaValue("width_at_10", psm.width_at_10);
f.setMetaValue("start_position_at_5", psm.start_position_at_5);
f.setMetaValue("start_position_at_10", psm.start_position_at_10);
f.setMetaValue("start_position_at_50", psm.start_position_at_50);
f.setMetaValue("end_position_at_5", psm.end_position_at_5);
f.setMetaValue("end_position_at_10", psm.end_position_at_10);
f.setMetaValue("end_position_at_50", psm.end_position_at_50);
f.setMetaValue("total_width", psm.total_width);
f.setMetaValue("tailing_factor", psm.tailing_factor);
f.setMetaValue("asymmetry_factor", psm.asymmetry_factor);
f.setMetaValue("slope_of_baseline", psm.slope_of_baseline);
f.setMetaValue("baseline_delta_2_height", psm.baseline_delta_2_height);
f.setMetaValue("points_across_baseline", psm.points_across_baseline);
f.setMetaValue("points_across_half_height", psm.points_across_half_height);
}
mrmFeature.addFeature(f, chromatogram.getNativeID()); //map index and feature
}
}
template <typename SpectrumT, typename TransitionT>
void pickPrecursorChromatograms(const MRMTransitionGroup<SpectrumT, TransitionT>& transition_group,
const std::vector<SpectrumT>& picked_chroms,
MRMFeature& mrmFeature,
const std::vector<SpectrumT>& smoothed_chroms,
const double best_left, const double best_right,
const bool use_consensus_,
double & total_intensity,
const SpectrumT & master_peak_container,
const std::vector< double > & left_edges,
const std::vector< double > & right_edges,
const int chr_idx,
const int peak_idx)
{
for (Size k = 0; k < transition_group.getPrecursorChromatograms().size(); k++)
{
const SpectrumT& chromatogram = transition_group.getPrecursorChromatograms()[k];
// Identify precursor index
// note: this is only valid if all transitions are detecting transitions
Size prec_idx = transition_group.getChromatograms().size() + k;
double local_left = best_left;
double local_right = best_right;
if (!use_consensus_ && right_edges.size() > prec_idx && left_edges.size() > prec_idx)
{
local_left = left_edges[prec_idx];
local_right = right_edges[prec_idx];
}
SpectrumT used_chromatogram;
// resample the current chromatogram
if (peak_integration_ == "original")
{
used_chromatogram = resampleChromatogram_(chromatogram, master_peak_container, local_left, local_right);
// const SpectrumT& used_chromatogram = chromatogram; // instead of resampling
}
else if (peak_integration_ == "smoothed" && smoothed_chroms.size() <= prec_idx)
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Tried to calculate peak area and height without any smoothed chromatograms for precursors");
}
else if (peak_integration_ == "smoothed")
{
used_chromatogram = resampleChromatogram_(smoothed_chroms[prec_idx], master_peak_container, local_left, local_right);
}
else
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
String("Peak integration chromatogram ") + peak_integration_ + " is not a valid method for MRMTransitionGroupPicker");
}
Feature f;
double quality = 0;
f.setQuality(0, quality);
f.setOverallQuality(quality);
PeakIntegrator::PeakArea pa = pi_.integratePeak(used_chromatogram, local_left, local_right);
double peak_integral = pa.area;
double peak_apex_int = pa.height;
if (background_subtraction_ != "none")
{
double background{0};
double avg_noise_level{0};
if ((peak_integration_ == "smoothed") && smoothed_chroms.size() <= prec_idx)
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Tried to calculate background estimation without any smoothed chromatograms");
}
else if (background_subtraction_ == "original")
{
const double intensity_left = chromatogram.PosBegin(local_left)->getIntensity();
const double intensity_right = (chromatogram.PosEnd(local_right) - 1)->getIntensity();
const UInt n_points = std::distance(chromatogram.PosBegin(local_left), chromatogram.PosEnd(local_right));
avg_noise_level = (intensity_right + intensity_left) / 2;
background = avg_noise_level * n_points;
}
else if (background_subtraction_ == "exact")
{
PeakIntegrator::PeakBackground pb = pi_.estimateBackground(used_chromatogram, local_left, local_right, pa.apex_pos);
background = pb.area;
avg_noise_level = pb.height;
}
peak_integral -= background;
peak_apex_int -= avg_noise_level;
if (peak_integral < 0) {peak_integral = 0;}
if (peak_apex_int < 0) {peak_apex_int = 0;}
f.setMetaValue("area_background_level", background);
f.setMetaValue("noise_background_level", avg_noise_level);
}
f.setMZ(chromatogram.getPrecursor().getMZ());
if (k == 0) {mrmFeature.setMZ(chromatogram.getPrecursor().getMZ());} // only use m/z if first (monoisotopic) isotope
if (chromatogram.metaValueExists("precursor_mz")) // legacy code (ensures that old tests still work)
{
f.setMZ(chromatogram.getMetaValue("precursor_mz"));
if (k == 0) {mrmFeature.setMZ(chromatogram.getMetaValue("precursor_mz"));} // only use m/z if first (monoisotopic) isotope
}
f.setRT(picked_chroms[chr_idx][peak_idx].getPos());
f.setIntensity(peak_integral);
ConvexHull2D hull;
hull.setHullPoints(pa.hull_points);
f.getConvexHulls().push_back(hull);
f.setMetaValue("native_id", chromatogram.getNativeID());
f.setMetaValue("peak_apex_int", peak_apex_int);
if (use_precursors_ && transition_group.getTransitions().empty())
{
total_intensity += peak_integral;
}
mrmFeature.addPrecursorFeature(f, chromatogram.getNativeID());
}
}
// maybe private, but we have tests
/**
@brief Remove overlapping features.
Remove features that are within the current seed (between best_left and
best_right) or overlap with it. An overlapping feature is defined as a
feature that has either of its borders within the border of the current
peak
Directly adjacent features are allowed, e.g. they can share one
border.
*/
template <typename SpectrumT>
void remove_overlapping_features(std::vector<SpectrumT>& picked_chroms, double best_left, double best_right)
{
// delete all seeds that lie within the current seed
Size count_inside = 0;
for (Size k = 0; k < picked_chroms.size(); k++)
{
for (Size i = 0; i < picked_chroms[k].size(); i++)
{
if (picked_chroms[k][i].getPos() >= best_left && picked_chroms[k][i].getPos() <= best_right)
{
picked_chroms[k][i].setIntensity(0.0);
count_inside++;
}
}
}
Size count_overlap = 0;
// delete all seeds that overlap within the current seed
for (Size k = 0; k < picked_chroms.size(); k++)
{
for (Size i = 0; i < picked_chroms[k].size(); i++)
{
if (picked_chroms[k][i].getIntensity() <= 1e-11) {continue; }
double left = picked_chroms[k].getFloatDataArrays()[PeakPickerChromatogram::IDX_LEFTBORDER][i];
double right = picked_chroms[k].getFloatDataArrays()[PeakPickerChromatogram::IDX_RIGHTBORDER][i];
if ((left > best_left && left < best_right)
|| (right > best_left && right < best_right))
{
picked_chroms[k][i].setIntensity(0.0);
count_overlap++;
}
}
}
OPENMS_LOG_DEBUG << " ** Removed " << count_inside << " peaks enclosed in and " <<
count_overlap << " peaks overlapping with added feature." << std::endl;
}
/// Find largest peak in a vector of chromatograms
void findLargestPeak(const std::vector<MSChromatogram >& picked_chroms, int& chr_idx, int& peak_idx);
/**
@brief Given a vector of chromatograms, find the indices of the chromatogram
containing the widest peak and of the position of highest intensity.
@param[in] picked_chroms The vector of chromatograms
@param[out] chrom_idx The index of the chromatogram containing the widest peak
@param[out] point_idx The index of the point with highest intensity
*/
void findWidestPeakIndices(const std::vector<MSChromatogram>& picked_chroms, Int& chrom_idx, Int& point_idx) const;
protected:
/// Synchronize members with param class
void updateMembers_() override;
/// Assignment operator is protected for algorithm
MRMTransitionGroupPicker& operator=(const MRMTransitionGroupPicker& rhs);
/**
@brief Select matching precursor or fragment ion chromatogram
*/
template <typename SpectrumT, typename TransitionT>
const SpectrumT& selectChromHelper_(const MRMTransitionGroup<SpectrumT, TransitionT>& transition_group, const String& native_id)
{
if (transition_group.hasChromatogram(native_id))
{
return transition_group.getChromatogram(native_id);
}
else if (transition_group.hasPrecursorChromatogram(native_id))
{
return transition_group.getPrecursorChromatogram(native_id);
}
else
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Did not find chromatogram for id '" + native_id + "'.");
}
}
/**
@brief Compute transition group quality (higher score is better)
This is only based on the co-elution of the chromatograms and internal
consistency without any library information.
For the final score (larger is better), consider these scores:
- missing_peaks (the more peaks are missing, the worse)
- multiple_peaks
- mean of the shapes (1 is very good, 0 is bad)
- mean of the coelutions (0 is good, 1 is ok, above 1 is pretty bad)
These scores are similar to the ones computed by MRMFeatureFinderScoring
and a simple sum of these scores is returned.
*/
template <typename SpectrumT, typename TransitionT>
double computeQuality_(const MRMTransitionGroup<SpectrumT, TransitionT>& transition_group,
const std::vector<SpectrumT>& picked_chroms,
const int chr_idx,
const double best_left,
const double best_right,
String& outlier)
{
// Resample all chromatograms around the current estimated peak and
// collect the raw intensities. For resampling, use a bit more on either
// side to correctly identify shoulders etc.
double resample_boundary = resample_boundary_; // sample 15 seconds more on each side
SpectrumT master_peak_container;
const SpectrumT& ref_chromatogram = selectChromHelper_(transition_group, picked_chroms[chr_idx].getNativeID());
prepareMasterContainer_(ref_chromatogram, master_peak_container, best_left - resample_boundary, best_right + resample_boundary);
std::vector<std::vector<double> > all_ints;
for (Size k = 0; k < picked_chroms.size(); k++)
{
const SpectrumT& chromatogram = selectChromHelper_(transition_group, picked_chroms[k].getNativeID());
const SpectrumT used_chromatogram = resampleChromatogram_(chromatogram,
master_peak_container, best_left - resample_boundary, best_right + resample_boundary);
std::vector<double> int_here;
for (const auto& peak : used_chromatogram) int_here.push_back(peak.getIntensity());
// Remove chromatograms without a single peak
double tic = std::accumulate(int_here.begin(), int_here.end(), 0.0);
if (tic > 1e-11) all_ints.push_back(int_here);
}
// Compute the cross-correlation for the collected intensities
std::vector<double> mean_shapes;
std::vector<double> mean_coel;
for (Size k = 0; k < all_ints.size(); k++)
{
std::vector<double> shapes;
std::vector<double> coel;
for (Size i = 0; i < all_ints.size(); i++)
{
if (i == k) {continue;}
OpenSwath::Scoring::XCorrArrayType res = OpenSwath::Scoring::normalizedCrossCorrelation(
all_ints[k], all_ints[i], boost::numeric_cast<int>(all_ints[i].size()), 1);
// the first value is the x-axis (retention time) and should be an int -> it show the lag between the two
double res_coelution = std::abs(OpenSwath::Scoring::xcorrArrayGetMaxPeak(res)->first);
double res_shape = std::abs(OpenSwath::Scoring::xcorrArrayGetMaxPeak(res)->second);
shapes.push_back(res_shape);
coel.push_back(res_coelution);
}
// We have computed the cross-correlation of chromatogram k against
// all others. Use the mean of these computations as the value for k.
OpenSwath::mean_and_stddev msc;
msc = std::for_each(shapes.begin(), shapes.end(), msc);
double shapes_mean = msc.mean();
msc = std::for_each(coel.begin(), coel.end(), msc);
double coel_mean = msc.mean();
// mean shape scores below 0.5-0.6 should be a real sign of trouble ... !
// mean coel scores above 3.5 should be a real sign of trouble ... !
mean_shapes.push_back(shapes_mean);
mean_coel.push_back(coel_mean);
}
// find the chromatogram with the minimal shape score and the maximal
// coelution score -> if it is the same chromatogram, the chance is
// pretty good that it is different from the others...
int min_index_shape = std::distance(mean_shapes.begin(), std::min_element(mean_shapes.begin(), mean_shapes.end()));
int max_index_coel = std::distance(mean_coel.begin(), std::max_element(mean_coel.begin(), mean_coel.end()));
// Look at the picked peaks that are within the current left/right borders
int missing_peaks = 0;
int multiple_peaks = 0;
// collect all seeds that lie within the current seed
std::vector<double> left_borders;
std::vector<double> right_borders;
for (Size k = 0; k < picked_chroms.size(); k++)
{
double l_tmp;
double r_tmp;
double max_int = -1;
int pfound = 0;
l_tmp = -1;
r_tmp = -1;
for (Size i = 0; i < picked_chroms[k].size(); i++)
{
if (picked_chroms[k][i].getPos() >= best_left && picked_chroms[k][i].getPos() <= best_right)
{
pfound++;
if (picked_chroms[k][i].getIntensity() > max_int)
{
max_int = picked_chroms[k][i].getIntensity() > max_int;
l_tmp = picked_chroms[k].getFloatDataArrays()[PeakPickerChromatogram::IDX_LEFTBORDER][i];
r_tmp = picked_chroms[k].getFloatDataArrays()[PeakPickerChromatogram::IDX_RIGHTBORDER][i];
}
}
}
if (l_tmp > 1e-11) left_borders.push_back(l_tmp);
if (r_tmp > 1e-11) right_borders.push_back(r_tmp);
if (pfound == 0) missing_peaks++;
if (pfound > 1) multiple_peaks++;
}
// Check how many chromatograms had exactly one peak picked between our
// current left/right borders -> this would be a sign of consistency.
OPENMS_LOG_DEBUG << " Overall found missing : " << missing_peaks << " and multiple : " << multiple_peaks << std::endl;
/// left_borders / right_borders might not have the same length since we might have peaks missing!!
// Is there one transitions that is very different from the rest (e.g.
// the same element has a bad shape and a bad coelution score) -> potential outlier
if (min_index_shape == max_index_coel)
{
OPENMS_LOG_DEBUG << " Element " << min_index_shape << " is a candidate for removal ... " << std::endl;
outlier = String(picked_chroms[min_index_shape].getNativeID());
}
else
{
outlier = "none";
}
// For the final score (larger is better), consider these scores:
// - missing_peaks (the more peaks are missing, the worse)
// - multiple_peaks
// - mean of the shapes (1 is very good, 0 is bad)
// - mean of the co-elution scores (0 is good, 1 is ok, above 1 is pretty bad)
double shape_score = std::accumulate(mean_shapes.begin(), mean_shapes.end(), 0.0) / mean_shapes.size();
double coel_score = std::accumulate(mean_coel.begin(), mean_coel.end(), 0.0) / mean_coel.size();
coel_score = (coel_score - 1.0) / 2.0;
double score = shape_score - coel_score - 1.0 * missing_peaks / picked_chroms.size();
OPENMS_LOG_DEBUG << " Computed score " << score << " (from " << shape_score <<
" - " << coel_score << " - " << 1.0 * missing_peaks / picked_chroms.size() << ")" << std::endl;
return score;
}
/**
@brief Recalculate the borders of the peak
By collecting all left and right borders of contained peaks, a consensus
peak is computed. By looking at the means and standard deviations of all
the peak borders it is estimated whether the proposed peak border
deviates too much from the consensus one. If the deviation is too high
(in this case), then we fall back to the "consensus" (a median here).
*/
template <typename SpectrumT>
void recalculatePeakBorders_(const std::vector<SpectrumT>& picked_chroms, double& best_left, double& best_right, double max_z)
{
// 1. Collect all seeds that lie within the current seed
// - Per chromatogram only the most intense one counts, otherwise very
// - low intense peaks can contribute disproportionally to the voting
// - procedure.
// TODO Especially with DDA MS1 "transitions" from FFID, you often have exactly the same
// borders and the logs get confusing and you get -Nan CVs. You also might save time if you use a set here.
std::vector<double> left_borders;
std::vector<double> right_borders;
for (Size k = 0; k < picked_chroms.size(); k++)
{
double max_int = -1;
double left = -1;
double right = -1;
for (Size i = 0; i < picked_chroms[k].size(); i++)
{
if (picked_chroms[k][i].getPos() >= best_left && picked_chroms[k][i].getPos() <= best_right)
{
if (picked_chroms[k].getFloatDataArrays()[PeakPickerChromatogram::IDX_ABUNDANCE][i] > max_int)
{
max_int = picked_chroms[k].getFloatDataArrays()[PeakPickerChromatogram::IDX_ABUNDANCE][i];
left = picked_chroms[k].getFloatDataArrays()[PeakPickerChromatogram::IDX_LEFTBORDER][i];
right = picked_chroms[k].getFloatDataArrays()[PeakPickerChromatogram::IDX_RIGHTBORDER][i];
}
}
}
if (max_int > -1 )
{
left_borders.push_back(left);
right_borders.push_back(right);
OPENMS_LOG_DEBUG << " * peak " << k << " left boundary " << left_borders.back() << " with inty " << max_int << std::endl;
OPENMS_LOG_DEBUG << " * peak " << k << " right boundary " << right_borders.back() << " with inty " << max_int << std::endl;
}
}
// Return for empty peak list
if (right_borders.empty())
{
return;
}
// FEATURE IDEA: instead of Z-score use modified Z-score for small data sets
// http://d-scholarship.pitt.edu/7948/1/Seo.pdf
// http://www.itl.nist.gov/div898/handbook/eda/section3/eda35h.htm
// 1. calculate median
// 2. MAD = calculate difference to median for each value -> take median of that
// 3. Mi = 0.6745*(xi - median) / MAD
// 2. Calculate mean and standard deviation
// If the coefficient of variation is too large for one border, we use a
// "pseudo-median" instead of the border of the most intense peak.
double mean, stdev;
// Right borders
mean = std::accumulate(right_borders.begin(), right_borders.end(), 0.0) / (double) right_borders.size();
stdev = std::sqrt(std::inner_product(right_borders.begin(), right_borders.end(), right_borders.begin(), 0.0)
/ right_borders.size() - mean * mean);
std::sort(right_borders.begin(), right_borders.end());
OPENMS_LOG_DEBUG << " - Recalculating right peak boundaries " << mean << " mean / best "
<< best_right << " std " << stdev << " : " << std::fabs(best_right - mean) / stdev
<< " coefficient of variation" << std::endl;
// Compare right borders of best transition with the mean
if (std::fabs(best_right - mean) / stdev > max_z)
{
best_right = right_borders[right_borders.size() / 2]; // pseudo median
OPENMS_LOG_DEBUG << " - CV too large: correcting right boundary to " << best_right << std::endl;
}
// Left borders
mean = std::accumulate(left_borders.begin(), left_borders.end(), 0.0) / (double) left_borders.size();
stdev = std::sqrt(std::inner_product(left_borders.begin(), left_borders.end(), left_borders.begin(), 0.0)
/ left_borders.size() - mean * mean);
std::sort(left_borders.begin(), left_borders.end());
OPENMS_LOG_DEBUG << " - Recalculating left peak boundaries " << mean << " mean / best "
<< best_left << " std " << stdev << " : " << std::fabs(best_left - mean) / stdev
<< " coefficient of variation" << std::endl;
// Compare left borders of best transition with the mean
if (std::fabs(best_left - mean) / stdev > max_z)
{
best_left = left_borders[left_borders.size() / 2]; // pseudo median
OPENMS_LOG_DEBUG << " - CV too large: correcting left boundary to " << best_left << std::endl;
}
}
/// @name Resampling methods
//@{
/**
@brief Create an empty master peak container that has the correct mz / RT values set
The empty master peak container fill be filled with mz / RT values at the
positions where the reference chromatogram has values. The container will
only be populated between the boundaries given. The output container
will contain peaks with mz / RT values but all intensity values will be zero.
@param[in] ref_chromatogram Reference chromatogram containing mz / RT values (possibly beyond the desired range)
@param[out] master_peak_container Output container to be populated
@param[in] left_boundary Left boundary of values the container should be populated with
@param[in] right_boundary Right boundary of values the container should be populated with
*/
template <typename PeakContainerT>
void prepareMasterContainer_(const PeakContainerT& ref_chromatogram,
PeakContainerT& master_peak_container,
double left_boundary,
double right_boundary)
{
OPENMS_PRECONDITION(master_peak_container.empty(), "Master peak container must be empty")
// get the start / end point of this chromatogram => then add one more
// point beyond the two boundaries to make the resampling accurate also
// at the edge.
auto begin = ref_chromatogram.begin();
while (begin != ref_chromatogram.end() && begin->getPos() < left_boundary) {begin++; }
if (begin != ref_chromatogram.begin()) { begin--; }
auto end = begin;
while (end != ref_chromatogram.end() && end->getPos() < right_boundary) {end++; }
if (end != ref_chromatogram.end()) { end++; }
// resize the master container and set the m/z values to the ones of the master container
master_peak_container.resize(distance(begin, end)); // initialize to zero
auto it = master_peak_container.begin();
for (auto chrom_it = begin; chrom_it != end; chrom_it++, it++)
{
it->setPos(chrom_it->getPos());
}
}
/**
@brief Resample a container at the positions indicated by the master peak container
@param[in] chromatogram Container with the input data
@param[in] master_peak_container Container with the mz / RT values at which to resample
@param[in] left_boundary Left boundary of values the container should be resampled
@param[in] right_boundary Right boundary of values the container should be resampled
@return A container which contains the data from the input chromatogram resampled at the positions of the master container
*/
template <typename PeakContainerT>
PeakContainerT resampleChromatogram_(const PeakContainerT& chromatogram,
const PeakContainerT& master_peak_container,
double left_boundary,
double right_boundary)
{
// get the start / end point of this chromatogram => then add one more
// point beyond the two boundaries to make the resampling accurate also
// at the edge.
auto begin = chromatogram.begin();
while (begin != chromatogram.end() && begin->getPos() < left_boundary) {begin++;}
if (begin != chromatogram.begin()) { begin--; }
auto end = begin;
while (end != chromatogram.end() && end->getPos() < right_boundary) {end++;}
if (end != chromatogram.end()) { end++; }
auto resampled_peak_container = master_peak_container; // copy the master container, which contains the RT values
LinearResamplerAlign lresampler;
lresampler.raster(begin, end, resampled_peak_container.begin(), resampled_peak_container.end());
return resampled_peak_container;
}
//@}
// Members
String peak_integration_;
String background_subtraction_;
bool recalculate_peaks_;
bool use_precursors_;
bool use_consensus_;
bool compute_peak_quality_;
bool compute_peak_shape_metrics_;
bool compute_total_mi_;
double min_qual_;
int stop_after_feature_;
double stop_after_intensity_ratio_;
double min_peak_width_;
double recalculate_peaks_max_z_;
double resample_boundary_;
/**
@brief Which method to use for selecting peaks' boundaries
Valid values are: "largest", "widest"
*/
String boundary_selection_method_;
PeakPickerChromatogram picker_;
PeakIntegrator pi_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/OPENSWATH/PeakPickerMobilogram.h | .h | 9,661 | 232 | // Copyright (c) 2002-present, The OpenMS Team -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Justin Sing $
// $Authors: Justin Sing $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/KERNEL/MSSpectrum.h>
#include <OpenMS/KERNEL/MSChromatogram.h>
#include <OpenMS/KERNEL/ChromatogramPeak.h>
#include <OpenMS/KERNEL/Mobilogram.h>
#include <OpenMS/KERNEL/MobilityPeak1D.h>
#include <OpenMS/PROCESSING/NOISEESTIMATION/SignalToNoiseEstimatorMedian.h>
#include <OpenMS/PROCESSING/SMOOTHING/SavitzkyGolayFilter.h>
#include <OpenMS/PROCESSING/SMOOTHING/GaussFilter.h>
#include <OpenMS/PROCESSING/CENTROIDING/PeakPickerHiRes.h>
#include <vector>
namespace OpenMS
{
/**
@brief The PeakPickerMobilogram finds peaks a single mobilogram.
@htmlinclude OpenMS_PeakPickerMobilogram.parameters
It uses the PeakPickerHiRes internally to find interesting seed candidates.
These candidates are then expanded and a right/left border of the peak is
searched.
Additionally, overlapping peaks can be removed.
*/
class OPENMS_DLLAPI PeakPickerMobilogram :
public DefaultParamHandler
{
public:
//@{
/// Constructor
PeakPickerMobilogram();
/// Destructor
~PeakPickerMobilogram() override {}
//@}
/// indices into FloatDataArrays of resulting picked mobilogram
enum FLOATINDICES { IDX_FWHM = 0, IDX_ABUNDANCE = 1, IDX_LEFTBORDER = 2, IDX_RIGHTBORDER = 3, IDX_OF_LEFTBORDER_IDX = 4, IDX_OF_RIGHTBORDER_IDX = 5, SIZE_OF_FLOATINDICES };
/// Struct to hold peak positions
struct PeakPositions {
size_t left; // Left position of the peak
size_t apex; // Apex (highest point) position of the peak
size_t right; // Right position of the peak
};
/**
@brief Finds peaks in a single mobilogram and annotates left/right borders
It uses a modified algorithm of the PeakPickerHiRes
This function will return a picked mobilogram
*/
void pickMobilogram(const Mobilogram& mobilogram, Mobilogram& picked_mobilogram);
/**
@brief Finds peaks in a single mobilogram and annotates left/right borders
It uses a modified algorithm of the PeakPickerHiRes
This function will return a picked mobilogram and a smoothed mobilogram
*/
void pickMobilogram(Mobilogram mobilogram, Mobilogram& picked_mobilogram, Mobilogram& smoothed_mobilogram);
/**
@brief Filters a vector of mobilograms for the highest peak based on the picked mobilogram
*/
void filterTopPeak(Mobilogram& picked_mobilogram, std::vector<Mobilogram>& mobilograms, PeakPositions& peak_pos);
/**
@brief Filters a single mobilogram for the highest peak based on the picked mobilogram
*/
void filterTopPeak(Mobilogram& picked_mobilogram, Mobilogram& mobilogram, PeakPositions& peak_pos);
/// Temporary vector to hold the integrated intensities
std::vector<double> integrated_intensities_;
/// Temporary vector to hold the peak left widths
std::vector<Size> left_width_;
/// Temporary vector to hold the peak right widths
std::vector<Size> right_width_;
protected:
void pickMobilogram_(const Mobilogram& mobilogram, Mobilogram& picked_mobilogram);
/**
@brief Compute peak area (peak integration)
*/
void integratePeaks_(const Mobilogram& mobilogram);
/**
@brief Helper function to find the closest peak in a mobilogram to "target_im"
The search will start from the index current_peak, so the function is
assuming the closest peak is to the right of current_peak.
It will return the index of the closest peak in the mobilogram.
*/
Size findClosestPeak_(const Mobilogram& mobilogram, double target_im, Size current_peak = 0);
/**
@brief Helper function to find the highest peak in a mobilogram
This function takes the integrated intensities, left widths, right widths from the peak picker and finds the highest peak in the mobilogram. The left, apex, and right positions of the highest peak are returned.
If the peak picker found no peaks (i.e. intensities is empty), the returned PeakPositions object will have it's left, apex, and right set based on the input im_size. The peak picker could fail if the input mobilogram is sparse.
@note The left, apex, and right positions are indices into the mobilogram.
@param[in] intensities A vector of doubles containing the intensities of the peaks in the mobilogram
@param[in] left_widths A vector of Size values containing the left widths of the peaks in the mobilogram
@param[in] right_widths A vector of Size values containing the right widths of the peaks in the mobilogram
@param[in] im_size The size/length of the mobilogram
@return A PeakPositions object containing the left, apex, and right positions of the highest peak in the mobilogram
*/
static PeakPositions findHighestPeak_(const std::vector<double> intensities,
const std::vector<Size> left_widths,
const std::vector<Size> right_widths,
const size_t im_size);
/**
@brief Helper function to filter peak intensities in a mobilogram
This function takes a mobilogram and filters the peak intensities based on the left and right indices provided.
@note This function modifies the input mobilogram in place.
@param[in,out] mobilogram A Mobilogram object
@param[in] left_index The left index of the peak range to filter
@param[in] right_index The right index of the peak range to filter
*/
void filterPeakIntensities_(Mobilogram& mobilogram,
size_t left_index,
size_t right_index);
/**
@brief Helper function to filter peak intensities for a vector of mobilograms
This function takes a vector of mobilograms and filters the peak intensities based on the left and right indices provided.
@note This function modifies the input mobilograms in place.
@param[in,out] mobilograms A vector of Mobilogram objects
@param[in] left_index The left index of the peak range to filter
@param[in] right_index The right index of the peak range to filter
*/
void filterPeakIntensities_(std::vector<Mobilogram>& mobilograms,
size_t left_index,
size_t right_index);
/**
@brief Helper function yo convert OpenMS FloatDataArray to a vector of doubles
@param[in] floatDataArray A const reference to a FloatDataArray object
@return A vector of doubles containing the values from the FloatDataArray
*/
static std::vector<double> extractFloatValues_(const OpenMS::DataArrays::FloatDataArray& floatDataArray);
/**
@brief Helper function to convert OpenMS IntegerDataArray to a vector of std::size
@param[in] floatDataArray A const reference to an FloatDataArray object
@return A vector of std::size containing the values from the IntegerDataArray
*/
static std::vector<std::size_t> extractIntValues_(const OpenMS::DataArrays::FloatDataArray& floatDataArray);
/**
@brief Filter vector of mobilograms for the highest peak based on the picked mobilogram
*/
PeakPositions filterTopPeak_(Mobilogram& picked_mobilogram, std::vector<Mobilogram>& mobilograms);
/**
@brief Filter single mobilogram for the highest peak based on the picked mobilogram
*/
PeakPositions filterTopPeak_(Mobilogram& picked_mobilogram, Mobilogram& mobilograms);
/**
@brief Helper function to remove overlapping peaks in a single Chromatogram
*/
void removeOverlappingPeaks_(const Mobilogram& mobilogram, Mobilogram& picked_mobilogram);
/// Synchronize members with param class
void updateMembers_() override;
// Members
/// Frame length for the SGolay smoothing
UInt sgolay_frame_length_;
/// Polynomial order for the SGolay smoothing
UInt sgolay_polynomial_order_;
/// Width of the Gaussian smoothing
double gauss_width_;
/// Whether to use Gaussian smoothing
bool use_gauss_;
/// Whether to resolve overlapping peaks
bool remove_overlapping_;
/// Forced peak with
double peak_width_;
/// Signal to noise threshold
double signal_to_noise_;
/// Signal to noise window length
double sn_win_len_;
/// Signal to noise bin count
UInt sn_bin_count_;
/// Whether to write out log messages of the SN estimator
bool write_sn_log_messages_;
/// Peak picker method
String method_;
PeakPickerHiRes pp_;
SavitzkyGolayFilter sgolay_;
GaussFilter gauss_;
};
} | Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/OPENSWATH/SwathWindowLoader.h | .h | 2,751 | 82 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hannes Roest$
// $Authors: Hannes Roest$
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/config.h>
#include <OpenMS/OPENSWATHALGO/DATAACCESS/SwathMap.h>
#include <vector>
namespace OpenMS
{
/**
* @brief Class to read a file describing the Swath Windows
*
* The file must of be tab delimited and of the following format:
* window_lower window_upper
* 400 425
* 425 450
* ...
*
* Note that the first line is a header and will be skipped.
*
*/
class OPENMS_DLLAPI SwathWindowLoader
{
public:
/**
@brief Annotate a Swath map using a Swath window file specifying the individual windows
@note It is assumed that the files in the swath_maps vector are in the
same order as the windows in the provided file (usually from lowest to
highest).
@param[in] filename The filename of the tab delimited file
@param[in,out] swath_maps The list of SWATH maps (assumed to be in the same order as in the file)
@param[in] do_sort Sort the windows after reading in ascending order
@param[in] force Force overriding the window boundaries, even if the new boundaries are wider than the data boundaries
@throw Exception::IllegalArgument if the number of maps in the file and the provided input maps to not match, or if the new boundaries are outside of the data boundaries (unless force==true)
*/
static void annotateSwathMapsFromFile(const std::string& filename,
std::vector<OpenSwath::SwathMap>& swath_maps,
bool do_sort,
bool force);
/**
@brief Reading a tab delimited file specifying the SWATH windows
The file must of be tab delimited and of the following format:
\verbatim
window_lower window_upper
400 425
425 450
...
\endverbatim
Note that the first line is a header and will be skipped.
@param[in] filename The filename of the tab delimited file
@param[out] swath_prec_lower The output vector for the window start
@param[out] swath_prec_upper The output vector for the window end
@throw Exception::InvalidValue if window's start >= end
*
*/
static void readSwathWindows(const std::string& filename,
std::vector<double>& swath_prec_lower,
std::vector<double>& swath_prec_upper);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/SpectrumAccessSqMass.h | .h | 3,867 | 111 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hannes Roest $
// $Authors: Hannes Roest $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/KERNEL/MSSpectrum.h>
#include <OpenMS/KERNEL/MSChromatogram.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/FORMAT/HANDLERS/MzMLSqliteHandler.h>
#include <OpenMS/OPENSWATHALGO/DATAACCESS/ISpectrumAccess.h>
#include <memory>
namespace OpenMS
{
/**
* @brief An implementation of the Spectrum Access interface using SQL files
*
* The interface takes an MzMLSqliteHandler object to access spectra and
* chromatograms from a sqlite file (sqMass). Currently access to individual
* spectra and chromatograms are not supported due to large overhead of
* opening a DB connection and performing a single query.
*
* Instead, the users should use getAllSpectra which returns all available
* spectra together.
*
* The interface allows to be constructed in a way as to only provide access
* to a subset of spectra / chromatograms by supplying a set of indices which
* are then used to provide a transparent interface to any consumer who will
* get access to the described subset of spectra / chromatograms. This can be
* useful to provide a specific interface to MS1 or MS2 spectra only or to
* different DIA / SWATH-MS windows.
*
* Parallel access is supported through this interface as it is read-only and
* sqlite3 supports multiple parallel read threads as long as they use a
* different db connection.
*
* Sample usage:
*
*
* @code
* // Obtain swath_map with boundaries first
* std::vector<int> indices = sql_mass_reader.readSpectraForWindow(swath_map);
* OpenMS::Internal::MzMLSqliteHandler handler(file);
* OpenSwath::SpectrumAccessPtr sptr(new OpenMS::SpectrumAccessSqMass(handler, indices));
* swath_maps[k].sptr = sptr;
* @endcode
*
*
*/
class OPENMS_DLLAPI SpectrumAccessSqMass :
public OpenSwath::ISpectrumAccess
{
public:
typedef OpenMS::MSSpectrum MSSpectrumType;
typedef OpenMS::MSChromatogram MSChromatogramType;
/// Constructor
SpectrumAccessSqMass(const OpenMS::Internal::MzMLSqliteHandler& handler);
SpectrumAccessSqMass(const OpenMS::Internal::MzMLSqliteHandler& handler, const std::vector<int> & indices);
SpectrumAccessSqMass(const SpectrumAccessSqMass& sp, const std::vector<int>& indices);
/// Destructor
~SpectrumAccessSqMass() override;
/// Copy constructor
SpectrumAccessSqMass(const SpectrumAccessSqMass & rhs);
/// Light clone operator (actual data will not get copied)
std::shared_ptr<OpenSwath::ISpectrumAccess> lightClone() const override;
OpenSwath::SpectrumPtr getSpectrumById(int /* id */) override;
OpenSwath::SpectrumMeta getSpectrumMetaById(int /* id */) const override;
/// Load all spectra from the underlying sqMass file into memory
void getAllSpectra(std::vector< OpenSwath::SpectrumPtr > & spectra, std::vector< OpenSwath::SpectrumMeta > & spectra_meta) const;
std::vector<std::size_t> getSpectraByRT(double /* RT */, double /* deltaRT */) const override;
size_t getNrSpectra() const override;
OpenSwath::ChromatogramPtr getChromatogramById(int /* id */) override;
size_t getNrChromatograms() const override;
std::string getChromatogramNativeID(int /* id */) const override;
private:
/// Access to underlying sqMass file
OpenMS::Internal::MzMLSqliteHandler handler_;
/// Optional subset of spectral indices
std::vector<int> sidx_;
};
} //end namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/MRMFeatureAccessOpenMS.h | .h | 5,085 | 204 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hannes Roest $
// $Authors: Hannes Roest $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/OPENSWATHALGO/DATAACCESS/ITransition.h>
#include <OpenMS/KERNEL/Feature.h>
#include <OpenMS/KERNEL/MRMFeature.h>
#include <OpenMS/KERNEL/MRMTransitionGroup.h>
#include <OpenMS/PROCESSING/NOISEESTIMATION/SignalToNoiseEstimatorMedian.h>
#include <memory>
// These classes are minimal implementations of the interfaces defined in ITransition:
// - IFeature
// - IMRMFeature
// - ITransitionGroup
// - ISignalToNoise
namespace OpenMS
{
/**
@brief An implementation of the OpenSWATH Feature Access interface using OpenMS
*/
class OPENMS_DLLAPI FeatureOpenMS :
public OpenSwath::IFeature
{
public:
explicit FeatureOpenMS(Feature& feature);
~FeatureOpenMS() override;
void getRT(std::vector<double>& rt) const override;
void getIntensity(std::vector<double>& intens) const override;
float getIntensity() const override;
double getRT() const override;
private:
Feature* feature_;
};
/**
@brief An implementation of the OpenSWATH MRM Feature Access interface using OpenMS
*/
class OPENMS_DLLAPI MRMFeatureOpenMS :
public OpenSwath::IMRMFeature
{
public:
explicit MRMFeatureOpenMS(MRMFeature& mrmfeature);
~MRMFeatureOpenMS() override;
std::shared_ptr<OpenSwath::IFeature> getFeature(std::string nativeID) override;
std::shared_ptr<OpenSwath::IFeature> getPrecursorFeature(std::string nativeID) override;
std::vector<std::string> getNativeIDs() const override;
std::vector<std::string> getPrecursorIDs() const override;
float getIntensity() const override;
double getRT() const override;
double getMetaValue(std::string name) const;
size_t size() const override;
private:
const MRMFeature& mrmfeature_;
std::map<std::string, std::shared_ptr<FeatureOpenMS> > features_;
std::map<std::string, std::shared_ptr<FeatureOpenMS> > precursor_features_;
};
/**
@brief An implementation of the OpenSWATH Transition Group Access interface using OpenMS
*/
template <typename SpectrumT, typename TransitionT>
class TransitionGroupOpenMS :
public OpenSwath::ITransitionGroup
{
public:
TransitionGroupOpenMS(MRMTransitionGroup<SpectrumT, TransitionT>& trgroup) :
trgroup_(trgroup)
{
}
~TransitionGroupOpenMS() override
{
}
std::size_t size() const override
{
return trgroup_.size();
}
std::vector<std::string> getNativeIDs() const override
{
std::vector<std::string> result;
for (std::size_t i = 0; i < this->size(); i++)
{
result.push_back(trgroup_.getChromatograms()[i].getNativeID());
}
return result;
}
void getLibraryIntensities(std::vector<double>& intensities) const override
{
trgroup_.getLibraryIntensity(intensities);
}
private:
const MRMTransitionGroup<SpectrumT, TransitionT>& trgroup_;
};
/**
@brief An implementation of the OpenSWATH SignalToNoise Access interface using OpenMS
*/
template <typename ContainerT>
class SignalToNoiseOpenMS :
public OpenSwath::ISignalToNoise
{
public:
SignalToNoiseOpenMS(ContainerT& chromat,
double sn_win_len_, unsigned int sn_bin_count_, bool write_log_messages) :
chromatogram_(chromat), sn_()
{
OpenMS::Param snt_parameters = sn_.getParameters();
snt_parameters.setValue("win_len", sn_win_len_);
snt_parameters.setValue("bin_count", sn_bin_count_);
if (write_log_messages)
{
snt_parameters.setValue("write_log_messages", "true");
}
else
{
snt_parameters.setValue("write_log_messages", "false");
}
sn_.setParameters(snt_parameters);
sn_.init(chromatogram_);
}
double getValueAtRT(double RT) override
{
if (chromatogram_.empty()) {return -1;}
// Note that MZBegin does not seem to return the same iterator on
// different setups, see https://github.com/OpenMS/OpenMS/issues/1163
auto iter = chromatogram_.PosEnd(RT);
// ensure that iter is valid
if (iter == chromatogram_.end())
{
iter--;
}
auto prev = iter;
if (prev != chromatogram_.begin())
{
prev--;
}
if (std::fabs(prev->getPos() - RT) < std::fabs(iter->getPos() - RT) )
{
// prev is closer to the apex
return sn_.getSignalToNoise((Size) distance(chromatogram_.begin(),prev));
}
else
{
// iter is closer to the apex
return sn_.getSignalToNoise((Size) distance(chromatogram_.begin(),iter));
}
}
private:
const ContainerT& chromatogram_;
OpenMS::SignalToNoiseEstimatorMedian< ContainerT > sn_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/DataAccessHelper.h | .h | 2,777 | 64 | // 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 <fstream>
#include <boost/numeric/conversion/cast.hpp>
#include <OpenMS/KERNEL/MSSpectrum.h>
#include <OpenMS/KERNEL/MSChromatogram.h>
#include <OpenMS/ANALYSIS/TARGETED/TargetedExperiment.h>
#include <OpenMS/OPENSWATHALGO/DATAACCESS/TransitionExperiment.h>
#include <OpenMS/OPENSWATHALGO/DATAACCESS/ISpectrumAccess.h>
namespace OpenMS
{
/**
@brief Several helpers to convert OpenMS datastructures to structures that
implement the OpenSWATH interfaces.
*/
class OPENMS_DLLAPI OpenSwathDataAccessHelper
{
public:
/// Convert a SpectrumPtr to an OpenMS Spectrum
static void convertToOpenMSSpectrum(const OpenSwath::SpectrumPtr& sptr, OpenMS::MSSpectrum & spectrum);
/// Convert an OpenMS Spectrum to an SpectrumPtr
static OpenSwath::SpectrumPtr convertToSpectrumPtr(const OpenMS::MSSpectrum & spectrum);
/// Convert a ChromatogramPtr to an OpenMS Chromatogram
static void convertToOpenMSChromatogram(const OpenSwath::ChromatogramPtr& cptr, OpenMS::MSChromatogram & chromatogram);
/// Convert an OpenMS Chromatogram to an ChromatogramPtr
static OpenSwath::ChromatogramPtr convertToChromatogramPtr(const OpenMS::MSChromatogram & chromatogram);
static void convertToOpenMSChromatogramFilter(OpenMS::MSChromatogram & chromatogram,
const OpenSwath::ChromatogramPtr& cptr,
double rt_min,
double rt_max);
/// convert from the OpenMS TargetedExperiment to the LightTargetedExperiment
static void convertTargetedExp(const OpenMS::TargetedExperiment & transition_exp_, OpenSwath::LightTargetedExperiment & transition_exp);
/// convert from the OpenMS TargetedExperiment Peptide to the LightTargetedExperiment Peptide
static void convertTargetedCompound(const TargetedExperiment::Peptide& pep, OpenSwath::LightCompound& comp);
/// convert from the OpenMS TargetedExperiment Compound to the LightTargetedExperiment Compound
static void convertTargetedCompound(const TargetedExperiment::Compound& compound, OpenSwath::LightCompound& comp);
/// convert from the LightCompound to an OpenMS AASequence (with correct modifications)
static void convertPeptideToAASequence(const OpenSwath::LightCompound & peptide, AASequence & aa_sequence);
};
} //end namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/SpectrumAccessOpenMSInMemory.h | .h | 3,176 | 93 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hannes Roest $
// $Authors: Hannes Roest $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/KERNEL/MSSpectrum.h>
#include <OpenMS/KERNEL/MSChromatogram.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/OPENSWATHALGO/DATAACCESS/ISpectrumAccess.h>
#include <memory>
namespace OpenMS
{
/**
* @brief An implementation of the OpenSWATH Spectrum Access interface completely in memory
*
* This implementation of the spectrum access interface ensures that all data
* is held completely in memory and is quickly accessible. This class can be
* generated by passing any object implementing the Spectrum Access interface
* and guarantees to provide the same access to the raw data as the original
* object with the added benefits (and downside) of keeping all data in system
* memory.
*
* A possible example
*
* @code
* OpenSwath::ISpectrumAccess * data_access;
* fillData(data_access); // assume that data_access points to some data
* OpenSwath::ISpectrumAccess * in_memory_data_access = SpectrumAccessOpenMSInMemory(data_access);
* @endcode
*
* After executing this code, two variables exist: data_access which provides
* access to the original data but does so in one of multiple ways which is
* not transparent to the user. However, in_memory_data_access will provide
* access to the same data but with the guarantee that the data is available
* in memory and not read from the disk.
*
*/
class OPENMS_DLLAPI SpectrumAccessOpenMSInMemory :
public OpenSwath::ISpectrumAccess
{
public:
typedef OpenMS::PeakMap MSExperimentType;
typedef OpenMS::MSSpectrum MSSpectrumType;
typedef OpenMS::MSChromatogram MSChromatogramType;
/// Constructor
explicit SpectrumAccessOpenMSInMemory(OpenSwath::ISpectrumAccess & origin);
/// Destructor
~SpectrumAccessOpenMSInMemory() override;
/// Copy constructor
SpectrumAccessOpenMSInMemory(const SpectrumAccessOpenMSInMemory & rhs);
/// Light clone operator (actual data will not get copied)
std::shared_ptr<OpenSwath::ISpectrumAccess> lightClone() const override;
OpenSwath::SpectrumPtr getSpectrumById(int id) override;
OpenSwath::SpectrumMeta getSpectrumMetaById(int id) const override;
std::vector<std::size_t> getSpectraByRT(double RT, double deltaRT) const override;
size_t getNrSpectra() const override;
OpenSwath::ChromatogramPtr getChromatogramById(int id) override;
size_t getNrChromatograms() const override;
std::string getChromatogramNativeID(int id) const override;
private:
std::vector< OpenSwath::SpectrumPtr > spectra_;
std::vector< OpenSwath::SpectrumMeta > spectra_meta_;
std::vector< OpenSwath::ChromatogramPtr > chromatograms_;
std::vector< std::string > chromatogram_ids_;
};
} //end namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/SpectrumAccessOpenMS.h | .h | 2,543 | 87 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hannes Roest $
// $Authors: Hannes Roest $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/KERNEL/MSSpectrum.h>
#include <OpenMS/KERNEL/MSChromatogram.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/OPENSWATHALGO/DATAACCESS/ISpectrumAccess.h>
#include <memory>
namespace OpenMS
{
/**
@brief An implementation of the OpenSWATH Spectrum Access interface using OpenMS
*/
class OPENMS_DLLAPI SpectrumAccessOpenMS :
public OpenSwath::ISpectrumAccess
{
public:
typedef OpenMS::PeakMap MSExperimentType;
typedef OpenMS::MSSpectrum MSSpectrumType;
typedef OpenMS::MSChromatogram MSChromatogramType;
/// Constructor
explicit SpectrumAccessOpenMS(std::shared_ptr<MSExperimentType> ms_experiment);
/// Destructor
~SpectrumAccessOpenMS() override;
/**
@brief Copy constructor
Performs a light copy operation when another SpectrumAccessOpenMS
instance is given: only a copy of the pointer to the underlying
MSExperiment is stored, so after this, both instances (rhs and *this)
will point to the same MSExperiment.
*/
SpectrumAccessOpenMS(const SpectrumAccessOpenMS & rhs);
/**
@brief Light clone operator (actual data will not get copied)
Creates a light clone of the current instance, with the clone pointing to
the same underlying MSExperiment.
*/
std::shared_ptr<OpenSwath::ISpectrumAccess> lightClone() const override;
OpenSwath::SpectrumPtr getSpectrumById(int id) override;
OpenSwath::SpectrumMeta getSpectrumMetaById(int id) const override;
std::vector<std::size_t> getSpectraByRT(double RT, double deltaRT) const override;
size_t getNrSpectra() const override;
SpectrumSettings getSpectraMetaInfo(int id) const;
OpenSwath::ChromatogramPtr getChromatogramById(int id) override;
// FEATURE ?
// ChromatogramPtr getChromatogramByPrecursorMZ(double mz, double deltaMZ);
size_t getNrChromatograms() const override;
ChromatogramSettings getChromatogramMetaInfo(int id) const;
std::string getChromatogramNativeID(int id) const override;
private:
std::shared_ptr<MSExperimentType> ms_experiment_;
};
} //end namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/SimpleOpenMSSpectraAccessFactory.h | .h | 1,024 | 37 | // 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, Witold Wolski $
// --------------------------------------------------------------------------
#pragma once
#include <fstream>
#include <OpenMS/OPENSWATHALGO/DATAACCESS/ISpectrumAccess.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <memory>
namespace OpenMS
{
/**
@brief A factory method that returns two ISpectrumAccess implementations
*/
class OPENMS_DLLAPI SimpleOpenMSSpectraFactory
{
public:
/// Simple Factory method to get a SpectrumAccess Ptr from an MSExperiment
static OpenSwath::SpectrumAccessPtr getSpectrumAccessOpenMSPtr(const std::shared_ptr<OpenMS::PeakMap>& exp);
private:
static bool isExperimentCached(const std::shared_ptr<OpenMS::PeakMap>& exp);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/SpectrumAccessOpenMSCached.h | .h | 2,715 | 90 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hannes Roest $
// $Authors: Hannes Roest $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/KERNEL/MSSpectrum.h>
#include <OpenMS/KERNEL/MSChromatogram.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/FORMAT/CachedMzML.h>
#include <OpenMS/OPENSWATHALGO/DATAACCESS/ISpectrumAccess.h>
#include <fstream>
namespace OpenMS
{
/**
@brief An implementation of the Spectrum Access interface using on-disk caching
This class implements the OpenSWATH Spectrum Access interface
(ISpectrumAccess) using the CachedmzML class which is able to read and
write a cached mzML file.
@note This implementation is @a not thread-safe since it keeps internally a
single file access pointer which it moves when accessing a specific
data item. The caller is responsible to ensure that access is performed
atomically.
*/
class OPENMS_DLLAPI SpectrumAccessOpenMSCached :
public OpenSwath::ISpectrumAccess,
public OpenMS::CachedmzML
{
public:
typedef OpenMS::PeakMap MSExperimentType;
typedef OpenMS::MSSpectrum MSSpectrumType;
/**
@brief Constructor, opens the file stream
@param[in] filename The filename of the .mzML file (it is assumed a second
file .mzML.cached exists).
@throws Exception::FileNotFound is thrown if the file is not found
@throws Exception::ParseError is thrown if the file cannot be parsed
*/
explicit SpectrumAccessOpenMSCached(const String& filename);
/**
@brief Destructor
*/
~SpectrumAccessOpenMSCached() override;
/// Copy constructor
SpectrumAccessOpenMSCached(const SpectrumAccessOpenMSCached & rhs);
/// Light clone operator (actual data will not get copied)
std::shared_ptr<OpenSwath::ISpectrumAccess> lightClone() const override;
OpenSwath::SpectrumPtr getSpectrumById(int id) override;
OpenSwath::SpectrumMeta getSpectrumMetaById(int id) const override;
std::vector<std::size_t> getSpectraByRT(double RT, double deltaRT) const override;
size_t getNrSpectra() const override;
SpectrumSettings getSpectraMetaInfo(int id) const;
OpenSwath::ChromatogramPtr getChromatogramById(int id) override;
size_t getNrChromatograms() const override;
ChromatogramSettings getChromatogramMetaInfo(int id) const;
std::string getChromatogramNativeID(int id) const override;
};
} //end namespace
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/SpectrumAccessQuadMZTransforming.h | .h | 1,678 | 59 | // 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/ANALYSIS/OPENSWATH/DATAACCESS/SpectrumAccessTransforming.h>
namespace OpenMS
{
/**
* @brief A transforming m/z wrapper around spectrum access using a quadratic equation.
*
* For each spectrum access, each m/z value is transformed using the equation
* mz = a + b * mz + c * mz^2
*
* This can be used to implement an on-line mass correction for TOF
* instruments (for example).
*
*/
class OPENMS_DLLAPI SpectrumAccessQuadMZTransforming :
public SpectrumAccessTransforming
{
public:
/** @brief Constructor
* @param[in] sptr The spectrum to work on
* @param[in] a Regression parameter 0
* @param[in] b Regression parameter 1
* @param[in] c Regression parameter 2
* @param[in] ppm Whether the transformation should be applied in ppm domain
* (if false, it is applied directly in m/z domain)
*
*/
explicit SpectrumAccessQuadMZTransforming(OpenSwath::SpectrumAccessPtr sptr,
double a, double b, double c, bool ppm);
~SpectrumAccessQuadMZTransforming() override;
std::shared_ptr<OpenSwath::ISpectrumAccess> lightClone() const override;
OpenSwath::SpectrumPtr getSpectrumById(int id) override;
private:
double a_;
double b_;
double c_;
bool ppm_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/SpectrumAccessTransforming.h | .h | 1,401 | 54 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hannes Roest $
// $Authors: Hannes Roest $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/config.h>
#include <OpenMS/OPENSWATHALGO/DATAACCESS/ISpectrumAccess.h>
namespace OpenMS
{
/**
* @brief An abstract base class implementing a transforming wrapper around spectrum access.
*
*/
class OPENMS_DLLAPI SpectrumAccessTransforming :
public OpenSwath::ISpectrumAccess
{
public:
explicit SpectrumAccessTransforming(OpenSwath::SpectrumAccessPtr sptr);
~SpectrumAccessTransforming() override = 0;
std::shared_ptr<ISpectrumAccess> lightClone() const override = 0;
OpenSwath::SpectrumPtr getSpectrumById(int id) override;
OpenSwath::SpectrumMeta getSpectrumMetaById(int id) const override;
std::vector<std::size_t> getSpectraByRT(double RT, double deltaRT) const override;
size_t getNrSpectra() const override;
OpenSwath::ChromatogramPtr getChromatogramById(int id) override;
size_t getNrChromatograms() const override;
std::string getChromatogramNativeID(int id) const override;
protected:
OpenSwath::SpectrumAccessPtr sptr_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/NASequence.h | .h | 17,349 | 584 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Samuel Wein $
// $Authors: Samuel Wein, Timo Sachsenberg, Hendrik Weisser $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CHEMISTRY/EmpiricalFormula.h>
#include <OpenMS/CHEMISTRY/Ribonucleotide.h>
#include <OpenMS/CONCEPT/HashUtils.h>
#include <OpenMS/CONCEPT/Types.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <functional>
#include <iosfwd>
#include <vector>
namespace OpenMS
{
/**
* @brief Representation of a nucleic acid sequence
*
* NASequence represents nucleic acid sequences (RNA) in %OpenMS. Each NASequence consists
* of a vector of pointers to Ribonucleotides as well as RibonucleotideChainEnds representing
* the 5' and 3' ends of the sequence. Each Ribonucleotide has only a single instance.
* These are accessible through RibonucleotideDB. Modified Ribonucleotides are included in RibonucleotideDB
* and are expressed as the Modomics Short name surrounded by brackets when converted to string.
*
* @ingroup Chemistry
*/
class OPENMS_DLLAPI NASequence
{
/**
@brief an enum of all possible fragment ion types
*/
public:
enum NASFragmentType
{ //< NB: Not all fragments types are valid for all residue types, this class should probably get split
Full = 0, ///< with N-terminus and C-terminus
Internal, ///< internal, without any termini
FivePrime, ///< only 5' terminus
ThreePrime, ///< only 3' terminus
AIon, ///< MS:1001229 N-terminus up to the C-alpha/carbonyl carbon bond
BIon, ///< MS:1001224 N-terminus up to the peptide bond
CIon, ///< MS:1001231 N-terminus up to the amide/C-alpha bond
XIon, ///< MS:1001228 amide/C-alpha bond up to the C-terminus
YIon, ///< MS:1001220 peptide bond up to the C-terminus
ZIon, ///< MS:1001230 C-alpha/carbonyl carbon bond
Precursor, ///< MS:1001523 Precursor ion
BIonMinusH20, ///< MS:1001222 b ion without water
YIonMinusH20, ///< MS:1001223 y ion without water
BIonMinusNH3, ///< MS:1001232 b ion without ammonia
YIonMinusNH3, ///< MS:1001233 y ion without ammonia
NonIdentified, ///< MS:1001240 Non-identified ion
Unannotated, ///< no stored annotation
WIon, ///< W ion, added for nucleic acid support
AminusB, ///< A ion with base loss, added for nucleic acid support
DIon, ///< D ion, added for nucleic acid support
SizeOfNASFragmentType
};
using ConstRibonucleotidePtr = const Ribonucleotide*;
class Iterator;
/** @brief ConstIterator of NASequence class.
*
* References to the pointers are returned dereferenced.
* So we don't need to write (*iterator)->getCode(), but can simply use iterator->getCode().
*/
class OPENMS_DLLAPI ConstIterator
{
public:
typedef Ribonucleotide value_type;
typedef const value_type& const_reference;
typedef value_type& reference;
typedef const value_type* const_pointer;
typedef std::vector<const value_type*>::difference_type difference_type;
typedef const value_type* pointer;
typedef std::random_access_iterator_tag iterator_category;
/** @name Constructors and destructors
*/
//@{
/// default constructor
ConstIterator() = default;
/// detailed constructor with pointer to the vector and offset position
ConstIterator(const std::vector<const Ribonucleotide*>* vec_ptr, difference_type position)
{
vector_ = vec_ptr;
position_ = position;
}
/// copy constructor
ConstIterator(const ConstIterator& rhs) : vector_(rhs.vector_), position_(rhs.position_)
{
}
/// copy constructor from Iterator
ConstIterator(const NASequence::Iterator& rhs) : vector_(rhs.vector_), position_(rhs.position_)
{
}
/// destructor
virtual ~ConstIterator()
{
}
//@}
/// assignment operator
ConstIterator& operator=(const ConstIterator& rhs)
{
if (this != &rhs)
{
position_ = rhs.position_;
vector_ = rhs.vector_;
}
return *this;
}
/** @name Operators
*/
//@{
/// dereference operator
const_reference operator*() const
{
return *(*vector_)[position_];
}
/// dereference operator
const_pointer operator->() const
{
return (*vector_)[position_];
}
/// forward jump operator
const ConstIterator operator+(difference_type diff) const
{
return ConstIterator(vector_, position_ + diff);
}
difference_type operator-(ConstIterator rhs) const
{
return position_ - rhs.position_;
}
/// backward jump operator
const ConstIterator operator-(difference_type diff) const
{
return ConstIterator(vector_, position_ - diff);
}
/// equality comparator
bool operator==(const ConstIterator& rhs) const
{
return (std::tie(vector_, position_) == std::tie(rhs.vector_, rhs.position_));
}
/// inequality operator
bool operator!=(const ConstIterator& rhs) const
{
return !(operator==(rhs));
}
/// increment operator
ConstIterator& operator++()
{
++position_;
return *this;
}
/// decrement operator
ConstIterator& operator--()
{
--position_;
return *this;
}
//@}
protected:
// pointer to the vector
const std::vector<const Ribonucleotide*>* vector_;
// position in the vector
difference_type position_;
};
/** @brief Iterator of NASequence class.
*
* References to the pointers are returned dereferenced.
* So we don't need to write (*iterator)->getCode(), but can simply use iterator->getCode().
*/
class OPENMS_DLLAPI Iterator
{
public:
friend class NASequence::ConstIterator;
typedef Ribonucleotide value_type;
typedef const value_type& const_reference;
typedef value_type& reference;
typedef const value_type* const_pointer;
typedef const value_type* pointer;
typedef std::vector<const value_type*>::difference_type difference_type;
/** @name Constructors and destructors
*/
//@{
Iterator() = default;
/// detailed constructor with pointer to the vector and offset position
Iterator(std::vector<const Ribonucleotide*>* vec_ptr, difference_type position)
{
vector_ = vec_ptr;
position_ = position;
}
/// copy constructor
Iterator(const Iterator& rhs) : vector_(rhs.vector_), position_(rhs.position_)
{
}
/// destructor
virtual ~Iterator()
{
}
//@}
/// assignment operator
Iterator& operator=(const Iterator& rhs)
{
if (this != &rhs)
{
position_ = rhs.position_;
vector_ = rhs.vector_;
}
return *this;
}
/** @name Operators
*/
//@{
/// dereference operator
const_reference operator*() const
{
return *(*vector_)[position_];
}
/// dereference operator
const_pointer operator->() const
{
return (*vector_)[position_];
}
/// mutable dereference operator
pointer operator->()
{
return (*vector_)[position_];
}
/// forward jump operator
const Iterator operator+(difference_type diff) const
{
return Iterator(vector_, position_ + diff);
}
difference_type operator-(Iterator rhs) const
{
return position_ - rhs.position_;
}
/// backward jump operator
const Iterator operator-(difference_type diff) const
{
return Iterator(vector_, position_ - diff);
}
/// equality comparator
bool operator==(const Iterator& rhs) const
{
return (std::tie(vector_, position_) == std::tie(rhs.vector_, rhs.position_));
}
/// inequality operator
bool operator!=(const Iterator& rhs) const
{
return !this->operator==(rhs);
}
/// increment operator
Iterator& operator++()
{
++position_;
return *this;
}
/// decrement operator
Iterator& operator--()
{
--position_;
return *this;
}
//@}
protected:
std::vector<const Ribonucleotide*>* vector_;
// position in the vector
difference_type position_;
};
public:
/*
* Default constructors and assignment operators.
*/
NASequence() = default; /// default constructor
NASequence(const NASequence&) = default; ///< Copy constructor
NASequence(NASequence&&) = default; ///< Move constructor
NASequence& operator=(const NASequence&) & = default; ///< Copy assignment operator
NASequence& operator=(NASequence&&) & = default; ///< Move assignment operator
/// full constructor
NASequence(std::vector<const Ribonucleotide*> s, const RibonucleotideChainEnd* five_prime, const RibonucleotideChainEnd* three_prime);
virtual ~NASequence() = default; /// destructor
bool operator==(const NASequence& rhs) const; ///< element-wise equality
bool operator!=(const NASequence& rhs) const; ///< not quality
bool operator<(const NASequence& rhs) const; ///< less operator
/// getter / setter for sequence
void setSequence(const std::vector<const Ribonucleotide*>& seq);
const std::vector<const Ribonucleotide*>& getSequence() const
{
return seq_;
}
std::vector<const Ribonucleotide*>& getSequence()
{
return seq_;
}
/// getter / setter for ribonucleotide elements (easily wrapped using pyOpenMS)
void set(size_t index, const Ribonucleotide* r);
const Ribonucleotide* get(size_t index)
{
return seq_[index];
}
/// getter / setter for sequence elements (C++ container style)
inline const Ribonucleotide*& operator[](size_t index)
{
return seq_[index];
}
inline const Ribonucleotide* const& operator[](size_t index) const
{
return seq_[index];
}
bool empty() const;
size_t size() const;
void clear();
/// 5' and 3' modifications
bool hasFivePrimeMod() const;
void setFivePrimeMod(const RibonucleotideChainEnd* r);
const RibonucleotideChainEnd* getFivePrimeMod() const;
bool hasThreePrimeMod() const;
void setThreePrimeMod(const RibonucleotideChainEnd* r);
const RibonucleotideChainEnd* getThreePrimeMod() const;
/// iterators
inline Iterator begin()
{
return Iterator(&seq_, 0);
}
inline ConstIterator begin() const
{
return ConstIterator(&seq_, 0);
}
inline Iterator end()
{
return Iterator(&seq_, (Int)seq_.size());
}
inline ConstIterator end() const
{
return ConstIterator(&seq_, (Int)seq_.size());
}
inline ConstIterator cbegin() const
{
return ConstIterator(&seq_, 0);
}
inline ConstIterator cend() const
{
return ConstIterator(&seq_, (Int)seq_.size());
}
/// utility functions
/**
* @brief Get the Monoisotopic Weight of a NASequence. NB returns the uncharged mass + or - proton masses to match the charge param
*
* @param[in] type fragment type to return
* @param[in] charge how many protons to add or subtract, NB the mass returned is the UNCHARGED MASS
*
* @return double
*/
double getMonoWeight(NASFragmentType type = Full, Int charge = 0) const;
/**
* @brief Get the Average Weight of a NASequence. NB returns the uncharged mass + or - proton masses to match the charge param
*
* @param[in] type fragment type to return
* @param[out] charge how many protons to add or subtract, NB the mass returned is the UNCHARGED MASS
*
* @return double
*/
double getAverageWeight(NASFragmentType type = Full, Int charge = 0) const;
/**
* @brief Get the formula for a NASequence
*
* @param[in] type fragment type for formula
* @param[out] charge how many H to add or subtract
*
* @return EmpiricalFormula
*/
EmpiricalFormula getFormula(NASFragmentType type = Full, Int charge = 0) const;
/**
* @brief Return sequence prefix of the given length (not end index!)
*
* @param[in] length
* @return NASequence
*/
NASequence getPrefix(Size length) const;
/**
* @brief Return sequence suffix of the given length (not start index!)
*
* @param[in] length
* @return NASequence
*/
NASequence getSuffix(Size length) const;
/**
* @brief Return subsequence with given starting position and length
*
* @param[in] start
* @param[in] length
*
* @return NASequence
*/
NASequence getSubsequence(Size start = 0, Size length = Size(-1)) const;
/**
@brief create NASequence object by parsing an OpenMS string
@param[in] s Input string
@throws Exception::ParseError if an invalid string representation of a nucleic acid sequence is passed
*/
static NASequence fromString(const String& s);
/** @name Stream operators
writes a NASequence to an output stream
*/
friend OPENMS_DLLAPI std::ostream& operator<<(std::ostream& os, const NASequence& seq);
/**
@brief create NASequence object by parsing a C string (character array)
@param[in] s Input string
@throws Exception::ParseError if an invalid string representation of a nucleic acid sequence is passed
*/
static NASequence fromString(const char* s);
std::string toString() const;
private:
// TODO: query RNA / DNA depending on type
static void parseString_(const String& s, NASequence& nas);
/**
@brief Parses modifications in square brackets
@param[in] str_it Current position in the string to be parsed
@param[in] str Full input string
@param[in,out] nas Current AASequence object (will be modified with the correct ribo added)
@return Position at which to continue parsing
*/
// TODO: query RNA / DNA depending on type
static String::ConstIterator parseMod_(const String::ConstIterator str_it, const String& str, NASequence& nas);
std::vector<const Ribonucleotide*> seq_;
const RibonucleotideChainEnd* five_prime_ = nullptr;
const RibonucleotideChainEnd* three_prime_ = nullptr;
};
} // namespace OpenMS
// Hash function specialization for NASequence
// Placed in std namespace to allow use with std::unordered_map/set
namespace std
{
/**
* @brief Hash function for OpenMS::NASequence.
*
* Computes a hash based on the ribonucleotide sequence (codes),
* and the 5' and 3' terminal modifications.
*
* Design decisions:
* - Uses ribonucleotide codes instead of pointers for portability
* - Includes 5' and 3' terminal modification codes
* - Hash is consistent with operator== when all Ribonucleotide pointers originate
* from RibonucleotideDB (the singleton guarantees identical codes map to identical pointers)
*
* @pre All Ribonucleotide* in the sequence must originate from RibonucleotideDB.
* If pointers from different sources with identical codes are used,
* hash equality may not imply object equality (violating hash contract).
*
* @note Hash is reproducible across process runs for equal sequences.
*/
template<>
struct hash<OpenMS::NASequence>
{
std::size_t operator()(const OpenMS::NASequence& seq) const noexcept
{
std::size_t seed = 0;
// Hash each ribonucleotide in the sequence
for (const auto& ribo : seq)
{
// Hash the code (stable identifier)
const OpenMS::String& code = ribo.getCode();
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(code));
}
// Hash 5' terminal modification if present
const OpenMS::RibonucleotideChainEnd* five_prime = seq.getFivePrimeMod();
if (five_prime != nullptr)
{
// Use a different seed offset for 5' to distinguish from 3'
std::size_t five_hash = OpenMS::fnv1a_hash_string(five_prime->getCode());
OpenMS::hash_combine(seed, five_hash ^ 0x355052494dULL); // "5PRIM" in hex-like
}
// Hash 3' terminal modification if present
const OpenMS::RibonucleotideChainEnd* three_prime = seq.getThreePrimeMod();
if (three_prime != nullptr)
{
// Use a different seed offset for 3'
std::size_t three_hash = OpenMS::fnv1a_hash_string(three_prime->getCode());
OpenMS::hash_combine(seed, three_hash ^ 0x335052494dULL); // "3PRIM" in hex-like
}
return seed;
}
};
} // namespace std
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/DigestionEnzymeDB.h | .h | 7,803 | 245 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Xiao Liang $
// $Authors: Xiao Liang, Chris Bielow $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CHEMISTRY/DigestionEnzyme.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/FORMAT/ParamXMLFile.h>
#include <OpenMS/SYSTEM/File.h>
#include <set>
#include <map>
namespace OpenMS
{
/**
@ingroup Chemistry
@brief Digestion enzyme database (base class)
Template parameters:
@p DigestionEnzymeType should be a subclass of DigestionEnzyme.
@p InstanceType should be a subclass of DigestionEnzymeDB ("Curiously Recurring Template Pattern", see https://stackoverflow.com/a/34519373).
*/
template<typename DigestionEnzymeType, typename InstanceType> class DigestionEnzymeDB
{
public:
/** @name Typedefs
*/
//@{
typedef typename std::set<const DigestionEnzymeType*>::const_iterator ConstEnzymeIterator;
typedef typename std::set<const DigestionEnzymeType*>::iterator EnzymeIterator;
//@}
/// this member function serves as a replacement of the constructor
static InstanceType* getInstance()
{
static InstanceType* db_ = nullptr;
if (db_ == nullptr)
{
db_ = new InstanceType;
}
return db_;
}
/** @name Constructors and Destructors
*/
//@{
/// destructor
virtual ~DigestionEnzymeDB()
{
for (ConstEnzymeIterator it = const_enzymes_.begin(); it != const_enzymes_.end(); ++it)
{
delete *it;
}
}
//@}
/** @name Accessors
*/
//@{
/// returns a pointer to the enzyme with name (supports synonym names)
/// @throw Exception::ElementNotFound if enzyme is unknown
/// @note enzymes are registered in regular and in toLowercase() style, if unsure use toLowercase
const DigestionEnzymeType* getEnzyme(const String& name) const
{
auto pos = enzyme_names_.find(name);
if (pos == enzyme_names_.end())
{
throw Exception::ElementNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, name);
}
return pos->second;
}
/// returns a pointer to the enzyme with cleavage regex
/// @throw Exception::IllegalArgument if enzyme regex is unregistered.
const DigestionEnzymeType* getEnzymeByRegEx(const String& cleavage_regex) const
{
if (!hasRegEx(cleavage_regex))
{
// @TODO: why does this use a different exception than "getEnzyme"?
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
String("Enzyme with regex " + cleavage_regex + " was not registered in Enzyme DB, register first!").c_str());
}
return enzyme_regex_.at(cleavage_regex);
}
/// returns all the enzyme names (does NOT include synonym names)
void getAllNames(std::vector<String>& all_names) const
{
all_names.clear();
for (ConstEnzymeIterator it = const_enzymes_.begin(); it != const_enzymes_.end(); ++it)
{
all_names.push_back((*it)->getName());
}
}
//@}
/** @name Predicates
*/
//@{
/// returns true if the db contains a enzyme with the given name (supports synonym names)
bool hasEnzyme(const String& name) const
{
return (enzyme_names_.find(name) != enzyme_names_.end());
}
/// returns true if the db contains a enzyme with the given regex
bool hasRegEx(const String& cleavage_regex) const
{
return (enzyme_regex_.find(cleavage_regex) != enzyme_regex_.end());
}
/// returns true if the db contains the enzyme of the given pointer
bool hasEnzyme(const DigestionEnzymeType* enzyme) const
{
return (const_enzymes_.find(enzyme) != const_enzymes_.end() );
}
//@}
/** @name Iterators
*/
//@{
inline ConstEnzymeIterator beginEnzyme() const { return const_enzymes_.begin(); } // we only allow constant iterators -- this DB is not meant to be modifiable
inline ConstEnzymeIterator endEnzyme() const { return const_enzymes_.end(); }
//@}
protected:
DigestionEnzymeDB(const String& db_file = "")
{
if (!db_file.empty())
{
readEnzymesFromFile_(db_file);
}
}
///copy constructor
DigestionEnzymeDB(const DigestionEnzymeDB& enzymes_db) = delete;
//@}
/** @name Assignment
*/
//@{
/// assignment operator
DigestionEnzymeDB& operator=(const DigestionEnzymeDB& enzymes_db) = delete;
//@}
/// reads enzymes from the given file
void readEnzymesFromFile_(const String& filename)
{
String file = File::find(filename);
Param param;
ParamXMLFile().load(file, param);
if (param.empty()) return;
std::vector<String> split;
String(param.begin().getName()).split(':', split);
if (split[0] != "Enzymes")
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, split[0], "name 'Enzymes' expected");
}
try
{
std::map<String, String> values;
String previous_enzyme = split[1];
// this iterates over all the "ITEM" elements in the XML file:
for (Param::ParamIterator it = param.begin(); it != param.end(); ++it)
{
String(it.getName()).split(':', split);
if (split[0] != "Enzymes") break; // unexpected content in the XML file
if (split[1] != previous_enzyme)
{
// add enzyme and reset:
addEnzyme_(parseEnzyme_(values));
previous_enzyme = split[1];
values.clear();
}
values[it.getName()] = String(it->value.toString());
}
// add last enzyme
addEnzyme_(parseEnzyme_(values));
}
catch (Exception::BaseException& e)
{
throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, e.what(), "");
}
}
/// parses an enzyme, given the key/value pairs from an XML file
const DigestionEnzymeType* parseEnzyme_(std::map<String, String>& values) const
{
DigestionEnzymeType* enzy_ptr = new DigestionEnzymeType();
for (std::map<String, String>::iterator it = values.begin(); it != values.end(); ++it)
{
const String& key = it->first;
const String& value = it->second;
if (!enzy_ptr->setValueFromFile(key, value))
{
OPENMS_LOG_ERROR << "Error while parsing enzymes file: unknown key '" << key << "' with value '" << value << "'" << std::endl;
}
}
return enzy_ptr;
}
/// add to internal data; also update indices for search by name and regex
void addEnzyme_(const DigestionEnzymeType* enzyme)
{
// add to internal storage
const_enzymes_.insert(enzyme);
// add to internal indices (by name and its synonyms)
String name = enzyme->getName();
enzyme_names_[name] = enzyme;
enzyme_names_[name.toLower()] = enzyme;
for (std::set<String>::const_iterator it = enzyme->getSynonyms().begin(); it != enzyme->getSynonyms().end(); ++it)
{
enzyme_names_[*it] = enzyme;
}
// ... and by regex
if (enzyme->getRegEx() != "")
{
enzyme_regex_[enzyme->getRegEx()] = enzyme;
}
return;
}
std::map<String, const DigestionEnzymeType*> enzyme_names_; ///< index by names
std::map<String, const DigestionEnzymeType*> enzyme_regex_; ///< index by regex
std::set<const DigestionEnzymeType*> const_enzymes_; ///< set of enzymes
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/RibonucleotideDB.h | .h | 3,490 | 104 | // 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/CHEMISTRY/Ribonucleotide.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <memory>
#include <unordered_map>
namespace OpenMS
{
/** @ingroup Chemistry
@brief Database of ribonucleotides (modified and unmodified)
The information in this class comes primarily from the Modomics database (http://modomics.genesilico.pl/modifications/) and is read from a tab-separated text file in @p data/CHEMISTRY/Modomics.tsv.
In addition, OpenMS-specific (as well as potentially user-supplied) modification definitions are read from the file @p data/CHEMISTRY/Custom_RNA_modifications.tsv.
*/
class OPENMS_DLLAPI RibonucleotideDB final
{
public:
using ConstRibonucleotidePtr = const Ribonucleotide *;
/// const iterator type definition
typedef std::vector<std::unique_ptr<Ribonucleotide>>::const_iterator ConstIterator;
/// replacement for constructor (singleton pattern)
static RibonucleotideDB* getInstance();
/// destructor
~RibonucleotideDB() = default;
/// copy constructor not available
RibonucleotideDB(const RibonucleotideDB& other) = delete;
/// assignment operator not available
RibonucleotideDB& operator=(const RibonucleotideDB& other) = delete;
/// Const iterator to beginning of database
inline ConstIterator begin() const
{
return ribonucleotides_.begin();
}
/// Const iterator to end of database
inline ConstIterator end() const
{
return ribonucleotides_.end();
}
/**
@brief Get a ribonucleotide by its code (short name)
@throw Exception::ElementNotFound if nothing was found
*/
ConstRibonucleotidePtr getRibonucleotide(const std::string& code);
/**
@brief Get the ribonucleotide with the longest code that matches a prefix of @p seq
@throw Exception::ElementNotFound if nothing was found
*/
ConstRibonucleotidePtr getRibonucleotidePrefix(const std::string& seq);
/**
@brief Get the alternatives for an ambiguous modification code
@throw Exception::ElementNotFound if nothing was found
*/
std::pair<ConstRibonucleotidePtr, ConstRibonucleotidePtr> getRibonucleotideAlternatives(const std::string& code);
protected:
/// default constructor
RibonucleotideDB();
/// read (modified) nucleotides from input file
void readFromFile_(const std::string& path);
/// read from a newer version of Modomics that uses a JSON file
void readFromJSON_(const std::string& path);
/// create a (modified) nucleotide from an input row
const std::unique_ptr<Ribonucleotide> parseRow_(const std::string& row, Size line_count);
/// list of known (modified) nucleotides
std::vector<std::unique_ptr<Ribonucleotide>> ribonucleotides_;
/// mapping of codes (short names) to indexes into @p ribonucleotides_
std::unordered_map<std::string, Size> code_map_;
/// mapping of ambiguity codes to the alternatives they represent
std::map<std::string, std::pair<ConstRibonucleotidePtr, ConstRibonucleotidePtr>> ambiguity_map_;
Size max_code_length_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/DigestionEnzyme.h | .h | 4,519 | 168 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Xiao Liang $
// $Authors: Xiao Liang $
// --------------------------------------------------------------------------
//
#pragma once
#include <OpenMS/CHEMISTRY/EmpiricalFormula.h>
#include <OpenMS/CONCEPT/HashUtils.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <functional>
#include <iosfwd>
#include <set>
#include <vector>
namespace OpenMS
{
/**
@ingroup Chemistry
@brief Base class for digestion enzymes
*/
class OPENMS_DLLAPI DigestionEnzyme
{
public:
/** @name Constructors
*/
//@{
/// Copy constructor
DigestionEnzyme(const DigestionEnzyme&) = default;
/// Move constructor
DigestionEnzyme(DigestionEnzyme&&) = default;
/// Detailed constructor
explicit DigestionEnzyme(const String& name,
const String& cleavage_regex,
const std::set<String>& synonyms = std::set<String>(),
String regex_description = "");
/// Detailed constructor 2
explicit DigestionEnzyme(const String& name,
String cut_before,
const String& nocut_after = "",
String sense = "C",
const std::set<String>& synonyms = std::set<String>(),
String regex_description = "");
/// Destructor
virtual ~DigestionEnzyme();
//@}
/** @name Assignment
*/
//@{
/// Assignment operator
DigestionEnzyme& operator=(const DigestionEnzyme&) = default;
/// Move assignment operator
DigestionEnzyme& operator=(DigestionEnzyme&&) & = default;
//@}
/** Accessors
*/
//@{
/// sets the name of the enzyme
void setName(const String& name);
/// returns the name of the enzyme
const String& getName() const;
/// sets the synonyms
void setSynonyms(const std::set<String>& synonyms);
/// adds a synonym
void addSynonym(const String& synonym);
/// returns the synonyms
const std::set<String>& getSynonyms() const;
/// sets the cleavage regex
void setRegEx(const String& cleavage_regex);
/// returns the cleavage regex
const String& getRegEx() const;
/// sets the regex description
void setRegExDescription(const String& value);
/// returns the regex description
const String& getRegExDescription() const;
//@}
/** @name Predicates
*/
//@{
/// equality operator
bool operator==(const DigestionEnzyme& enzyme) const;
/// inequality operator
bool operator!=(const DigestionEnzyme& enzyme) const;
/// equality operator for regex
bool operator==(const String& cleavage_regex) const;
/// equality operator for regex
bool operator!=(const String& cleavage_regex) const;
/// order operator
bool operator<(const DigestionEnzyme& enzyme) const;
//@}
/**
@brief Set the value of a member variable based on an entry from an input file
Returns whether the key was recognized and the value set successfully.
*/
virtual bool setValueFromFile(const String& key, const String& value);
/// ostream iterator to write the enzyme to a stream
friend OPENMS_DLLAPI std::ostream& operator<<(std::ostream& os, const DigestionEnzyme& enzyme);
protected:
/// default constructor
DigestionEnzyme();
// basic
String name_;
String cleavage_regex_;
std::set<String> synonyms_;
String regex_description_;
};
OPENMS_DLLAPI std::ostream& operator<<(std::ostream& os, const DigestionEnzyme& enzyme);
} // namespace OpenMS
namespace std
{
/// std::hash specialization for DigestionEnzyme
template<>
struct hash<OpenMS::DigestionEnzyme>
{
std::size_t operator()(const OpenMS::DigestionEnzyme& enzyme) const noexcept
{
std::size_t seed = OpenMS::fnv1a_hash_string(enzyme.getName());
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(enzyme.getRegEx()));
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(enzyme.getRegExDescription()));
// Hash the synonyms set
for (const auto& syn : enzyme.getSynonyms())
{
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(syn));
}
return seed;
}
};
} // namespace std
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/AASequence.h | .h | 26,816 | 743 | // 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, Timo Sachsenberg $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CHEMISTRY/EmpiricalFormula.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/CONCEPT/Types.h>
#include <OpenMS/CONCEPT/HashUtils.h>
#include <OpenMS/CHEMISTRY/Residue.h>
#include <OpenMS/CHEMISTRY/ResidueModification.h>
#include <vector>
#include <iosfwd>
#include <map>
#include <functional>
namespace OpenMS
{
/**
@brief Representation of a peptide/protein sequence
This class represents amino acid sequences in %OpenMS. An AASequence
instance primarily contains a sequence of residues. The sequence is
represented as a vector of pointers to instances of Residue. Each amino
acid has only one instance, which is accessible using the ResidueDB
instance (singleton).
To create an AASequence instance for a specific amino acid sequence, use
the AASequence::fromString function. For example,
<tt>AASequence::fromString(".DFPIANGER.")</tt> produces an instance of
AASequence for the peptide "DFPIANGER". Please note that both the N- and
the C-terminal are explicitly represented by dots.
A critical property of amino acid sequences is that they can be modified.
Which means that one or more amino acids are chemically modified, e.g.
oxidized. This is represented via Residue instances which carry a
ResidueModification object. This is also handled in the ResidueDB.
Modifications are specified using a unique string identifier present in
the ModificationsDB in round brackets after the modified amino acid or by
providing the mass of the residue in square brackets. For example
<tt>AASequence::fromString(".DFPIAM(Oxidation)GER.")</tt> creates an
instance of the peptide "DFPIAMGER" with an oxidized methionine
(<tt>AASequence::fromString(".DFPIAM(UniMod:35)GER.")</tt>,
<tt>AASequence::fromString(".DFPIAM[+16]GER.")</tt> and
<tt>AASequence::fromString(".DFPIAM[147]GER.")</tt> are all equivalent).
N- and C-terminal modifications are represented by brackets to the right
of the dots terminating the sequence. For example,
<tt>".(Dimethyl)DFPIAMGER."</tt> and <tt>".DFPIAMGER.(Label:18O(2))"</tt>
represent the labelling of the N- and C-terminus respectively, but
<tt>".DFPIAMGER(Phospho)."</tt> will be interpreted as a phosphorylation
of the last arginine at its side chain.
Note there is a subtle difference between
<tt>AASequence::fromString(".DFPIAM[+16]GER.")</tt> and
<tt>AASequence::fromString(".DFPIAM[+15.9949]GER.")</tt> -- while the
former will try to find the @e first modification matching to a mass
difference of 16 +/- 0.5, the latter will try to find the @e closest
matching modification to the exact mass. This usually gives the intended
results while the first approach may not.
Arbitrary/unknown amino acids (usually due to an unknown modification)
can be specified using tags preceded by X: "X[weight]". This indicates a
new amino acid ("X") with the specified weight, e.g. "RX[148.5]T"". Note
that this tag does not alter the amino acids to the left (R) or right
(T). Rather, X represents an amino acid on its own. Be careful when
converting such AASequence objects to an EmpiricalFormula using
getFormula(), as tags will not be considered in this case (there exists
no formula for them). However, they have an influence on getMonoWeight()
and getAverageWeight()!
@note For C/N terminal modifications, the absolute mass is assumed to be
1 (H) for the N-terminus and 17 (OH) for the C-terminus, therefore a
modification specified as absolute n[43]PEPTIDE would translate to
n[+42]PEPTIDE using relative masses. Note that there can be ambiguity in
cases where the loss includes the terminal amino acids.
@ingroup Chemistry
*/
class OPENMS_DLLAPI AASequence final
{
public:
class Iterator;
/** @brief ConstIterator for AASequence
AASequence constant iterator
*/
class OPENMS_DLLAPI ConstIterator final
{
public:
// TODO Iterator constructor for ConstIterator
typedef const Residue& const_reference;
typedef Residue& reference;
typedef const Residue* const_pointer;
typedef std::vector<const Residue*>::difference_type difference_type;
typedef Residue value_type;
typedef const Residue* pointer;
typedef std::random_access_iterator_tag iterator_category;
/** @name Constructors and destructors
*/
//@{
/// default constructor
ConstIterator() = default;
/// detailed constructor with pointer to the vector and offset position
ConstIterator(const std::vector<const Residue*>* vec_ptr, difference_type position)
: vector_{vec_ptr},
position_{position}
{
}
/// copy constructor
ConstIterator(const ConstIterator& rhs) = default;
/// copy constructor from Iterator
ConstIterator(const AASequence::Iterator& rhs) :
vector_(rhs.vector_),
position_(rhs.position_)
{
}
/// destructor
~ConstIterator() = default;
//@}
/// assignment operator
ConstIterator& operator=(const ConstIterator& rhs) = default;
/** @name Operators
*/
//@{
/// dereference operator
const_reference operator*() const
{
return *(*vector_)[position_];
}
/// dereference operator
const_pointer operator->() const
{
return (*vector_)[position_];
}
/// forward jump operator
const ConstIterator operator+(difference_type diff) const
{
return ConstIterator(vector_, position_ + diff);
}
difference_type operator-(ConstIterator rhs) const
{
return position_ - rhs.position_;
}
/// backward jump operator
const ConstIterator operator-(difference_type diff) const
{
return ConstIterator(vector_, position_ - diff);
}
/// equality comparator
bool operator==(const ConstIterator& rhs) const
{
return vector_ == rhs.vector_ && position_ == rhs.position_;
}
/// inequality operator
bool operator!=(const ConstIterator& rhs) const
{
return vector_ != rhs.vector_ || position_ != rhs.position_;
}
/// increment operator
ConstIterator& operator++()
{
++position_;
return *this;
}
/// decrement operator
ConstIterator& operator--()
{
--position_;
return *this;
}
//@}
protected:
// pointer to the AASequence vector
const std::vector<const Residue*>* vector_ {};
// position in the AASequence vector
difference_type position_ {};
};
/** @brief Iterator class for AASequence
Mutable iterator for AASequence
*/
class OPENMS_DLLAPI Iterator final
{
public:
friend class AASequence::ConstIterator;
typedef const Residue& const_reference;
typedef Residue& reference;
typedef const Residue* const_pointer;
typedef const Residue* pointer;
typedef std::vector<const Residue*>::difference_type difference_type;
/** @name Constructors and destructors
*/
//@{
/// default constructor
Iterator() = default;
/// detailed constructor with pointer to the vector and offset position
Iterator(std::vector<const Residue*>* vec_ptr, difference_type position)
: vector_ {vec_ptr},
position_{position}
{
}
/// copy constructor
Iterator(const Iterator& rhs) = default;
/// destructor
~Iterator() = default;
//@}
/// assignment operator
Iterator& operator=(const Iterator& rhs)
{
if (this != &rhs)
{
position_ = rhs.position_;
vector_ = rhs.vector_;
}
return *this;
}
/** @name Operators
*/
//@{
/// dereference operator
const_reference operator*() const
{
return *(*vector_)[position_];
}
/// dereference operator
const_pointer operator->() const
{
return (*vector_)[position_];
}
/// mutable dereference operator
pointer operator->()
{
return (*vector_)[position_];
}
/// forward jump operator
const Iterator operator+(difference_type diff) const
{
return Iterator(vector_, position_ + diff);
}
difference_type operator-(Iterator rhs) const
{
return position_ - rhs.position_;
}
/// backward jump operator
const Iterator operator-(difference_type diff) const
{
return Iterator(vector_, position_ - diff);
}
/// equality comparator
bool operator==(const Iterator& rhs) const
{
return vector_ == rhs.vector_ && position_ == rhs.position_;
}
/// inequality operator
bool operator!=(const Iterator& rhs) const
{
return vector_ != rhs.vector_ || position_ != rhs.position_;
}
/// increment operator
Iterator& operator++()
{
++position_;
return *this;
}
/// decrement operator
Iterator& operator--()
{
--position_;
return *this;
}
//@}
protected:
// pointer to the AASequence vector
std::vector<const Residue*>* vector_ {};
// position in the AASequence vector
difference_type position_ {};
};
/** @name Constructors and Destructors
*/
//@{
/// Default constructor
AASequence() = default;
/// Copy constructor
AASequence(const AASequence&) = default;
/// Move constructor
AASequence(AASequence&&) = default;
/// Destructor
~AASequence() = default;
//@}
/// Assignment operator
AASequence& operator=(const AASequence&) = default;
/// Move assignment operator
AASequence& operator=(AASequence&&) = default;
/// check if sequence is empty
bool empty() const;
/** @name Accessors
*/
//@{
/**
@brief returns the peptide as string with modifications embedded in brackets
Uses round brackets when possible (id is known) or square brackets for
unknown modifications where only the mass is known.
i.e.: .[43]PEPC(Carbamidomethyl)PEPM[147]PEPR.[-1]
@note For unknown modifications, the function will attempt to use the
exact same format used in the input
*/
String toString() const;
/// returns the peptide as string without any modifications or (e.g., "PEPTIDER")
String toUnmodifiedString() const;
/**
@brief returns the peptide as string with UniMod-style modifications embedded in brackets
Annotates modification with UniMod identifier (when identifier is
known) and uses square brackets for unknown modifications (only mass is known).
i.e.: .[43]PEPC(UniMod:4)PEPM[147]PEPR.[16]
*/
String toUniModString() const;
/**
@brief create a TPP compatible string of the modified sequence using bracket notation.
Instead of using the modification names, it writes the modification masses in brackets
i.e.:
- n[43]PEPC[160]PEPM[147]PEPRc[16]
- n[+42]PEPC[+57]PEPM[+16]PEPRc[-1]
will be produced, depending on whether relative or absolute masses are used.
@param[in] integer_mass Whether to use integer masses in brackets (default is true, if false, accurate masses will be written)
@param[in] mass_delta Whether to write absolute masses M[147] or relative mass deltas M[+16] (default is false)
@param[in] fixed_modifications Optional list of fixed modifications that should not be added to the output (they are considered to be present in all cases)
@note Using integer masses may mean that there could be multiple modifications mapping to the same mass
*/
String toBracketString(bool integer_mass = true,
bool mass_delta = false,
const std::vector<String> & fixed_modifications = std::vector<String>()) const;
/// set the modification of the residue at position index.
/// if an empty string is passed replaces the residue with its unmodified version
void setModification(Size index, const String& modification);
/// sets the modification of AA at @p index by providing an already, potentially modified residue
void setModification(Size index, const Residue* modification);
/// sets the modification of AA at @p index by providing a pointer to a ResidueModification object found in the ModificationsDB
void setModification(Size index, const ResidueModification* modification);
/// sets the modification of AA at @p index by providing a ResidueModification object
/// stricter than just looking for the name and adds the Modification to the DB if not present
void setModification(Size index, const ResidueModification& modification);
/// modifies the residue at @p index in the sequence and potentially in the ResidueDB
void setModificationByDiffMonoMass(Size index, double diffMonoMass);
/// sets the N-terminal modification (by lookup in the mod names of the ModificationsDB)
/// throws if nothing is found (since the name is not enough information to create a new mod)
void setNTerminalModification(const String& modification);
/// sets the N-terminal modification
void setNTerminalModification(const ResidueModification* modification);
/// sets the N-terminal modification (copies and adds to database if not present)
void setNTerminalModification(const ResidueModification& mod);
/// sets the N-terminal modification by the monoisotopic mass difference it introduces (creates a "user-defined" mod if not present)
void setNTerminalModificationByDiffMonoMass(double diffMonoMass, bool protein_term);
/// returns the name (ID) of the N-terminal modification, or an empty string if none is set
const String& getNTerminalModificationName() const;
/// returns a pointer to the N-terminal modification, or zero if none is set
const ResidueModification* getNTerminalModification() const;
/// sets the C-terminal modification (by lookup in the mod names of the ModificationsDB)
/// throws if nothing is found (since the name is not enough information to create a new mod)
void setCTerminalModification(const String& modification);
/// sets the C-terminal modification (must be present in the database)
void setCTerminalModification(const ResidueModification* modification);
/// sets the C-terminal modification (copies and adds to database if not present)
void setCTerminalModification(const ResidueModification& mod);
/// sets the C-terminal modification by the monoisotopic mass difference it introduces (creates a "user-defined" mod if not present)
void setCTerminalModificationByDiffMonoMass(double diffMonoMass, bool protein_term);
/// returns the name (ID) of the C-terminal modification, or an empty string if none is set
const String& getCTerminalModificationName() const;
/// returns a pointer to the C-terminal modification, or zero if none is set
const ResidueModification* getCTerminalModification() const;
/// returns a pointer to the residue at position @p index
const Residue& getResidue(Size index) const;
/// returns the formula of the peptide
EmpiricalFormula getFormula(Residue::ResidueType type = Residue::Full, Int charge = 0) const;
/// returns the average weight of the peptide
double getAverageWeight(Residue::ResidueType type = Residue::Full, Int charge = 0) const;
/// returns the mono isotopic weight of the peptide in the given ionic form
/// @note will not (and cannot) control whether the required ion can exist
/// (e.g. x/c ions for monomers) as it does not do fragmentation but rather
/// supplementing/deduction of the sequence to its ionic form.
double getMonoWeight(Residue::ResidueType type = Residue::Full, Int charge = 0) const;
/// returns mass-to-charge ratio of the peptide in the given ionic form
/// @note will not (and cannot) control whether the required ion can exist
/// (e.g. x/c ions for monomers) as it does not do fragmentation but rather
/// supplementing/deduction of the sequence to its ionic form.
/// @throws Exception::InvalidValue if @p charge==0
double getMZ(Int charge, Residue::ResidueType type = Residue::Full) const;
/// returns a pointer to the residue at given position
const Residue& operator[](Size index) const;
/// adds the residues of the peptide
AASequence operator+(const AASequence& peptide) const;
/// adds the residues of a peptide
AASequence& operator+=(const AASequence&);
/// adds the residues of the peptide
AASequence operator+(const Residue* residue) const;
/// adds the residues of a peptide
AASequence& operator+=(const Residue*);
/// returns the number of residues
Size size() const;
/// returns a peptide sequence of the first index residues
AASequence getPrefix(Size index) const;
/// returns a peptide sequence of the last index residues
AASequence getSuffix(Size index) const;
/// returns a peptide sequence of number residues, beginning at position index
AASequence getSubsequence(Size index, UInt number) const;
/// compute frequency table of amino acids
void getAAFrequencies(std::map<String, Size>& frequency_table) const;
//@}
/** @name Predicates
*/
//@{
/// returns true if the peptide contains the given residue
bool has(const Residue& residue) const;
/// returns true if the peptide contains the given peptide
/// @note c-term and n-term mods are ignored
bool hasSubsequence(const AASequence& peptide) const;
/// returns true if the peptide has the given prefix
/// n-term mod is also checked (c-term as well, if prefix is of same length)
bool hasPrefix(const AASequence& peptide) const;
/// returns true if the peptide has the given suffix
/// c-term mod is also checked (n-term as well, if suffix is of same length)
bool hasSuffix(const AASequence& peptide) const;
/// predicate which is true if the peptide is N-term modified
bool hasNTerminalModification() const;
/// predicate which is true if the peptide is C-term modified
bool hasCTerminalModification() const;
/// returns true if any of the residues or termini are modified
bool isModified() const;
/// equality operator. Two sequences are equal iff all amino acids including PTMs are equal
bool operator==(const AASequence& rhs) const;
/// lesser than operator which compares the C-term mods, sequence including PTMS and N-term mods; can be used for maps
bool operator<(const AASequence& rhs) const;
/// inequality operator. Complement of equality operator.
bool operator!=(const AASequence& rhs) const;
//@}
/** @name Iterators
*/
//@{
inline Iterator begin() { return Iterator(&peptide_, 0); }
inline ConstIterator begin() const { return ConstIterator(&peptide_, 0); }
inline Iterator end() { return Iterator(&peptide_, (Int) peptide_.size()); }
inline ConstIterator end() const { return ConstIterator(&peptide_, (Int) peptide_.size()); }
//@}
/** @name Stream operators
*/
//@{
/// writes a peptide to an output stream
friend OPENMS_DLLAPI std::ostream& operator<<(std::ostream& os, const AASequence& peptide);
/// reads a peptide from an input stream
friend OPENMS_DLLAPI std::istream& operator>>(std::istream& is, const AASequence& peptide);
//@}
/**
@brief create AASequence object by parsing an OpenMS string
@param[in] s Input string
@param[in] permissive If set, skip spaces and replace stop codon symbols ("*", "#", "+") by "X" (unknown amino acid) during parsing
@throws Exception::ParseError if an invalid string representation of an AA sequence is passed
*/
static AASequence fromString(const String& s,
bool permissive = true);
/**
@brief create AASequence object by parsing a C string (character array)
@param[in] s Input string
@param[in] permissive If set, skip spaces and replace stop codon symbols ("*", "#", "+") by "X" (unknown amino acid) during parsing
@throws Exception::ParseError if an invalid string representation of an AA sequence is passed
*/
static AASequence fromString(const char* s,
bool permissive = true);
/// @brief constructor from String
/// @param[in] s A String representing the amino acid sequence
explicit AASequence(const String& s);
/// @brief constructor from C string
/// @param[in] s A C-style string representing the amino acid sequence
explicit AASequence(const char* s);
/// @brief constructor from String
/// @param[in] s A String representing the amino acid sequence
/// @param[in] permissive If set, skip spaces and replace stop codon symbols ("*", "#", "+") by "X" (unknown amino acid) during parsing
explicit AASequence(const String& s, bool permissive);
/// @brief constructor from C string
/// @param[in] s A C-style string representing the amino acid sequence
/// @param[in] permissive If set, skip spaces and replace stop codon symbols ("*", "#", "+") by "X" (unknown amino acid) during parsing
explicit AASequence(const char* s, bool permissive);
protected:
std::vector<const Residue*> peptide_;
const ResidueModification* n_term_mod_ = nullptr;
const ResidueModification* c_term_mod_ = nullptr;
/**
@brief Parses modifications in round brackets (an identifier)
If dot notation is used it resolves cterm ambiguity based on the presence
of the dot.
@param[in] str_it Current position in the string to be parsed
@param[in] str Full input string
@param[in,out] aas Current AASequence object (will be modified with the correct residue added)
@param[in] specificity Whether the current modification should be interpreted as N- or C-terminal
@return Position at which to continue parsing
*/
static String::ConstIterator parseModRoundBrackets_(const String::ConstIterator str_it,
const String& str,
AASequence& aas,
const ResidueModification::TermSpecificity& specificity);
/**
@brief Parses modifications in square brackets (a mass)
If dot notation is used it resolves cterm ambiguity based on the presence
of the dot.
@param[in] str_it Current position in the string to be parsed
@param[in] str Full input string
@param[in,out] aas Current AASequence object (will be modified with the correct residue added)
@param[in] specificity Whether the current modification should be interpreted as N- or C-terminal
@return Position at which to continue parsing
*/
static String::ConstIterator parseModSquareBrackets_(const String::ConstIterator str_it,
const String& str,
AASequence& aas,
const ResidueModification::TermSpecificity& specificity);
static void parseString_(const String& peptide, AASequence& aas,
bool permissive = true);
};
OPENMS_DLLAPI std::ostream& operator<<(std::ostream& os, const AASequence& peptide);
OPENMS_DLLAPI std::istream& operator>>(std::istream& os, const AASequence& peptide);
} // namespace OpenMS
// Hash function specialization for AASequence
// Placed in std namespace to allow use with std::unordered_map/set
namespace std
{
/**
* @brief Hash function for OpenMS::AASequence.
*
* Computes a hash based on the amino acid sequence (one-letter codes),
* modifications on each residue, and terminal modifications.
*
* Design decisions:
* - Uses one-letter codes instead of pointers for portability
* - Includes modification IDs for modified residues
* - Includes terminal modifications
* - Hash is consistent with operator==
*
* @note Hash is reproducible across process runs for equal sequences.
*/
template<>
struct hash<OpenMS::AASequence>
{
std::size_t operator()(const OpenMS::AASequence& seq) const noexcept
{
std::size_t seed = 0;
// Hash each residue
for (const auto& residue : seq)
{
// Hash one-letter code (single character, fast)
const OpenMS::String& olc = residue.getOneLetterCode();
if (!olc.empty())
{
OpenMS::hash_combine(seed, OpenMS::hash_char(olc[0]));
}
// Hash modification if present
const OpenMS::ResidueModification* mod = residue.getModification();
if (mod != nullptr)
{
// Use full ID for portability (e.g., "Oxidation (M)")
// String inherits from std::string, no copy needed
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(mod->getFullId()));
}
}
// Hash N-terminal modification if present
const OpenMS::ResidueModification* n_mod = seq.getNTerminalModification();
if (n_mod != nullptr)
{
// Use a different seed offset for N-term to distinguish from C-term
std::size_t n_hash = OpenMS::fnv1a_hash_string(n_mod->getFullId());
OpenMS::hash_combine(seed, n_hash ^ 0x4e5445524dULL); // "NTERM" in hex-like
}
// Hash C-terminal modification if present
const OpenMS::ResidueModification* c_mod = seq.getCTerminalModification();
if (c_mod != nullptr)
{
// Use a different seed offset for C-term
std::size_t c_hash = OpenMS::fnv1a_hash_string(c_mod->getFullId());
OpenMS::hash_combine(seed, c_hash ^ 0x435445524dULL); // "CTERM" in hex-like
}
return seed;
}
};
} // namespace std
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/ModifiedNASequenceGenerator.h | .h | 2,313 | 62 | // 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/CHEMISTRY/NASequence.h>
#include <OpenMS/CHEMISTRY/Ribonucleotide.h>
#include <vector>
#include <map>
#include <set>
namespace OpenMS
{
/*
* @brief This class applies fixed and variable modifications to (unmodified)
* nucleic acid sequences, combinatorically generating modified sequences.
*
*/
class OPENMS_DLLAPI ModifiedNASequenceGenerator
{
public:
using ConstRibonucleotidePtr = const Ribonucleotide*;
/// Applies fixed modifications to a single NASequence
static void applyFixedModifications(
const std::set<ConstRibonucleotidePtr>& fixed_mods,
NASequence& sequence);
/// Applies variable modifications to a single NASequence. If keep_original is set the original (e.g. unmodified version) is also returned
static void applyVariableModifications(
const std::set<ConstRibonucleotidePtr>& var_mods,
const NASequence& seq, Size max_variable_mods_per_NASequence,
std::vector<NASequence>& all_modified_NASequences,
bool keep_original = true);
protected:
/// Recursively generate all combinatorial placements at compatible sites
static void recurseAndGenerateVariableModifiedSequences_(
const std::vector<int>& subset_indices,
const std::map<int, std::vector<ConstRibonucleotidePtr>>& map_compatibility,
int depth,
const NASequence& current_NASequence,
std::vector<NASequence>& modified_NASequences);
/// Fast implementation of modification placement. No combinatorial placement is needed in this case
/// - just every site is modified once by each compatible modification.
/// Already modified residues are skipped
static void applyAtMostOneVariableModification_(
const std::set<ConstRibonucleotidePtr>& var_mods,
const NASequence& seq,
std::vector<NASequence>& all_modified_NASequences,
bool keep_original = true);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/RNaseDigestion.h | .h | 2,425 | 68 | // 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, Samuel Wein $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CHEMISTRY/EnzymaticDigestion.h>
#include <OpenMS/CHEMISTRY/NASequence.h>
#include <OpenMS/METADATA/ID/IdentificationData.h>
#include <boost/regex.hpp>
namespace OpenMS
{
/**
@brief Class for the enzymatic digestion of RNAs
@see @ref DigestionEnzymeRNA
@ingroup Chemistry
*/
class OPENMS_DLLAPI RNaseDigestion: public EnzymaticDigestion
{
public:
/// Sets the enzyme for the digestion
void setEnzyme(const DigestionEnzyme* enzyme) override;
/// Sets the enzyme for the digestion (by name)
void setEnzyme(const String& name);
/**
@brief Performs the enzymatic digestion of a (potentially modified) RNA
Only fragments of appropriate length (between @p min_length and @p max_length) are returned.
*/
void digest(const NASequence& rna, std::vector<NASequence>& output,
Size min_length = 0, Size max_length = 0) const;
/**
@brief Performs the enzymatic digestion of all RNA parent sequences in @p IdentificationData
Digestion products are stored as IdentifiedOligos with corresponding ParentMatch annotations.
Only fragments of appropriate length (between @p min_length and @p max_length) are included.
*/
void digest(IdentificationData& id_data, Size min_length = 0,
Size max_length = 0) const;
protected:
const Ribonucleotide* five_prime_gain_; ///< 5' mod added by the enzyme
const Ribonucleotide* three_prime_gain_; ///< 3' mod added by the enzyme
std::vector<boost::regex> cuts_after_regexes_; ///< a vector of reg. exp. for enzyme cutting pattern, each regex represents a single nucleotide
std::vector<boost::regex> cuts_before_regexes_; ///< a vector reg. exp. for enzyme cutting pattern
/**
@brief Returns the positions of digestion products in the RNA as pairs: (start, length)
*/
std::vector<std::pair<Size, Size>> getFragmentPositions_(
const NASequence& rna, Size min_length, Size max_length)
const;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/ModifiedPeptideGenerator.h | .h | 4,000 | 79 | // 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/DATASTRUCTURES/StringListUtils.h>
#include <OpenMS/CHEMISTRY/ResidueModification.h>
#include <OpenMS/CHEMISTRY/AASequence.h>
#include <vector>
#include <map>
#include <unordered_map>
#include <set>
namespace OpenMS
{
class OPENMS_DLLAPI ModifiedPeptideGenerator
{
/*
* @brief Modifications can be generated and applied to AASequences.
*/
public:
// struct needed to wrap the template for pyOpenMS
struct MapToResidueType { std::unordered_map<const ResidueModification*, const Residue*> val; };
/**
* @brief Retrieve modifications from strings
*
* @param[in] modNames The list of modification names
* @return A map of modifications and associated residue
* ResidueModifications are referenced by Residues in AASequence objects. Every time an AASequence object
* with modifications is constructed, it needs to query if the (modified) Residue is already
* registered in ResidueDB. This implies a lock of the whole db. To make modified peptide generation lock-free, we
* query and cache all modified residues once so we can directly apply them without further queries.
*/
static MapToResidueType getModifications(const StringList& modNames);
// Applies fixed modifications to a single peptide
static void applyFixedModifications(
const MapToResidueType& fixed_mods,
AASequence& peptide);
// Applies variable modifications to a single peptide. If keep_original is set the original (e.g. unmodified version) is also returned
static void applyVariableModifications(
const MapToResidueType& var_mods,
const AASequence& peptide,
Size max_variable_mods_per_peptide,
std::vector<AASequence>& all_modified_peptides,
bool keep_original=true);
protected:
static const int N_TERM_MODIFICATION_INDEX; // magic constant to distinguish N_TERM only modifications from ANYWHERE modifications placed at N-term residue
static const int C_TERM_MODIFICATION_INDEX; // magic constant to distinguish C_TERM only modifications from ANYWHERE modifications placed at C-term residue
// Lookup datastructure to allow lock-free generation of modified peptides. Modifications without origin (e.g., "Protein N-term") set the residue to nullptr.
static MapToResidueType createResidueModificationToResidueMap_(const std::vector<const ResidueModification*>& mods);
// Fast implementation of modification placement. No combinatoric placement is needed in this case - just every site is modified once by each compatible modification. Already modified residues are skipped
static void applyAtMostOneVariableModification_(
const MapToResidueType& var_mods,
const AASequence& peptide,
std::vector<AASequence>& all_modified_peptides,
bool keep_original=true);
private:
/// take a vector of AASequences @p original_sequences, and for each mod in @p mods, add a version with mod at index @p idx_to_modify. In-place, with the original sequences recieving the first mod in @p mods.
static void applyAllModsAtIdxAndExtend_(std::vector<AASequence>& original_sequences, int idx_to_modify, const std::vector<const ResidueModification*>& mods, const MapToResidueType& var_mods);
/// applies a modification @p m to the @p current_peptide at @p current_index. Overwrites mod if it exists. Looks up in var_mods for existing modified Residue pointers.
static void applyModToPep_(AASequence& current_peptide, int current_index, const ResidueModification* m, const MapToResidueType& var_mods);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/Ribonucleotide.h | .h | 7,034 | 218 | // 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/String.h>
#include <OpenMS/CHEMISTRY/EmpiricalFormula.h>
#include <OpenMS/CONCEPT/HashUtils.h>
#include <functional>
#include <iosfwd>
namespace OpenMS
{
/** @ingroup Chemistry
@brief Representation of a ribonucleotide (modified or unmodified)
The available information is based on the Modomics database (http://modomics.genesilico.pl/modifications/).
@see RibonucleotideDB
*/
class OPENMS_DLLAPI Ribonucleotide
{
friend class RibonucleotideDB;
public:
enum TermSpecificityNuc
{
ANYWHERE,
FIVE_PRIME,
THREE_PRIME,
NUMBER_OF_TERM_SPECIFICITY
};
/** @name Constructors
*/
//@{
/// Constructor
Ribonucleotide(const String& name = "unknown ribonucleotide",
const String& code = ".",
const String& new_code = "",
const String& html_code = ".",
const EmpiricalFormula& formula = EmpiricalFormula(),
char origin = '.',
double mono_mass = 0.0,
double avg_mass = 0.0,
enum TermSpecificityNuc term_spec = ANYWHERE,
const EmpiricalFormula& baseloss_formula =
default_baseloss_);
/// Copy constructor
Ribonucleotide(const Ribonucleotide& ribo) = default;
/// Destructor
virtual ~Ribonucleotide();
//@}
/** @name Assignment
*/
//@{
/// assignment operator
Ribonucleotide& operator=(const Ribonucleotide& ribo) = default;
//@}
/** @name Equality
*/
//@{
/// Equality operator
bool operator==(const Ribonucleotide& ribonucleotide) const;
//@}
/** Accessors
*/
//@{
/// Return the short name
const String getCode() const;
/// Set the short name
void setCode(const String& code);
/// Get the name of the ribonucleotide
const String getName() const;
/// Set the name of the ribonucleotide
void setName(const String& name);
/// Get formula for the ribonucleotide
const EmpiricalFormula getFormula() const;
/// Set the empirical formula for the ribonucleotide
void setFormula(const EmpiricalFormula& formula);
/// Get the monoisotopic mass of the ribonucleotide
double getMonoMass() const;
/// Set the monoisotopic mass of the ribonucleotide
void setMonoMass(double mono_mass);
/// Set the average mass of the ribonucleotide
double getAvgMass() const;
/// Get the average mass of the ribonucleotide
void setAvgMass(double avg_mass);
/// Get the "new" (Modomics) code
const String getNewCode() const;
/// Set the "new" (Modomics) code
void setNewCode(const String &new_code);
/// ostream iterator to write the residue to a stream
friend OPENMS_DLLAPI std::ostream& operator<<(std::ostream& os, const Ribonucleotide& ribo);
/// Get the code of the unmodified base (e.g., "A", "C", ...)
char getOrigin() const;
/// Set the code of the unmodified base (e.g., "A", "C", ...)
void setOrigin(char origin);
/// Set the HTML (RNAMods) code
String getHTMLCode() const;
/// Get the HTML (RNAMods) code
void setHTMLCode(const String& html_code);
/// Get the terminal specificity
enum TermSpecificityNuc getTermSpecificity() const;
/// Set the terminal specificity
void setTermSpecificity(enum TermSpecificityNuc term_spec);
/// Get sum formula after loss of the nucleobase
const EmpiricalFormula getBaselossFormula() const;
/// Set the sum formula after loss of the nucleobase
void setBaselossFormula(const EmpiricalFormula& formula);
//@}
/// Return true if this is a modified ribonucleotide and false otherwise
bool isModified() const;
/// Return whether this is an "ambiguous" modification (representing isobaric modifications on the base/ribose)
bool isAmbiguous() const;
protected:
/// Default value for sum formula after nucleobase loss
static const EmpiricalFormula default_baseloss_;
String name_; ///< full name
String code_; ///< short name
String new_code_; ///< Modomics code
String html_code_; ///< RNAMods code
EmpiricalFormula formula_; ///< sum formula
char origin_; ///< character of unmodified version of ribonucleotide
double mono_mass_; ///< monoisotopic mass
double avg_mass_; ///< average mass
enum TermSpecificityNuc term_spec_; ///< terminal specificity
EmpiricalFormula baseloss_formula_; ///< sum formula after loss of the nucleobase
};
/// Stream output operator
OPENMS_DLLAPI std::ostream& operator<<(std::ostream& os, const Ribonucleotide& ribo);
/// Dummy nucleotide used to represent 5' and 3' chain ends. Usually, just the phosphates.
using RibonucleotideChainEnd = Ribonucleotide;
} // namespace OpenMS
// Hash function specialization for Ribonucleotide
// Placed in std namespace to allow use with std::unordered_map/set
namespace std
{
/**
* @brief Hash function for OpenMS::Ribonucleotide.
*
* Computes a hash based on all fields used in operator==:
* name_, code_, new_code_, html_code_, formula_, origin_,
* mono_mass_, avg_mass_, term_spec_, and baseloss_formula_.
*
* @note Hash is consistent with operator==: equal objects produce equal hashes.
*/
template<>
struct hash<OpenMS::Ribonucleotide>
{
std::size_t operator()(const OpenMS::Ribonucleotide& ribo) const noexcept
{
std::size_t seed = 0;
// Hash all fields used in operator==
// String fields: name_, code_, new_code_, html_code_
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(ribo.getName()));
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(ribo.getCode()));
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(ribo.getNewCode()));
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(ribo.getHTMLCode()));
// EmpiricalFormula fields: formula_, baseloss_formula_
OpenMS::hash_combine(seed, std::hash<OpenMS::EmpiricalFormula>{}(ribo.getFormula()));
OpenMS::hash_combine(seed, std::hash<OpenMS::EmpiricalFormula>{}(ribo.getBaselossFormula()));
// Primitive fields: origin_ (char), mono_mass_, avg_mass_ (double), term_spec_ (enum)
OpenMS::hash_combine(seed, OpenMS::hash_char(ribo.getOrigin()));
OpenMS::hash_combine(seed, OpenMS::hash_float(ribo.getMonoMass()));
OpenMS::hash_combine(seed, OpenMS::hash_float(ribo.getAvgMass()));
OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(ribo.getTermSpecificity())));
return seed;
}
};
} // namespace std
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/EnzymaticDigestion.h | .h | 11,158 | 235 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow, Xiao Liang $
// $Authors: Marc Sturm, Chris Bielow, Jeremi Maciejewski $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CHEMISTRY/DigestionEnzyme.h>
#include <OpenMS/CONCEPT/Types.h>
#include <boost/regex_fwd.hpp> // forward declaration of boost::regex
#include <functional> // for std::function
#include <memory> // unique_ptr
#include <string>
#include <vector>
namespace OpenMS
{
class StringView;
/**
@brief Class for the enzymatic digestion of sequences
Digestion can be performed using simple regular expressions,
e.g. [KR] | [^P]
for trypsin. Also missed cleavages can be modeled, i.e. adjacent peptides are not cleaved
due to enzyme malfunction/access restrictions. If @em n missed cleavages are given, all possible resulting
peptides (cleaved and uncleaved) with up to @em n missed cleavages are returned.
Thus @b no random selection of just @em n specific missed cleavage sites is performed.
@see ProteaseDigestion for functionality specific to protein digestion.
@ingroup Chemistry
*/
class OPENMS_DLLAPI EnzymaticDigestion
{
public:
/// when querying for valid digestion products, this determines if the specificity of the two peptide ends is considered important
enum Specificity
{ // note: the value of the first three items is important, since some engines just report the number of required termini (0, 1, 2)
SPEC_NONE = 0, ///< no requirements on start / end
SPEC_SEMI = 1, ///< semi specific, i.e., one of the two cleavage sites must fulfill requirements
SPEC_FULL = 2, ///< fully enzyme specific, e.g., tryptic (ends with KR, AA-before is KR), or peptide is at protein terminal ends
SPEC_UNKNOWN = 3,
SPEC_NOCTERM = 8, ///< no requirements on CTerm (currently not supported in the class)
SPEC_NONTERM = 9, ///< no requirements on NTerm (currently not supported in the class)
SIZE_OF_SPECIFICITY = 10
};
/// Names of the Specificity
static const std::string NamesOfSpecificity[SIZE_OF_SPECIFICITY];
/// Name for no cleavage
static const std::string NoCleavage;
/// Name for unspecific cleavage
static const std::string UnspecificCleavage;
/// Default constructor
EnzymaticDigestion();
/// Copy constructor
EnzymaticDigestion(const EnzymaticDigestion& rhs);
/// Assignment operator
EnzymaticDigestion& operator=(const EnzymaticDigestion& rhs);
/// Destructor
virtual ~EnzymaticDigestion();
/// Returns the number of missed cleavages for the digestion
Size getMissedCleavages() const;
/// Sets the number of missed cleavages for the digestion (default is 0). This setting is ignored when log model is used.
void setMissedCleavages(Size missed_cleavages);
/// Returns the enzyme for the digestion
String getEnzymeName() const;
/// Sets the enzyme for the digestion
virtual void setEnzyme(const DigestionEnzyme* enzyme);
/// Returns the specificity for the digestion
Specificity getSpecificity() const;
/// Sets the specificity for the digestion (default is SPEC_FULL).
void setSpecificity(Specificity spec);
/// convert spec string name to enum
/// returns SPEC_UNKNOWN if @p name is not valid
static Specificity getSpecificityByName(const String& name);
/**
@brief Performs the enzymatic digestion of an unmodified sequence.
By returning only references into the original string this is very fast.
@param[in] sequence Sequence to digest
@param[out] output Digestion products
@param[in] min_length Minimal length of reported products
@param[in] max_length Maximal length of reported products (0 = no restriction)
@return Number of discarded digestion products (which are not matching length restrictions)
*/
Size digestUnmodified(const StringView& sequence, std::vector<StringView>& output, Size min_length = 1, Size max_length = 0) const;
/**
@brief Performs the enzymatic digestion of an unmodified sequence.
By returning only positions into the original string this is very fast and compared to the StringView output
version of this function it is independent of the original sequence. Can be used for matching products to
determine e.g. missing ones. @todo could be set of pairs.
@param[in] sequence Sequence to digest
@param[out] output Digestion products as vector of pairs of start and end positions
@param[in] min_length Minimal length of reported products
@param[in] max_length Maximal length of reported products (0 = no restriction)
@return Number of discarded digestion products (which are not matching length restrictions)
*/
Size digestUnmodified(const StringView& sequence, std::vector<std::pair<Size, Size>>& output, Size min_length = 1, Size max_length = 0) const;
/**
@brief Is the peptide fragment starting at position @p pep_pos with length @p pep_length within the sequence @p protein generated by the current enzyme?
Checks if peptide is a valid digestion product of the enzyme, taking into account specificity and the MC flag provided here.
@param[in] protein Protein sequence
@param[in] pep_pos Starting index of potential peptide
@param[in] pep_length Length of potential peptide
@param[in] ignore_missed_cleavages Do not compare MC's of potential peptide to the maximum allowed MC's
@return True if peptide has correct n/c terminals (according to enzyme, specificity and missed cleavages)
*/
bool isValidProduct(const String& protein, int pep_pos, int pep_length, bool ignore_missed_cleavages = true) const;
/**
@brief Counts the number of internal cleavage sites (missed cleavages) in a protein sequence.
@param[in] sequence Sequence
@return Number of internal cleavage sites (= missed cleavages in the sequence)
*/
Size countInternalCleavageSites(const String& sequence) const;
/**
@brief Filter based on the number of missed cleavages.
@param[in] sequence Unmodified (!) amino acid sequence to check.
@param[in] filter A predicate that takes as parameter the number of missed cleavages in the sequence and returns true if the sequence should be filtered out.
@return Whether the sequence should be filtered out.
*/
bool filterByMissedCleavages(const String& sequence, const std::function<bool(const Int)>& filter) const;
protected:
/**
@brief supports functionality for ProteaseDigestion as well (which is deeply weaved into the function)
To avoid code duplication, this is stored here and called by wrappers.
Do not duplicate the code, just for the sake of semantics (unless we can come up with a clean separation)
Note: the overhead of allow_nterm_protein_cleavage and allow_random_asp_pro_cleavage is marginal; the main runtime is spend during tokenize_()
*/
bool isValidProduct_(const String& sequence,
int pos,
int length,
bool ignore_missed_cleavages,
bool allow_nterm_protein_cleavage,
bool allow_random_asp_pro_cleavage) const;
/**
@brief Digests the sequence using the enzyme's regular expression
The resulting split positions include @p start as first position, but not end.
If start is negative, it is reset to zero.
If end is negative or beyond @p sequence's size(), it is set to size().
All returned positions are relative to the full @p sequence.
Returned positions include @p start and any positions between start and end matching the regex.
@param[in] sequence ...
@param[in] start Start digestion after this point
@param[in] end Past-the-end index into @p sequence
@return Cleavage positions (this includes @p start, but not @p end)
*/
std::vector<int> tokenize_(const String& sequence, int start = 0, int end = -1) const;
/**
@brief Generates semi-specific digestion products
Function handling semi-specific digestion (specificity_ == Specificity::SPEC_SEMI).
It is intended for calling after tokenizing and missed cleavages variants generation.
Fully-specific variants are skipped.
Also generates semi-specific variants with missed cleavages.
@param[in] cleavage_positions A (sorted!) vector of cleavage positions, as returned by tokenize_(). First and last cleavage should be sequence termini.
@param[out] output A vector into which produced variants are emplaced.
@param[in] min_length Minimal length of reported products
@param[in] max_length Maximal length of reported products
@return number of digestion products NOT matching the length restrictions.
@throw Exception::InvalidValue if number of cleavage_positions is smaller than 2 (at least sequence termini are required).
@throw Exception::Precondition if vector cleavage_positions is not sorted.
*/
Size semiSpecificDigestion_(const std::vector<int>& cleavage_positions, std::vector<std::pair<Size, Size>>& output, Size min_length = 0, Size max_length = -1) const;
/**
@brief Helper function for digestUnmodified()
This function implements digestUnmodified() starting from the result of tokenize_().
The separation enables derived classes to modify the result of tokenize_() during the in-silico digestion.
@return number of digestion products NOT matching the length restrictions
*/
Size digestAfterTokenize_(const std::vector<int>& fragment_positions, const StringView& sequence, std::vector<StringView>& output, Size min_length = 0, Size max_length = -1) const;
Size digestAfterTokenize_(const std::vector<int>& fragment_positions, const StringView& sequence, std::vector<std::pair<Size, Size>>& output, Size min_length = 0, Size max_length = -1) const;
/**
@brief Counts the number of missed cleavages in a sequence fragment
@param[in] cleavage_positions Positions of cleavage in protein as obtained from tokenize_()
@param[in] seq_start Index into sequence
@param[in] seq_end Past-the-end index into sequence
@return number of missed cleavages of peptide
*/
Size countMissedCleavages_(const std::vector<int>& cleavage_positions, Size seq_start, Size seq_end) const;
/// Number of missed cleavages
Size missed_cleavages_;
/// Used enzyme
const DigestionEnzyme* enzyme_;
/// Regex for tokenizing (huge speedup by making this a member instead of stack object in tokenize_())
std::unique_ptr<boost::regex> re_; // use PImpl, since #include cost is huge
/// specificity of enzyme
Specificity specificity_;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/ResidueDB.h | .h | 5,871 | 174 | // 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, Jang Jang Jin$
// --------------------------------------------------------------------------
#pragma once
#include <unordered_map>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/CONCEPT/Macros.h> // for OPENMS_PRECONDITION
#include <map>
#include <set>
#include <array>
namespace OpenMS
{
// forward declarations
class ResidueModification;
class Residue;
/** @ingroup Chemistry
@brief OpenMS stores a central database of all residues in the ResidueDB.
All (unmodified) residues are added to the database on construction.
Modified residues get created and added if getModifiedResidue is called.
*/
class OPENMS_DLLAPI ResidueDB
{
public:
/// singleton
static ResidueDB* getInstance();
/** @name Constructors and Destructors
*/
//@{
/// destructor
virtual ~ResidueDB();
//@}
/** @name Accessors
*/
//@{
/// returns the number of residues stored
Size getNumberOfResidues() const;
/// returns the number of modified residues stored
Size getNumberOfModifiedResidues() const;
/// returns a pointer to the residue with name, 3 letter code or 1 letter code name
const Residue* getResidue(const String& name) const;
/// returns a pointer to the residue with 1 letter code name
const Residue* getResidue(const unsigned char& one_letter_code) const;
/**
@brief Returns a pointer to a modified residue given a modification name
The "base" residue is looked up in ModificationsDB using the modification name.
The modified residue is added to the database if it doesn't exist yet.
*/
const Residue* getModifiedResidue(const String& name);
/**
@brief Returns a pointer to a modified residue given a residue and a modification name
The modified residue is added to the database if it doesn't exist yet.
@throw Exception::IllegalArgument if the residue was not found
@throw Exception::InvalidValue if no matching modification was found (via ModificationsDB::getModification)
*/
const Residue* getModifiedResidue(const Residue* residue, const String& name);
/**
@brief Returns a pointer to a modified residue given a residue and a pointer to a modification from the ModificationsDB
The modified residue is added to the database if it doesn't exist yet. The origin of the modification has to match the residue and
the term has to be ResidueModification::Anywhere.
@throw Exception::IllegalArgument if the residue was not found
*/
const Residue* getModifiedResidue(const Residue* residue, const ResidueModification* mod);
/**
@brief returns a set of all residues stored in this residue db
Following sets are available:
All - all residues
Natural20 - default 20 naturally occurring residues
Natural19WithoutI - default natural amino acids, excluding isoleucine (isobaric to leucine)
Natural19WithoutL - default natural amino acids, excluding leucine (isobaric to isoleucine)
Natural19J - default natural amino acids, (isobaric leucine/isoleucine are marked by 'J')
AmbiguousWithoutX - all amino acids, including ambiguous ones: B (asparagine or aspartate), Z (glutamine or glutamate), J (isoleucine or leucine)
Ambiguous - all amino acids including all ambiguous ones (X can be every other amino acid)
AllNatural - naturally occurring residues, including selenocysteine (U)
returns an empty set if the specified residue set is not defined
*/
const std::set<const Residue*> getResidues(const String& residue_set = "All") const;
/// returns all residue sets that are registered which this instance
const std::set<String> getResidueSets() const;
//@}
/** @name Predicates
*/
//@{
/// returns true if the db contains a residue with the given name
bool hasResidue(const String& name) const;
/// returns true if the db contains the residue of the given pointer
bool hasResidue(const Residue* residue) const;
//@}
protected:
/// initializes all residues by building
void initResidues_();
/** @name Private Constructors
*/
//@{
/// default constructor
ResidueDB();
///copy constructor
ResidueDB(const ResidueDB& residue_db);
//@}
/** @name Assignment
*/
//@{
/// assignment operator
ResidueDB& operator=(const ResidueDB& aa) = delete;
//@}
// construct all residues
void buildResidues_();
/// creates and adds residues to a lookup table including the residue set
void insertResidueAndAssociateWithResidueSet_(Residue* residue, const std::vector<String>& residue_sets);
/// add residue and add names to lookup
void addResidue_(Residue* residue);
/// adds names of single residue to the index
void addResidueNames_(const Residue*);
/// adds names of single modified residue to the index
void addModifiedResidueNames_(const Residue*);
std::map<String, std::map<String, const Residue*> > residue_mod_names_;
/// all (unmodified) residues
std::set<const Residue*> const_residues_;
/// all modified residues
std::set<const Residue*> const_modified_residues_;
std::set<String> residue_sets_;
/// lookup from name to residue
std::unordered_map<String, const Residue*> residue_names_;
/// fast lookup table for residues
std::array<const Residue*, 256> residue_by_one_letter_code_ = {{nullptr}};
std::map<String, std::set<const Residue*> > residues_by_set_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/Residue.h | .h | 19,706 | 610 | // 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, Jang Jang Jin$
// --------------------------------------------------------------------------
//
#pragma once
#include <OpenMS/CHEMISTRY/EmpiricalFormula.h>
#include <OpenMS/CONCEPT/HashUtils.h>
#include <OpenMS/CONCEPT/Types.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <array>
#include <functional>
#include <iosfwd>
#include <set>
#include <vector>
namespace OpenMS
{
class ResidueModification;
/**
@ingroup Chemistry
@brief Representation of an amino acid residue.
This class represents an amino acid. These can have many different attributes, like
the formula physico-chemical values of properties and so on.
A very important property of amino acid residues are their modifications. By default no
modification is present. Any modification which is present in the ModificationsDB can
be applied, if appropriate.
*/
class OPENMS_DLLAPI Residue
{
friend class ResidueDB;
public:
/** @name Formula conversion
*
* @brief Computes empirical formula required to add to the desired type
*
* Computes the empirical formula required to be added to convert an
* internal residue (inside an AA sequence) to that of a residue of the
* desired type. For example, to obtain the conversion formula for an
* internal ion to a "y ion", use getInternalToYTerm().
*
* Formulae that need to be added to the internal residues to get to
* fragment type from http://www.matrixscience.com/help/fragmentation_help.html
*
* Which means that we follow Biemann nomenclature.
* For a small description of the differernt ion types, see the enum @ref ResidueType.
*/
//@{
inline static const EmpiricalFormula& getInternalToFull()
{
static const EmpiricalFormula to_full = EmpiricalFormula("H2O");
return to_full;
}
inline static const EmpiricalFormula& getInternalToNTerm()
{
static const EmpiricalFormula to_full = EmpiricalFormula("H");
return to_full;
}
inline static const EmpiricalFormula& getInternalToCTerm()
{
static const EmpiricalFormula to_full = EmpiricalFormula("OH");
return to_full;
}
inline static const EmpiricalFormula& getInternalToAIon()
{
// Mind the "-"
static const EmpiricalFormula to_full =
getInternalToNTerm() - EmpiricalFormula("CHO");
return to_full;
}
inline static const EmpiricalFormula& getInternalToBIon()
{
// Mind the "-"
static const EmpiricalFormula to_full =
getInternalToNTerm() - EmpiricalFormula("H");
return to_full;
}
inline static const EmpiricalFormula& getInternalToCIon()
{
static const EmpiricalFormula to_full =
getInternalToNTerm() + EmpiricalFormula("NH2");
return to_full;
}
inline static const EmpiricalFormula& getInternalToXIon()
{
// Mind the "-"
static const EmpiricalFormula to_full =
getInternalToCTerm() + EmpiricalFormula("CO") - EmpiricalFormula("H");
return to_full;
}
inline static const EmpiricalFormula& getInternalToYIon()
{
static const EmpiricalFormula to_full =
getInternalToCTerm() + EmpiricalFormula("H");
return to_full;
}
inline static const EmpiricalFormula& getInternalToZIon()
{
// Mind the "-"
static const EmpiricalFormula to_full =
getInternalToCTerm() - EmpiricalFormula("NH2");
return to_full;
}
inline static const EmpiricalFormula& getInternalToZp1Ion()
{
// Mind the "-"
static const EmpiricalFormula to_full =
getInternalToCTerm() - EmpiricalFormula("NH");
return to_full;
}
inline static const EmpiricalFormula& getInternalToZp2Ion()
{
// Mind the "-"
static const EmpiricalFormula to_full =
getInternalToCTerm() - EmpiricalFormula("N");
return to_full;
}
//@}
/** @name Enums
*/
//@{
/// Residue types: Note that all weights and elemental compositions of fragment "ions" are given for their neutral forms.
/// Furthermore, all fragment ion types are based on the Biemann nomenclature (http://www.matrixscience.com/help/fragmentation_help.html)
/// See https://github.com/OpenMS/OpenMS/issues/7219 for a discussion with more details and links.
enum ResidueType
{
Full = 0, ///< with N-terminus and C-terminus
Internal, ///< internal residue, without any termini
NTerminal, ///< only N-terminus
CTerminal, ///< only C-terminus
AIon, ///< MS:1001229 N-terminus up to the C-alpha/carbonyl carbon bond
BIon, ///< MS:1001224 N-terminus up to the peptide bond
CIon, ///< MS:1001231 N-terminus up to the amide/C-alpha bond
XIon, ///< MS:1001228 amide/C-alpha bond up to the C-terminus
YIon, ///< MS:1001220 peptide bond up to the C-terminus
ZIon, ///< MS:1001230 C-alpha/carbonyl carbon bond [CID fragment]
Zp1Ion, ///< MS:1001230 C-alpha/carbonyl carbon bond (free radical, z+1 "ion") [main EAD fragment]
Zp2Ion, ///< MS:1001230 C-alpha/carbonyl carbon bond (free radical, z+2 "ion" with additional abstracted hydrogen) [EAD fragment at higher precursor charges]
Precursor, ///< MS:1001523 Precursor ion
BIonMinusH20, ///< MS:1001222 b ion without water
YIonMinusH20, ///< MS:1001223 y ion without water
BIonMinusNH3, ///< MS:1001232 b ion without ammonia
YIonMinusNH3, ///< MS:1001233 y ion without ammonia
NonIdentified, ///< MS:1001240 Non-identified ion
Unannotated, ///< no stored annotation
SizeOfResidueType
};
//@}
/// Names corresponding to the ResidueType enum
static inline std::array<std::string_view, Residue::ResidueType::SizeOfResidueType> names_of_residuetype {
"full",
"internal",
"N-terminal",
"C-terminal",
"a-ion",
"b-ion",
"c-ion",
"x-ion",
"y-ion",
"z-ion",
"z+1-ion",
"z+2-ion",
"precursor-ion",
"b-H2O-ion",
"y-H2O-ion",
"b-NH3-ion",
"y-NH3-ion",
"Non-identified ion",
"unannotated"
};
/// returns the ion name given as a residue type
static String getResidueTypeName(const ResidueType res_type);
/** @name Constructors
*/
//@{
/// Default constructor (needed by pyOpenMS)
Residue();
/// Copy constructor
Residue(const Residue&) = default;
/// Move constructor
Residue(Residue&&) = default;
// Detailed constructor
Residue(const String& name,
const String& three_letter_code,
const String& one_letter_code,
const EmpiricalFormula& formula,
double pka = 0,
double pkb = 0,
double pkc = -1,
double gb_sc = 0,
double gb_bb_l = 0,
double gb_bb_r = 0,
const std::set<String>& synonyms = std::set<String>());
/// Destructor
virtual ~Residue();
//@}
/** @name Assignment
*/
//@{
/// Assignment operator
Residue& operator=(const Residue&) = default;
/// Move assignment operator
Residue& operator=(Residue&&) & = default;
//@}
/** @name Accessors
*/
//@{
/// sets the name of the residue
void setName(const String& name);
/// returns the name of the residue
const String& getName() const;
/// sets the synonyms
void setSynonyms(const std::set<String>& synonyms);
/// adds a synonym
void addSynonym(const String& synonym);
/// returns the synonyms
const std::set<String>& getSynonyms() const;
/// sets the name of the residue as three letter code (String of size 3)
void setThreeLetterCode(const String& three_letter_code);
/// returns the name of the residue as three letter code (String of size 3)
const String& getThreeLetterCode() const;
/// sets the name as one letter code (String of size 1)
void setOneLetterCode(const String& one_letter_code);
/// returns the name as one letter code (String of size 1)
const String& getOneLetterCode() const;
/// adds a neutral loss formula
void addLossFormula(const EmpiricalFormula&);
/// sets the neutral loss formulas
void setLossFormulas(const std::vector<EmpiricalFormula>&);
/// adds N-terminal losses
void addNTermLossFormula(const EmpiricalFormula&);
/// sets the N-terminal losses
void setNTermLossFormulas(const std::vector<EmpiricalFormula>&);
/// returns the neutral loss formulas
const std::vector<EmpiricalFormula>& getLossFormulas() const;
/// returns N-terminal loss formulas
const std::vector<EmpiricalFormula>& getNTermLossFormulas() const;
/// set the neutral loss molecule name
void setLossNames(const std::vector<String>& name);
/// sets the N-terminal loss names
void setNTermLossNames(const std::vector<String>& name);
/// add neutral loss molecule name
void addLossName(const String& name);
/// adds a N-terminal loss name
void addNTermLossName(const String& name);
/// gets neutral loss name (if there is one, else returns an empty string)
const std::vector<String>& getLossNames() const;
/// returns the N-terminal loss names
const std::vector<String>& getNTermLossNames() const;
/// set empirical formula of the residue (must be full, with N and C-terminus)
void setFormula(const EmpiricalFormula& formula);
/// returns the empirical formula of the residue
EmpiricalFormula getFormula(ResidueType res_type = Full) const;
/// sets average weight of the residue (must be full, with N and C-terminus)
void setAverageWeight(double weight);
/// returns average weight of the residue
double getAverageWeight(ResidueType res_type = Full) const;
/// sets monoisotopic weight of the residue (must be full, with N and C-terminus)
void setMonoWeight(double weight);
/// returns monoisotopic weight of the residue
double getMonoWeight(ResidueType res_type = Full) const;
/// returns a pointer to the modification, or a null pointer if none is set
const ResidueModification* getModification() const;
/// sets the modification by name; the mod should be present in ModificationsDB
void setModification(const String& name);
/// sets the modification by existing ResMod (make sure it exists in ModificationsDB)
void setModification(const ResidueModification* mod);
/// sets the modification by looking for an exact match in the DB first, otherwise creating a
/// new entry
void setModification(const ResidueModification& mod);
/// sets a modification by monoisotopic mass difference. Searches in DBs first with a tolerance.
/// If not found, creates a new entry with name = OneLetterResidueCode[+/-diffMonoMass] and adds this as user-defined mod.
void setModificationByDiffMonoMass(double diffMonoMass);
/// returns the name (ID) of the modification, or an empty string if none is set
const String& getModificationName() const;
/// sets the low mass marker ions as a vector of formulas
void setLowMassIons(const std::vector<EmpiricalFormula>& low_mass_ions);
/// returns a vector of formulas with the low mass markers of the residue
const std::vector<EmpiricalFormula>& getLowMassIons() const;
/// sets the residue sets the amino acid is contained in (e.g. Natural20)
void setResidueSets(const std::set<String>& residues_sets);
/// adds a residue set to the residue sets (e.g. Natural20)
void addResidueSet(const String& residue_sets);
/// returns the residue sets this residue is contained in (e.g. Natural20)
const std::set<String>& getResidueSets() const;
/// returns the pka of the residue
double getPka() const;
/// returns the pkb of the residue
double getPkb() const;
/// returns the pkc of the residue if it exists otherwise -1
double getPkc() const;
/// calculates the isoelectric point using the pk* values
double getPiValue() const;
/// sets the pka of the residue
void setPka(double value);
/// sets the pkb of the residue
void setPkb(double value);
/// sets the pkc of the residue
void setPkc(double value);
/// returns the side chain basicity
double getSideChainBasicity() const;
/// sets the side chain basicity
void setSideChainBasicity(double gb_sc);
/// returns the backbone basicity if located in N-terminal direction
double getBackboneBasicityLeft() const;
/// sets the N-terminal direction backbone basicity
void setBackboneBasicityLeft(double gb_bb_l);
/// returns the C-terminal direction backbone basicity
double getBackboneBasicityRight() const;
/// sets the C-terminal direction backbone basicity
void setBackboneBasicityRight(double gb_bb_r);
//@}
/** @name Predicates
*/
//@{
/// true if the residue has neutral loss
bool hasNeutralLoss() const;
/// true if N-terminal neutral losses are set
bool hasNTermNeutralLosses() const;
/// equality operator
bool operator==(const Residue& residue) const;
/// inequality operator
bool operator!=(const Residue& residue) const;
/// equality operator for one letter code
bool operator==(char one_letter_code) const;
/// equality operator for one letter code
bool operator!=(char one_letter_code) const;
/// true if the residue is a modified one
bool isModified() const;
/// true if the residue is contained in the set
bool isInResidueSet(const String& residue_set);
//@}
/// helper for mapping residue types to letters for Text annotations and labels
static std::string residueTypeToIonLetter(const ResidueType& res_type);
/// Write as Origin+Modification, e.g. M(Oxidation), or X[945.34] or N[+14.54] for user-defined mods.
/// This requires the Residue to have a valid OneLetterCode and an optional (but valid) ResidueModification (see ResidueModification::toString())
String toString() const;
/// ostream iterator to write the residue to a stream
friend OPENMS_DLLAPI std::ostream& operator<<(std::ostream& os, const Residue& residue);
protected:
/// the name of the residue
String name_ = "unknown";
std::set<String> synonyms_;
String three_letter_code_;
String one_letter_code_;
EmpiricalFormula formula_;
EmpiricalFormula internal_formula_;
double average_weight_ = 0;
double mono_weight_ = 0;
/// pointer to the modification
const ResidueModification* modification_ = nullptr;
// loss
std::vector<String> loss_names_;
std::vector<EmpiricalFormula> loss_formulas_;
std::vector<String> NTerm_loss_names_;
std::vector<EmpiricalFormula> NTerm_loss_formulas_;
/// low mass markers like immonium ions
std::vector<EmpiricalFormula> low_mass_ions_;
// pka values
double pka_ = 0;
// pkb values
double pkb_ = 0;
// pkc values
double pkc_ = -1.0;
/// SideChainBasicity
double gb_sc_ = 0;
/// BackboneBasicityLeft
double gb_bb_l_ = 0;
/// BackboneBasicityRight
double gb_bb_r_ = 0;
/// residue sets this amino acid is contained in
std::set<String> residue_sets_;
// pre-calculated residue type delta weights for more efficient weight calculation
static const double internal_to_full_monoweight_;
static const double internal_to_nterm_monoweight_;
static const double internal_to_cterm_monoweight_;
static const double internal_to_a_monoweight_;
static const double internal_to_b_monoweight_;
static const double internal_to_c_monoweight_;
static const double internal_to_x_monoweight_;
static const double internal_to_y_monoweight_;
static const double internal_to_z_monoweight_;
static const double internal_to_zp1_monoweight_;
static const double internal_to_zp2_monoweight_;
};
// write 'name threelettercode onelettercode formula'
OPENMS_DLLAPI std::ostream& operator<<(std::ostream& os, const Residue& residue);
} // namespace OpenMS
namespace std
{
/// @brief Hash specialization for OpenMS::Residue
/// Hashes all fields used in operator== for consistency.
template<>
struct hash<OpenMS::Residue>
{
std::size_t operator()(const OpenMS::Residue& r) const noexcept
{
std::size_t seed = 0;
// Hash name_
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(r.getName()));
// Hash synonyms_ (std::set<String>)
for (const auto& syn : r.getSynonyms())
{
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(syn));
}
// Hash three_letter_code_
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(r.getThreeLetterCode()));
// Hash one_letter_code_
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(r.getOneLetterCode()));
// Hash formula_
OpenMS::hash_combine(seed, std::hash<OpenMS::EmpiricalFormula>{}(r.getFormula()));
// Hash average_weight_
OpenMS::hash_combine(seed, OpenMS::hash_float(r.getAverageWeight()));
// Hash mono_weight_
OpenMS::hash_combine(seed, OpenMS::hash_float(r.getMonoWeight()));
// Hash modification_ (pointer comparison in operator==)
OpenMS::hash_combine(seed, OpenMS::hash_int(reinterpret_cast<std::uintptr_t>(r.getModification())));
// Hash loss_names_ (std::vector<String>)
for (const auto& name : r.getLossNames())
{
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(name));
}
// Hash loss_formulas_ (std::vector<EmpiricalFormula>)
for (const auto& formula : r.getLossFormulas())
{
OpenMS::hash_combine(seed, std::hash<OpenMS::EmpiricalFormula>{}(formula));
}
// Hash NTerm_loss_names_ (std::vector<String>)
for (const auto& name : r.getNTermLossNames())
{
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(name));
}
// Hash NTerm_loss_formulas_ (std::vector<EmpiricalFormula>)
for (const auto& formula : r.getNTermLossFormulas())
{
OpenMS::hash_combine(seed, std::hash<OpenMS::EmpiricalFormula>{}(formula));
}
// Hash low_mass_ions_ (std::vector<EmpiricalFormula>)
for (const auto& formula : r.getLowMassIons())
{
OpenMS::hash_combine(seed, std::hash<OpenMS::EmpiricalFormula>{}(formula));
}
// Hash pka_
OpenMS::hash_combine(seed, OpenMS::hash_float(r.getPka()));
// Hash pkb_
OpenMS::hash_combine(seed, OpenMS::hash_float(r.getPkb()));
// Hash pkc_
OpenMS::hash_combine(seed, OpenMS::hash_float(r.getPkc()));
// Hash gb_sc_
OpenMS::hash_combine(seed, OpenMS::hash_float(r.getSideChainBasicity()));
// Hash gb_bb_l_
OpenMS::hash_combine(seed, OpenMS::hash_float(r.getBackboneBasicityLeft()));
// Hash gb_bb_r_
OpenMS::hash_combine(seed, OpenMS::hash_float(r.getBackboneBasicityRight()));
// Hash residue_sets_ (std::set<String>)
for (const auto& rs : r.getResidueSets())
{
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(rs));
}
return seed;
}
};
} // namespace std
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/SimpleTSGXLMS.h | .h | 14,017 | 277 | // 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/CHEMISTRY/Residue.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/METADATA/DataArrays.h>
#include <OpenMS/ANALYSIS/XLMS/OPXLDataStructs.h>
namespace OpenMS
{
class AASequence;
/**
@brief Generates theoretical spectra for cross-linked peptides
The spectra this class generates are vectors of SimplePeaks.
This class generates the same peak types as TheoreticalSpectrumGeneratorXLMS
and the interface is very similar, but it is simpler and faster.
SimplePeak only contains an mz value and a charge. No intensity values
or String annotations or other additional DataArrays are generated.
@htmlinclude OpenMS_SimpleTSGXLMS.parameters
@ingroup Chemistry
*/
class OPENMS_DLLAPI SimpleTSGXLMS :
public DefaultParamHandler
{
public:
/**
* @brief A simple struct to represent peaks with mz and charge and sort them easily
*/
struct SimplePeak
{
double mz;
int charge;
SimplePeak(double mz, int charge)
: mz(mz), charge(charge)
{}
SimplePeak()
: mz(0.0), charge(0)
{}
};
/**
* @brief Comparator to sort SimplePeaks by mz
*/
struct SimplePeakComparator
{
bool operator() (const SimplePeak& a, const SimplePeak& b)
{
return a.mz < b.mz;
}
};
struct LossIndex
{
bool has_H2O_loss = false;
bool has_NH3_loss = false;
};
/** @name Constructors and Destructors
*/
//@{
/// default constructor
SimpleTSGXLMS();
/// copy constructor
SimpleTSGXLMS(const SimpleTSGXLMS & source);
/// destructor
~SimpleTSGXLMS() override;
//@}
/// assignment operator
SimpleTSGXLMS & operator=(const SimpleTSGXLMS & tsg);
/**
* @brief Generates fragment ions not containing the cross-linker for one peptide.
B-ions are generated from the beginning of the peptide up to the first linked position,
y-ions are generated from the second linked position up the end of the peptide.
If link_pos_2 is 0, a mono-link or cross-link is assumed and the second position is the same as the first position.
For a loop-link two different positions can be set and link_pos_2 must be larger than link_pos.
The generated ion types and other additional settings are determined by the tool parameters.
@param[in] spectrum The spectrum to which the new peaks are added. Does not have to be empty, the generated peaks will be pushed onto it.
@param[in] peptide The peptide to fragment
@param[in] link_pos The position of the cross-linker on the given peptide
@param[in] charge The maximal charge of the ions
@param[in] link_pos_2 A second position for the linker, in case it is a loop link
*/
virtual void getLinearIonSpectrum(std::vector< SimplePeak >& spectrum, AASequence& peptide, Size link_pos, int charge = 1, Size link_pos_2 = 0) const;
/**
* @brief Generates fragment ions containing the cross-linker for one peptide.
*
B-ions are generated from the first linked position up to the end of the peptide,
y-ions are generated from the beginning of the peptide up to the second linked position.
If link_pos_2 is 0, a mono-link or cross-link is assumed and the second position is the same as the first position.
For a loop-link two different positions can be set and link_pos_2 must be larger than link_pos.
Since in the case of a cross-link a whole second peptide is attached to the other side of the cross-link,
a precursor mass for the two peptides and the linker is needed.
In the case of a loop link the precursor mass is the mass of the only peptide and the linker.
Although this function is more general, currently it is mainly used for loop-links and mono-links,
because residues in the second, unknown peptide cannot be considered for possible neutral losses.
The generated ion types and other additional settings are determined by the tool parameters.
@param[in] spectrum The spectrum to which the new peaks are added. Does not have to be empty, the generated peaks will be pushed onto it.
@param[in] peptide The peptide to fragment
@param[in] link_pos The position of the cross-linker on the given peptide
@param[in] precursor_mass The mass of the whole cross-link candidate or the precursor mass of the experimental MS2 spectrum.
@param[in] min_charge The minimal charge of the ions
@param[in] max_charge The maximal charge of the ions, it should be the precursor charge and is used to generate precursor ion peaks
@param[in] link_pos_2 A second position for the linker, in case it is a loop link
*/
virtual void getXLinkIonSpectrum(std::vector< SimplePeak >& spectrum, AASequence& peptide, Size link_pos, double precursor_mass, int min_charge, int max_charge, Size link_pos_2 = 0) const;
/**
* @brief Generates fragment ions containing the cross-linker for a pair of peptides.
*
B-ions are generated from the first linked position up to the end of the peptide,
y-ions are generated from the beginning of the peptide up to the second linked position.
This function generates neutral loss ions by considering both linked peptides.
Only one of the peptides, decided by @p frag_alpha, is fragmented.
This simplifies the function, but it has to be called twice to get all fragments of a peptide pair.
The generated ion types and other additional settings are determined by the tool parameters.
This function is not suitable to generate fragments for mono-links or loop-links.
@param[in] spectrum The spectrum to which the new peaks are added. Does not have to be empty, the generated peaks will be pushed onto it.
@param[in] crosslink ProteinProteinCrossLink to be fragmented
@param[in] frag_alpha True, if the fragmented peptide is the Alpha peptide.
@param[in] min_charge The minimal charge of the ions
@param[in] max_charge The maximal charge of the ions, it should be the precursor charge and is used to generate precursor ion peaks
*/
virtual void getXLinkIonSpectrum(std::vector< SimplePeak >& spectrum, OPXLDataStructs::ProteinProteinCrossLink& crosslink, bool frag_alpha, int min_charge, int max_charge) const;
/// overwrite
void updateMembers_() override;
protected:
/**
* @brief Adds cross-link-less ions of a specific ion type and charge to a spectrum
* @param[in] spectrum The spectrum to which the new peaks are added. Does not have to be empty, the generated peaks will be pushed onto it.
* @param[in] peptide The peptide to fragment
* @param[in] link_pos The position of the cross-linker on the given peptide
* @param[in] res_type The ion type of the added peaks
* @param[in] forward_losses vector of LossIndex generated by getForwardLosses_
* @param[in] backward_losses vector of LossIndex generated by getBackwardLosses_
* @param[in] charge The charge of the added peaks
* @param[in] link_pos_2 A second position for the linker, in case it is a loop link
*/
virtual void addLinearPeaks_(std::vector< SimplePeak >& spectrum, AASequence& peptide, Size link_pos, Residue::ResidueType res_type, std::vector< LossIndex >& forward_losses, std::vector< LossIndex >& backward_losses, int charge = 1, Size link_pos_2 = 0) const;
/**
* @brief Adds precursor masses including neutral losses for the given charge
* @param[in] spectrum The spectrum to which the peaks are added
* @param[in] precursor_mass The mass of the uncharged precursor
* @param[in] charge The charge of the precursor
*/
virtual void addPrecursorPeaks_(std::vector< SimplePeak >& spectrum, double precursor_mass, int charge) const;
/**
* @brief Adds neutral losses for an ion to a spectrum
* @param[in] spectrum The spectrum to which the new peak is added
* @param[in] mono_weight monoisotopic mass of the current ion
* @param[in] charge The charge of the ion
* @param[in] losses a LossIndex with which to modify the current ion
*/
virtual void addLosses_(std::vector< SimplePeak >& spectrum, double mono_weight, int charge, LossIndex & losses) const;
/**
* @brief Adds one-residue-linked ion peaks, that are specific to XLMS
These fragments consist of one whole peptide, the cross-linker and a part of the linked residue from the second peptide.
The residue fragment on the linker is an internal ion from a y- and an a-fragmentation with the length of one residue.
The function is called KLinked for now, but instead of K it is whatever residue the linker is bound to.
* @param[in] spectrum The spectrum to which the peaks are added
* @param[in] peptide The fragmented peptide
* @param[in] link_pos position of the linker on the fragmented peptide
* @param[in] precursor_mass The mass of the whole cross-link candidate or the precursor mass of the experimental MS2 spectrum.
* @param[in] charge The charge of the ion
*/
virtual void addKLinkedIonPeaks_(std::vector< SimplePeak >& spectrum, AASequence & peptide, Size link_pos, double precursor_mass, int charge) const;
/**
* @brief Adds cross-linked ions of a specific ion type and charge to a spectrum
This version of the function is for mono-links and loop-links.
* @param[in] spectrum The spectrum to which the new peaks are added. Does not have to be empty, the generated peaks will be pushed onto it.
* @param[in] peptide The peptide to fragment
* @param[in] link_pos The position of the cross-linker on the given peptide
* @param[in] precursor_mass The mass of the whole cross-link candidate or the precursor mass of the experimental MS2 spectrum.
* @param[in] res_type The ion type of the added peaks
* @param[in] forward_losses vector of LossIndex generated by getForwardLosses_
* @param[in] backward_losses vector of LossIndex generated by getBackwardLosses_
* @param[in] charge The charge of the added peaks
* @param[in] link_pos_2 A second position for the linker, in case it is a loop link
*/
virtual void addXLinkIonPeaks_(std::vector<SimplePeak>& spectrum, AASequence& peptide, Size link_pos, double precursor_mass, Residue::ResidueType res_type, std::vector< LossIndex > & forward_losses, std::vector< LossIndex > & backward_losses, int charge, Size link_pos_2 = 0) const;
/**
* @brief Adds cross-linked ions of a specific ion type and charge to a spectrum
This version of the function is for cross-linked peptide pairs.
* @param[in] spectrum The spectrum to which the new peaks are added. Does not have to be empty, the generated peaks will be pushed onto it.
* @param[in] crosslink The ProteinProteinCrossLink to be fragmented
* @param[in] frag_alpha True, if the fragmented peptide is the Alpha peptide. Used for ion-name annotation.
* @param[in] res_type The ion type of the added peaks
* @param[in] forward_losses vector of LossIndex generated by getForwardLosses_ for the fragmented peptide
* @param[in] backward_losses vector of LossIndex generated by getBackwardLosses_ for the fragmented peptide
* @param[in] losses_peptide2 set of losses for the second, not fragmented peptide, e.g. last set from getForwardLosses_ for the second peptide
* @param[in] charge The charge of the added peaks
*/
virtual void addXLinkIonPeaks_(std::vector< SimplePeak >& spectrum, OPXLDataStructs::ProteinProteinCrossLink & crosslink, bool frag_alpha, Residue::ResidueType res_type, std::vector< LossIndex > & forward_losses, std::vector< LossIndex > & backward_losses, LossIndex & losses_peptide2, int charge) const;
/**
* @brief Calculates sets of possible neutral losses for each position in the given peptide
This function generates a vector of sets. Each set contains the possible neutral losses for a specific prefix of the peptide.
* @param[in] peptide The peptide or ion for which to collect possible losses
*/
std::vector< LossIndex > getForwardLosses_(AASequence & peptide) const;
/**
* @brief Calculates sets of possible neutral losses for each position in the given peptide
This function generates a vector of sets. Each set contains the possible neutral losses for a specific suffix of the peptide.
* @param[in] peptide The peptide or ion for which to collect possible losses
*/
std::vector< LossIndex > getBackwardLosses_(AASequence & peptide) const;
bool add_b_ions_;
bool add_y_ions_;
bool add_a_ions_;
bool add_c_ions_;
bool add_x_ions_;
bool add_z_ions_;
bool add_first_prefix_ion_;
bool add_losses_;
bool add_charges_;
bool add_isotopes_;
bool add_precursor_peaks_;
bool add_abundant_immonium_ions_;
Int max_isotope_;
double pre_int_;
double pre_int_H2O_;
double pre_int_NH3_;
bool add_k_linked_ions_;
std::map< String, LossIndex > loss_db_;
double loss_H2O_ = 0;
double loss_NH3_ = 0;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/ModificationsDB.h | .h | 14,025 | 285 | // 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/CHEMISTRY/AASequence.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/CHEMISTRY/ResidueModification.h>
#include <set>
#include <memory> // unique_ptr
#include <unordered_map>
namespace OpenMS
{
// forward declarations
class ResidueModification;
class Residue;
/** @ingroup Chemistry
@brief database which holds all residue modifications from UniMod
This singleton class serves as a storage of the available modifications
represented by UniMod (www.unimod.org). The modifications are identified
by their name and possibly other IDs from UniMod or the PSI-MOD ontology.
Modifications can have different specificities, e.g. they can occur only
at the termini, anywhere or only at specific amino acids.
The modifications are defined in share/OpenMS/CHEMISTRY/unimod.xml and
in share/OpenMS/CHEMISTRY/PSI-MOD.obo. The unimod file can be directly
downloaded from unimod.org and replaced if the modifications change.
To add a new modification, not contained in UniMod, one should follow
the way described at the unimod.org website and download the file then
from unimod.org. The same can be done to add support for the modifications
to search engines, e.g. Mascot.
In some scenarios, it might be useful to define different modification
databases. This can be done by providing a path through
initializeModificationsDB(), however it is important that this is done
*before* the first call to getInstance().
*/
class OPENMS_DLLAPI ModificationsDB
{
public:
/// Returns a pointer to the modifications DB (singleton)
static ModificationsDB* getInstance();
/// Initializes the modification DB with non-default modification files (can only be done once)
static ModificationsDB* initializeModificationsDB(OpenMS::String unimod_file = "CHEMISTRY/unimod.xml", OpenMS::String custommod_file = "CHEMISTRY/custom_mods.xml", OpenMS::String psimod_file = "CHEMISTRY/PSI-MOD.obo", OpenMS::String xlmod_file = "CHEMISTRY/XLMOD.obo");
/// Check whether ModificationsDB was instantiated before
static bool isInstantiated();
friend class CrossLinksDB;
// for access to addNewModification_ (without checking presence)
friend class Residue;
friend class AASequence;
/// Returns the number of modifications read from the unimod.xml file
Size getNumberOfModifications() const;
/**
@brief Returns the modification with the given index.
note: out-of-bounds check is only performed in debug mode.
*/
const ResidueModification* getModification(Size index) const;
/**
@brief Collects all modifications which have the given name as synonym
@todo use set as return value. Would be more efficient in pyopenms
If @p residue is set, only modifications with matching residue of origin are considered.
If @p term_spec is set, only modifications with matching term specificity are considered.
The resulting set of modifications will be empty if no modification exists that fulfills the criteria.
*/
void searchModifications(std::set<const ResidueModification*>& mods,
const String& mod_name,
const String& residue = "",
ResidueModification::TermSpecificity term_spec = ResidueModification::NUMBER_OF_TERM_SPECIFICITY) const;
/**
@brief Returns a pointer to an exact match of the given modification if present in the DB.
This should be used if e.g. only a stack copy of the modification is available but you need
a pointer to the modification in the database.
@return The matching modification given the constraints. Returns nullptr
if no modification exists that is an exact match accoring to the equals operator.
*/
const ResidueModification* searchModification(const ResidueModification& mod_in) const;
/**
@brief Returns the modification which has the given name as synonym (fast version)
Unlike searchModifications(), only returns the one occurrence of the
modification (the last occurrence). It is therefore required to check @p
multiple_matches to ensure that only a single modification was found.
If @p residue is set, only modifications with matching residue of origin are considered.
If @p term_spec is set, only modifications with matching term specificity are considered.
@return The matching modification given the constraints. Returns nullptr
if no modification exists that fulfills the criteria. If multiple
modifications are found, the @p multiple_matches flag will be set.
*/
const ResidueModification* searchModificationsFast(const String& mod_name,
bool& multiple_matches,
const String& residue = "",
ResidueModification::TermSpecificity term_spec = ResidueModification::NUMBER_OF_TERM_SPECIFICITY) const;
/**
@brief Returns the modification with the given name
If @p residue is set, only modifications with matching residue of origin are considered.
If @p term_spec is set, only modifications with matching term specificity are considered.
If more than one matching modification is found, the first one is returned with a warning.
@note Will never return a null pointer, instead will throw an exceptions.
@throw Exception::ElementNotFound if no modification named @p mod_name exists (via searchModifications())
@throw Exception::InvalidValue if no matching modification exists
*/
const ResidueModification* getModification(const String& mod_name, const String& residue = "", ResidueModification::TermSpecificity term_spec = ResidueModification::NUMBER_OF_TERM_SPECIFICITY) const;
/// Returns true if the modification exists
bool has(const String& modification) const;
/**
@brief Add a new modification to ModificationsDB.
If the modification already exists (based on its fullID) it is not added.
@return a pointer to the modification in the ModificationDB (which can differ from input if mod was already present).
@param[in] new_mod Owning pointer, which transfers ownership to ModificationsDB (mod might get deleted if already present!)
*/
const ResidueModification* addModification(std::unique_ptr<ResidueModification> new_mod);
/**
@brief Add a new modification to ModificationsDB.
If the modification already exists (based on its fullID) it is not added. A copy will be made on the heap and added to the ModificationsDB otherwise.
@return a pointer to the modification in the ModificationDB (which can differ from input if mod was already present).
@param[in] new_mod The new modification object. A copy will be made on the heap and added to the ModificationsDB if not already present.
*/
const ResidueModification* addModification(const ResidueModification& new_mod);
/**
@brief Returns the index of the modification in the mods_ vector; a unique name must be given
return numeric_limits<Size>::max() if not exactly one matching modification was found
or no matching residue or modification were found
@throw Exception::ElementNotFound if not exactly one matching modification was found.
*/
Size findModificationIndex(const String& mod_name) const;
/**
@brief Collects all modifications with delta mass inside a tolerance window
@warning This function adds the results in the order of appearance in the DB, not considering proximity in mass. Use searchModificationsByDiffMonoMassSorted for this.
If @p residue is set, only modifications with matching residue of origin are considered.
If @p term_spec is set, only modifications with matching term specificity are considered.
*/
void searchModificationsByDiffMonoMass(std::vector<String>& mods, double mass, double max_error, const String& residue = "", ResidueModification::TermSpecificity term_spec = ResidueModification::NUMBER_OF_TERM_SPECIFICITY);
void searchModificationsByDiffMonoMass(std::vector<const ResidueModification*>& mods, double mass, double max_error, const String& residue = "", ResidueModification::TermSpecificity term_spec = ResidueModification::NUMBER_OF_TERM_SPECIFICITY);
/**
@brief Collects all modifications with delta mass inside a tolerance window and adds them sorted
by mass difference
If @p residue is set, only modifications with matching residue of origin are considered.
If @p term_spec is set, only modifications with matching term specificity are considered.
*/
void searchModificationsByDiffMonoMassSorted(std::vector<String>& mods, double mass, double max_error, const String& residue = "", ResidueModification::TermSpecificity term_spec = ResidueModification::NUMBER_OF_TERM_SPECIFICITY);
void searchModificationsByDiffMonoMassSorted(std::vector<const ResidueModification*>& mods, double mass, double max_error, const String& residue = "", ResidueModification::TermSpecificity term_spec = ResidueModification::NUMBER_OF_TERM_SPECIFICITY);
/** @brief Returns the best matching modification for the given delta mass and residue
Query the modifications DB to get the best matching modification with
the given delta mass at the given residue (NULL pointer means no result,
maybe the maximal error tolerance needs to be increased). Possible
input for CAM modification would be a delta mass of 57 and a residue
of "C".
@note If there are multiple possible matches with equal masses, it
will choose the _first_ match which defaults to the first matching
UniMod entry.
@param[in] mass The monoisotopic mass of the residue including the mass of the modification
@param[in] max_error The maximal mass error in the modification search
@param[in] residue The residue at which the modifications occurs
@param[in] term_spec Only modifications with matching term specificity are considered.
@return A pointer to the best matching modification (or NULL if none was found)
*/
const ResidueModification* getBestModificationByDiffMonoMass(double mass, double max_error, const String& residue = "", ResidueModification::TermSpecificity term_spec = ResidueModification::NUMBER_OF_TERM_SPECIFICITY);
/// Collects all modifications that can be used for identification searches
void getAllSearchModifications(std::vector<String>& modifications) const;
/// Writes tab separated entries: FullId,FullName,Origin,AA,TerminusSpecificity,DiffMonoMass (including header) to TSV file
void writeTSV(const String& filename);
protected:
/// Stores whether ModificationsDB was instantiated before
static bool is_instantiated_;
/// Stores the modifications
std::vector<ResidueModification*> mods_;
/// Stores the mappings of (unique) names to the modifications
std::unordered_map<String, std::set<const ResidueModification*> > modification_names_;
/** @brief Helper function to check if a residue matches the origin for a modification
*
* Special cases are handled as follows:
* * if the origin of the modification is not "X" (everything), then the
* residue either needs to match the origin exactly or it must be one of "X", ".", or "?"
* * if the origin of the modification is "X" (can match any amino acid),
* then any residue should match -- except if the modification is
* user-defined and maps to an unknown amino acid (indicated by "X")
*
* Underlying logic to determine whether a given residue matches the
* modification: if the modification does not have origin of "X"
* (everything) then it is sufficient to check that the residue matches the origin
*
*/
bool residuesMatch_(const char residue, const ResidueModification* curr_mod) const;
private:
/** @name Constructors and Destructors
@param[in] unimod_file Path to the Unimod XML file
@param[in] psimod_file Path to the PSI-MOD OBO file
@param[in] xlmod_file Path to the XLMOD OBO file
*/
//@{
explicit ModificationsDB(const OpenMS::String& unimod_file = "CHEMISTRY/unimod.xml", const OpenMS::String& custommod_file = "CHEMISTRY/custom_mods.xml", const OpenMS::String& psimod_file = "CHEMISTRY/PSI-MOD.obo", const OpenMS::String& xlmod_file = "CHEMISTRY/XLMOD.obo");
/// Copy constructor
ModificationsDB(const ModificationsDB& residue_db);
/// Destructor
virtual ~ModificationsDB();
//@}
/** @name Assignment
*/
//@{
/// Assignment operator
ModificationsDB & operator=(const ModificationsDB& aa);
//@}
/**
@brief Add a new modification to ModificationsDB without checking if it was inside already.
@param[in] new_mod A copy will be made on the heap and added to the modification if not already present.
*/
const ResidueModification* addNewModification_(const ResidueModification& new_mod);
/**
@brief Adds modifications from a given file in OBO format
@throw Exception::ParseError if the file cannot be parsed correctly
*/
void readFromOBOFile(const String& filename);
/// Adds modifications from a given file in Unimod XML format
void readFromUnimodXMLFile(const String& filename);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/DecoyGenerator.h | .h | 3,432 | 96 | // 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/CONCEPT/Types.h>
#include <OpenMS/MATH/MathFunctions.h>
#include <unordered_map>
namespace OpenMS
{
class AASequence;
class DigestionEnzymeProtein;
/**
@brief Methods to generate isobaric decoy sequences for DDA target-decoy searches.
*/
class OPENMS_DLLAPI DecoyGenerator
{
public:
// initializes random generator
DecoyGenerator();
// destructor
~DecoyGenerator() = default;
// random seed for shuffling
void setSeed(UInt64 seed);
/*
@brief reverses the protein sequence.
note: modifications are discarded
*/
AASequence reverseProtein(const AASequence& protein) const;
/*
@brief reverses the protein's peptide sequences between enzymatic cutting positions.
note: modifications are discarded
*/
AASequence reversePeptides(const AASequence& protein, const String& protease) const;
/**
@brief Generate decoy protein sequences using shuffle algorithm
Digests the protein using the specified protease and shuffles each resulting peptide
to minimize sequence identity with the target. For top-down proteomics, use "no cleavage"
as the protease to shuffle the entire protein as a single sequence.
@param[in] protein The protein sequence to generate decoys from
@param[in] protease The enzyme name (e.g., "Trypsin", "Trypsin/P", "no cleavage")
@param[in] decoy_factor Number of decoy variants to generate per target peptide (default: 1)
@return Vector of shuffled decoy sequences (one entry per decoy variant)
@note
- Peptides <= 2 amino acids are kept unchanged
- Each peptide uses a fresh DecoyGenerator with fixed seed to ensure
identical peptides produce identical decoys across different proteins
- Modifications are discarded
- Returns decoy_factor number of complete protein sequences
*/
std::vector<AASequence> shuffle(const AASequence& protein, const String& protease, int decoy_factor = 1);
/*
@brief shuffle the protein's peptide sequences between enzymatic cutting positions.
each peptide is shuffled @p max_attempts times to minimize sequence identity.
Note:
- Generated decoys are retrieved from a cache to prevent that same peptide (in different proteins)
leads to different decoys.
- modifications are discarded
*/
AASequence shufflePeptides(
const AASequence& aas,
const String& protease,
const int max_attempts = 100
);
private:
// sequence identity by matching AAs
static double SequenceIdentity_(const String& decoy, const String& target);
// portable shuffle
Math::RandomShuffler shuffler_;
// ensures that shuffling same peptide (in different proteins) leads to same decoy
std::unordered_map<std::string, std::string> td_cache_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/ModificationDefinition.h | .h | 4,415 | 146 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: $
// --------------------------------------------------------------------------
//
#pragma once
#include <OpenMS/CONCEPT/Types.h>
#include <OpenMS/CONCEPT/HashUtils.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/CHEMISTRY/ResidueModification.h>
#include <cstdint>
#include <functional>
namespace OpenMS
{
/** @ingroup Chemistry
@brief Representation of modification definition
This class defines a modification type e.g. a input parameter of a search engine.
The modification is defined using an unique name of the modification present
in the modifications DB instance.
*/
class OPENMS_DLLAPI ModificationDefinition
{
public:
/** @name Constructor and Destructors
*/
//@{
/// default constructor
ModificationDefinition();
/// copy constructor
ModificationDefinition(const ModificationDefinition& rhs);
/// detailed constructor specifying the modification by name
explicit ModificationDefinition(const String& mod, bool fixed = true, UInt max_occur = 0);
/// direct constructor from a residue modification
explicit ModificationDefinition(const ResidueModification& mod, bool fixed = true, UInt max_occur = 0);
/// destructor
virtual ~ModificationDefinition();
//@}
/** @name Accessors
*/
//@{
/// sets whether this modification definition is fixed or variable (modification must occur vs. can occur)
void setFixedModification(bool fixed);
/// returns if the modification if fixed true, else false
bool isFixedModification() const;
/// set the maximal number of occurrences per peptide (unbounded if 0)
void setMaxOccurrences(UInt num);
/// returns the maximal number of occurrences per peptide
UInt getMaxOccurrences() const;
/// returns the name of the modification
String getModificationName() const;
/// sets the modification, allowed are unique names provided by ModificationsDB
void setModification(const String& modification);
/**
@brief Returns the modification
@throw Exception::InvalidValue if no modification was set
*/
const ResidueModification& getModification() const;
//@}
/** @name Assignment
*/
//@{
/// assignment operator
ModificationDefinition& operator=(const ModificationDefinition& element);
//@}
/** @name Predicates
*/
//@{
/// equality operator
bool operator==(const ModificationDefinition& rhs) const;
/// inequality operator
bool operator!=(const ModificationDefinition& rhs) const;
/// less than operator for e.g. usage in maps; only mod FullIds are compared!
bool operator<(const OpenMS::ModificationDefinition&) const;
//@}
protected:
/// the modification
const ResidueModification* mod_;
/// fixed (true) or variable (false)
bool fixed_modification_;
/// maximal number of occurrences per peptide
UInt max_occurrences_;
};
} // namespace OpenMS
namespace std
{
/**
* @brief Hash function for OpenMS::ModificationDefinition.
*
* Computes a hash based on all fields used in operator==:
* - mod_ pointer (pointer identity, not content)
* - fixed_modification_ (bool)
* - max_occurrences_ (UInt)
*
* @note Since operator== compares pointer addresses (not dereferencing),
* this hash uses pointer identity. Hash is consistent within a process
* but not reproducible across process runs due to address space layout.
*/
template<>
struct hash<OpenMS::ModificationDefinition>
{
std::size_t operator()(const OpenMS::ModificationDefinition& md) const noexcept
{
// Hash the modification pointer as uintptr_t (matches pointer comparison in operator==)
std::size_t seed = OpenMS::hash_int(reinterpret_cast<std::uintptr_t>(&md.getModification()));
// Hash fixed_modification_ flag
OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(md.isFixedModification())));
// Hash max_occurrences_
OpenMS::hash_combine(seed, OpenMS::hash_int(md.getMaxOccurrences()));
return seed;
}
};
} // namespace std
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/ResidueModification.h | .h | 19,067 | 503 | // 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/DATASTRUCTURES/String.h>
#include <OpenMS/CHEMISTRY/EmpiricalFormula.h>
#include <OpenMS/CONCEPT/HashUtils.h>
#include <functional>
#include <set>
namespace OpenMS
{
// forward declaration
class Residue;
/** @brief Representation of a modification on an amino acid residue
This class represents a modification of a Residue. A residue modification
has several attributes like the diff formula, a terminal specificity,
a mass and maybe an origin which means a specific residue which it can
be applied to. A residue modification can be represented by its Unimod name
identifier (Id), e.g. "Oxidation (M)" or "Oxidation". This is a unique key which
only occurs once in an OpenMS instance stored in the ModificationsDB.
Example: methionine sulfoxide formation by oxidation of methionine
@code
Function | Result
----------------------------------------------------
getFullId() | "Oxidation (M)"
getId() | "Oxidation"
getFullName() | "Oxidation or Hydroxylation"
getUniModAccession() | "UniMod:312"
@endcode
Note that some modifications are not explicitly defined from an input
file but get added on the fly when reading amino acid sequences with
bracket notation, e.g. "PEPTX[999]IDE". If there is no known modification
corresponding to the indicated mass, then a new ResidueModification will
be created which will return the initial string through "getFullId()" --
which will either be "[999]" for internal modifications or ".[999]" for
N/C-terminal modifications. Please use "isUserDefined" to check for
user-defined modifications (those without 'Id' but with a 'FullId').
*/
class OPENMS_DLLAPI ResidueModification
{
public:
/** Enums
*/
//@{
/** @brief Position where the modification is allowed to occur
The allowed sites are
Anywhere
Any C-term
Any N-term
Protein C-term
Protein N-term
This does not describe which modifications are valid for a
specific amino acid!
*/
enum TermSpecificity
{
ANYWHERE = 0, ///< The modification can go anywhere
C_TERM = 1, ///< The modification can only be C-terminal on the peptide
N_TERM = 2, ///< The modification can only be N-terminal on the peptide
PROTEIN_C_TERM = 3, ///< The modification can only be protein C-terminal (on a C-terminal peptide)
PROTEIN_N_TERM = 4, ///< The modification can only be protein N-terminal (on a N-terminal peptide)
NUMBER_OF_TERM_SPECIFICITY
};
/** @brief Classification of the modification
*/
enum SourceClassification
{
ARTIFACT = 0, ///< A technical or chemical artefact
HYPOTHETICAL, ///< A hypothetical modification
NATURAL, ///< A natural modification
POSTTRANSLATIONAL, ///< A post-translational modification
MULTIPLE, ///< A combination of multiple modifications
CHEMICAL_DERIVATIVE, ///< A chemical derivative
ISOTOPIC_LABEL, ///< A chemical label (artificial)
PRETRANSLATIONAL, ///< A pre-translational modification
OTHER_GLYCOSYLATION, ///< Other glycosylation (i.e. neither N nor O-linked)
NLINKED_GLYCOSYLATION, ///< N-linked glycosylation
AA_SUBSTITUTION, ///< An amino acid substitution that presents like a modification
OTHER, ///< Other modification
NONSTANDARD_RESIDUE, ///< A non-standard amino acid
COTRANSLATIONAL, ///< A co-translational modification
OLINKED_GLYCOSYLATION, ///< A O-linked glycosylation
UNKNOWN, ///< An unknown modification
NUMBER_OF_SOURCE_CLASSIFICATIONS
};
//@}
/** @name Constructors and Destructors
*/
//@{
/// Default constructor
ResidueModification();
/// Copy constructor
ResidueModification(const ResidueModification&) = default;
/// Move constructor
ResidueModification(ResidueModification&&) = default;
/// Destructor
virtual ~ResidueModification();
//@}
/** @name Assignment operator
*/
//@{
/// Assignment operator
ResidueModification& operator=(const ResidueModification&) = default;
/// Move assignment operator
ResidueModification& operator=(ResidueModification&&) & = default;
//@}
/** @name Accessors
*/
//@{
/// set the identifier of the modification
void setId(const String& id);
/// returns the identifier of the modification
const String& getId() const;
/**
@brief Sets the full identifier (Unimod Accession + origin, if available)
With empty argument, create a full ID based on (short) ID, terminal specificity and residue of origin.
@throw Exception::MissingInformation if both argument @p full_id and member @p id_ are empty.
*/
void setFullId(const String& full_id = "");
/// returns the full identifier of the mod (Unimod accession + origin, if available)
/**
@brief Returns the full identifier (Unimod Accession + origin, if available)
@note This field is used for user-defined modifications as well and will
be set to a string such as "[999]" for internal modifications or
".[999]" for N/C-terminal modifications. Please use "isUserDefined" to
check for user-defined modifications.
*/
const String& getFullId() const;
/// sets the unimod record id
void setUniModRecordId(const Int& id);
/// gets the unimod record id
const Int& getUniModRecordId() const;
/// returns the unimod accession if available
const String getUniModAccession() const;
/// set the MOD:XXXXX accession of PSI-MOD
void setPSIMODAccession(const String& id);
/// returns the PSI-MOD accession if available
const String& getPSIMODAccession() const;
/// sets the full name of the modification; must NOT contain the origin (or . for terminals!)
void setFullName(const String& full_name);
/// returns the full name of the modification
const String& getFullName() const;
/// sets the name of modification
void setName(const String& name);
/// returns the PSI-MS-label if available; e.g. Mascot uses this name
const String& getName() const;
/**
@brief Sets the term specificity
@throw Exception::InvalidValue if no valid specificity was given
*/
void setTermSpecificity(TermSpecificity term_spec);
/**
@brief Sets the terminal specificity using a name
Valid names: "C-term", "N-term", "none"
@throw Exception::InvalidValue if no valid specificity was given
*/
void setTermSpecificity(const String& name);
/// returns terminal specificity
TermSpecificity getTermSpecificity() const;
/**
@brief Returns the name of the terminal specificity
By default, returns the name of the specificity set in member @p term_spec_.
Alternatively, returns the name corresponding to argument @p term_spec.
*/
String getTermSpecificityName(TermSpecificity term_spec = NUMBER_OF_TERM_SPECIFICITY) const;
/**
@brief Sets the origin (i.e. modified amino acid)
@p origin must be a valid amino acid one-letter code or X, i.e. a letter from A to Y, excluding B and J.
X represents any amino acid (for modifications with terminal specificity).
@throw Exception::InvalidValue if @p origin is not in the valid range
*/
void setOrigin(char origin);
/// Returns the origin (i.e. modified amino acid)
char getOrigin() const;
/// classification as defined by the PSI-MOD
void setSourceClassification(const String& classification);
/// sets the source classification
void setSourceClassification(SourceClassification classification);
/// returns the source classification, if none was set, it is unspecific
SourceClassification getSourceClassification() const;
/// returns the classification
String getSourceClassificationName(SourceClassification classification = NUMBER_OF_SOURCE_CLASSIFICATIONS) const;
/// sets the average mass
void setAverageMass(double mass);
/// returns the average mass if set
double getAverageMass() const;
/// sets the monoisotopic mass (this must include the weight of the residue itself!)
void setMonoMass(double mass);
/// return the monoisotopic mass, or 0.0 if not set
double getMonoMass() const;
/// set the difference average mass
void setDiffAverageMass(double mass);
/// returns the difference average mass, or 0.0 if not set
double getDiffAverageMass() const;
/// sets the difference monoisotopic mass
void setDiffMonoMass(double mass);
/// returns the diff monoisotopic mass, or 0.0 if not set
double getDiffMonoMass() const;
/// set the formula (no masses will be changed)
void setFormula(const String& composition);
/// returns the chemical formula if set
const String& getFormula() const;
/// sets diff formula (no masses will be changed)
void setDiffFormula(const EmpiricalFormula& diff_formula);
/// returns the diff formula if one was set
const EmpiricalFormula& getDiffFormula() const;
/// sets the synonyms of that modification
void setSynonyms(const std::set<String>& synonyms);
/// adds a synonym to the unique list
void addSynonym(const String& synonym);
/// returns the set of synonyms
const std::set<String>& getSynonyms() const;
/// sets the neutral loss formula
void setNeutralLossDiffFormulas(const std::vector<EmpiricalFormula>& diff_formulas);
/// returns the neutral loss diff formula (if available)
const std::vector<EmpiricalFormula>& getNeutralLossDiffFormulas() const;
/// set the neutral loss mono weight
void setNeutralLossMonoMasses(std::vector<double> mono_masses);
/// returns the neutral loss mono weight
std::vector<double> getNeutralLossMonoMasses() const;
/// set the neutral loss average weight
void setNeutralLossAverageMasses(std::vector<double> average_masses);
/// returns the neutral loss average weight
std::vector<double> getNeutralLossAverageMasses() const;
//@}
/** @name Predicates
*/
//@{
/// returns true if a neutral loss formula is set
bool hasNeutralLoss() const;
/// returns true if it is a user-defined modification (empty id)
bool isUserDefined() const;
/// equality operator
bool operator==(const ResidueModification& modification) const;
/// inequality operator
bool operator!=(const ResidueModification& modification) const;
/// less operator
bool operator<(const ResidueModification& modification) const;
//@}
/// Creates a new modification from a mass and adds it to ModificationsDB.
/// If not terminal, needs a Residue to be put on.
/// @param[in] mod The mass to put between the brackets (might contain +/- at the front)
/// @param[in] mass Basically, the same as mod, just as double (since usually both representations are present when calling this function and to avoid overhead??)
/// @param[in] delta_mass Is the given mass a delta mass (i.e. does @p mod contain a = or -)?
/// @param[in] specificity To which site can this mod be applied?
/// @param[in] residue [only required for ANYWHERE term spec] Residue with further information (e.g. residue weights) for the new mod
/// @return a new or existing mod; registered to ModDB in both cases, so the pointer is non-owning (FullId is e.g. M[+1234.1] and FullName [+1234.1]. Id and Name are empty as defined for a "user-defined" mod.
static const ResidueModification* createUnknownFromMassString(const String& mod,
const double mass,
const bool delta_mass,
const TermSpecificity specificity,
const Residue* residue = nullptr);
/** @brief Merge a set of mods to a given modification (usually the one which is already present, but can be null)
If only one mod is combined in total, it is not changed to an unknown mod but remains a 'known' mod.
If base is already contained in @p addons, it is not added again.
All mods given here must have the same term specificity and origin (which might be 'X', i.e. no restriction), otherwise a Precondition exception is thrown.
If base and addons is empty, a null_ptr is returned.
@param[in] base An already present mod, can be a nullptr
@param[in] addons A set of mods to add on top of the mod.
@param[in] allow_unknown_masses If any input (incl. base) is already an unknown mass, nothing is done
@param[in] residue [only required for ANYWHERE term spec] Residue with further information (e.g. residue weights) for the new mod
@return A (new custom) mod, which is registered in ModificationsDB if needed.
@throws Exception::Precondition if term spec or origins to not match between all given mods
**/
static const ResidueModification* combineMods(const ResidueModification* base,
const std::set<const ResidueModification*>& addons,
bool allow_unknown_masses = false,
const Residue* residue = nullptr);
/// Convert to string (incl. origin/terminal), in order of preference:
/// + using the ID, as X(ID), e.g. 'M(Oxidation)' or '.(Acetyl)'
/// + using the FullName
/// + using the delta_mono_mass, e.g. 'M[+15.65]'
/// + using the mono_mass, e.g. 'M[56.23]'
///
/// The mono_mass must not be negative (undistinguishable to delta_mono_mass when parsing)
String toString() const;
/// converts the mass to a string with preceding '+' or '-' sign
/// e.g. '-19.34' or '+1.003'
static String getDiffMonoMassString(const double diff_mono_mass);
/// return a string of the form '[+>mass<] (the '+' might be a '-', if mass is negative).
static String getDiffMonoMassWithBracket(const double diff_mono_mass);
/// return a string of the form '[>mass<]
static String getMonoMassWithBracket(const double mono_mass);
protected:
String id_;
String full_id_;
String psi_mod_accession_;
// The UniMod record id (an integer)
Int unimod_record_id_;
String full_name_;
String name_;
TermSpecificity term_spec_;
char origin_;
SourceClassification classification_;
double average_mass_;
double mono_mass_;
double diff_average_mass_;
double diff_mono_mass_;
String formula_;
EmpiricalFormula diff_formula_;
std::set<String> synonyms_;
std::vector<EmpiricalFormula> neutral_loss_diff_formulas_;
std::vector<double> neutral_loss_mono_masses_;
std::vector<double> neutral_loss_average_masses_;
};
} // namespace OpenMS
// Hash function specialization for ResidueModification
// Placed in std namespace to allow use with std::unordered_map/set
namespace std
{
/**
* @brief Hash function for OpenMS::ResidueModification.
*
* Computes a hash based on all fields used in operator==:
* id, full_id, psi_mod_accession, unimod_record_id, full_name, name,
* term_spec, origin, classification, masses (average, mono, diff_average, diff_mono),
* formula, diff_formula, synonyms, and neutral loss data.
*
* @note Hash is consistent with operator== - equal objects produce equal hashes.
*/
template<>
struct hash<OpenMS::ResidueModification>
{
std::size_t operator()(const OpenMS::ResidueModification& mod) const noexcept
{
// Hash string fields
std::size_t seed = OpenMS::fnv1a_hash_string(mod.getId());
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(mod.getFullId()));
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(mod.getPSIMODAccession()));
OpenMS::hash_combine(seed, OpenMS::hash_int(mod.getUniModRecordId()));
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(mod.getFullName()));
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(mod.getName()));
// Hash enum fields (as integers)
OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(mod.getTermSpecificity())));
OpenMS::hash_combine(seed, OpenMS::hash_char(mod.getOrigin()));
OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(mod.getSourceClassification())));
// Hash mass fields
OpenMS::hash_combine(seed, OpenMS::hash_float(mod.getAverageMass()));
OpenMS::hash_combine(seed, OpenMS::hash_float(mod.getMonoMass()));
OpenMS::hash_combine(seed, OpenMS::hash_float(mod.getDiffAverageMass()));
OpenMS::hash_combine(seed, OpenMS::hash_float(mod.getDiffMonoMass()));
// Hash formula fields
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(mod.getFormula()));
OpenMS::hash_combine(seed, std::hash<OpenMS::EmpiricalFormula>{}(mod.getDiffFormula()));
// Hash synonyms (set<String>)
const auto& synonyms = mod.getSynonyms();
OpenMS::hash_combine(seed, OpenMS::hash_int(synonyms.size()));
for (const auto& syn : synonyms)
{
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(syn));
}
// Hash neutral loss diff formulas (vector<EmpiricalFormula>)
const auto& nl_formulas = mod.getNeutralLossDiffFormulas();
OpenMS::hash_combine(seed, OpenMS::hash_int(nl_formulas.size()));
for (const auto& nlf : nl_formulas)
{
OpenMS::hash_combine(seed, std::hash<OpenMS::EmpiricalFormula>{}(nlf));
}
// Hash neutral loss mono masses (vector<double>)
const auto& nl_mono = mod.getNeutralLossMonoMasses();
OpenMS::hash_combine(seed, OpenMS::hash_int(nl_mono.size()));
for (double mass : nl_mono)
{
OpenMS::hash_combine(seed, OpenMS::hash_float(mass));
}
// Hash neutral loss average masses (vector<double>)
const auto& nl_avg = mod.getNeutralLossAverageMasses();
OpenMS::hash_combine(seed, OpenMS::hash_int(nl_avg.size()));
for (double mass : nl_avg)
{
OpenMS::hash_combine(seed, OpenMS::hash_float(mass));
}
return seed;
}
};
} // namespace std
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/CrossLinksDB.h | .h | 1,633 | 64 | // 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/CHEMISTRY/ModificationsDB.h>
namespace OpenMS
{
class OPENMS_DLLAPI CrossLinksDB :
public ModificationsDB
{
public:
/// Returns a pointer to the modifications DB (singleton)
inline static CrossLinksDB* getInstance()
{
static CrossLinksDB* db_ = new CrossLinksDB;
return db_;
}
/**
@brief Adds modifications from a given file in OBO format
@note readFromOBOFile should be called in a single threaded context with
no other threads accessing the CrossLinkDB
@throw Exception::ParseError if the file cannot be parsed correctly
*/
void readFromOBOFile(const String& filename);
/// Collects all modifications that can be used for identification searches
void getAllSearchModifications(std::vector<String>& modifications) const;
private:
/** @name Constructors and Destructors
*/
//@{
/// Default constructor
CrossLinksDB();
/// Copy constructor
CrossLinksDB(const CrossLinksDB& residue_db);
/// Destructor
~CrossLinksDB() override;
//@}
/** @name Assignment
*/
//@{
/// Assignment operator
CrossLinksDB & operator=(const CrossLinksDB& aa);
//@}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/ProteaseDigestion.h | .h | 4,635 | 97 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow, Xiao Liang $
// $Authors: Marc Sturm, Chris Bielow $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CONCEPT/Types.h>
#include <OpenMS/CHEMISTRY/AASequence.h>
#include <OpenMS/CHEMISTRY/EnzymaticDigestion.h>
#include <vector>
namespace OpenMS
{
/**
@brief Class for the enzymatic digestion of proteins represented as AASequence or String
Digestion can be performed using simple regular expressions,
e.g. [KR] | [^P]
for trypsin. Also missed cleavages can be modeled, i.e. adjacent peptides are not cleaved
due to enzyme malfunction/access restrictions. If @em n missed cleavages are allowed, all possible resulting
peptides (cleaved and uncleaved) with up to @em n missed cleavages are returned.
Thus @b no random selection of just @em n specific missed cleavage sites is performed.
@ingroup Chemistry
*/
class OPENMS_DLLAPI ProteaseDigestion: public EnzymaticDigestion
{
public:
using EnzymaticDigestion::setEnzyme;
/// Sets the enzyme for the digestion (by name)
void setEnzyme(const String& name);
/**
@brief Performs the enzymatic digestion of a protein represented as AASequence.
Digestion logic is implemented by overloaded function @p digest .
@param[in] protein Sequence to digest
@param[in] output Digestion products (peptides)
@param[in] min_length Minimal length of reported products
@param[in] max_length Maximal length of reported products (0 = no restriction)
@return Number of discarded digestion products (which are not matching length restrictions)
*/
Size digest(const AASequence& protein, std::vector<AASequence>& output, Size min_length = 1, Size max_length = 0) const;
/**
@brief Performs the enzymatic digestion of a protein represented as AASequence.
Digestion takes into account the value of
- the **missed cleavages** member, see @p setMissedCleavages()
- the **specificity** member, see @p setSpecificity()
Currently, Specificity::SPEC_SEMI and Specificity::SPEC_FULL are supported.
Others raise an exception
@param[in] protein Sequence to digest
@param[in] output Digestion products (start and past-the-end indices of peptides)
@param[in] min_length Minimal length of reported products
@param[in] max_length Maximal length of reported products (0 = no restriction)
@return Number of discarded digestion products (which are not matching length restrictions)
@throw Exception::InvalidValue If object's specificity_ value is not supported.
*/
Size digest(const AASequence& protein, std::vector<std::pair<size_t,size_t>>& output, Size min_length = 1, Size max_length = 0) const;
/// Returns the number of peptides a digestion of @p protein would yield under the current enzyme and missed cleavage settings.
Size peptideCount(const AASequence& protein);
/**
@brief Variant of EnzymaticDigestion::isValidProduct() with support for n-term protein cleavage and random D|P cleavage
Checks if peptide is a valid digestion product of the enzyme, taking into account specificity and the flags provided here.
@param[in] protein Protein sequence
@param[in] pep_pos Starting index of potential peptide
@param[in] pep_length Length of potential peptide
@param[in] ignore_missed_cleavages Do not compare MC's of potential peptide to the maximum allowed MC's
@param[in] allow_nterm_protein_cleavage Regard peptide as n-terminal of protein if it starts only at pos=1 or 2 and protein starts with 'M'
@param[in] allow_random_asp_pro_cleavage Allow cleavage at D|P sites to count as n/c-terminal.
@return True if peptide has correct n/c terminals (according to enzyme, specificity and above flags)
*/
bool isValidProduct(const String& protein, int pep_pos, int pep_length, bool ignore_missed_cleavages = true, bool allow_nterm_protein_cleavage = false, bool allow_random_asp_pro_cleavage = false) const;
/// forwards to isValidProduct using protein.toUnmodifiedString()
bool isValidProduct(const AASequence& protein, int pep_pos, int pep_length, bool ignore_missed_cleavages = true, bool allow_nterm_protein_cleavage = false, bool allow_random_asp_pro_cleavage = false) const;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/ProteaseDB.h | .h | 1,651 | 54 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Xiao Liang $
// $Authors: Xiao Liang, Chris Bielow $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CHEMISTRY/DigestionEnzymeDB.h>
#include <OpenMS/CHEMISTRY/DigestionEnzymeProtein.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <vector>
namespace OpenMS
{
/**
@ingroup Chemistry
@brief Database for enzymes that digest proteins (proteases)
The enzymes stored in this DB are defined in an XML file under share/CHEMISTRY/Enzymes.xml.
*/
class OPENMS_DLLAPI ProteaseDB: public DigestionEnzymeDB<DigestionEnzymeProtein, ProteaseDB>
{
// allow access to constructor in DigestionEnzymeDB::getInstance():
friend class DigestionEnzymeDB<DigestionEnzymeProtein, ProteaseDB>;
protected:
/// constructor
ProteaseDB();
public:
/// returns all the enzyme names available for XTandem
void getAllXTandemNames(std::vector<String>& all_names) const;
/// returns all the enzyme names available for Comet
void getAllCometNames(std::vector<String>& all_names) const;
/// returns all the enzyme names available for OMSSA
void getAllOMSSANames(std::vector<String>& all_names) const;
/// returns all the enzyme names available for MSGFPlus
void getAllMSGFNames(std::vector<String>& all_names) const;
/// writes the full names to a TSV file
void writeTSV(const String& filename);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/Tagger.h | .h | 4,611 | 100 | // 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/DATASTRUCTURES/ListUtils.h>
#include <map>
namespace OpenMS
{
class MSSpectrum;
/**
* @brief Calculate sequence tags from m/z values
*
* Current restrictions and potential extensions:
* - first prefix/suffix ion don't give rise to first character in tags (as currently ion types are not specified)
* - gaps are not supported
* - I/L are treated redundantly, all possible combinations are written out
**/
class OPENMS_DLLAPI Tagger
{
public:
/**
@brief Constructor for Tagger
The parameter @p max_charge_ should be >= @p min_charge_.
Also @p max_tag_length should be >= @p min_tag_length.
@param[in] min_tag_length the minimal sequence tag length.
@param[in] tolerance the tolerance for matching residue masses to peak delta masses.
@param[in] max_tag_length the maximal sequence tag length.
@param[in] min_charge minimal fragment charge considered for each sequence tag.
@param[in] max_charge maximal fragment charge considered for each sequence tag.
@param[in,out] fixed_mods a list of modification names. The modified residues replace the unmodified versions.
@param[in,out] var_mods a list of modification names. The modified residues are added as additional entries to the list of residues.
@param[in] tol_is_ppm if set to true, the tolerance is interpreted as ppm, otherwise as absolute value. Defaults to true.
*/
Tagger(size_t min_tag_length, double tolerance, size_t max_tag_length = 65535, size_t min_charge = 1, size_t max_charge = 1, const StringList& fixed_mods = StringList(), const StringList& var_mods = StringList(), bool tol_is_ppm = true);
/**
@brief Generate tags from mass vector @p mzs
The parameter @p tags is filled with one string per sequence tag.
It uses the standard residues from ResidueDB including
the fixed and variable modifications given to the constructor.
@param[in] mzs a vector of mz values, containing the mz values from a centroided fragment spectrum.
@param[out] tags the vector of tags, that is filled with this function.
*/
void getTag(const std::vector<double>& mzs, std::vector<std::string>& tags) const;
/**
@brief Generate tags from an MSSpectrum
The parameter @p tags is filled with one string per sequence tag.
It uses the standard residues from ResidueDB including
the fixed and variable modifications given to the constructor.
@param[in] spec a centroided fragment spectrum.
@param[out] tags the vector of tags, that is filled with this function.
*/
void getTag(const MSSpectrum& spec, std::vector<std::string>& tags) const;
/**
@brief Change the maximal charge considered by the tagger
Allows to change the maximal considered charge e.g. based on a spectra
precursor charge without calling the constructor multiple times.
@param[in] max_charge the new maximal charge.
*/
void setMaxCharge(size_t max_charge);
private:
double min_gap_; ///< will be set to smallest residue mass in ResidueDB
double max_gap_; ///< will be set to highest residue mass in ResidueDB
double tolerance_; ///< tolerance
bool tol_is_ppm_; ///< is the tolerance in ppm
size_t min_tag_length_; ///< minimum tag length
size_t max_tag_length_; ///< maximum tag length
size_t min_charge_; ///< minimal fragment charge
size_t max_charge_; ///< maximal fragment charge
std::map<double, char> mass2aa_; ///< mapping of residue masses to their one letter codes
/// get a residue one letter code by matching the mass @p m to the map of residues mass2aa_, returns ' ' if there is no match.
char getAAByMass_(double m) const;
/// start searching for tags starting from peak @p i of the mz vector @p mzs
void getTag_(std::string& tag, const std::vector<double>& mzs, const size_t i, std::vector<std::string>& tags, const size_t charge) const;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/DigestionEnzymeRNA.h | .h | 2,835 | 75 | // 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/CHEMISTRY/DigestionEnzyme.h>
namespace OpenMS
{
/**
@brief Representation of a digestion enzyme for RNA (RNase)
The cutting sites of these enzymes are defined using two different mechanisms:
First, a single regular expression that is applied to strings of unmodified RNA sequence and defines cutting sites via zero-length matches (using lookahead/lookbehind assertions).
This is the same mechanism that is used for proteases (@see @ref ProteaseDigestion).
However, due to the complex notation involved, this approach is not practical for modification-aware digestion.
Thus, the second mechanism uses two regular expressions ("cuts after"/"cuts before"), which are applied to the short codes (e.g. "m6A") of sequential ribonucleotides.
If both expressions match, then there is a cutting site between the two ribonucleotides.
There is support for terminal (5'/3') modifications that may be generated on fragments as a result of RNase cleavage.
A typical example is 3'-phosphate, resulting from cleavage of the phosphate backbone.
@ingroup Chemistry
*/
class OPENMS_DLLAPI DigestionEnzymeRNA: public DigestionEnzyme
{
public:
/// sets the "cuts after ..." regular expression
void setCutsAfterRegEx(const String& value);
/// returns the "cuts after ..." regular expression
String getCutsAfterRegEx() const;
/// sets the "cuts before ..." regular expression
void setCutsBeforeRegEx(const String& value);
/// returns the "cuts before ..." regular expression
String getCutsBeforeRegEx() const;
/// sets the 3' gain (as a nucleotide modification code)
void setThreePrimeGain(const String& value);
/// returns the 3' gain (as a nucleotide modification code)
String getThreePrimeGain() const;
/// sets the 5' gain (as a nucleotide modification code)
void setFivePrimeGain(const String& value);
/// returns the 5' gain (as a nucleotide modification code)
String getFivePrimeGain() const;
/**
@brief Set the value of a member variable based on an entry from an input file
Returns whether the key was recognized and the value set successfully.
*/
bool setValueFromFile(const String& key, const String& value) override;
protected:
String three_prime_gain_;
String five_prime_gain_;
String cuts_after_regex_;
String cuts_before_regex_;
};
typedef DigestionEnzymeRNA RNase;
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/AdductInfo.h | .h | 3,168 | 74 | // 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/DATASTRUCTURES/String.h>
#include <OpenMS/CHEMISTRY/EmpiricalFormula.h>
namespace OpenMS
{
class OPENMS_DLLAPI AdductInfo
{
public:
/**
C'tor, to build a representation of an adduct.
@param[in] name Identifier as given in the Positive/Negative-Adducts file, e.g. 'M+2K-H;1+'
@param[in] adduct Formula of the adduct, e.g. '2K-H'
@param[in] charge The charge (must not be 0; can be negative), e.g. 1
@param[in] mol_multiplier Molecular multiplier, e.g. for charged dimers '2M+H;+1'
**/
AdductInfo(const String& name, const EmpiricalFormula& adduct, int charge, UInt mol_multiplier = 1);
/// returns the neutral mass of the small molecule without adduct (creates monomer from nmer, decharges and removes the adduct (given m/z of [nM+Adduct]/|charge| returns mass of [M])
double getNeutralMass(double observed_mz) const;
/// returns the m/z of the small molecule with neutral mass @p neutral_mass if the adduct is added (given mass of [M] returns m/z of [nM+Adduct]/|charge|)
double getMZ(double neutral_mass) const;
/// returns the mass shift caused by this adduct if charges are compensated with protons
double getMassShift(bool use_avg_mass = false) const;
/// checks if an adduct (e.g.a 'M+2K-H;1+') is valid, i.e. if the losses (==negative amounts) can actually be lost by the compound given in @p db_entry.
/// If the negative parts are present in @p db_entry, true is returned.
/// @param[in] db_entry The empirical formula to check compatibility with
bool isCompatible(const EmpiricalFormula& db_entry) const;
/// get charge of adduct
int getCharge() const;
/// original string used for parsing
const String& getName() const;
/// sum formula of adduct itself. Useful for comparison with feature adduct annotation
const EmpiricalFormula& getEmpiricalFormula() const;
/// get molecular multiplier
UInt getMolMultiplier() const;
/// parse an adduct string containing a formula (must contain 'M') and charge, separated by ';'.
/// e.g. M+H;1+
/// 'M' can have multipliers, e.g. '2M + H;1+' (for a singly charged dimer)
/// @param[in] adduct The adduct string to parse
static AdductInfo parseAdductString(const String& adduct);
/// equality operator
bool operator==(const AdductInfo& other) const;
private:
/// members
String name_; ///< arbitrary name, only used for error reporting
EmpiricalFormula ef_; ///< Sum formula for the actual adduct e.g. 'H' in 2M+H;+1
double mass_; ///< computed from ef_.getMonoWeight(), but stored explicitly for efficiency
int charge_; ///< negative or positive charge; must not be 0
UInt mol_multiplier_; ///< Mol multiplier, e.g. 2 in 2M+H;+1
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/ElementDB.h | .h | 6,206 | 153 | // 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, Timo Sachsenberg, Chris Bielow, Jang Jang Jin$
// --------------------------------------------------------------------------
//
#pragma once
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/CHEMISTRY/ISOTOPEDISTRIBUTION/IsotopeDistribution.h>
#include <map>
#include <memory>
#include <unordered_map>
#include <string>
namespace OpenMS
{
class Element;
/** @ingroup Chemistry
@brief Singleton that stores elements and isotopes.
The elements weights (in the default file) are taken from
"Isotopic Compositions of the Elements 1997", Pure Appl. Chem., 70(1), 217-235, 1998.
(http://www.iupac.org/reports/1998/7001rosman/)
The isotope distributions (in the default file) are taken from
"Atomic weights of the elements. Review 2000" (IUPAC Technical Report)
Pure Appl. Chem., 2003, Vol. 75, No. 6, pp. 683-799
doi:10.1351/pac200375060683
Specific isotopes of elements can be accessed by writing the atomic number of the isotope
in brackets followed by the element name, e.g. "(2)H" for deuterium.
@improvement include exact mass values for the isotopes (done) and update IsotopeDistribution (Andreas)
@improvement add exact isotope distribution based on exact isotope values (Andreas)
*/
class OPENMS_DLLAPI ElementDB
{
public:
/** @name Accessors
*/
//@{
/// returns a pointer to the singleton instance of the element db
/// This is thread safe upon first and subsequent calls.
static ElementDB* getInstance();
/// returns a hashmap that contains names mapped to pointers to the elements
const std::unordered_map<std::string, const Element*>& getNames() const;
/// returns a hashmap that contains symbols mapped to pointers to the elements
const std::unordered_map<std::string, const Element*>& getSymbols() const;
/// returns a hashmap that contains atomic numbers mapped to pointers of the elements
const std::unordered_map<unsigned int, const Element*>& getAtomicNumbers() const;
/** returns a pointer to the element with name or symbol given in parameter name;
* if no element exists with that name or symbol 0 is returned
* @param[in] name name or symbol of the element
*/
const Element* getElement(const std::string& name) const;
/// returns a pointer to the element of atomic number; if no element is found 0 is returned
const Element* getElement(unsigned int atomic_number) const;
/** Adds or replaces a new element to the database
*
* Adds a new element (or replaces an existing one if @em replace_existing is true).
*
* @param[in] name Common name of the element
* @param[in] symbol Element symbol (one or two letter)
* @param[in] an Atomic number (number of protons)
* @param[in] abundance List of abundances for each isotope (e.g. {{12u, 0.9893}, {13u, 0.0107}} for Carbon)
* @param[in] mass List of masses for each isotope (e.g. {{12u, 12.0}, {13u, 13.003355}} for Carbon)
* @param[in] replace_existing If the element must be replaced (i.e. is not new), either allow that (=true), or throw an exception (=false).
*
* @throw Exception::IllegalArgument if element already exists in DB, but @p replace_existing is false
*
* @note Do not use this function inside parallel code as it modifies a singleton that is shared between threads.
*/
void addElement(const std::string& name,
const std::string& symbol,
const unsigned int an,
const std::map<unsigned int, double>& abundance,
const std::map<unsigned int, double>& mass,
bool replace_existing);
//@}
/** @name Predicates
*/
//@{
/// returns true if the db contains an element with the given name
bool hasElement(const std::string& name) const;
/// returns true if the db contains an element with the given atomic_number
bool hasElement(unsigned int atomic_number) const;
//@}
protected:
/** parses a isotope distribution of abundances and masses
**/
IsotopeDistribution parseIsotopeDistribution_(const std::map<unsigned int, double>& abundance, const std::map<unsigned int, double>& mass);
/** calculates the average weight based on isotope abundance and mass
**/
double calculateAvgWeight_(const std::map<unsigned int, double>& abundance, const std::map<unsigned int, double>& mass);
/**_ calculates the mono weight based on the most abundant isotope
**/
double calculateMonoWeight_(const std::map<unsigned int, double>& abundance, const std::map<unsigned int, double>& mass);
/// constructs element objects
void storeElements_();
/// build element objects from given abundances, masses, name, symbol, and atomic number
void buildElement_(const std::string& name, const std::string& symbol, const unsigned int an, const std::map<unsigned int, double>& abundance, const std::map<unsigned int, double>& mass);
/// add element objects to documentation maps
void addElementToMaps_(const std::string& name, const std::string& symbol, const unsigned int an, std::unique_ptr<const Element> e);
/// constructs isotope objects
void storeIsotopes_(const std::string& name, const std::string& symbol, const unsigned int an, const std::map<unsigned int, double>& Z_to_mass, const IsotopeDistribution& isotopes);
/**_ resets all containers
**/
void clear_();
std::unordered_map<std::string, const Element*> names_;
std::unordered_map<std::string, const Element*> symbols_;
std::unordered_map<unsigned int, const Element*> atomic_numbers_;
private:
ElementDB();
~ElementDB();
ElementDB(const ElementDB& db) = delete;
ElementDB(const ElementDB&& db) = delete;
ElementDB& operator=(const ElementDB& db) = delete;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/TheoreticalSpectrumGeneratorXLMS.h | .h | 18,682 | 314 | // 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/CHEMISTRY/Residue.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/METADATA/DataArrays.h>
#include <OpenMS/ANALYSIS/XLMS/OPXLDataStructs.h>
namespace OpenMS
{
class AASequence;
/**
@brief Generates theoretical spectra for cross-linked peptides
The spectra this class generates are instances of the PeakSpectrum class.
This class generates the same peak types as SimpleTSGXLMS
and the interface is very similar, but it is more complex and slower.
If the parameters add_metainfo and add_charges are set to true, it will
generate a StringDataArray for String annotations of ion types
and an IntegerDataArray for peak charges and add them to the DataArrays
of the produced PeakSpectrum. The spectra from this class are mainly used
for annotation of matched experimental spectra.
@htmlinclude OpenMS_TheoreticalSpectrumGeneratorXLMS.parameters
@ingroup Chemistry
*/
class OPENMS_DLLAPI TheoreticalSpectrumGeneratorXLMS :
public DefaultParamHandler
{
public:
struct LossIndex
{
bool has_H2O_loss = false;
bool has_NH3_loss = false;
};
/** @name Constructors and Destructors
*/
//@{
/// default constructor
TheoreticalSpectrumGeneratorXLMS();
/// copy constructor
TheoreticalSpectrumGeneratorXLMS(const TheoreticalSpectrumGeneratorXLMS & source);
/// destructor
~TheoreticalSpectrumGeneratorXLMS() override;
//@}
/// assignment operator
TheoreticalSpectrumGeneratorXLMS & operator=(const TheoreticalSpectrumGeneratorXLMS & tsg);
/**
* @brief Generates fragment ions not containing the cross-linker for one peptide.
B-ions are generated from the beginning of the peptide up to the first linked position,
y-ions are generated from the second linked position up the end of the peptide.
If link_pos_2 is 0, a mono-link or cross-link is assumed and the second position is the same as the first position.
For a loop-link two different positions can be set and link_pos_2 must be larger than link_pos.
The generated ion types and other additional settings are determined by the tool parameters.
@param[in] spectrum The spectrum to which the new peaks are added. Does not have to be empty, the generated peaks will be pushed onto it.
@param[in] peptide The peptide to fragment
@param[in] link_pos The position of the cross-linker on the given peptide
@param[in] frag_alpha True, if the fragmented peptide is the Alpha peptide. Used for ion-name annotation.
@param[in] charge The maximal charge of the ions
@param[in] link_pos_2 A second position for the linker, in case it is a loop link
*/
virtual void getLinearIonSpectrum(PeakSpectrum & spectrum, AASequence & peptide, Size link_pos, bool frag_alpha, int charge = 1, Size link_pos_2 = 0) const;
/**
* @brief Generates fragment ions containing the cross-linker for one peptide.
*
B-ions are generated from the first linked position up to the end of the peptide,
y-ions are generated from the beginning of the peptide up to the second linked position.
If link_pos_2 is 0, a mono-link or cross-link is assumed and the second position is the same as the first position.
For a loop-link two different positions can be set and link_pos_2 must be larger than link_pos.
Since in the case of a cross-link a whole second peptide is attached to the other side of the cross-link,
a precursor mass for the two peptides and the linker is needed.
In the case of a loop link the precursor mass is the mass of the only peptide and the linker.
Although this function is more general, currently it is mainly used for loop-links and mono-links,
because residues in the second, unknown peptide cannot be considered for possible neutral losses.
The generated ion types and other additional settings are determined by the tool parameters.
@param[in] spectrum The spectrum to which the new peaks are added. Does not have to be empty, the generated peaks will be pushed onto it.
@param[in] peptide The peptide to fragment
@param[in] link_pos The position of the cross-linker on the given peptide
@param[in] precursor_mass The mass of the whole cross-link candidate or the precursor mass of the experimental MS2 spectrum.
@param[in] frag_alpha True, if the fragmented peptide is the Alpha peptide. Used for ion-name annotation.
@param[in] mincharge The minimal charge of the ions
@param[in] maxcharge The maximal charge of the ions, it should be the precursor charge and is used to generate precursor ion peaks
@param[in] link_pos_2 A second position for the linker, in case it is a loop link
*/
virtual void getXLinkIonSpectrum(PeakSpectrum & spectrum, AASequence & peptide, Size link_pos, double precursor_mass, bool frag_alpha, int mincharge, int maxcharge, Size link_pos_2 = 0) const;
/**
* @brief Generates fragment ions containing the cross-linker for a pair of peptides.
*
B-ions are generated from the first linked position up to the end of the peptide,
y-ions are generated from the beginning of the peptide up to the second linked position.
This function generates neutral loss ions by considering both linked peptides.
Only one of the peptides, decided by @p frag_alpha, is fragmented.
This function is not suitable to generate fragments for mono-links or loop-links.
This simplifies the function, but it has to be called twice to get all fragments of a peptide pair.
The generated ion types and other additional settings are determined by the tool parameters.
@param[in] spectrum The spectrum to which the new peaks are added. Does not have to be empty, the generated peaks will be pushed onto it.
@param[in] crosslink ProteinProteinCrossLink to be fragmented
@param[in] frag_alpha True, if the fragmented peptide is the Alpha peptide.
@param[in] mincharge The minimal charge of the ions
@param[in] maxcharge The maximal charge of the ions, it should be the precursor charge and is used to generate precursor ion peaks
*/
virtual void getXLinkIonSpectrum(PeakSpectrum & spectrum, OPXLDataStructs::ProteinProteinCrossLink & crosslink, bool frag_alpha, int mincharge, int maxcharge) const;
/// overwrite
void updateMembers_() override;
protected:
/**
* @brief Adds cross-link-less ions of a specific ion type and charge to a spectrum and adds ion name and charge annotations to the DataArrays
* @param[in] spectrum The spectrum to which the new peaks are added. Does not have to be empty, the generated peaks will be pushed onto it.
* @param[in] charges A DataArray collecting the charges of the added peaks
* @param[in] ion_names A DataArray collecting the ion names of the added peaks
* @param[in] peptide The peptide to fragment
* @param[in] link_pos The position of the cross-linker on the given peptide
* @param[in] frag_alpha True, if the fragmented peptide is the Alpha peptide. Used for ion-name annotation.
* @param[in] res_type The ion type of the added peaks
* @param[in] forward_losses vector of sets of losses generated by getForwardLosses_
* @param[in] backward_losses vector of sets of losses generated by getBackwardLosses_
* @param[in] charge The charge of the added peaks
* @param[in] link_pos_2 A second position for the linker, in case it is a loop link
*/
virtual void addLinearPeaks_(PeakSpectrum & spectrum, DataArrays::IntegerDataArray & charges, DataArrays::StringDataArray & ion_names, AASequence & peptide, Size link_pos, bool frag_alpha, Residue::ResidueType res_type, std::vector< LossIndex > & forward_losses, std::vector< LossIndex > & backward_losses, int charge = 1, Size link_pos_2 = 0) const;
/**
* @brief Adds a single peak to a spectrum and its charge and ion name to the given DataArrays
The ion_type is a string in this form: "alpha|xi",
the first word can be either "alpha" or "beta" and indicates the fragmented peptide,
the two letters at the end are either "ci" or "xi" for linear ion or cross-linked ion.
* @param[in] spectrum The spectrum to which the new peak is added
* @param[in] charges A DataArray collecting the charges of the added peaks
* @param[in] ion_names A DataArray collecting the ion names of the added peaks
* @param[in] pos
* @param[in] intensity
* @param[in] res_type The ion type of the added peak
* @param[in] ion_index The index of the ion (fragmentation position)
* @param[in] charge The charge of the ion
* @param[in] ion_type Another cross-linking specific ion-type
*/
virtual void addPeak_(PeakSpectrum & spectrum, DataArrays::IntegerDataArray & charges, DataArrays::StringDataArray & ion_names, double pos, double intensity, Residue::ResidueType res_type, Size ion_index, int charge, String ion_type) const;
/**
* @brief Adds precursor masses including neutral losses for the given charge and adds charge and ion name to the given DataArrays
* @param[in] spectrum The spectrum to which the peaks are added
* @param[in] charges A DataArray collecting the charges of the added peaks
* @param[in] ion_names A DataArray collecting the ion names of the added peaks
* @param[in] precursor_mass The mass of the uncharged precursor
* @param[in] charge The charge of the precursor
*/
virtual void addPrecursorPeaks_(PeakSpectrum & spectrum, DataArrays::IntegerDataArray & charges, DataArrays::StringDataArray & ion_names, double precursor_mass, int charge) const;
/**
* @brief Adds losses for a linear ion
* @param[in] spectrum The spectrum to which the new peak is added
* @param[in] charges A DataArray collecting the charges of the added peaks
* @param[in] ion_names A DataArray collecting the ion names of the added peaks
* @param[in] mono_weight monoisotopic mass of the current ion
* @param[in] res_type The ion type of the current ion
* @param[in] frag_index The index of the ion (fragmentation position)
* @param[in] intensity
* @param[in] charge The charge of the ion
* @param[in] ion_type Another cross-linking specific ion-type
* @param[in] losses a set of LossMasses with which to modify the current ion
*/
virtual void addLinearIonLosses_(PeakSpectrum & spectrum, DataArrays::IntegerDataArray& charges, DataArrays::StringDataArray& ion_names, double mono_weight, Residue::ResidueType res_type, Size frag_index, double intensity, int charge, String ion_type, LossIndex & losses) const;
/**
* @brief Adds losses for a cross-linked ion
* @param[in] spectrum The spectrum to which the new peak is added
* @param[in] charges A DataArray collecting the charges of the added peaks
* @param[in] ion_names A DataArray collecting the ion names of the added peaks
* @param[in] mono_weight monoisotopic mass of the current ion
* @param[in] intensity
* @param[in] charge The charge of the ion
* @param[in] ion_type Another cross-linking specific ion-type
* @param[in] losses a set of LossMasses with which to modify the current ion
*/
virtual void addXLinkIonLosses_(PeakSpectrum& spectrum, DataArrays::IntegerDataArray& charges, DataArrays::StringDataArray& ion_names, double mono_weight, double intensity, int charge, String ion_type, LossIndex & losses) const;
/**
* @brief Adds one-residue-linked ion peaks, that are specific to XLMS
These fragments consist of one whole peptide, the cross-linker and a part of the linked residue from the second peptide.
The residue fragment on the linker is an internal ion from a y- and an a-fragmentation with the length of one residue.
The function is called KLinked for now, but instead of K it is whatever the linker is attached to.
* @param[in] spectrum The spectrum to which the peaks are added
* @param[in] charges A DataArray collecting the charges of the added peaks
* @param[in] ion_names A DataArray collecting the ion names of the added peaks
* @param[in] peptide The fragmented peptide
* @param[in] link_pos position of the linker on the fragmented peptide
* @param[in] precursor_mass The mass of the whole cross-link candidate or the precursor mass of the experimental MS2 spectrum.
* @param[in] frag_alpha True, if the fragmented peptide is the Alpha peptide. Used for ion-name annotation.
* @param[in] charge The charge of the ion
*/
virtual void addKLinkedIonPeaks_(PeakSpectrum & spectrum, DataArrays::IntegerDataArray & charges, DataArrays::StringDataArray & ion_names, AASequence & peptide, Size link_pos, double precursor_mass, bool frag_alpha, int charge) const;
/**
* @brief Adds cross-linked ions of a specific ion type and charge to a spectrum and adds ion name and charge annotations to the DataArrays
This version of the function is for mono-links and loop-links.
* @param[in] spectrum The spectrum to which the new peaks are added. Does not have to be empty, the generated peaks will be pushed onto it.
* @param[in] charges A DataArray collecting the charges of the added peaks
* @param[in] ion_names A DataArray collecting the ion names of the added peaks
* @param[in] peptide The peptide to fragment
* @param[in] link_pos The position of the cross-linker on the given peptide
* @param[in] precursor_mass The mass of the whole cross-link candidate or the precursor mass of the experimental MS2 spectrum.
* @param[in] frag_alpha True, if the fragmented peptide is the Alpha peptide. Used for ion-name annotation.
* @param[in] res_type The ion type of the added peaks
* @param[in] forward_losses vector of sets of losses generated by getForwardLosses_
* @param[in] backward_losses vector of sets of losses generated by getBackwardLosses_
* @param[in] charge The charge of the added peaks
* @param[in] link_pos_2 A second position for the linker, in case it is a loop link
*/
virtual void addXLinkIonPeaks_(PeakSpectrum& spectrum, DataArrays::IntegerDataArray & charges, DataArrays::StringDataArray & ion_names, AASequence & peptide, Size link_pos, double precursor_mass, bool frag_alpha, Residue::ResidueType res_type, std::vector< LossIndex > & forward_losses, std::vector< LossIndex > & backward_losses, int charge, Size link_pos_2 = 0) const;
/**
* @brief Adds cross-linked ions of a specific ion type and charge to a spectrum and adds ion name and charge annotations to the DataArrays
This version of the function is for cross-linked peptide pairs.
* @param[in] spectrum The spectrum to which the new peaks are added. Does not have to be empty, the generated peaks will be pushed onto it.
* @param[in] charges A DataArray collecting the charges of the added peaks
* @param[in] ion_names A DataArray collecting the ion names of the added peaks
* @param[in] crosslink The ProteinProteinCrossLink to be fragmented
* @param[in] frag_alpha True, if the fragmented peptide is the Alpha peptide. Used for ion-name annotation.
* @param[in] res_type The ion type of the added peaks
* @param[in] forward_losses vector of sets of losses generated by getForwardLosses_ for the fragmented peptide
* @param[in] backward_losses vector of sets of losses generated by getBackwardLosses_ for the fragmented peptide
* @param[in] losses_peptide2 set of losses for the second, not fragmented peptide, e.g. last set from getForwardLosses_ for the second peptide
* @param[in] charge The charge of the added peaks
*/
virtual void addXLinkIonPeaks_(PeakSpectrum & spectrum, DataArrays::IntegerDataArray & charges, DataArrays::StringDataArray & ion_names, OPXLDataStructs::ProteinProteinCrossLink & crosslink, bool frag_alpha, Residue::ResidueType res_type, std::vector< LossIndex > & forward_losses, std::vector< LossIndex > & backward_losses, LossIndex & losses_peptide2, int charge) const;
/**
* @brief Calculates sets of possible neutral losses for each position in the given peptide
This function generates a vector of sets. Each set contains the possible neutral losses for a specific prefix of the peptide.
* @param[in] peptide The peptide or ion for which to collect possible losses
*/
std::vector< LossIndex > getForwardLosses_(AASequence & peptide) const;
/**
* @brief Calculates sets of possible neutral losses for each position in the given peptide
This function generates a vector of sets. Each set contains the possible neutral losses for a specific suffix of the peptide.
* @param[in] peptide The peptide or ion for which to collect possible losses
*/
std::vector< LossIndex > getBackwardLosses_(AASequence & peptide) const;
bool add_b_ions_;
bool add_y_ions_;
bool add_a_ions_;
bool add_c_ions_;
bool add_x_ions_;
bool add_z_ions_;
bool add_first_prefix_ion_;
bool add_losses_;
bool add_metainfo_;
bool add_charges_;
bool add_isotopes_;
bool add_precursor_peaks_;
bool add_abundant_immonium_ions_;
double a_intensity_;
double b_intensity_;
double c_intensity_;
double x_intensity_;
double y_intensity_;
double z_intensity_;
Int max_isotope_;
double rel_loss_intensity_;
double pre_int_;
double pre_int_H2O_;
double pre_int_NH3_;
bool add_k_linked_ions_;
std::map< String, LossIndex > loss_db_;
double loss_H2O_ = 0;
double loss_NH3_ = 0;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/DigestionEnzymeProtein.h | .h | 4,569 | 169 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Xiao Liang $
// $Authors: Xiao Liang $
// --------------------------------------------------------------------------
//
#pragma once
#include <OpenMS/CHEMISTRY/DigestionEnzyme.h>
namespace OpenMS
{
/**
@ingroup Chemistry
@brief Representation of a digestion enzyme for proteins (protease)
*/
class OPENMS_DLLAPI DigestionEnzymeProtein :
public DigestionEnzyme
{
public:
/** @name Constructors
*/
//@{
/// Default constructor
DigestionEnzymeProtein();
/// Constructor from base class (adding defaults for the missing stuff)
explicit DigestionEnzymeProtein(const DigestionEnzyme& d);
/// Copy constructor
DigestionEnzymeProtein(const DigestionEnzymeProtein&) = default;
/// Move constructor
DigestionEnzymeProtein(DigestionEnzymeProtein&&) = default;
/// Detailed constructor
explicit DigestionEnzymeProtein(const String& name,
const String& cleavage_regex,
const std::set<String>& synonyms = std::set<String>(),
String regex_description = "",
EmpiricalFormula n_term_gain = EmpiricalFormula("H"),
EmpiricalFormula c_term_gain = EmpiricalFormula("OH"),
String psi_id = "",
String xtandem_id = "",
Int comet_id = -1,
Int msgf_id = -1,
Int omssa_id = -1);
/// Destructor
~DigestionEnzymeProtein() override;
//@}
/** @name Assignment
*/
//@{
/// Assignment operator
DigestionEnzymeProtein& operator=(const DigestionEnzymeProtein&) = default;
/// Move assignment operator
DigestionEnzymeProtein& operator=(DigestionEnzymeProtein&&) & = default;
//@}
/** Accessors
*/
//@{
/// sets the N-terminal gain
void setNTermGain(const EmpiricalFormula& value);
/// returns N-terminal gain
EmpiricalFormula getNTermGain() const;
/// sets the C-terminal gain
void setCTermGain(const EmpiricalFormula& value);
/// returns C-terminal gain
EmpiricalFormula getCTermGain() const;
/// sets the PSI ID
void setPSIID(const String& value);
/// returns the PSI ID
String getPSIID() const;
/// sets the X! Tandem enzyme ID
void setXTandemID(const String& value);
/// returns the X! Tandem enzyme ID
String getXTandemID() const;
/// sets the Comet enzyme ID
void setCometID(Int value);
/// returns the Comet enzyme ID
Int getCometID() const;
/// sets the MSGFPlus enzyme id
void setMSGFID(Int value);
/// returns the MSGFPlus enzyme id
Int getMSGFID() const;
/// sets the OMSSA enzyme ID
void setOMSSAID(Int value);
/// returns the OMSSA enzyme ID
Int getOMSSAID() const;
//@}
/** @name Predicates
*/
//@{
/// equality operator
bool operator==(const DigestionEnzymeProtein& enzyme) const;
/// inequality operator
bool operator!=(const DigestionEnzymeProtein& enzyme) const;
// Note: comparison operator is not inherited. TODO rename and make virtual
/// equality operator for regex
bool operator==(const String& cleavage_regex) const;
/// equality operator for regex
bool operator!=(const String& cleavage_regex) const;
/// order operator
bool operator<(const DigestionEnzymeProtein& enzyme) const;
//@}
/**
@brief Set the value of a member variable based on an entry from an input file
Returns whether the key was recognized and the value set successfully.
*/
bool setValueFromFile(const String& key, const String& value) override;
/// ostream iterator to write the enzyme to a stream
friend OPENMS_DLLAPI std::ostream& operator<<(std::ostream& os, const DigestionEnzymeProtein& enzyme);
protected:
EmpiricalFormula n_term_gain_;
EmpiricalFormula c_term_gain_;
String psi_id_;
String xtandem_id_;
Int comet_id_;
Int msgf_id_;
Int omssa_id_;
};
OPENMS_DLLAPI std::ostream& operator<<(std::ostream& os, const DigestionEnzymeProtein& enzyme);
typedef DigestionEnzymeProtein Protease;
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/NucleicAcidSpectrumGenerator.h | .h | 3,774 | 113 | // 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/MSSpectrum.h>
#include <OpenMS/METADATA/DataArrays.h>
#include <OpenMS/CHEMISTRY/NASequence.h>
namespace OpenMS
{
class NASequence;
/**
@brief Generates theoretical spectra for nucleic acid sequences
@htmlinclude OpenMS_NucleicAcidSpectrumGenerator.parameters
@ingroup Chemistry
*/
class OPENMS_DLLAPI NucleicAcidSpectrumGenerator :
public DefaultParamHandler
{
public:
/** @name Constructors and Destructors
*/
//@{
/// default constructor
NucleicAcidSpectrumGenerator();
/// copy constructor
NucleicAcidSpectrumGenerator(const NucleicAcidSpectrumGenerator& source);
/// destructor
~NucleicAcidSpectrumGenerator() override;
//@}
/// assignment operator
NucleicAcidSpectrumGenerator& operator=(const NucleicAcidSpectrumGenerator& source);
/** @name Acessors
*/
//@{
/// Generates a spectrum for an oligonucleotide sequence, with the ion types that are set in the tool parameters
void getSpectrum(MSSpectrum& spectrum, const NASequence& oligo, Int min_charge, Int max_charge) const;
/**
@brief Generates spectra in multiple charge states for an oligonucleotide sequence
@param[out] spectra Output spectra
@param[out] oligo Target oligonucleotide sequence
@param[in] charges Set of charge states to generate
@param[in] base_charge Minimum charge for peaks in each spectrum
One spectrum per element in @p charges is generated in @p spectra.
All values in @p charges must be either positive or negative.
This function is more efficient than calling getSpectrum() multiple times, because spectra of lower charge states are reused.
*/
void getMultipleSpectra(std::map<Int, MSSpectrum>& spectra, const NASequence& oligo, const std::set<Int>& charges, Int base_charge = 1) const;
/// overwrite
void updateMembers_() override;
//@}
protected:
/// Helper function to add (uncharged) fragment peaks to a spectrum
void addFragmentPeaks_(MSSpectrum& spectrum, const std::vector<double>& fragment_masses, const String& ion_type, double offset, double intensity, Size start = 0) const;
/// Special version of addFragmentPeaks_() for a-B ions
void addAMinusBPeaks_(MSSpectrum& spectrum, const std::vector<double>& fragment_masses, const NASequence& oligo, Size start = 0) const;
/// Generates a spectrum containing peaks for uncharged fragment masses
MSSpectrum getUnchargedSpectrum_(const NASequence& oligo) const;
/// Adds a charged version of an uncharged spectrum to another spectrum
void addChargedSpectrum_(MSSpectrum& spectrum, const MSSpectrum& uncharged_spectrum, Int charge, bool add_precursor) const;
bool add_a_ions_;
bool add_b_ions_;
bool add_c_ions_;
bool add_d_ions_;
bool add_w_ions_;
bool add_x_ions_;
bool add_y_ions_;
bool add_z_ions_;
bool add_aB_ions_;
bool add_first_prefix_ion_;
bool add_metainfo_;
bool add_precursor_peaks_;
bool add_all_precursor_charges_ ;
double a_intensity_;
double b_intensity_;
double c_intensity_;
double d_intensity_;
double w_intensity_;
double x_intensity_;
double y_intensity_;
double z_intensity_;
double aB_intensity_;
double precursor_intensity_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/EmpiricalFormula.h | .h | 14,715 | 369 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow, Ahmed Khalil $
// $Authors: Andreas Bertsch, Chris Bielow $
// --------------------------------------------------------------------------
//
#pragma once
#include <iosfwd>
#include <algorithm>
#include <map>
#include <set>
#include <string>
#include <functional>
#include <vector>
#include <OpenMS/CONCEPT/Types.h>
#include <OpenMS/CONCEPT/HashUtils.h>
#include <OpenMS/CHEMISTRY/Element.h>
namespace OpenMS
{
class String;
class ElementDB;
class IsotopeDistribution;
class IsotopePatternGenerator;
class CoarseIsotopePatternGenerator;
/**
@ingroup Chemistry
@brief Representation of an empirical formula
The formula can be used as follows: elements are represented through its symbol or full name.
The symbol or name is followed by a number. If not, the frequency is set to one. Examples
are CH3OH or CarbonHydrogen3OH. The names must start with an capital letter (symbols always have
an upper-case letter at the beginning). Additionally charges can be used with '+' followed by
a number, if no number follows the charge of +1 is set. Negative charges can be added using a '-'
sign. However, negative charges are only set if the last element in the string also has a number.
E.g. H4C-1, does not set a negative charge, only -1 Carbon atoms, correctly it should be stated
H4C-1-.
This class also supports the usage of specific isotopes. By default "C" describes not one isotope
but a natural distribution or different isotopes. This distribution can be accessed via the
member getIsotopeDistribution().
If one wants only use a specific isotope, it can be specified using "(",")"
brackets. For example, to specify 13C a heavy isotope of carbon it is
expressed as "(13)C". The isotope distribution of that instance contains
only one isotope, 13C itself with a frequency of 100%. It is possible to
mix isotopes, for example "(13)C1CH6O" specifies an ethanol molecule with
one 12C and one 13C isotope.
Instances EmpiricalFormula support a (limited) set of mathematical operations. Additions and subtractions
are supported in different flavors. However, one must be careful, because this can lead to negative
frequencies. In most cases this might be misleading, however, the class therefore supports difference
formulae. E.g. formula differences of reactions from post-translational modifications.
*/
class OPENMS_DLLAPI EmpiricalFormula
{
protected:
/// Internal typedef for the used map type
typedef std::map<const Element*, SignedSize> MapType_;
public:
/** @name Typedefs
*/
//@{
/// Iterators
typedef MapType_::const_iterator ConstIterator;
typedef MapType_::const_iterator const_iterator;
typedef MapType_::iterator Iterator;
typedef MapType_::iterator iterator;
//@}
/** @name Constructors and Destructors
*/
//@{
/// Default constructor
EmpiricalFormula();
/// Copy constructor
EmpiricalFormula(const EmpiricalFormula&) = default;
/// Move constructor
EmpiricalFormula(EmpiricalFormula&&) = default;
/**
Constructor from an OpenMS String
@throw throws ParseError if the formula cannot be parsed
*/
explicit EmpiricalFormula(const String& rhs);
/// Constructor with element pointer and number
EmpiricalFormula(SignedSize number, const Element* element, SignedSize charge = 0);
/// Destructor
virtual ~EmpiricalFormula();
//@}
/**
@brief Create EmpiricalFormula object from a String
@param[in] rhs Input string
@throws Exception::ParseError if the formula cannot be parsed
*/
static EmpiricalFormula fromString(const String& rhs)
{
EmpiricalFormula ef(rhs);
return ef;
}
/** @name Accessors
*/
//@{
/// returns the monoisotopic (most abundant isotope per element) weight of the formula (includes proton charges)
double getMonoWeight() const;
/// returns the sum of the lightest isotopes per element in the formula (includes proton charges)
double getLightestIsotopeWeight() const;
/// returns the average weight of the formula (includes proton charges)
double getAverageWeight() const;
/// returns the total number of discrete isotopes
double calculateTheoreticalIsotopesNumber() const;
/**
@brief Fills this EmpiricalFormula with an approximate elemental composition for a given average weight and approximate elemental stoichiometry
@param[in] average_weight Average weight to estimate an EmpiricalFormula for
@param[in] C The approximate relative stoichiometry of Carbons to other elements in this molecule
@param[in] H The approximate relative stoichiometry of Hydrogens to other elements in this molecule
@param[in] N The approximate relative stoichiometry of Nitrogens to other elements in this molecule
@param[in] O The approximate relative stoichiometry of Oxygens to other elements in this molecule
@param[in] S The approximate relative stoichiometry of Sulfurs to other elements in this molecule
@param[in] P The approximate relative stoichiometry of Phosphoruses to other elements in this molecule
@return bool flag for whether the approximation succeeded without requesting negative hydrogens. true = no problems, 1 = negative hydrogens requested.
*/
bool estimateFromWeightAndComp(double average_weight, double C, double H, double N, double O, double S, double P);
/**
@brief Fills this EmpiricalFormula with an approximate elemental composition for a given monoisotopic weight and approximate elemental stoichiometry
@param[in] mono_weight Monoisotopic weight to estimate an EmpiricalFormula for
@param[in] C The approximate relative stoichiometry of Carbons to other elements in this molecule
@param[in] H The approximate relative stoichiometry of Hydrogens to other elements in this molecule
@param[in] N The approximate relative stoichiometry of Nitrogens to other elements in this molecule
@param[in] O The approximate relative stoichiometry of Oxygens to other elements in this molecule
@param[in] S The approximate relative stoichiometry of Sulfurs to other elements in this molecule
@param[in] P The approximate relative stoichiometry of Phosphoruses to other elements in this molecule
@return bool flag for whether the approximation succeeded without requesting negative hydrogens. true = no problems, 1 = negative hydrogens requested.
*/
bool estimateFromMonoWeightAndComp(double mono_weight, double C, double H, double N, double O, double S, double P);
/**
@brief Fills this EmpiricalFormula with an approximate elemental composition for a given average weight,
exact number of sulfurs, and approximate elemental stoichiometry
@param[in] average_weight Average weight to estimate an EmpiricalFormula for
@param[in] S The exact number of Sulfurs in this molecule
@param[in] C The approximate relative stoichiometry of Carbons to other elements (excluding Sulfur) in this molecule
@param[in] H The approximate relative stoichiometry of Hydrogens to other elements (excluding Sulfur) in this molecule
@param[in] N The approximate relative stoichiometry of Nitrogens to other elements (excluding Sulfur) in this molecule
@param[in] O The approximate relative stoichiometry of Oxygens to other elements (excluding Sulfur) in this molecule
@param[in] P The approximate relative stoichiometry of Phosphoruses to other elements (excluding Sulfur) in this molecule
@return bool flag for whether the approximation succeeded without requesting negative hydrogens. true = no problems, false = negative hydrogens requested.
*/
bool estimateFromWeightAndCompAndS(double average_weight, UInt S, double C, double H, double N, double O, double P);
/**
@brief returns the isotope distribution of the formula
The details of the calculation of the isotope distribution
are described in the doc to the CoarseIsotopePatternGenerator class.
@param[in] method the method that will be used for the calculation of the IsotopeDistribution
*/
IsotopeDistribution getIsotopeDistribution(const IsotopePatternGenerator& method) const;
/**
@brief returns the fragment isotope distribution of this given a precursor formula
and conditioned on a set of isolated precursor isotopes.
The max_depth of the isotopic distribution is set to max(precursor_isotopes)+1.
@param[in] precursor the empirical formula of the precursor
@param[in] precursor_isotopes the precursor isotopes that were isolated
@param[in] method the method that will be used for the calculation of the IsotopeDistribution
@return the conditional IsotopeDistribution of the fragment
*/
IsotopeDistribution getConditionalFragmentIsotopeDist(const EmpiricalFormula& precursor,
const std::set<UInt>& precursor_isotopes,
const CoarseIsotopePatternGenerator& method) const;
/// returns the number of atoms for a certain @p element (can be negative)
SignedSize getNumberOf(const Element* element) const;
/// returns the atoms total (not absolute: negative counts for certain elements will reduce the overall count). Negative result is possible.
SignedSize getNumberOfAtoms() const;
/// returns the charge
Int getCharge() const;
/// sets the charge
void setCharge(Int charge);
/// returns the formula as a string (charges are not included)
String toString() const;
/// returns the formula as a map (charges are not included)
std::map<std::string, int> toMap() const;
//@}
/** Assignment
*/
//@{
/// Assignment operator
EmpiricalFormula& operator=(const EmpiricalFormula&) = default;
/// Move assignment operator
EmpiricalFormula& operator=(EmpiricalFormula&&) & = default;
/// adds the elements of the given formula
EmpiricalFormula& operator+=(const EmpiricalFormula& rhs);
/// multiplies the elements and charge with a factor
EmpiricalFormula operator*(const SignedSize& times) const;
/// adds the elements of the given formula and returns a new formula
EmpiricalFormula operator+(const EmpiricalFormula& rhs) const;
/// subtracts the elements of a formula
EmpiricalFormula& operator-=(const EmpiricalFormula& rhs);
/// subtracts the elements of a formula an returns a new formula
EmpiricalFormula operator-(const EmpiricalFormula& rhs) const;
//@}
/**@name Predicates
*/
//@{
/// returns true if the formula does not contain a element
bool isEmpty() const;
/// returns true if charge != 0
bool isCharged() const;
/// returns true if the formula contains the element
bool hasElement(const Element* element) const;
/// returns true if all elements from @p ef are LESS abundant (negative allowed) than the corresponding elements of this EmpiricalFormula
bool contains(const EmpiricalFormula& ef) const;
/// returns true if the formulas contain equal elements in equal quantities
bool operator==(const EmpiricalFormula& rhs) const;
/// returns true if the formulas differ in elements composition
bool operator!=(const EmpiricalFormula& rhs) const;
/// less operator
bool operator<(const EmpiricalFormula& rhs) const;
//@}
/// writes the formula to a stream
friend OPENMS_DLLAPI std::ostream& operator<<(std::ostream& os, const EmpiricalFormula& formula);
/** @name Iterators
*/
//@{
inline ConstIterator begin() const { return formula_.begin(); }
inline ConstIterator end() const { return formula_.end(); }
inline Iterator begin() { return formula_.begin(); }
inline Iterator end() { return formula_.end(); }
//@}
/** @name Static member functions
*/
// @TODO: make these static member variables instead?
//@{
/// Efficiently generates a formula for hydrogen
static EmpiricalFormula hydrogen(int n_atoms = 1);
/// Efficiently generates a formula for water
static EmpiricalFormula water(int n_molecules = 1);
//@}
protected:
/// remove elements with count 0
void removeZeroedElements_();
MapType_ formula_;
Int charge_;
Int parseFormula_(std::map<const Element*, SignedSize>& ef, const String& formula) const;
};
OPENMS_DLLAPI std::ostream& operator<<(std::ostream& os, const EmpiricalFormula& formula);
} // namespace OpenMS
// Hash function specialization for EmpiricalFormula
// Placed in std namespace to allow use with std::unordered_map/set
namespace std
{
/**
* @brief Hash function for OpenMS::EmpiricalFormula.
*
* Computes a hash based on element symbols and their counts,
* plus the charge. The hash is consistent with operator==.
*
* Design decisions:
* - Uses element symbols (not pointers) to distinguish isotopes like (13)C vs C
* - Sorts elements by symbol for reproducible hash across runs
* - FNV-1a based combining for good distribution
*
* @note Hash is reproducible across process runs on the same platform.
*/
template<>
struct hash<OpenMS::EmpiricalFormula>
{
std::size_t operator()(const OpenMS::EmpiricalFormula& ef) const noexcept
{
// Collect elements with symbols for deterministic ordering
// (map iteration order depends on pointer addresses which vary across runs)
// Use symbols instead of atomic numbers to distinguish isotopes like (13)C vs C
// Typical formulas have only 4-6 elements, so no need to reserve
std::vector<std::pair<std::string, OpenMS::SignedSize>> elements;
for (const auto& [element_ptr, count] : ef)
{
elements.emplace_back(element_ptr->getSymbol(), count);
}
// Sort by symbol for reproducible hash
std::sort(elements.begin(), elements.end());
// Hash in sorted order
std::size_t seed = 0;
for (const auto& [symbol, count] : elements)
{
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(symbol));
OpenMS::hash_combine(seed, OpenMS::hash_int(count));
}
// Hash the charge
OpenMS::hash_combine(seed, OpenMS::hash_int(ef.getCharge()));
return seed;
}
};
} // namespace std
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/ModificationDefinitionsSet.h | .h | 6,410 | 164 | // 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/CHEMISTRY/AASequence.h>
#include <OpenMS/CHEMISTRY/ModificationDefinition.h>
#include <OpenMS/CONCEPT/Types.h> // for "UInt"
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h> // for "StringList"
#include <OpenMS/DATASTRUCTURES/StringListUtils.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <set>
namespace OpenMS
{
/** @ingroup Chemistry
@brief Representation of a set of modification definitions
This class enhances the modification definitions as defined in the
class ModificationDefinition into a set of definitions. This is also
e.g. used as input parameters in search engines.
*/
class OPENMS_DLLAPI ModificationDefinitionsSet
{
public:
/** @name Constructor and Destructors
*/
//@{
/// default constructor
ModificationDefinitionsSet();
/// copy constructor
ModificationDefinitionsSet(const ModificationDefinitionsSet& rhs);
/// detailed constructor with StringLists
ModificationDefinitionsSet(const StringList& fixed_modifications, const StringList& variable_modifications);
/// destructor
virtual ~ModificationDefinitionsSet();
//@}
/** @name Accessors
*/
//@{
/// sets the maximal number of modifications allowed per peptide
void setMaxModifications(Size max_mod);
/// return the maximal number of modifications allowed per peptide
Size getMaxModifications() const;
/// returns the number of modifications stored in this set
Size getNumberOfModifications() const;
/// returns the number of fixed modifications stored in this set
Size getNumberOfFixedModifications() const;
/// returns the number of variable modifications stored in this set
Size getNumberOfVariableModifications() const;
/// adds a modification definition to the set
void addModification(const ModificationDefinition& mod_def);
/// sets the modification definitions
void setModifications(const std::set<ModificationDefinition>& mod_defs);
/** @brief set the modification definitions from a string
The strings should contain a comma separated list of modifications. The names
can be PSI-MOD identifier or any other unique name supported by PSI-MOD. TermSpec
definitions and other specific definitions are given by the modifications themselves.
*/
void setModifications(const String& fixed_modifications, const String& variable_modifications);
/// same as above, but using StringList instead of comma separated strings
void setModifications(const StringList& fixed_modifications, const StringList& variable_modifications);
/// returns the stored modification definitions
std::set<ModificationDefinition> getModifications() const;
/// returns the stored fixed modification definitions
const std::set<ModificationDefinition>& getFixedModifications() const;
/// returns the stored variable modification definitions
const std::set<ModificationDefinition>& getVariableModifications() const;
/// returns only the names of the modifications stored in the set
std::set<String> getModificationNames() const;
/// populates the output lists with the modification names (use e.g. for ProteinIdentification::SearchParameters)
void getModificationNames(StringList& fixed_modifications, StringList& variable_modifications) const;
/// returns only the names of the fixed modifications
std::set<String> getFixedModificationNames() const;
/// returns only the names of the variable modifications
std::set<String> getVariableModificationNames() const;
//@}
/** @name Assignment
*/
//@{
/// assignment operator
ModificationDefinitionsSet& operator=(const ModificationDefinitionsSet& element);
//@}
/** @name Predicates
*/
//@{
/// returns true if the peptide is compatible with the definitions, e.g. does not contain other modifications
bool isCompatible(const AASequence& peptide) const;
/// equality operator
bool operator==(const ModificationDefinitionsSet& rhs) const;
/// inequality operator
bool operator!=(const ModificationDefinitionsSet& rhs) const;
//@}
/**
@brief Finds modifications in the set that match a given (delta) mass
@param[out] matches Matching modifications (output), sorted by mass error
@param[in] mass Query mass
@param[in] residue Query residue
@param[in] term_spec Query term specificity
@param[in] consider_variable Consider the variable modifications?
@param[in] consider_fixed Consider the fixed modifications?
@param[in] is_delta Is @p mass a delta mass (mass difference)?
@param[in] tolerance Numeric tolerance (in Da) for mass matching
@throw Exception::IllegalArgument if both @p consider_variable and @p consider_fixed are false
*/
void findMatches(std::multimap<double, ModificationDefinition>& matches, double mass, const String& residue = "", ResidueModification::TermSpecificity term_spec = ResidueModification::NUMBER_OF_TERM_SPECIFICITY, bool consider_fixed = true, bool consider_variable = true, bool is_delta = true, double tolerance = 0.01) const;
/// Infers the sets of defined modifications from the modifications present on peptide identifications
void inferFromPeptides(const PeptideIdentificationList& peptides);
protected:
std::set<ModificationDefinition> variable_mods_;
std::set<ModificationDefinition> fixed_mods_;
Size max_mods_per_peptide_;
/// helper function for findMatches() - finds matching modifications in @p source and adds them to @p matches
static void addMatches_(std::multimap<double, ModificationDefinition>& matches, double mass, const String& residue, ResidueModification::TermSpecificity term_spec, const std::set<ModificationDefinition>& source, bool is_delta, double tolerance);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/TheoreticalSpectrumGenerator.h | .h | 7,793 | 156 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg, Eugen Netz $
// $Authors: Andreas Bertsch $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CHEMISTRY/Residue.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/METADATA/DataArrays.h>
#include <OpenMS/KERNEL/MSSpectrum.h>
namespace OpenMS
{
class AASequence;
/**
@brief Generates theoretical spectra for peptides with various options
If the tool parameter add_metainfo is set to true,
ion names like y8+ or [M-H2O+2H]++ are written as strings in a StringDataArray with the name
corresponding to the constant Constants::UserParam::IonNames
and charges are written as integers in an IntegerDataArray with the name "Charges"
in the returned PeakSpectrum.
The getSpectrum function can be called with the same PeakSpectrum multiple times to add additional peaks.
If the PeakSpectrum already has DataArrays, then the first StringDataArray and the first IntegerDataArray
are extended. Therefore it is not recommended to add to or change the PeakSpectrum or these DataArrays
between calls of the getSpectrum function with the same PeakSpectrum.
@note The generation of neutral loss peaks is very slow in this class.
Something similar to the neutral loss precalculation used in TheoreticalSpectrumGeneratorXLMS
should be implemented here as well.
@htmlinclude OpenMS_TheoreticalSpectrumGenerator.parameters
@ingroup Chemistry
*/
class OPENMS_DLLAPI TheoreticalSpectrumGenerator :
public DefaultParamHandler
{
public:
/** @name Constructors and Destructors
*/
//@{
/// default constructor
TheoreticalSpectrumGenerator();
/// copy constructor
TheoreticalSpectrumGenerator(const TheoreticalSpectrumGenerator& source);
/// destructor
~TheoreticalSpectrumGenerator() override;
//@}
/// assignment operator
TheoreticalSpectrumGenerator& operator=(const TheoreticalSpectrumGenerator& tsg);
/**
* Generates a simple tandem MS Spectrum,
* @param[out] spectrum Each peak is only represented as a single m/z value
* @param[in] peptide The input peptide
* @param[in] charge The max charge of the peaks
*/
void getPrefixAndSuffixIonsMZ(std::vector<float>& spectrum, const AASequence& peptide, int charge) const;
/** @name Acessors
*/
//@{
/// Generates a spectrum for a peptide sequence, with the ion types that are set in the tool parameters
/// If precursor_charge is set to 0 max_charge + 1 will be used.
/// @throw Exception::InvalidParameter if precursor_charge < max_charge
virtual void getSpectrum(PeakSpectrum& spec, const AASequence& peptide, Int min_charge, Int max_charge, Int precursor_charge = 0) const;
/// Generates a spectrum for a peptide sequence based on activation method and precursor charge.
/// Activation method 'CID' or 'HCID' will generate only b- and y-ions.
/// Activation method 'ECD' or 'ETD' will generate only c- and z-ions.
/// If precursor charge is greater than 2 ions with charge 1 & 2 will be generated, else only ions of charge 1 will appear in the spectrum.
/// @throw Exception::InvalidParameter If fragmentation method is anything else than 'CID', 'HCID', 'ECD' or 'ETD'.
static MSSpectrum generateSpectrum(const Precursor::ActivationMethod& fm, const AASequence& seq, int precursor_charge);
/// overwrite
void updateMembers_() override;
//@}
protected:
/// adds peaks to a spectrum of the given ion-type, peptide, charge, and intensity, also adds charges and ion names to the DataArrays, if the add_metainfo parameter is set to true
virtual void addPeaks_(PeakSpectrum& spectrum, const AASequence& peptide, DataArrays::StringDataArray& ion_names, DataArrays::IntegerDataArray& charges, MSSpectrum::Chunks& chunks, const Residue::ResidueType res_type, Int charge = 1) const;
/// adds the precursor peaks to the spectrum, also adds charges and ion names to the DataArrays, if the add_metainfo parameter is set to true
virtual void addPrecursorPeaks_(PeakSpectrum& spec, const AASequence& peptide, DataArrays::StringDataArray& ion_names, DataArrays::IntegerDataArray& charges, Int charge = 1) const;
/// Adds the common, most abundant immonium ions to the theoretical spectra if the residue is contained in the peptide sequence, also adds charges and ion names to the DataArrays, if the add_metainfo parameter is set to true
void addAbundantImmoniumIons_(PeakSpectrum& spec, const AASequence& peptide, DataArrays::StringDataArray& ion_names, DataArrays::IntegerDataArray& charges) const;
/// helper to add an isotope cluster to a spectrum, also adds charges and ion names to the DataArrays, if the add_metainfo parameter is set to true
void addIsotopeCluster_(PeakSpectrum& spectrum, const AASequence& ion, DataArrays::StringDataArray& ion_names, DataArrays::IntegerDataArray& charges, const Residue::ResidueType res_type, Int charge, double intensity) const;
/// helper to add full neutral loss ladders (for isotope clusters), also adds charges and ion names to the DataArrays, if the add_metainfo parameter is set to true
void addLosses_(PeakSpectrum& spectrum, const AASequence& ion, DataArrays::StringDataArray& ion_names, DataArrays::IntegerDataArray& charges, double intensity, const Residue::ResidueType res_type, int charge) const;
/// helper to add full neutral loss ladders (for single peaks), also adds charges and ion names to the DataArrays, if the add_metainfo parameter is set to true
void addLossesFaster_(PeakSpectrum& spectrum, double mz, const std::set<EmpiricalFormula>& f_losses, int ion_ordinal, DataArrays::StringDataArray& ion_names, DataArrays::IntegerDataArray& charges, const std::map<EmpiricalFormula, String>& formula_str_cache, double intensity, const String& annotation_prefix_string, bool add_metainfo, int charge) const;
/// helper for getPrefixAndSuffixIonsMZ. For given Ion-Type and charge calculates a peaks
static void addPrefixAndSuffixIons_(std::vector<float>& spectrum, const AASequence& peptide, Residue::ResidueType res_type, int charge);
void addInternalFragmentPeaks_(PeakSpectrum& spectrum,
const AASequence& peptide,
DataArrays::StringDataArray& ion_names,
DataArrays::IntegerDataArray& charges,
MSSpectrum::Chunks& chunks,
const Residue::ResidueType res_type,
Int charge) const;
bool add_b_ions_;
bool add_y_ions_;
bool add_a_ions_;
bool add_c_ions_;
bool add_x_ions_;
bool add_z_ions_;
bool add_zp1_ions_;
bool add_zp2_ions_;
bool add_first_prefix_ion_;
bool add_losses_;
bool add_term_losses_;
bool add_metainfo_;
bool add_isotopes_;
bool add_internal_fragments_;
int isotope_model_;
bool add_precursor_peaks_;
bool add_all_precursor_charges_ ;
bool add_abundant_immonium_ions_;
bool sort_by_position_;
double a_intensity_;
double b_intensity_;
double c_intensity_;
double x_intensity_;
double y_intensity_;
double z_intensity_;
Int max_isotope_;
double rel_loss_intensity_;
double max_isotope_probability_;
double pre_int_;
double pre_int_H2O_;
double pre_int_NH3_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/Element.h | .h | 4,510 | 166 | // 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/CONCEPT/Types.h>
#include <OpenMS/CONCEPT/HashUtils.h>
#include <OpenMS/CHEMISTRY/ISOTOPEDISTRIBUTION/IsotopeDistribution.h>
#include <functional>
#include <string>
#define OPENMS_CHEMISTRY_ELEMENT_NAME_DEFAULT "unknown"
#define OPENMS_CHEMISTRY_ELEMENT_SYMBOL_DEFAULT "??"
#define OPENMS_CHEMISTRY_ELEMENT_WEIGHT_DEFAULT 0.0
#define OPENMS_CHEMISTRY_ELEMENT_ATOMICNUMBER_DEFAULT 0
namespace OpenMS
{
/** @ingroup Chemistry
@brief Representation of an element
This contains information on an element and its isotopes, including a
common name, atomic symbol and mass/abundance of its isotopes.
*/
class OPENMS_DLLAPI Element
{
public:
/** @name Constructor and Destructors
*/
//@{
/// default constructor
Element();
/// copy constructor
Element(const Element & element);
/// detailed constructor
Element(const std::string & name,
const std::string & symbol,
unsigned int atomic_number,
double average_weight,
double mono_weight,
const IsotopeDistribution & isotopes);
/// destructor
virtual ~Element();
//@}
/** @name Accessors
*/
//@{
/// sets unique atomic number
void setAtomicNumber(unsigned int atomic_number);
/// returns the unique atomic number
unsigned int getAtomicNumber() const;
/// sets the average weight of the element
void setAverageWeight(double weight);
/// returns the average weight of the element
double getAverageWeight() const;
/// sets the mono isotopic weight of the element
void setMonoWeight(double weight);
/// returns the mono isotopic weight of the element
double getMonoWeight() const;
/// sets the isotope distribution of the element
void setIsotopeDistribution(const IsotopeDistribution & isotopes);
/// returns the isotope distribution of the element
const IsotopeDistribution & getIsotopeDistribution() const;
/// set the name of the element
void setName(const std::string & name);
/// returns the name of the element
const std::string & getName() const;
/// sets symbol of the element
void setSymbol(const std::string & symbol);
/// returns symbol of the element
const std::string & getSymbol() const;
//@}
/** @name Assignment
*/
//@{
/// assignment operator
Element & operator=(const Element & element);
//@}
/** @name Predicates
*/
//@{
/// equality operator
bool operator==(const Element & element) const;
/// inequality operator
bool operator!=(const Element & element) const;
/// less operator
bool operator<(const Element & element) const;
//@}
/// writes the element to an output stream
friend OPENMS_DLLAPI std::ostream & operator<<(std::ostream & os, const Element & element);
protected:
/// name of the element
std::string name_;
/// symbol of the element
std::string symbol_;
/// atomic number of the element
unsigned int atomic_number_;
/// average weight over all isotopes
double average_weight_;
/// mono isotopic weight of the most frequent isotope
double mono_weight_;
/// distribution of the isotopes (mass and natural frequency)
IsotopeDistribution isotopes_;
};
OPENMS_DLLAPI std::ostream & operator<<(std::ostream &, const Element &);
} // namespace OpenMS
// Hash function specialization for Element
namespace std
{
template<>
struct hash<OpenMS::Element>
{
std::size_t operator()(const OpenMS::Element& e) const noexcept
{
std::size_t seed = OpenMS::fnv1a_hash_string(e.getName());
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(e.getSymbol()));
OpenMS::hash_combine(seed, OpenMS::hash_int(e.getAtomicNumber()));
OpenMS::hash_combine(seed, OpenMS::hash_float(e.getAverageWeight()));
OpenMS::hash_combine(seed, OpenMS::hash_float(e.getMonoWeight()));
OpenMS::hash_combine(seed, std::hash<OpenMS::IsotopeDistribution>{}(e.getIsotopeDistribution()));
return seed;
}
};
} // namespace std
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/RNaseDB.h | .h | 1,023 | 37 | // 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/CHEMISTRY/DigestionEnzymeDB.h>
#include <OpenMS/CHEMISTRY/DigestionEnzymeRNA.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <vector>
namespace OpenMS
{
/**
@ingroup Chemistry
@brief Database for enzymes that digest RNA (RNases)
The enzymes stored in this DB are defined in an XML file under "share/CHEMISTRY/Enzymes_RNA.xml".
*/
class OPENMS_DLLAPI RNaseDB: public DigestionEnzymeDB<DigestionEnzymeRNA, RNaseDB>
{
// allow access to constructor in DigestionEnzymeDB::getInstance():
friend class DigestionEnzymeDB<DigestionEnzymeRNA, RNaseDB>;
protected:
/// constructor
RNaseDB();
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/SpectrumAnnotator.h | .h | 5,784 | 124 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Mathias Walzer $
// $Authors: Mathias Walzer $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/KERNEL/MSSpectrum.h>
#include <OpenMS/CHEMISTRY/TheoreticalSpectrumGenerator.h>
#include <OpenMS/COMPARISON/SpectrumAlignment.h>
#include <OpenMS/KERNEL/Peak1D.h>
#include <OpenMS/METADATA/PeptideHit.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <boost/regex.hpp>
namespace OpenMS
{
/**
@brief Annotates spectra from identifications and theoretical spectra or
identifications from spectra and theoretical spectra matching
with various options
@htmlinclude OpenMS_SpectrumAnnotator.parameters
@ingroup Chemistry
*/
class OPENMS_DLLAPI SpectrumAnnotator :
public DefaultParamHandler
{
public:
/** @name Constructors and Destructors
*/
//@{
/// default constructor
SpectrumAnnotator();
/// copy constructor
SpectrumAnnotator(const SpectrumAnnotator & source);
/// destructor
~SpectrumAnnotator() override;
//@}
/// assignment operator
SpectrumAnnotator & operator=(const SpectrumAnnotator & tsg);
/** @name Available annotators
*/
//@{
/**
@brief Adds ion match annotation to the @p spec input spectrum
@param[in] spec A PeakSpectrum containing the peaks from which the @p pi identifications are made
@param[out] ph A spectrum identifications to be used for the annotation, looking up matches from a spectrum and the theoretical spectrum inferred from the identifications sequence
@param[in] tg A TheoreticalSpectrumGenerator to infer the theoretical spectrum. Its own parameters define which ion types are referred
@param[in] sa A SpectrumAlignment to match the theoretical spectrum with the measured. Its own parameters define the match tolerance
The matches are added as DataArrays to the spectrum (Names: IonName and IonMatchError). The parameters of the TheoreticalSpectrumGenerator define the comprehensiveness of the available matching. The parameters of SpectrumAlignment define the matching tolerance.
See the parameter section of this class for the available options.
*/
void annotateMatches(PeakSpectrum &spec, const PeptideHit& ph, const TheoreticalSpectrumGenerator& tg, const SpectrumAlignment& sa) const;
/**
@brief Adds ion match statistics to @p pi PeptideIdentifcation
@param[in] pi A spectrum identifications to be annotated, looking up matches from a spectrum and the theoretical spectrum inferred from the identifications sequence
@param[in] spec A PeakSpectrum containing the peaks from which the @p pi identifications are made
@param[in] tg A TheoreticalSpectrumGenerator to infer the theoretical spectrum. Its own parameters define which ion types are referred
@param[in] sa A SpectrumAlignment to match the theoretical spectrum with the measured. Its own parameters define the match tolerance
The ion match statistics are added as UserParams to either the PeptideIdentification (parameters of the matching) and PeptideHit. The parameters of the TheoreticalSpectrumGenerator define the comprehensiveness of the available matching. The parameters of SpectrumAlignment define the matching tolerance.
See the parameter section of this class for the available statistics.
*/
void addIonMatchStatistics(PeptideIdentification& pi, MSSpectrum &spec, const TheoreticalSpectrumGenerator& tg, const SpectrumAlignment& sa) const;
/**
@brief Adds peak annotations to the @p ph PeptideHit
@param[in] ph A PeptideHit whose PeakAnnotations vector will be filled with the ion matches
@param[in] spec A PeakSpectrum containing the peaks from which the @p ph identifications are made
@param[in] tg A TheoreticalSpectrumGenerator to infer the theoretical spectrum. Its own parameters define which ion types are referred
@param[in] sa A SpectrumAlignment to match the theoretical spectrum with the measured. Its own parameters define the match tolerance
@param[in] include_unmatched_peaks If true, all spectrum peaks will be included in the PeakAnnotations vector.
Unmatched peaks will have empty annotation strings. If false (default), only matched peaks are included.
This method directly fills the PeakAnnotations vector of the PeptideHit with the matched ions.
Each matched peak gets a PeakAnnotation containing the annotation string (ion name), charge, m/z and intensity.
The parameters of the TheoreticalSpectrumGenerator define the comprehensiveness of the available matching.
The parameters of SpectrumAlignment define the matching tolerance.
*/
void addPeakAnnotationsToPeptideHit(PeptideHit& ph, const PeakSpectrum& spec, const TheoreticalSpectrumGenerator& tg, const SpectrumAlignment& sa, bool include_unmatched_peaks = false) const;
/// overwrite
void updateMembers_() override;
//@}
protected:
bool basic_statistics_;
bool list_of_ions_matched_;
bool max_series_;
bool SN_statistics_;
bool precursor_statistics_;
unsigned topNmatch_fragmenterrors_;
bool fragmenterror_statistics_;
bool terminal_series_match_ratio_;
static const boost::regex nt_regex_;
static const boost::regex ct_regex_;
static const boost::regex noloss_regex_;
static const boost::regex seriesposition_regex_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/AAIndex.h | .h | 25,779 | 1,244 | // 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/CHEMISTRY/AASequence.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/CONCEPT/Constants.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <cmath>
namespace OpenMS
{
/**
@brief Representation of selected %AAIndex properties
The literature that describe the indices can be found with:
@n Kawashima, S., Ogata, H., and Kanehisa, M. (1999).
@n <em>AAindex: Amino Acid Index Database</em>,
@n Nucleic Acids Res, 27(1), 368–369.
The provided values are:
- GB500 Estimated gas-phase basicity at 500 K,
- VASM830103 Relative population of conformational state E,
- NADH010106 Hydropathy scale (36% accessibility),
- FAUJ880111 Positive charge,
- WILM950102 Hydrophobicity coefficient in RP-HPLC, C8 with 0.1%TFA/MeCN/H2 O,
- OOBM850104 Optimized average non-bonded energy per atom,
- KHAG800101 The Kerr-constant increments,
- NADH010107 Hydropathy scale (50% accessibility),
- ROBB760107 Information measure for extended without H-bond,
- FINA770101 Helix-coil equilibrium constant,
- ARGP820102 Signal sequence helical potential.
Upper-case one-letter-code can be used to access the properties of a single amino acid.
@ingroup Chemistry
*/
class OPENMS_DLLAPI AAIndex
{
public:
/// Constructor not implemented
AAIndex() = delete;
/// Returns if the residue is aliphatic (1.0 or 0.0)
static double aliphatic(char aa)
{
if (aa == 'A' || aa == 'G' || aa == 'F' || aa == 'I' || aa == 'M' || aa == 'L' || aa == 'P' || aa == 'V')
{
return 1.0;
}
else
{
return 0.0;
}
}
/// Returns if the residue is acidic (1.0 or 0.0)
static double acidic(char aa)
{
if (aa == 'D' || aa == 'E')
{
return 1.0;
}
else
{
return 0.0;
}
}
/// Returns if the residue is basic (1.0 or 0.0)
static double basic(char aa)
{
if (aa == 'K' || aa == 'R' || aa == 'H' || aa == 'W')
{
return 1.0;
}
else
{
return 0.0;
}
}
/// Returns if the residue is polar (1.0 or 0.0)
static double polar(char aa)
{
if (aa == 'S' || aa == 'T' || aa == 'Y' || aa == 'H' || aa == 'C' || aa == 'N' || aa == 'Q' || aa == 'W')
{
return 1.0;
}
else
{
return 0.0;
}
}
//I A/L R/K N/M D/F C/P Q/S E/T G/W H/Y I/V
//49.1 133. -3.6 0. 0. 20. 0. 64.6 75.7 18.9
//15.6 0. 6.8 54.7 43.8 44.4 31.0 70.5 0. 29.5
/**
@brief The Kerr-constant increments (Khanarian-Moore, 1980)
LIT:0611050b<br>
Khanarian, G. and Moore, W.J.<br>
The Kerr effect of amino acids in water<br>
Aust. J. Chem. 33, 1727-1741 (1980) (Cys Lys Tyr !)
@exception InvalidValue is thrown if an undefined one-letter-code is used
*/
static double getKHAG800101(char aa)
{
switch (aa)
{
case 'A':
return 49.1;
case 'R':
return 133.;
case 'N':
return -3.6;
case 'D':
return 0.;
case 'C':
return 0.;
case 'Q':
return 20.;
case 'E':
return 0.;
case 'G':
return 64.6;
case 'H':
return 75.7;
case 'I':
return 18.9;
case 'L':
return 15.6;
case 'K':
return 0.;
case 'M':
return 6.8;
case 'F':
return 54.7;
case 'P':
return 43.8;
case 'S':
return 44.4;
case 'T':
return 31.0;
case 'W':
return 70.5;
case 'Y':
return 0.;
case 'V':
return 29.5;
default:
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Unknown amino acid one-letter-code", String(aa));
}
}
//I A/L R/K N/M D/F C/P Q/S E/T G/W H/Y I/V
//0.159 0.194 0.385 0.283 0.187 0.236 0.206 0.049 0.233 0.581
//0.083 0.159 0.198 0.682 0.366 0.150 0.074 0.463 0.737 0.301
/**
@brief Relative population of conformational state E (Vasquez et al., 1983)
LIT:0908110<br>
Vasquez, M., Nemethy, G. and Scheraga, H.A.<br>
Computed conformational states of the 20 naturally occurring amino acid
residues and of the prototype residue alpha-aminobutyric acid<br>
Macromolecules 16, 1043-1049 (1983) (Pro !)
@exception InvalidValue is thrown if an undefined one-letter-code is used
*/
static double getVASM830103(char aa)
{
switch (aa)
{
case 'A':
return 0.159;
case 'R':
return 0.194;
case 'N':
return 0.385;
case 'D':
return 0.283;
case 'C':
return 0.187;
case 'Q':
return 0.236;
case 'E':
return 0.206;
case 'G':
return 0.049;
case 'H':
return 0.233;
case 'I':
return 0.581;
case 'L':
return 0.083;
case 'K':
return 0.159;
case 'M':
return 0.198;
case 'F':
return 0.682;
case 'P':
return 0.366;
case 'S':
return 0.150;
case 'T':
return 0.074;
case 'W':
return 0.463;
case 'Y':
return 0.737;
case 'V':
return 0.301;
default:
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Unknown amino acid one-letter-code", String(aa));
}
}
//NADH010105 0.958 NADH010104 0.914 NADH010103 0.881<br>
//ZHOH040103 0.819 NADH010107 0.811 BAEK050101 0.809<br>
//NADH010102 0.808 PONP800103 0.803 VINM940103 -0.813<br>
//KRIW710101 -0.846 KRIW790101 -0.861
//I A/L R/K N/M D/F C/P Q/S E/T G/W H/Y I/V
//5 -57 -77 45 224 -67 -8 -47 -50 83
//82 -38 83 117 -103 -41 79 130 27 117
/**
@brief Hydropathy scale based on self-information values in the two-state model (36% accessibility) (Naderi-Manesh et al., 2001)
PMID:11170200<br>
Naderi-Manesh, H., Sadeghi, M., Arab, S. and Moosavi Movahedi, A.A.<br>
Prediction of protein surface accessibility with information theory<br>
Proteins. 42, 452-459 (2001)
@exception InvalidValue is thrown if an undefined one-letter-code is used
*/
static double getNADH010106(char aa)
{
switch (aa)
{
case 'A':
return 5;
case 'R':
return -57;
case 'N':
return -77;
case 'D':
return 45;
case 'C':
return 224;
case 'Q':
return -67;
case 'E':
return -8;
case 'G':
return -47;
case 'H':
return -50;
case 'I':
return 83;
case 'L':
return 82;
case 'K':
return -38;
case 'M':
return 83;
case 'F':
return 117;
case 'P':
return -103;
case 'S':
return -41;
case 'T':
return 79;
case 'W':
return 130;
case 'Y':
return 27;
case 'V':
return 117;
default:
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Unknown amino acid one-letter-code", String(aa));
}
}
//NADH010106 0.811
//I A/L R/K N/M D/F C/P Q/S E/T G/W H/Y I/V
//-2 -41 -97 248 329 -37 117 -66 -70 28
//36 115 62 120 -132 -52 174 179 -7 114
/**
@brief Hydropathy scale based on self-information values in the two-state model (50% accessibility) (Naderi-Manesh et al., 2001)
PMID:11170200<br>
Naderi-Manesh, H., Sadeghi, M., Arab, S. and Moosavi Movahedi, A.A.<br>
Prediction of protein surface accessibility with information theory<br>
Proteins. 42, 452-459 (2001)
@exception InvalidValue is thrown if an undefined one-letter-code is used
*/
static double getNADH010107(char aa)
{
switch (aa)
{
case 'A':
return -2;
case 'R':
return -41;
case 'N':
return -97;
case 'D':
return 248;
case 'C':
return 329;
case 'Q':
return -37;
case 'E':
return 117;
case 'G':
return -66;
case 'H':
return -70;
case 'I':
return 28;
case 'L':
return 36;
case 'K':
return 115;
case 'M':
return 62;
case 'F':
return 120;
case 'P':
return -132;
case 'S':
return -52;
case 'T':
return 174;
case 'W':
return 179;
case 'Y':
return -7;
case 'V':
return 114;
default:
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Unknown amino acid one-letter-code", String(aa));
}
}
//WILM950101 0.838 MEEJ810102 0.809
//I A/L R/K N/M D/F C/P Q/S E/T G/W H/Y I/V
//2.62 1.26 -1.27 -2.84 0.73 -1.69 -0.45 -1.15 -0.74 4.38
//6.57 -2.78 -3.12 9.14 -0.12 -1.39 1.81 5.91 1.39 2.30
/**
@brief Hydrophobicity coefficient in RP-HPLC, C8 with 0.1%TFA/MeCN/H2O (Wilce et al. 1995)
Wilce, M.C., Aguilar, M.I. and Hearn, M.T.<br>
Physicochemical basis of amino acid hydrophobicity scales: evaluation of four
new scales of amino acid hydrophobicity coefficients derived from RP-HPLC of
peptides<br>
Anal Chem. 67, 1210-1219 (1995)
@exception InvalidValue is thrown if an undefined one-letter-code is used
*/
static double getWILM950102(char aa)
{
switch (aa)
{
case 'A':
return 2.62;
case 'R':
return 1.26;
case 'N':
return -1.27;
case 'D':
return -2.84;
case 'C':
return 0.73;
case 'Q':
return -1.69;
case 'E':
return -0.45;
case 'G':
return -1.15;
case 'H':
return -0.74;
case 'I':
return 4.38;
case 'L':
return 6.57;
case 'K':
return -2.78;
case 'M':
return -3.12;
case 'F':
return 9.14;
case 'P':
return -0.12;
case 'S':
return -1.39;
case 'T':
return 1.81;
case 'W':
return 5.91;
case 'Y':
return 1.39;
case 'V':
return 2.30;
default:
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Unknown amino acid one-letter-code", String(aa));
}
}
//I A/L R/K N/M D/F C/P Q/S E/T G/W H/Y I/V
//0.0 1.1 -2.0 -2.6 5.4 2.4 3.1 -3.4 0.8 -0.1
//-3.7 -3.1 -2.1 0.7 7.4 1.3 0.0 -3.4 4.8 2.7
/**
@brief Information measure for extended without H-bond (Robson-Suzuki, 1976)
PMID:1003471<br>
Robson, B. and Suzuki, E.<br>
Conformational properties of amino acid residues in globular proteins<br>
J. Mol. Biol. 107, 327-356 (1976)
@exception InvalidValue is thrown if an undefined one-letter-code is used
*/
static double getROBB760107(char aa)
{
switch (aa)
{
case 'A':
return 0.0;
case 'R':
return 1.1;
case 'N':
return -2.0;
case 'D':
return -2.6;
case 'C':
return 5.4;
case 'Q':
return 2.4;
case 'E':
return 3.1;
case 'G':
return -3.4;
case 'H':
return 0.8;
case 'I':
return -0.1;
case 'L':
return -3.7;
case 'K':
return -3.1;
case 'M':
return -2.1;
case 'F':
return 0.7;
case 'P':
return 7.4;
case 'S':
return 1.3;
case 'T':
return 0.0;
case 'W':
return -3.4;
case 'Y':
return 4.8;
case 'V':
return 2.7;
default:
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Unknown amino acid one-letter-code", String(aa));
}
}
//I A/L R/K N/M D/F C/P Q/S E/T G/W H/Y I/V
//-2.49 2.55 2.27 8.86 -3.13 1.79 4.04 -0.56 4.22 -10.87
//-7.16 -9.97 -4.96 -6.64 5.19 -1.60 -4.75 -17.84 9.25 -3.97
/**
@brief Optimized average non-bonded energy per atom (Oobatake et al., 1985)
LIT:1207075b<br>
Oobatake, M., Kubota, Y. and Ooi, T.<br>
Optimization of amino acid parameters for correspondence of sequence to
tertiary structures of proteins<br>
Bull. Inst. Chem. Res., Kyoto Univ. 63, 82-94 (1985)
@exception InvalidValue is thrown if an undefined one-letter-code is used
*/
static double getOOBM850104(char aa)
{
switch (aa)
{
case 'A':
return -2.49;
case 'R':
return 2.55;
case 'N':
return 2.27;
case 'D':
return 8.86;
case 'C':
return -3.13;
case 'Q':
return 1.79;
case 'E':
return 4.04;
case 'G':
return -0.56;
case 'H':
return 4.22;
case 'I':
return -10.87;
case 'L':
return -7.16;
case 'K':
return -9.97;
case 'M':
return -4.96;
case 'F':
return -6.64;
case 'P':
return 5.19;
case 'S':
return -1.60;
case 'T':
return -4.75;
case 'W':
return -17.84;
case 'Y':
return 9.25;
case 'V':
return -3.97;
default:
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Unknown amino acid one-letter-code", String(aa));
}
}
//ZIMJ680104 0.813
//I A/L R/K N/M D/F C/P Q/S E/T G/W H/Y I/V
//0. 1. 0. 0. 0. 0. 0. 0. 1. 0.
//0. 1. 0. 0. 0. 0. 0. 0. 0. 0.
/**
@brief Positive charge (Fauchere et al., 1988)
LIT:1414114 PMID:3209351<br>
Fauchere, J.L., Charton, M., Kier, L.B., Verloop, A. and Pliska, V.<br>
Amino acid side chain parameters for correlation studies in biology and
pharmacology<br>
Int. J. Peptide Protein Res. 32, 269-278 (1988)
@exception InvalidValue is thrown if an undefined one-letter-code is used
*/
static double getFAUJ880111(char aa)
{
switch (aa)
{
case 'A':
return 0.;
case 'R':
return 1.;
case 'N':
return 0.;
case 'D':
return 0.;
case 'C':
return 0.;
case 'Q':
return 0.;
case 'E':
return 0.;
case 'G':
return 0.;
case 'H':
return 1.;
case 'I':
return 0.;
case 'L':
return 0.;
case 'K':
return 1.;
case 'M':
return 0.;
case 'F':
return 0.;
case 'P':
return 0.;
case 'S':
return 0.;
case 'T':
return 0.;
case 'W':
return 0.;
case 'Y':
return 0.;
case 'V':
return 0.;
default:
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Unknown amino acid one-letter-code", String(aa));
}
}
//SUEM840101 0.883 AURR980114 0.875 AURR980113 0.849<br>
//PTIO830101 0.826 KANM800103 0.823 QIAN880107 0.814<br>
//QIAN880106 0.810 MAXF760101 0.810 AURR980109 0.802
//I A/L R/K N/M D/F C/P Q/S E/T G/W H/Y I/V
//1.08 1.05 0.85 0.85 0.95 0.95 1.15 0.55 1.00 1.05
//1.25 1.15 1.15 1.10 0.71 0.75 0.75 1.10 1.10 0.95
/**
@brief Helix-coil equilibrium constant (Finkelstein-Ptitsyn, 1977)
LIT:2004052b PMID:843599<br>
Finkelstein, A.V. and Ptitsyn, O.B.<br>
Theory of protein molecule self-organization. II. A comparison of calculated
thermodynamic parameters of local secondary structures with experiments<br>
Biopolymers 16, 497-524 (1977) (Pro 0.096)
@exception InvalidValue is thrown if an undefined one-letter-code is used
*/
static double getFINA770101(char aa)
{
switch (aa)
{
case 'A':
return 1.08;
case 'R':
return 1.05;
case 'N':
return 0.85;
case 'D':
return 0.85;
case 'C':
return 0.95;
case 'Q':
return 0.95;
case 'E':
return 1.15;
case 'G':
return 0.55;
case 'H':
return 1.00;
case 'I':
return 1.05;
case 'L':
return 1.25;
case 'K':
return 1.15;
case 'M':
return 1.15;
case 'F':
return 1.10;
case 'P':
return 0.71;
case 'S':
return 0.75;
case 'T':
return 0.75;
case 'W':
return 1.10;
case 'Y':
return 1.10;
case 'V':
return 0.95;
default:
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Unknown amino acid one-letter-code", String(aa));
}
}
//ARGP820103 0.961 KYTJ820101 0.803 JURD980101 0.802
//I A/L R/K N/M D/F C/P Q/S E/T G/W H/Y I/V
//1.18 0.20 0.23 0.05 1.89 0.72 0.11 0.49 0.31 1.45
//3.23 0.06 2.67 1.96 0.76 0.97 0.84 0.77 0.39 1.08
/**
@brief Signal sequence helical potential (Argos et al., 1982)
LIT:0901079b PMID:7151796<br>
Argos, P., Rao, J.K.M. and Hargrave, P.A.<br>
Structural prediction of membrane-bound proteins<br>
Eur. J. Biochem. 128, 565-575 (1982)
@exception InvalidValue is thrown if an undefined one-letter-code is used
*/
static double getARGP820102(char aa)
{
switch (aa)
{
case 'A':
return 1.18;
case 'R':
return 0.20;
case 'N':
return 0.23;
case 'D':
return 0.05;
case 'C':
return 1.89;
case 'Q':
return 0.72;
case 'E':
return 0.11;
case 'G':
return 0.49;
case 'H':
return 0.31;
case 'I':
return 1.45;
case 'L':
return 3.23;
case 'K':
return 0.06;
case 'M':
return 2.67;
case 'F':
return 1.96;
case 'P':
return 0.76;
case 'S':
return 0.97;
case 'T':
return 0.84;
case 'W':
return 0.77;
case 'Y':
return 0.39;
case 'V':
return 1.08;
default:
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Unknown amino acid one-letter-code", String(aa));
}
}
/**
@brief Calculates an estimated gas-phase basicity for an amino acid sequence at a given temperature
Energy level E at each protonation site i is -GB(i) fractional proton population of a microstate k is <br>
P_k = exp (- E_k/(RT)) / ( sum_i exp (- E_i/(RT))) <br>
The apparent proton association constant K_app: K_app = sum_i GB(i)/(RT)<br>
Then the apparent GB is GB_app^ion = R * T * ln(K_app)
@exception InvalidValue is thrown if an undefined one-letter-code is used
*/
static double calculateGB(const AASequence& seq, double T = 500.0)
{
double R = Constants::GAS_CONSTANT / 1000.0; // ideal gas constant in kj/(K*mol)
char left = '>';
char right;
double k_app = 0.0; // apparent proton association constant
// energy level E at each protonation site i is -GB(i)
// fractional proton population of a microstate k is
// P_k = exp (- E_k/(RT)) / ( sum_i exp (- E_i/(RT)))
// the apparent proton association constant k_app:
// k_app = sum_i GB(i)/(RT)
// then the apparent GB is GB_app^ion = R * T * ln(k_app)
for (Size i = 0; i <= seq.size(); i++)
{
// aa left to current one
if (i > 0)
{
Residue leftchar = seq[i - 1];
left = leftchar.getOneLetterCode()[0];
}
// aa right to current one
if (i == seq.size())
{
right = '<';
}
else
{
Residue rightchar = seq[i];
right = rightchar.getOneLetterCode()[0];
}
double contrib = exp((GBleft_(left) + GBdeltaright_(right)) / (R * T));
if (i > 0 && i < seq.size())
{
contrib += exp(GBsidechain_(right) / (R * T));
}
k_app += contrib;
}
// calculate apparent GB
return R * T * log(k_app) / log(2.0);
}
protected:
/**
@brief Calculates part of the gas-phase basicity
For a detailed description see @ref calculateGB(const AASequence&, double) .
@exception InvalidValue is thrown if an undefined one-letter-code is used
*/
static double GBsidechain_(char aa)
{
switch (aa)
{
case 'A':
return 0.0;
case 'C':
return 0.0;
case 'D':
return 784.0;
case 'E':
return 790.0;
case 'F':
return 0.0;
case 'G':
return 0.0;
case 'H':
return 927.84;
case 'I':
return 0.0;
case 'K':
return 926.74;
case 'L':
return 0.0;
case 'M':
return 830.0;
case 'N':
return 864.94;
case 'P':
return 0.0;
case 'Q':
return 865.25;
case 'R':
return 1000.0;
case 'S':
return 775.0;
case 'T':
return 780.0;
case 'V':
return 0.0;
case 'W':
return 909.53;
case 'Y':
return 790.0;
default:
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Unknown amino acid one-letter-code", String(aa));
}
}
/**
@brief Calculates part of the gas-phase basicity
For a detailed description see @ref calculateGB(const AASequence&, double) .
@exception InvalidValue is thrown if an undefined one-letter-code is used
*/
static double GBleft_(char aa)
{
switch (aa)
{
case 'A':
return 881.82;
case 'C':
return 881.15;
case 'D':
return 880.02;
case 'E':
return 880.10;
case 'F':
return 881.08;
case 'G':
return 881.17;
case 'H':
return 881.27;
case 'I':
return 880.99;
case 'K':
return 880.06;
case 'L':
return 881.88;
case 'M':
return 881.38;
case 'N':
return 881.18;
case 'P':
return 881.25;
case 'Q':
return 881.50;
case 'R':
return 882.98;
case 'S':
return 881.08;
case 'T':
return 881.14;
case 'V':
return 881.17;
case 'W':
return 881.31;
case 'Y':
return 881.20;
case '>': //NH2
return 916.84;
default:
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Unknown amino acid one-letter-code", String(aa));
}
}
/**
@brief Calculates part of the gas-phase basicity
For a detailed description see @ref calculateGB(const AASequence&, double) .
@exception InvalidValue is thrown if an undefined one-letter-code is used
*/
static double GBdeltaright_(char aa)
{
switch (aa)
{
case 'A':
return 0.0;
case 'C':
return -0.69;
case 'D':
return -0.63;
case 'E':
return -0.39;
case 'F':
return 0.03;
case 'G':
return 0.92;
case 'H':
return -0.19;
case 'I':
return -1.17;
case 'K':
return -0.71;
case 'L':
return -0.09;
case 'M':
return 0.30;
case 'N':
return 1.56;
case 'P':
return 11.75;
case 'Q':
return 4.10;
case 'R':
return 6.28;
case 'S':
return 0.98;
case 'T':
return 1.21;
case 'V':
return -0.90;
case 'W':
return 0.10;
case 'Y':
return -0.38;
case '<': //COOH
return -95.82;
default:
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Unknown amino acid one-letter-code", String(aa));
}
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/MASSDECOMPOSITION/MassDecompositionAlgorithm.h | .h | 2,215 | 86 | // 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/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/CHEMISTRY/MASSDECOMPOSITION/MassDecomposition.h>
// ims includes
#ifdef OPENMS_COMPILER_MSVC
#pragma warning( push )
#pragma warning( disable : 4290 4267)
#endif
#include <OpenMS/CHEMISTRY/MASSDECOMPOSITION/IMS/RealMassDecomposer.h>
#include <OpenMS/CHEMISTRY/MASSDECOMPOSITION/IMS/IMSAlphabet.h>
#include <OpenMS/CHEMISTRY/MASSDECOMPOSITION/IMS/Weights.h>
#ifdef OPENMS_COMPILER_MSVC
#pragma warning( pop )
#endif
#include <vector>
namespace OpenMS
{
/**
@brief Mass decomposition algorithm, given a mass it suggests possible compositions
A mass decomposition algorithm decomposes a mass or a mass difference into
possible amino acids and frequencies of them, which add up to the given mass.
This class is a wrapper for the algorithm published in
@htmlinclude OpenMS_MassDecompositionAlgorithm.parameters
@ingroup Analysis_DeNovo
*/
class OPENMS_DLLAPI MassDecompositionAlgorithm :
public DefaultParamHandler
{
public:
/**
@name constructors and destructor
*/
//@{
/// Default constructor
MassDecompositionAlgorithm();
/// Destructor
~MassDecompositionAlgorithm() override;
//@}
/**
@name Operators
*/
//@{
/// returns the possible decompositions given the weight
void getDecompositions(std::vector<MassDecomposition> & decomps, double weight);
//@}
protected:
void updateMembers_() override;
ims::IMSAlphabet * alphabet_;
ims::RealMassDecomposer * decomposer_;
private:
// will not be implemented
/// Copy constructor
MassDecompositionAlgorithm(const MassDecompositionAlgorithm & deco);
/// assignment operator
MassDecompositionAlgorithm & operator=(const MassDecompositionAlgorithm & rhs);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/MASSDECOMPOSITION/MassDecomposition.h | .h | 2,394 | 91 | // 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/config.h>
#include <OpenMS/CONCEPT/Types.h>
#include <map>
namespace OpenMS
{
class String;
/**
@brief Class represents a decomposition of a mass into amino acids
This class represents a mass decomposition into amino acids. A
decomposition are amino acids given with frequencies which add
up to a specific mass.
*/
class OPENMS_DLLAPI MassDecomposition
{
public:
/**
@name Constructors and destructors
*/
//@{
/// default constructor
MassDecomposition();
/// copy constructor
MassDecomposition(const MassDecomposition& deco);
/// constructor with String as parameter
explicit MassDecomposition(const String& deco);
//@}
/**
@name Operators and accessors
*/
//@{
/// assignment operator
MassDecomposition& operator=(const MassDecomposition& rhs);
/// adds the mass decomposition d to this object
MassDecomposition& operator+=(const MassDecomposition& d);
/// returns the decomposition as a string
String toString() const;
/// returns the decomposition as a string; instead of frequencies the amino acids are repeated
String toExpandedString() const;
/// adds this decomposition and the decomposition given and returns a new composition
MassDecomposition operator+(const MassDecomposition& rhs) const;
/// returns the max frequency of this composition
Size getNumberOfMaxAA() const;
//@}
/**
@name Predicates
*/
//@{
/// less than predicate
bool operator<(const MassDecomposition& rhs) const;
/// equality operator
bool operator==(const String& deco) const;
/// returns true if tag is contained in the mass decomposition
bool containsTag(const String& tag) const;
/// returns true if the mass decomposition if contained in this instance
bool compatible(const MassDecomposition& deco) const;
//@}
protected:
std::map<char, Size> decomp_;
Size number_of_max_aa_;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/MASSDECOMPOSITION/IMS/RealMassDecomposer.h | .h | 3,902 | 108 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Anton Pervukhin <Anton.Pervukhin@CeBiTec.Uni-Bielefeld.DE> $
// --------------------------------------------------------------------------
//
#pragma once
#include <utility>
#include <map>
#include <memory>
#include <OpenMS/CHEMISTRY/MASSDECOMPOSITION/IMS/IntegerMassDecomposer.h>
namespace OpenMS
{
namespace ims
{
/**
@brief Handles decomposing of non-integer values/masses
over a set of non-integer weights with an error allowed.
Implements a decomposition of non-integer values with a certain error
allowed. Exactness of decomposition can also be tuned by setting a
precision factor for weights defining their scaling magnitude.
Works in fact as a wrapper for classes that handle exact mass decomposing
using integer arithmetics. Instead of decomposing a single value as done
by integer mass decomposers, @c RealMassDecomposer defines a set of values
that lie in the allowed range (defined by error and false negatives
appeared due to rounding), scales those to integers, decomposes
them using @c IntegerMassDecomposer, does some checks (i.e. on false
positives appeared due to rounding) and collects decompositions together.
@author Anton Pervukhin <Anton.Pervukhin@CeBiTec.Uni-Bielefeld.DE>
*/
class OPENMS_DLLAPI RealMassDecomposer
{
public:
/// Type of integer decomposer.
typedef IntegerMassDecomposer<> integer_decomposer_type;
/// Type of integer values that are decomposed.
typedef integer_decomposer_type::value_type integer_value_type;
/// Type of result decompositions from integer decomposer.
typedef integer_decomposer_type::decompositions_type decompositions_type;
/// Type of the number of decompositions.
typedef unsigned long long number_of_decompositions_type;
typedef std::map<unsigned int, std::pair<unsigned int, unsigned int> > constraints_type;
/**
Constructor with weights.
@param[in] weights Weights over which values/masses to be decomposed.
*/
explicit RealMassDecomposer(const Weights & weights);
/**
Gets all decompositions for a @c mass with an @c error allowed.
@param[in] mass Mass to be decomposed.
@param[out] error Error allowed between given and result decomposition.
@return All possible decompositions for a given mass and error.
*/
decompositions_type getDecompositions(double mass, double error);
decompositions_type getDecompositions(double mass, double error, const constraints_type & constraints);
/**
Gets a number of all decompositions for a @c mass with an @c error
allowed. It's similar to the @c getDecompositions(double,double) function
but less space consuming, since doesn't use container to store decompositions.
@param[in] mass Mass to be decomposed.
@param[out] error Error allowed between given and result decomposition.
@return Number of all decompositions for a given mass and error.
*/
number_of_decompositions_type getNumberOfDecompositions(double mass, double error);
private:
/// Weights over which values/masses to be decomposed.
Weights weights_;
/// Minimal and maximal rounding errors.
std::pair<double, double> rounding_errors_;
/// Precision to scale double values to integer
double precision_;
/**
Decomposer to be used for exact decomposing using
integer arithmetic.
*/
std::shared_ptr<integer_decomposer_type> decomposer_;
};
} // namespace ims
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/MASSDECOMPOSITION/IMS/Weights.h | .h | 6,406 | 223 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Anton Pervukhin <Anton.Pervukhin@CeBiTec.Uni-Bielefeld.DE> $
// --------------------------------------------------------------------------
//
#pragma once
#include <vector>
#include <iosfwd>
#include <OpenMS/config.h>
namespace OpenMS
{
namespace ims
{
/**
@brief Represents a set of weights (double values and scaled with a certain
precision their integer counterparts) with a quick access.
Many algorithms can't work with real-valued alphabets and need integer
weights. Those are usually obtained by dividing all alphabet masses by
a "precision" parameter (0; 1) and rounding the result to integers.
Class @c Weights allows access to the scaled masses (the weights) and to the
original masses as well. Weights are cached and will not be recalculated on
access.
@note Words 'weights' and 'masses' were used deliberately for naming
corresponding values to help users quickly understand how they can be used.
Names were chosen due to similarity in 'weights' and 'masses' interconnection
in this class with real life. In reality mass value is always the same, and
weight value depends on circumstances. The same as here original double
masses stay the same, and scaled integer weights depend on precision applied.
@author Anton Pervukhin <Anton.Pervukhin@CeBiTec.Uni-Bielefeld.DE>
*/
class OPENMS_DLLAPI Weights
{
public:
/// Type of integer values to be used.
typedef long unsigned int weight_type;
/// Type of double values to be used.
typedef double alphabet_mass_type;
/// Type of container to store integer values.
typedef std::vector<weight_type> weights_type;
/// Type of container to store double values.
typedef std::vector<alphabet_mass_type> alphabet_masses_type;
/// Type of container's size
typedef weights_type::size_type size_type;
/// Empty constructor.
Weights() {}
/**
Constructor with double values and precision.
@param[in] masses Original double values to be scaled.
@param[in] precision Precision to scale double values.
*/
Weights(const alphabet_masses_type & masses, alphabet_mass_type precision) :
alphabet_masses_(masses),
precision_(precision)
{
setPrecision(precision);
}
/**
Copy constructor.
@param[in] other Weights to be copied.
*/
Weights(const Weights & other) :
alphabet_masses_(other.alphabet_masses_),
precision_(other.precision_),
weights_(other.weights_) {}
/**
Assignment operator.
@param[in] other Weights to be assigned.
@return Reference to this object.
*/
Weights & operator=(const Weights & other);
/**
Gets size of a set of weights.
@return Size of a set of weights.
*/
size_type size() const
{
return weights_.size();
}
/**
Gets a scaled integer weight by index.
@param[in] i An index to access weights.
@return An integer weight.
*/
weight_type getWeight(size_type i) const
{
return weights_[i];
}
/**
Sets a new precision to scale double values to integer.
@param[in] precision A new precision.
*/
void setPrecision(alphabet_mass_type precision);
/**
Gets precision.
@return Precision to scale double values to integer.
*/
alphabet_mass_type getPrecision() const
{
return precision_;
}
/**
Operator to access weights by index.
@param[in] i An index to access weights.
@return An integer weight.
@see getWeight(size_type i)
*/
weight_type operator[](size_type i) const
{
return weights_[i];
}
/**
Gets a last weight.
@return a last weight.
*/
weight_type back() const
{
return weights_.back();
}
/**
Gets an original (double) alphabet mass by index.
@param[in] i An index to access alphabet masses.
@return A double alphabet mass.
*/
alphabet_mass_type getAlphabetMass(size_type i) const
{
return alphabet_masses_[i];
}
/**
Returns a parent mass for a given \c decomposition
*/
alphabet_mass_type getParentMass(const std::vector<unsigned int> & decomposition) const;
/**
Exchanges weight and mass at index1 with weight and mass at index2.
@param[in,out] index1 Index of weight and mass to be exchanged.
@param[in,out] index2 Index of weight and mass to be exchanged.
*/
void swap(size_type index1, size_type index2);
/**
Divides the integer weights by their gcd. The precision is also
adjusted.
For example, given alphabet weights 3.0, 5.0, 8.0 with precision 0.1, the
integer weights would be 30, 50, 80. After calling this method, the new
weights are 3, 5, 8 with precision 1.0 (since the gcd of 30, 50, and 80
is 10).
@return true if anything was changed, that is, if the gcd was > 1.
false if the gcd was already 1 or there are less than two weights.
*/
bool divideByGCD();
alphabet_mass_type getMinRoundingError() const;
alphabet_mass_type getMaxRoundingError() const;
private:
/**
Container to store original (double) alphabet masses.
*/
alphabet_masses_type alphabet_masses_;
/**
Precision which is used to scale double values to integer.
*/
alphabet_mass_type precision_;
/**
Container to store scaled integer weights.
*/
weights_type weights_;
};
/**
Prints weights to the stream @c os.
@param[out] os Output stream to which weights are written.
@param[out] weights Weights to be written.
*/
OPENMS_DLLAPI std::ostream & operator<<(std::ostream & os, const Weights & weights);
} // namespace ims
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/MASSDECOMPOSITION/IMS/IMSElement.h | .h | 6,446 | 243 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Anton Pervukhin <Anton.Pervukhin@CeBiTec.Uni-Bielefeld.DE> $
// --------------------------------------------------------------------------
//
#pragma once
#include <string>
#include <iosfwd>
#include <OpenMS/CHEMISTRY/MASSDECOMPOSITION/IMS/IMSIsotopeDistribution.h>
namespace OpenMS
{
namespace ims
{
/**
@brief Represents a chemical atom with name and isotope distribution.
Simulates a chemical atom with name and isotope distribution and can be
used as a base class for more complex structures that simulate non-trivial
bio-chemical molecules. @c Element 's name represents the atom's symbol
in a periodical table. Sequence is by default equal to name and
introduced for more complex molecules.
@author Anton Pervukhin <Anton.Pervukhin@CeBiTec.Uni-Bielefeld.DE>
*/
class OPENMS_DLLAPI IMSElement
{
public:
/// Type of element's name.
typedef std::string name_type;
/// Type of element's isotope distribution.
typedef IMSIsotopeDistribution isotopes_type;
/// Type of isotope mass.
typedef isotopes_type::mass_type mass_type;
/// Type of distribution nominal mass.
typedef isotopes_type::nominal_mass_type nominal_mass_type;
/// Type of isotopes size.
typedef isotopes_type::size_type size_type;
/// Mass of electron.
static const mass_type ELECTRON_MASS_IN_U;
/// Empty constructor.
IMSElement()
{}
/// Copy constructor.
IMSElement(const IMSElement & element) :
name_(element.name_),
sequence_(element.sequence_),
isotopes_(element.isotopes_)
{}
/// Constructor with name and isotope distribution.
IMSElement(const name_type & name,
const isotopes_type & isotopes) :
name_(name),
sequence_(name),
isotopes_(isotopes)
{}
/// Constructor with name and mass of single isotope.
IMSElement(const name_type & name,
mass_type mass) :
name_(name),
sequence_(name),
isotopes_(mass)
{}
/// Constructor with name and nominal mass.
IMSElement(const name_type & name,
nominal_mass_type nominal_mass = 0) :
name_(name),
sequence_(name),
isotopes_(nominal_mass)
{}
/**
Gets element's name. @note Name represents
a symbol of element/atom in a periodical table.
@return Name of element.
*/
const name_type & getName() const
{
return name_;
}
/**
Sets element's name. @note Name represents
a symbol of element/atom in a periodical table.
@param[in] name A new name to be set for element.
*/
void setName(const name_type & name)
{
this->name_ = name;
}
/**
Gets element's sequence.
@return Sequence of element.
*/
const name_type & getSequence() const
{
return sequence_;
}
/**
Sets element's sequence.
@param[in] sequence A new sequence to be set for element.
*/
void setSequence(const name_type & sequence)
{
this->sequence_ = sequence;
}
/**
Gets element's nominal mass.
@return A nominal mass of element.
*/
nominal_mass_type getNominalMass() const
{
return isotopes_.getNominalMass();
}
/**
Gets mass of element's isotope @c index.
@param[in] index Index of element's isotope.
@return mass of element's isotope with a given index.
*/
mass_type getMass(size_type index = 0) const
{
return isotopes_.getMass(index);
}
/**
Gets element's average mass.
@return An average mass of element.
*/
mass_type getAverageMass() const
{
return isotopes_.getAverageMass();
}
/**
Gets ion mass of element. By default ion lacks 1 electron,
but this can be changed by setting other @c electrons_number.
@param[in] electrons_number Number of electrons lacking in ion.
*/
mass_type getIonMass(int electrons_number = 1) const
{
return this->getMass() - electrons_number * ELECTRON_MASS_IN_U;
}
/**
Gets element's isotope distribution.
@return Element's isotope distribution.
*/
const IMSIsotopeDistribution & getIsotopeDistribution() const
{
return isotopes_;
}
/**
Sets element's isotope distribution.
@param[in] isotopes A new isotope distribution to be set for element.
*/
void setIsotopeDistribution(const IMSIsotopeDistribution & isotopes)
{
this->isotopes_ = isotopes;
}
/**
Assignment operator.
@param[in] element Element to be assigned to this one.
@return Reference to this object.
*/
IMSElement & operator=(const IMSElement & element);
/**
Equality operator. Returns true, if a given @c element is equal
to this one, false - otherwise.
@return true, if a given element is equal to this one,
false - otherwise
*/
bool operator==(const IMSElement & element) const;
/**
Inequality operator. Returns true, if a given @c element is
unequal to this one, false - otherwise.
@return true, if a given element is unequal to this one,
false - otherwise.
*/
bool operator!=(const IMSElement & element) const;
/// Default destructor.
virtual ~IMSElement() {}
private:
/// Element's name.
name_type name_;
/// Element's sequence.
name_type sequence_;
/// Element's isotope distribution.
isotopes_type isotopes_;
};
/**
Prints element to the stream @c os.
@param[in,out] os Output stream to which element is printed out.
@param[in] element Element to be printed out.
*/
OPENMS_DLLAPI std::ostream & operator<<(std::ostream & os, const IMSElement & element);
} // namespace ims
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/MASSDECOMPOSITION/IMS/IMSIsotopeDistribution.h | .h | 9,610 | 313 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Anton Pervukhin <Anton.Pervukhin@CeBiTec.Uni-Bielefeld.DE> $
// --------------------------------------------------------------------------
//
#pragma once
#include <algorithm> // std::min
#include <vector>
#include <iosfwd>
#include <algorithm>
#include <OpenMS/config.h>
namespace OpenMS
{
namespace ims
{
/**
@brief Represents a distribution of isotopes restricted to the first K elements.
Represents a distribution of isotopes of chemical elements as a list
of peaks each as a pair of mass and abundance. @c IsotopeDistribution
unlike @c IsotopeSpecies has one abundance per a nominal mass.
Here is an example in the format (mass; abundance %)
for molecule H2O (values are taken randomly):
- IsotopeDistribution
(18.00221; 99.03 %)
(19.00334; 0.8 %)
(20.00476; 0.17 %)
- IsotopeSpecies
(18.00197; 98.012 %)
(18.00989; 1.018 %)
(19.00312; 0.683 %)
(19.00531; 0.117 %)
(20.00413; 0.134 %)
(20.00831; 0.036 %)
To the sake of faster computations distribution is restricted
to the first K elements, where K can be set by adjusting size
@c SIZE of distribution. @note For the elements most abundant in
living beings (CHNOPS) this restriction is negligible, since abundances
decrease dramatically in isotopes order and are usually of no interest
starting from +10 isotope.
@c IsotopeDistribution implements folding with other distribution using an
algorithm described in details in paper:
Boecker et al. "Decomposing metabolic isotope patterns" WABI 2006. doi: 10.1007/11851561_2
Folding with itself is done using Russian Multiplication Scheme.
@author Anton Pervukhin <Anton.Pervukhin@CeBiTec.Uni-Bielefeld.DE>
*/
class OPENMS_DLLAPI IMSIsotopeDistribution
{
public:
/// Type of isotope mass.
typedef double mass_type;
/// Type of isotope abundance.
typedef double abundance_type;
/// Type of isotope nominal mass.
typedef unsigned int nominal_mass_type;
/// @brief Structure that represents an isotope peak - pair of mass and abundance.
struct Peak
{
Peak(mass_type local_mass = 0.0, abundance_type local_abundance = 0.0) :
mass(local_mass), abundance(local_abundance)
{}
bool operator==(const Peak& peak) const = default;
mass_type mass;
abundance_type abundance;
};
/// Type of isotope peak.
typedef Peak peak_type;
/// Type of container to store peaks.
typedef std::vector<peak_type> peaks_container;
/// Type of iterator over container with peaks.
typedef peaks_container::iterator peaks_iterator;
/// Type of const iterator over container with peaks.
typedef peaks_container::const_iterator const_peaks_iterator;
/// Type of peaks container's size.
typedef peaks_container::size_type size_type;
/// Type of container with isotope masses.
typedef std::vector<mass_type> masses_container;
/// Type of iterator over container with isotope masses.
typedef masses_container::iterator masses_iterator;
/// Type of const iterator over container with isotope masses.
typedef masses_container::const_iterator const_masses_iterator;
/// Type of container with isotope abundances.
typedef std::vector<abundance_type> abundances_container;
/// Type of iterator over container with isotope abundances.
typedef abundances_container::iterator abundances_iterator;
/// Type of const iterator over container with isotope abundances.
typedef abundances_container::const_iterator const_abundances_iterator;
/// Error to be allowed for isotope distribution.
static abundance_type ABUNDANCES_SUM_ERROR;
/// Length of isotope distribution.
static size_type SIZE;
/// Constructor with nominal mass.
explicit IMSIsotopeDistribution(nominal_mass_type nominalMass = 0) :
nominal_mass_(nominalMass)
{}
/// Constructor with single isotope.
explicit IMSIsotopeDistribution(mass_type mass) :
nominal_mass_(0)
{
peaks_.push_back(peaks_container::value_type(mass, 1.0));
}
/// Constructor with isotopes and nominal mass.
IMSIsotopeDistribution(const peaks_container & peaks,
nominal_mass_type nominalMass = 0) :
peaks_(peaks),
nominal_mass_(nominalMass)
{}
/// Copy constructor.
IMSIsotopeDistribution(const IMSIsotopeDistribution & distribution) :
peaks_(distribution.peaks_),
nominal_mass_(distribution.nominal_mass_)
{}
/// Destructor.
~IMSIsotopeDistribution()
{}
/**
Gets size of isotope distribution. @note Size is not smaller than
predefined @c SIZE.
@return Size of isotope distribution.
*/
size_type size() const { return std::min(peaks_.size(), SIZE); }
/**
Assignment operator.
@param[in] distribution Isotope distribution to be assigned to this one.
@return Reference to this object.
*/
IMSIsotopeDistribution & operator=(
const IMSIsotopeDistribution & distribution);
/**
Equality operator. Returns true, if a given @c distribution is equal
to this one, false - otherwise.
@return true, if a given distribution is equal to this distribution,
false - otherwise
*/
bool operator==(const IMSIsotopeDistribution & distribution) const;
/**
Inequality operator. Returns true, if a given @c distribution is
unequal to this one, false - otherwise.
@return true, if a given distribution is unequal to this
distribution, false - otherwise
*/
bool operator!=(const IMSIsotopeDistribution & distribution) const;
/**
Operator for folding this distribution with a given @c distribution.
@note Operator is unary, so result is stored in this
object itself.
@param[in] distribution Distribution to be folded with this one.
@return Reference to this object.
@see IsotopeDistribution& operator *=(unsigned int)
*/
IMSIsotopeDistribution & operator*=(
const IMSIsotopeDistribution & distribution);
/**
Operator for folding this distribution with itself @c pow times.
@note Operator is unary, so result is stored in this object itself.
@param[in] pow Number of times this distribution is to be folded with
itself.
@return Reference to this object.
@see IsotopeDistribution& operator *=(const IsotopeDistribution&)
*/
IMSIsotopeDistribution & operator*=(unsigned int pow);
/**
Gets a mass of isotope @c i.
@param[in] i An index of isotope.
@return Mass of isotope @c i.
*/
mass_type getMass(size_type i) const
{
return peaks_[i].mass + nominal_mass_ + i;
}
/**
Gets an abundance of isotope @c i.
@param[in] i An index of isotope.
@return An abundance of isotope @c i.
*/
abundance_type getAbundance(size_type i) const
{
return peaks_[i].abundance;
}
/**
Gets an average mass of all isotopes.
@return An average mass of all isotopes.
*/
mass_type getAverageMass() const;
/**
Gets a nominal mass of distribution.
@return The nominal mass of the distribution.
*/
nominal_mass_type getNominalMass() const { return nominal_mass_; }
/**
Sets a nominal mass for distribution.
@param[in] nominalMass The new nominal mass for the distribution.
*/
void setNominalMass(nominal_mass_type nominalMass)
{
this->nominal_mass_ = nominalMass;
}
/**
Gets masses of isotopes.
@return Masses of isotopes.
*/
masses_container getMasses() const;
/**
Gets abundances of isotopes.
@return Abundances of isotopes.
*/
abundances_container getAbundances() const;
/**
Normalizes distribution,
i.e. scaling abundances to be summed up to 1 with an error
@c ABUNDANCES_SUM_ERROR allowed.
*/
void normalize();
/**
Returns true if the distribution has no peaks, false - otherwise.
@return True if the distribution has no peaks, false - otherwise.
*/
bool empty() const { return peaks_.empty(); }
private:
/// Container for isotopes.
peaks_container peaks_;
/// Nominal mass of distribution.
nominal_mass_type nominal_mass_;
/// Sets peaks/isotopes container minimum size.
void setMinimumSize_();
};
/**
Prints isotope distribution to the stream @c os.
@param[out] os Output stream to which distribution is printed out.
@param[in] distribution Distribution to be printed out.
*/
OPENMS_DLLAPI std::ostream & operator<<(std::ostream & os,
const IMSIsotopeDistribution & distribution);
} // namespace ims
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/MASSDECOMPOSITION/IMS/IMSAlphabet.h | .h | 9,959 | 316 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Anton Pervukhin <Anton.Pervukhin@CeBiTec.Uni-Bielefeld.DE> $
// --------------------------------------------------------------------------
//
#pragma once
#include <vector>
#include <string>
#include <iosfwd>
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/CHEMISTRY/MASSDECOMPOSITION/IMS/IMSElement.h>
#include <OpenMS/CHEMISTRY/MASSDECOMPOSITION/IMS/IMSAlphabetParser.h>
namespace OpenMS
{
namespace ims
{
/**
@brief Holds an indexed list of bio-chemical elements.
Presents an indexed list of bio-chemical elements of type (or derived from
type) @c Element. Due to indexed structure @c Alphabet can be used similar
to @c std::vector, for example to add a new element to @c Alphabet function
@c push_back(element_type) can be used. Elements or their properties (such
as element's mass) can be accessed by index in a constant time. On the other
hand accessing elements by their names takes linear time. Due to this and
also the fact that @c Alphabet is 'heavy-weighted' (consisting of
@c Element -s or their derivatives where the depth of derivation as well is
undefined resulting in possibly 'heavy' access operations) it is recommended
not use @c Alphabet directly in operations where fast access to
@c Element 's properties is required. Instead consider to use
'light-weighted' equivalents, such as @c Weights.
Elements in @c Alphabet can be sorted by the @c Element 's properties:
sequence and mass. When alphabet's data is loaded from file it is
automatically sorted by mass. To load data from file default function
@c load(str::string& fname) can be used. Then elements have to be stored
in a flat file @c fname in a predefined format. To read more on this format,
please, @see AlphabetParser. If one wants to load data stored differently or
in its own file format (i.e. xml) one has to define a new parser derived from
@c AlphabetParser and pass its pointer together with the file name to function
@c load(const std::string& fname, AlphabetParser<>* parser). If there is any
error happened while loading data, @c IOException will be thrown.
*
*/
class OPENMS_DLLAPI IMSAlphabet
{
public:
typedef IMSElement element_type;
typedef element_type::mass_type mass_type;
typedef element_type::name_type name_type;
typedef std::vector<element_type> container;
typedef container::size_type size_type;
typedef container::iterator iterator;
typedef container::const_iterator const_iterator;
typedef std::vector<name_type> name_container;
typedef name_container::iterator name_iterator;
typedef name_container::const_iterator const_name_iterator;
typedef std::vector<mass_type> mass_container;
typedef mass_container::iterator mass_iterator;
typedef mass_container::const_iterator const_mass_iterator;
typedef std::vector<mass_type> masses_type;
/**
Empty constructor.
*/
IMSAlphabet() {}
/**
Constructor with elements.
@param[in] elements Elements to be set
*/
explicit IMSAlphabet(const container & elements) :
elements_(elements)
{}
/**
Copy constructor.
@param[out] alphabet Alphabet to be assigned
*/
IMSAlphabet(const IMSAlphabet & alphabet) :
elements_(alphabet.elements_)
{}
/**
Returns the alphabet size.
@return The size of alphabet.
*/
size_type size() const
{
return elements_.size();
}
/**
Gets the element with index @c index.
@note Operation takes constant time.
@param[in] index of the element
@return Element with the given index in alphabet
*/
const element_type & getElement(size_type index) const
{
return elements_[index];
}
/**
Overwrites an element in the alphabet with the @c name with a new element constructed
from the given name @c name and mass @c mass.
If the parameter @c forced is set to true, a new element will be appended to the alphabet
in the case the alphabet contains no element with the name @c name.
@param[in] name The name of the element that should be replaced in (or appended to) the alphabet.
@param[in] mass The new mass of the element in the alphabet.
@param[in] forced Indicates whether a new element should be created (if set to @c true) if there is no element with the name @c name or not (if set to @c false).
*/
void setElement(const name_type & name, mass_type mass, bool forced = false);
/**
Removes the element with name @c name from the alphabet.
@param[in] name The name of the element to be removed from the alphabet.
@return A boolean indicating whether an element was removed (@c true) or not (@c false).
*/
bool erase(const name_type & name);
/**
Gets the element with the symbol @name. If there is
no such element, throws @c Exception::InvalidValue.
@param[in] name Name of the element.
@return Element with the given name, or if there are no such element
@throws Exception::InvalidValue.
*/
const element_type & getElement(const name_type & name) const;
/**
Gets the symbol of the element with an index @c index in alphabet.
@param[in] index of the element.
@return Name of the element.
*/
const name_type & getName(size_type index) const;
/**
Gets mono isotopic mass of the element with the symbol @c name.
If there is no such element, throws an @c Exception::InvalidValue.
@param[in] name Symbol of the element.
@return Mass of the element, or if there are no element
@throws Exception::InvalidValue.
@see getMass(size_type index)
*/
mass_type getMass(const name_type & name) const;
/**
Gets mass of the element with an index @c index in alphabet.
@param[in] index Index of the element.
@return Mass of the element.
@see getMass(const std::string& name)
*/
mass_type getMass(size_type index) const;
/**
Gets masses of elements isotopes given by @c isotope_index.
@param[in] isotope_index Index of isotope
@return Masses of elements isotopes with the given index.
*/
masses_type getMasses(size_type isotope_index = 0) const;
/**
Gets average masses of elements.
@return Average masses of elements.
*/
masses_type getAverageMasses() const;
/**
Returns true if there is an element with symbol
@c name in the alphabet, false - otherwise.
@return True, if there is an element with symbol
@c name, false - otherwise.
*/
bool hasName(const name_type & name) const;
/**
Adds a new element with name @c name and mass @c value
to the alphabet.
@param[in] name Name of the element to be added.
@param[in] value Mass of the element to be added.
@see push_back(const element_type&)
*/
void push_back(const name_type & name, mass_type value)
{
push_back(element_type(name, value));
}
/**
Adds a new element @c element to the alphabet.
@param[in] element The @c Element to be added.
*/
void push_back(const element_type & element)
{
elements_.push_back(element);
}
/**
Clears the alphabet data.
*/
void clear()
{
elements_.clear();
}
/**
Sorts the alphabet by names.
@see sortByValues()
*/
virtual void sortByNames();
/**
Sorts the alphabet by mass values.
@see sortByNames()
*/
virtual void sortByValues();
/**
Loads the alphabet data from the file @c fname using the default
parser. If there is no file @c fname, throws an @c IOException.
@param[in] fname The file name to be loaded.
@throws Exception::IOException
@see load(const std::string& fname, AlphabetParser<>* parser)
*/
virtual void load(const std::string & fname);
/**
Loads the alphabet data from the file @c fname using @c parser.
If there is no file @c fname found, throws an @c IOException.
@param[in] fname File name to be loaded.
@param[in] parser Parser to be used by loading.
@throws Exception::IOException
@see load(const std::string& fname)
@see AlphabetParser
*/
virtual void load(const std::string & fname, IMSAlphabetParser<> & parser);
/**
Default destructor.
*/
virtual ~IMSAlphabet() {}
private:
/**
Elements of the alphabet.
*/
container elements_;
/**
@brief Private class-functor to sort out elements in mass ascending order.
*/
class OPENMS_DLLAPI MassSortingCriteria_
{
public:
bool operator()(const element_type & el1,
const element_type & el2) const
{
return el1.getMass() < el2.getMass();
}
};
};
/**
Prints alphabet to the stream @c os.
@param[out] os Output stream to which alphabet is written
@param[in] alphabet Alphabet to be written.
*/
OPENMS_DLLAPI std::ostream & operator<<(std::ostream & os, const IMSAlphabet & alphabet);
} // namespace ims
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/MASSDECOMPOSITION/IMS/MassDecomposer.h | .h | 3,333 | 107 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Anton Pervukhin <Anton.Pervukhin@CeBiTec.Uni-Bielefeld.DE> $
// --------------------------------------------------------------------------
//
#pragma once
#include <vector>
namespace OpenMS
{
namespace ims
{
/**
@brief An interface to handle decomposing of integer values/masses
over a set of integer weights (alphabet).
An interface that addresses the following "mass decomposition" problems:
- Existence Problem (whether the decomposition of the given mass exists),
- One Decomposition Problem (returns one possible decomposition),
- All Decompositions Problem (returns all possible decompositions),
- Number of Decompositions Problem (returns the number of possible
decompositions).
Those problems are solved in integer arithmetic, i.e. only exact
solutions are found with no error allowed.
@param[in] ValueType Type of values to be decomposed.
@param[in] DecompositionValueType Type of decomposition elements.
@author Anton Pervukhin <Anton.Pervukhin@CeBiTec.Uni-Bielefeld.DE>
*/
template <typename ValueType,
typename DecompositionValueType>
class MassDecomposer
{
public:
/**
Type of value to be decomposed.
*/
typedef ValueType value_type;
/**
Type of decomposition value.
*/
typedef DecompositionValueType decomposition_value_type;
/**
Type of decomposition container.
*/
typedef std::vector<decomposition_value_type> decomposition_type;
/**
Type of container for many decompositions.
*/
typedef std::vector<decomposition_type> decompositions_type;
/**
A virtual destructor.
*/
virtual ~MassDecomposer(){}
/**
Returns true if the decomposition for the given @c mass exists, otherwise - false.
@param[in] mass Mass to be checked on decomposing.
@return true, if the decomposition for @c mass exist, otherwise - false.
*/
virtual bool exist(value_type mass) = 0;
/**
Returns one possible decomposition of the given @c mass.
@param[in] mass Mass to be decomposed.
@return The decomposition of the @c mass, if one exists, otherwise - an empty container.
*/
virtual decomposition_type getDecomposition(value_type mass) = 0;
/**
Returns all possible decompositions for the given @c mass.
@param[in] mass Mass to be decomposed.
@return All possible decompositions of the @c mass, if there are any exist,
otherwise - an empty container.
*/
virtual decompositions_type getAllDecompositions(value_type mass) = 0;
/**
Returns the number of possible decompositions for the given @c mass.
*
@param[in] mass Mass to be decomposed.
@return The number of possible decompositions for the @c mass.
*/
virtual decomposition_value_type getNumberOfDecompositions(value_type mass) = 0;
};
} // namespace ims
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/MASSDECOMPOSITION/IMS/IntegerMassDecomposer.h | .h | 19,377 | 532 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Anton Pervukhin <Anton.Pervukhin@CeBiTec.Uni-Bielefeld.DE> $
// --------------------------------------------------------------------------
//
#pragma once
#include <vector>
#include <utility>
#include <OpenMS/CHEMISTRY/MASSDECOMPOSITION/IMS/Weights.h>
#include <OpenMS/CHEMISTRY/MASSDECOMPOSITION/IMS/MassDecomposer.h>
#include <OpenMS/MATH/MathFunctions.h>
namespace OpenMS
{
namespace ims
{
/**
@brief Implements @c MassDecomposer interface using algorithm and data
structures described in paper "Efficient Mass Decomposition"
S. Böcker, Z. Lipták, ACM SAC-BIO, 2004 doi:10.1145/1066677.1066715.
The main idea is instead of using the classical dynamic programming
algorithm, store the residues of the smallest decomposable numbers
for every modulo of the smallest alphabet mass.
@tparam ValueType Type of values to be decomposed.
@tparam DecompositionValueType Type of decomposition elements.
@author Anton Pervukhin <Anton.Pervukhin@CeBiTec.Uni-Bielefeld.DE>
@author Marcel Martin <Marcel.Martin@CeBiTec.Uni-Bielefeld.DE>
@author Henner Sudek <Henner.Sudek@CeBiTec.Uni-Bielefeld.DE>
*/
template <typename ValueType = long unsigned int,
typename DecompositionValueType = unsigned int>
class IntegerMassDecomposer :
public MassDecomposer<ValueType, DecompositionValueType>
{
public:
/// Type of value to be decomposed.
typedef typename MassDecomposer<ValueType, DecompositionValueType>::value_type value_type;
/// Type of decomposition value.
typedef typename MassDecomposer<ValueType, DecompositionValueType>::decomposition_value_type decomposition_value_type;
/// Type of decomposition.
typedef typename MassDecomposer<ValueType, DecompositionValueType>::decomposition_type decomposition_type;
/// Type of container for many decompositions.
typedef typename MassDecomposer<ValueType, DecompositionValueType>::decompositions_type decompositions_type;
/// Type of decomposition's size.
typedef typename decomposition_type::size_type size_type;
/**
Constructor with weights.
@param[in] alphabet Weights over which masses to be decomposed.
*/
explicit IntegerMassDecomposer(const Weights & alphabet);
/**
Returns true if decomposition over the @c mass exists, otherwise - false.
@param[in] mass Mass to be decomposed.
@return true if decomposition over a given mass exists, otherwise - false.
*/
bool exist(value_type mass) override;
/**
Gets one possible decomposition for @c mass.
@param[in] mass Mass to be decomposed.
@return One possible decomposition for a given mass.
*/
decomposition_type getDecomposition(value_type mass) override;
/**
Gets all possible decompositions for @c mass.
@param[in] mass Mass to be decomposed.
@return All possible decompositions for a given mass.
*/
decompositions_type getAllDecompositions(value_type mass) override;
/**
Gets number of all possible decompositions for a given @p mass.
Since using getAllDecomposition() the usage of this function could
be @b consuming.
@param[in] mass Mass to be decomposed
@return number of decompositions for a given mass.
*/
decomposition_value_type getNumberOfDecompositions(value_type mass) override;
private:
/**
Type of witness vector.
*/
typedef std::vector<std::pair<size_type, decomposition_value_type> > witness_vector_type;
/**
Type of rows of residues table.
*/
typedef std::vector<value_type> residues_table_row_type;
/**
Type of the residues table.
*/
typedef std::vector<residues_table_row_type> residues_table_type;
/**
Weights over which the mass is to be decomposed.
*/
Weights alphabet_;
/**
Table with the residues of the smallest decomposable numbers over
every modulo of the smallest alphabet mass are stored.
Corresponds to the Extended Residue Table in the paper.
*/
residues_table_type ertable_;
/**
List of the least common multiples. Corresponds to the lcm data structure
in the paper.
*/
residues_table_row_type lcms_;
/**
List of the counters for the least common multiples that store the number
how often the smallest alphabet mass fits into the corresponding least
common multiple(lcm).
*/
residues_table_row_type mass_in_lcms_;
/**
Represents an infinite value.
*/
value_type infty_;
/**
List of the witnesses that is used to find one mass decomposition.
Corresponds to the witness vector w in the paper.
*/
witness_vector_type witness_vector_;
/**
Fills the extended residues table.
*/
void fillExtendedResidueTable_(const Weights & _alphabet, residues_table_row_type & _lcms,
residues_table_row_type & _mass_in_lcms, const value_type _infty,
witness_vector_type & _witness_vector, residues_table_type & _ertable);
/**
Collects decompositions for @c mass by recursion.
@param[in] mass Mass to be decomposed.
@param[in] alphabetMassIndex An index of the mass in alphabet that is used on this step of recursion.
@param[in] decomposition Decomposition which is calculated on this step of recursion.
@param[in] decompositionsStore Container where decompositions are collected.
*/
void collectDecompositionsRecursively_(value_type mass, size_type alphabetMassIndex,
decomposition_type decomposition, decompositions_type & decompositionsStore);
};
template <typename ValueType, typename DecompositionValueType>
IntegerMassDecomposer<ValueType, DecompositionValueType>::IntegerMassDecomposer(
const Weights & alphabet) :
alphabet_(alphabet)
{
lcms_.resize(alphabet.size());
mass_in_lcms_.resize(alphabet.size());
infty_ = alphabet.getWeight(0) * alphabet.getWeight(alphabet.size() - 1);
fillExtendedResidueTable_(alphabet, lcms_, mass_in_lcms_, infty_, witness_vector_, ertable_);
}
template <typename ValueType, typename DecompositionValueType>
void IntegerMassDecomposer<ValueType, DecompositionValueType>::fillExtendedResidueTable_(
const Weights & _alphabet, residues_table_row_type & _lcms, residues_table_row_type & _mass_in_lcms,
const value_type _infty, witness_vector_type & _witnessVector, residues_table_type & _ertable)
{
if (_alphabet.size() < 2)
{
return;
}
// caches the most often used mass - smallest mass
value_type smallestMass = _alphabet.getWeight(0), secondMass = _alphabet.getWeight(1);
// initializes table: infinity everywhere except in the first field of every column
_ertable.reserve(_alphabet.size());
_ertable.assign(_alphabet.size(), std::vector<value_type>(smallestMass, _infty));
for (size_type i = 0; i < _alphabet.size(); ++i)
{
_ertable[i][0] = 0;
}
// initializes witness vector
_witnessVector.resize(smallestMass);
// fills second column (the first one is already correct)
size_type it_inc = secondMass % smallestMass, witness = 1;
//typename residues_table_row_type::iterator it = _ertable[1].begin() + it_inc;
value_type mass = secondMass;
// initializes counter to create a witness vector
decomposition_value_type counter = 0;
size_type it_i = it_inc;
while (it_i != 0)
{
_ertable[1][it_i] = mass;
mass += secondMass;
++counter;
_witnessVector[it_i] = std::make_pair(witness, counter);
//std::cerr << "BLA: " << counter << " " << &_ertable[1][0] << " " << it - _ertable[1].begin() << " " << _ertable[1].size() << std::endl;
it_i += it_inc;
if (it_i >= _ertable[1].size())
{
it_i -= _ertable[1].size();
}
}
// fills cache variables for i==1
value_type tmp_d = Math::gcd(smallestMass, secondMass);
_lcms[1] = secondMass * smallestMass / tmp_d;
_mass_in_lcms[1] = smallestMass / tmp_d;
// fills remaining table. i is the column index.
for (size_type i = 2; i < _alphabet.size(); ++i)
{
// caches often used i-th alphabet mass
value_type currentMass = _alphabet.getWeight(i);
value_type d = Math::gcd(smallestMass, currentMass);
// fills cache for various variables.
// note that values for i==0 are never assigned since they're unused anyway.
_lcms[i] = currentMass * smallestMass / d;
_mass_in_lcms[i] = smallestMass / d;
// Nijenhuis' improvement: Is currentMass composable with smaller alphabet?
if (currentMass >= _ertable[i - 1][currentMass % smallestMass])
{
_ertable[i] = _ertable[i - 1];
continue;
}
const residues_table_row_type & prev_column = _ertable[i - 1];
residues_table_row_type & cur_column = _ertable[i];
if (d == 1)
{
// This loop is for the case that the gcd is 1. The optimization used below
// is not applicable here.
// p_inc is used to change residue (p) efficiently
size_type p_inc = currentMass % smallestMass;
// n is the value that will be written into the table
value_type n = 0;
// current residue (in paper variable 'r' is used)
size_type p = 0;
// counter for creation of witness vector
decomposition_value_type local_counter = 0;
for (size_type m = smallestMass; m > 0; --m)
{
n += currentMass;
p += p_inc;
++local_counter;
if (p >= smallestMass)
{
p -= smallestMass;
}
if (n > prev_column[p])
{
n = prev_column[p];
local_counter = 0;
}
else
{
_witnessVector[p] = std::make_pair(i, local_counter);
}
cur_column[p] = n;
}
}
else
{
// If we're here, the gcd is not 1. We can use the following cache-optimized
// version of the algorithm. The trick is to put the iteration over all
// residue classes into the _inner_ loop.
//
// One could see it as going through one column in blocks which are gcd entries long.
size_type cur = currentMass % smallestMass;
size_type prev = 0;
size_type p_inc = cur - d;
// counters for creation of one witness vector
std::vector<decomposition_value_type> counters(smallestMass);
// copies first block from prev_column to cur_column
for (size_type j = 1; j < d; ++j)
{
cur_column[j] = prev_column[j];
}
// first loop: goes through all blocks, updating cur_column for the first time.
for (size_type m = smallestMass / d; m > 1; m--)
{
// r: current residue class
for (size_type r = 0; r < d; r++)
{
++counters[cur];
if (cur_column[prev] + currentMass > prev_column[cur])
{
cur_column[cur] = prev_column[cur];
counters[cur] = 0;
}
else
{
cur_column[cur] = cur_column[prev] + currentMass;
_witnessVector[cur] = std::make_pair(i, counters[cur]);
}
prev++;
cur++;
}
prev = cur - d;
// this does: cur = (cur + currentMass) % smallestMass - d;
cur += p_inc;
if (cur >= smallestMass)
{
cur -= smallestMass;
}
}
// second loop:
bool cont = true;
while (cont)
{
cont = false;
prev++;
cur++;
++counters[cur];
for (size_type r = 1; r < d; ++r)
{
if (cur_column[prev] + currentMass < cur_column[cur])
{
cur_column[cur] = cur_column[prev] + currentMass;
cont = true;
_witnessVector[cur] = std::make_pair(i, counters[cur]);
}
else
{
counters[cur] = 0;
}
prev++;
cur++;
}
prev = cur - d;
cur += p_inc;
if (cur >= smallestMass)
{
cur -= smallestMass;
}
}
}
}
}
template <typename ValueType, typename DecompositionValueType>
bool IntegerMassDecomposer<ValueType, DecompositionValueType>::
exist(value_type mass)
{
value_type residue = ertable_.back().at(mass % alphabet_.getWeight(0));
return residue != infty_ && mass >= residue;
}
template <typename ValueType, typename DecompositionValueType>
typename IntegerMassDecomposer<ValueType, DecompositionValueType>::decomposition_type
IntegerMassDecomposer<ValueType, DecompositionValueType>::getDecomposition(value_type mass)
{
decomposition_type decomposition;
if (!this->exist(mass))
{
return decomposition;
}
decomposition.reserve(alphabet_.size());
decomposition.resize(alphabet_.size());
// initial mass residue: in FIND-ONE algorithm in paper corresponds variable "r"
value_type r = mass % alphabet_.getWeight(0);
value_type m = ertable_.back().at(r);
decomposition.at(0) = static_cast<decomposition_value_type>
((mass - m) / alphabet_.getWeight(0));
while (m != 0)
{
size_type i = witness_vector_.at(r).first;
decomposition_value_type j = witness_vector_.at(r).second;
decomposition.at(i) += j;
if (m < j * alphabet_.getWeight(i))
{
break;
}
m -= j * alphabet_.getWeight(i);
r = m % alphabet_.getWeight(0);
}
return decomposition;
}
template <typename ValueType, typename DecompositionValueType>
typename IntegerMassDecomposer<ValueType, DecompositionValueType>::decompositions_type
IntegerMassDecomposer<ValueType, DecompositionValueType>::getAllDecompositions(value_type mass)
{
decompositions_type decompositionsStore;
decomposition_type decomposition(alphabet_.size());
collectDecompositionsRecursively_(mass, alphabet_.size() - 1, decomposition, decompositionsStore);
return decompositionsStore;
}
template <typename ValueType, typename DecompositionValueType>
void IntegerMassDecomposer<ValueType, DecompositionValueType>::
collectDecompositionsRecursively_(value_type mass, size_type alphabetMassIndex,
decomposition_type decomposition, decompositions_type & decompositionsStore)
{
if (alphabetMassIndex == 0)
{
value_type numberOfMasses0 = mass / alphabet_.getWeight(0);
if (numberOfMasses0 * alphabet_.getWeight(0) == mass)
{
decomposition[0] = static_cast<decomposition_value_type>(numberOfMasses0);
decompositionsStore.push_back(decomposition);
}
return;
}
// tested: caching these values gives us 15% better performance, at least
// with aminoacid-mono.masses
const value_type lcm = lcms_[alphabetMassIndex];
const value_type mass_in_lcm = mass_in_lcms_[alphabetMassIndex]; // this is alphabet mass divided by gcd
value_type mass_mod_alphabet0 = mass % alphabet_.getWeight(0); // trying to avoid modulo
const value_type mass_mod_decrement = alphabet_.getWeight(alphabetMassIndex) % alphabet_.getWeight(0);
for (value_type i = 0; i < mass_in_lcm; ++i)
{
// here is the conversion from value_type to decomposition_value_type
decomposition[alphabetMassIndex] = static_cast<decomposition_value_type>(i);
// this check is needed because mass could have unsigned type and after reduction on i*alphabetMass will be still be positive but huge
// and that will end up in infinite loop
if (mass < i * alphabet_.getWeight(alphabetMassIndex))
{
break;
}
// r: current residue class. will stay the same in the following loop
value_type r = ertable_[alphabetMassIndex - 1][mass_mod_alphabet0];
// TODO: if infty was std::numeric_limits<...>... the following 'if' would not be necessary
if (r != infty_)
{
for (value_type m = mass - i * alphabet_.getWeight(alphabetMassIndex); m >= r; m -= lcm)
{
// the condition of the 'for' loop (m >= r) and decrementing the mass
// in steps of the lcm ensures that m is decomposable. Therefore
// the recursion will result in at least one witness.
collectDecompositionsRecursively_(m, alphabetMassIndex - 1, decomposition, decompositionsStore);
decomposition[alphabetMassIndex] += mass_in_lcm;
// this check is needed because mass could have unsigned type and after reduction on i*alphabetMass will be still be positive but huge
// and that will end up in infinite loop
if (m < lcm)
{
break;
}
}
}
// subtle way of changing the modulo, instead of plain calculation it from (mass - i*currentAlphabetMass) % alphabetMass0 every time
if (mass_mod_alphabet0 < mass_mod_decrement)
{
mass_mod_alphabet0 += alphabet_.getWeight(0) - mass_mod_decrement;
}
else
{
mass_mod_alphabet0 -= mass_mod_decrement;
}
}
}
/**
Gets number of all possible decompositions for a given @p mass.
Since using getAllDecomposition() the usage of this function could
be @b consuming.
Needs the @p mass to be decomposed and returns the number of decompositions for that mass.
*/
template <typename ValueType, typename DecompositionValueType>
typename IntegerMassDecomposer<ValueType, DecompositionValueType>::decomposition_value_type IntegerMassDecomposer<ValueType,
DecompositionValueType>::getNumberOfDecompositions(value_type mass)
{
return static_cast<typename IntegerMassDecomposer<ValueType, DecompositionValueType>::decomposition_value_type>(getAllDecompositions(mass).size());
}
} // namespace ims
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/MASSDECOMPOSITION/IMS/IMSAlphabetParser.h | .h | 2,380 | 86 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Anton Pervukhin <Anton.Pervukhin@CeBiTec.Uni-Bielefeld.DE> $
// --------------------------------------------------------------------------
//
#pragma once
#include <fstream>
#include <istream>
#include <map>
#include <string>
#include <OpenMS/CONCEPT/Exception.h>
namespace OpenMS
{
namespace ims
{
/**
@brief An abstract templatized parser to load the data that is used to initialize @c Alphabet objects.
@c AlphabetParser reads the input source, which is given as a template parameter @c InputSource , by
@c load (const std::string& fname) function where @c fname is the source name.
Loaded data can be retrieved by calling @c getElements().
@see Alphabet
*/
template <typename AlphabetElementType = double,
typename Container = std::map<std::string, AlphabetElementType>,
typename InputSource = std::istream>
class IMSAlphabetParser
{
public:
/**
Type of data to be loaded.
*/
typedef Container ContainerType;
/**
Loads the data from the InputSource with the name @c fname.
If there is an error occurred while reading data from InputSource,
@c IOException is thrown.
@param[in] fname The name of the input source.
*/
void load(const std::string & fname);
/**
Gets the data that was loaded.
@return The data.
*/
virtual ContainerType & getElements() = 0;
/**
Parses the the given input source @c is .
@param[in] is The InputSource
*/
virtual void parse(InputSource & is) = 0;
/// Destructor
virtual ~IMSAlphabetParser() {}
};
template <typename AlphabetElementType, typename Container, typename InputSource>
void IMSAlphabetParser<AlphabetElementType, Container, InputSource>::load(const std::string & fname)
{
std::ifstream ifs(fname.c_str());
if (!ifs)
{
throw Exception::IOException(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, fname);
}
this->parse(ifs);
}
} // namespace ims
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/MASSDECOMPOSITION/IMS/IMSAlphabetTextParser.h | .h | 1,363 | 53 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Anton Pervukhin <Anton.Pervukhin@CeBiTec.Uni-Bielefeld.DE> $
// --------------------------------------------------------------------------
//
#pragma once
#include <OpenMS/CHEMISTRY/MASSDECOMPOSITION/IMS/IMSAlphabetParser.h>
namespace OpenMS
{
namespace ims
{
/**
@brief Implements abstract @c AlphabetParser to read data from the plain text format.
@c AlphabetTextParser parses the data source using overridden @c parse(std::istream&)
and stores the parsed data permanently. That can be retrieved by @c getElements() function.
*/
class OPENMS_DLLAPI IMSAlphabetTextParser :
public IMSAlphabetParser<>
{
private:
/**
The parsed data.
*/
ContainerType elements_;
public:
/**
Gets the parsed data.
@return The parsed data.
*/
ContainerType & getElements() override { return elements_; }
/**
Parses the input stream @c is.
@param[in] is The input stream to be parsed
*/
void parse(std::istream & is) override;
};
} // namespace ims
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/ISOTOPEDISTRIBUTION/IsoSpecWrapper.h | .h | 21,823 | 484 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hannes Rost $
// $Authors: Hannes Rost, Michał Startek, Mateusz Łącki $
// --------------------------------------------------------------------------
#pragma once
#include <vector>
#include <memory>
#include <OpenMS/CONCEPT/Types.h>
#include <OpenMS/CONCEPT/Constants.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/KERNEL/Peak1D.h>
#include <OpenMS/CHEMISTRY/EmpiricalFormula.h>
#include <OpenMS/CHEMISTRY/ISOTOPEDISTRIBUTION/IsotopeDistribution.h>
// forward declarations
namespace IsoSpec
{
class IsoLayeredGenerator;
class IsoThresholdGenerator;
class IsoOrderedGenerator;
}
namespace OpenMS
{
/**
* @brief Interface for the IsoSpec algorithm - a generator of infinitely-resolved theoretical spectra.
*
* Provides an interface to the IsoSpec algorithm. See IsoSpecWrapper and
* FineIsotopePatternGenerator for a more convenient wrapper. Implements a
* generator pattern using the nextConf function, which can be used to
* iterate through all configurations:
*
* @code
* IsoSpecGeneratorWrapperSubclass iso(...);
*
* while(iso.nextConf())
* {
* Peak1D conf = iso.getConf(); // and/or getMass, getIntensity, etc.
* // do some computations on that conf;
* }
* @endcode
*
*
* The computation is based on the IsoSpec algorithm
*
* @code
* Łącki MK, Startek M, Valkenborg D, Gambin A.
* IsoSpec: Hyperfast Fine Structure Calculator.
* Anal Chem. 2017 Mar 21;89(6):3272-3277. doi: 10.1021/acs.analchem.6b01459.
* @endcode
*
**/
class OPENMS_DLLAPI IsoSpecGeneratorWrapper
{
public:
/**
* @brief Move the generator to a next isotopologue
*
* Advance the internal generator to the next isotopologue. The value returned determines whether the
* generator has been exhausted (that is, all eligible configurations have already been visited).
* It is invalid to call any other generator methods before the first call to nextConf(), as well as
* after this method returns false.
*
* @returns A boolean value stating whether the generator has been exhausted.
*/
virtual bool nextConf() = 0;
/**
* @brief Obtain the current isotopologue
*
* @return The current isotopologue as a Peak1D
*
* @note It is invalid (undefined results) to call this method before the first call to nextConf(), or after it returns false
*/
virtual Peak1D getConf() = 0;
/**
* @brief Obtain the mass of the current isotopologue
*
* @return The mass of the current isotopologue
*
* @note It is invalid (undefined results) to call this method before the first call to nextConf(), or after it returns false
*/
virtual double getMass() = 0;
/**
* @brief Obtain the intensity (probability, relative peak height) of the current configuration
*
* @return The intensity (probability) of the current isotopologue
*
* @note It is invalid (undefined results) to call this method before the first call to nextConf(), or after it returns false
*/
virtual double getIntensity() = 0;
/**
* @brief Obtain the natural logarithm of the intensity (probability, relative peak height) of the current configuration
*
* This will be more precise (and faster) than just calling std::log(getIntensity()) - it will produce correct results even
* for configurations so unlikely that the double-precision floating point number returned from getIntensity() underflows to zero.
*
* @return The natural logarithm of intensity (probability) of the current isotopologue
*
* @note It is invalid (undefined results) to call this method before the first call to nextConf(), or after it returns false
*/
virtual double getLogIntensity() = 0;
/**
* @brief Destructor
*/
virtual ~IsoSpecGeneratorWrapper() = default;
};
/** @brief A convenience class for the IsoSpec algorithm - easier to use than the IsoSpecGeneratorWrapper classes.
*
* See FineIsotopePatternGenerator for a more convenient (but potentially
* slower) wrapper when using the algorithm in OpenMS.
*/
class OPENMS_DLLAPI IsoSpecWrapper
{
public:
/**
* @brief Run the algorithm
*
* This method will run the algorithm with parameters as set up by the constructor. It will return an
* IsotopeDistribution containing the observed configurations. The configurations are explicitly stored
* in memory, which may become a problem when considering some especially large distributions. If this,
* or (a rather small) performance overhead is a concern, then the
* generator methods (see IsoSpecGeneratorWrapper) should be used instead.
*
* This method is provided for convenience. As calling that method invalidates the object (the method should
* not be called again, nor anything other than destroying the object should be done with it), the most common
* usage pattern of IsoSpecGeneratorWrapper classes with the run method is:
*
* @code
* IsotopeDistribution dist = IsoSpecGeneratorWrapperSubclass(...).run();
* // do something with dist;
* @endcode
*
* @note Calling this method invalidates the object! In future versions this limitation might be removed.
*
**/
virtual IsotopeDistribution run() = 0;
virtual inline ~IsoSpecWrapper() = default;
};
//--------------------------------------------------------------------------
// IsoSpecGeneratorWrapper classes
//--------------------------------------------------------------------------
/**
* @brief Generate a p-set of configurations for a given p (that is, a set of configurations such that
* their probabilities sum up to p). The p in normal usage will usually be close to 1 (e.g. 0.99).
*
* An optimal p-set of isotopologues is the smallest set of isotopologues that, taken together, cover at
* least p of the probability space (that is, their probabilities sum up to at least p). This means that
* the computed spectrum is accurate to at least degree p, and that the L1 distance between the computed
* spectrum and the true spectrum is less than 1-p. The optimality of the p-set means that it contains
* the most probable configurations - any isotopologues outside of the returned p-set have lower intensity
* than the configurations in the p-set.
*
* This is the method most users will want: the p parameter directly controls the accuracy of results.
*
* Advanced usage note: The algorithm works by computing an optimal p'-set for a p' slightly larger than
* the requested p. By default these extra isotopologues are returned too (as they have to be computed
* anyway). It is possible to request them to be discarded, but not in the generator class - one should
* use IsoSpecTotalProbWrapper instead, at a greater computational and memory cost.
*
* The p is used as a hint for the algorithm - configurations will be returned in such an order that
* once the total accumulated probability crosses p, the returned set will be close to optimal.
* If exactly the optimal set is required, one should use (again, at an increased cost) the
* IsoSpecTotalProbWrapper class. The generator will still go over the entire configuration space
* if the user keeps requesting more configurations after crossing p.
*
* @note The eligible configurations are NOT guaranteed to be returned in any particular order.
*/
class OPENMS_DLLAPI IsoSpecTotalProbGeneratorWrapper : public IsoSpecGeneratorWrapper
{
public:
/**
* @brief Constructor
*
* @param[in] isotopeNumbers A vector of how many isotopes each element has, e.g. [2, 2, 3])
* @param[in] atomCounts How many atoms of each we have [e.g. 12, 6, 6 for Glucose]
* @param[in] isotopeMasses Array with the individual elements isotopic masses
* @param[in] isotopeProbabilities Array with the individual elements isotopic probabilities
* @param[in] p Total coverage of probability space desired, usually close to 1 (e.g. 0.99)
*
* @note This constructor is only useful if you need to define non-standard abundances
* of isotopes, for other uses the one accepting EmpiricalFormula is easier to use.
*
**/
IsoSpecTotalProbGeneratorWrapper(const std::vector<int>& isotopeNumbers,
const std::vector<int>& atomCounts,
const std::vector<std::vector<double> >& isotopeMasses,
const std::vector<std::vector<double> >& isotopeProbabilities,
double p);
/// delete copy constructor
IsoSpecTotalProbGeneratorWrapper(const IsoSpecTotalProbGeneratorWrapper&) = delete;
/**
* @brief Setup the algorithm to run on an EmpiricalFormula
*
**/
IsoSpecTotalProbGeneratorWrapper(const EmpiricalFormula& formula, double p);
~IsoSpecTotalProbGeneratorWrapper();
bool nextConf() final;
Peak1D getConf() final;
double getMass() final;
double getIntensity() final;
double getLogIntensity() final;
protected:
std::unique_ptr<IsoSpec::IsoLayeredGenerator> ILG;
};
/**
* @brief Provides a threshold-based generator of isotopologues: generates all isotopologues
* more probable than a given probability threshold.
*
* This is the simplest generator - most users will however want to use IsoSpecTotalProbGeneratorWrapper.
* The reason for it is that when thresholding by peak intensity one has no idea how far the obtained
* spectrum is from a real spectrum. For example, consider human insulin: if the threshold is set at
* 0.1 of the most intense peak, then the peaks above the threshold account for 99.7% of total probability
* for water, 82% for substance P, only 60% for human insulin, and 23% for titin.
* For a threshold of 0.01, the numbers will be: still 99.7% for water, 96% for substance P, 88% for human insulin
* and 72% for titin (it also took 5 minutes on an average notebook computer to process the 17 billion configurations
* involved).
*
* As you can see the threshold does not have a straightforward correlation to the accuracy of the final spectrum
* obtained - and accuracy of final spectrum is often what the user is interested in. The IsoSpecTotalProbGeneratorWrapper
* provides a way to directly parameterize based on the desired accuracy of the final spectrum - and should be used
* instead in most cases. The trade-off is that it's (slightly, though much less than it used to be) slower than
* Threshold algorithm.
*
* @note The eligible isotopologues are NOT guaranteed to be generated in any particular order.
*/
class OPENMS_DLLAPI IsoSpecThresholdGeneratorWrapper : public IsoSpecGeneratorWrapper
{
public:
/**
* @brief Constructor
*
* @param[in] isotopeNumbers A vector of how many isotopes each element has, e.g. [2, 2, 3])
* @param[in] atomCounts How many atoms of each we have [e.g. 12, 6, 6 for Glucose]
* @param[in] isotopeMasses Array with the individual elements isotopic masses
* @param[in] isotopeProbabilities Array with the individual elements isotopic probabilities
* @param[in] threshold Intensity threshold: will only compute peaks above this threshold
* @param[in] absolute Whether the threshold is absolute or relative (relative to the most intense peak)
*
* @note This constructor is only useful if you need to define non-standard abundances
* of isotopes, for other uses the one accepting EmpiricalFormula is easier to use.
*
**/
IsoSpecThresholdGeneratorWrapper(const std::vector<int>& isotopeNumbers,
const std::vector<int>& atomCounts,
const std::vector<std::vector<double> >& isotopeMasses,
const std::vector<std::vector<double> >& isotopeProbabilities,
double threshold,
bool absolute);
// delete copy constructor
IsoSpecThresholdGeneratorWrapper(const IsoSpecThresholdGeneratorWrapper&) = delete;
/**
* @brief Setup the algorithm to run on an EmpiricalFormula
*
**/
IsoSpecThresholdGeneratorWrapper(const EmpiricalFormula& formula, double threshold, bool absolute);
~IsoSpecThresholdGeneratorWrapper();
bool nextConf() final;
Peak1D getConf() final;
double getMass() final;
double getIntensity() final;
double getLogIntensity() final;
protected:
std::unique_ptr<IsoSpec::IsoThresholdGenerator> ITG;
};
/**
* @brief Generate the stream of configurations, ordered from most likely to least likely.
*
* This generator walks through the entire set of isotopologues of a given molecule, allowing
* the user to terminate the search on the fly. The returned isotopologues are guaranteed to
* be generated in order of descending probability (unlike
* IsoSpecThresholdGeneratorWrapper and IsoSpecTotalProbGeneratorWrapper
* which make no such guarantees).
*
* This causes the algorithm to run in \c O(n*log(n)) and means that is it much slower than the
* previous two classes IsoSpecThresholdGeneratorWrapper and IsoSpecTotalProbGeneratorWrapper.
*
* You should only use this generator if you don't know up-front when to stop the walk through
* the configuration space, and need to make the decision on the fly. If you know the threshold
* or the total probability needed, and only need the configurations sorted, it will be much
* faster to generate them using one of the previous algorithms and sort them afterwards.
*/
class OPENMS_DLLAPI IsoSpecOrderedGeneratorWrapper : public IsoSpecGeneratorWrapper
{
public:
/**
* @brief Constructor
*
* @param[in] isotopeNumbers A vector of how many isotopes each element has, e.g. [2, 2, 3])
* @param[in] atomCounts How many atoms of each we have [e.g. 12, 6, 6 for Glucose]
* @param[in] isotopeMasses Array with the individual elements isotopic masses
* @param[in] isotopeProbabilities Array with the individual elements isotopic probabilities
*
**/
IsoSpecOrderedGeneratorWrapper(const std::vector<int>& isotopeNumbers,
const std::vector<int>& atomCounts,
const std::vector<std::vector<double> >& isotopeMasses,
const std::vector<std::vector<double> >& isotopeProbabilities);
// delete copy constructor
IsoSpecOrderedGeneratorWrapper(const IsoSpecOrderedGeneratorWrapper&) = delete;
/**
* @brief Setup the algorithm to run on an EmpiricalFormula
*
**/
IsoSpecOrderedGeneratorWrapper(const EmpiricalFormula& formula);
~IsoSpecOrderedGeneratorWrapper();
inline bool nextConf() final;
inline Peak1D getConf() final;
inline double getMass() final;
inline double getIntensity() final;
inline double getLogIntensity() final;
protected:
std::unique_ptr<IsoSpec::IsoOrderedGenerator> IOG;
};
//--------------------------------------------------------------------------
// IsoSpecWrapper classes
//--------------------------------------------------------------------------
/**
* @brief Create a p-set of configurations for a given p (that is, a set of configurations such that
* their probabilities sum up to p). The p in normal usage will usually be close to 1 (e.g. 0.99).
*
* An optimal p-set of isotopologues is the smallest set of isotopologues that, taken together, cover at
* least p of the probability space (that is, their probabilities sum up to at least p). This means that
* the computed spectrum is accurate to at least degree p, and that the L1 distance between the computed
* spectrum and the true spectrum is less than 1-p. The optimality of the p-set means that it contains
* the most probable configurations - any isotopologues outside of the returned p-set have lower intensity
* than the configurations in the p-set.
*
* This is the method most users will want: the p parameter directly controls the accuracy of results.
*
* Advanced usage note: The algorithm works by computing an optimal p'-set for a p' slightly larger than
* the requested p. By default these extra isotopologues are returned too (as they have to be computed
* anyway). It is possible to request that the extra configurations be discarded, using the do_p_trim
* parameter. This will *increase* the runtime and especially the memory usage of the algorithm, and
* should not be done unless there is a good reason to.
*
* @note The eligible configurations are NOT guaranteed to be returned in any particular order.
*/
class OPENMS_DLLAPI IsoSpecTotalProbWrapper : public IsoSpecWrapper
{
public:
/**
* @brief Constructor
*
* @param[in] isotopeNumbers A vector of how many isotopes each element has, e.g. [2, 2, 3])
* @param[in] atomCounts How many atoms of each we have [e.g. 12, 6, 6 for Glucose]
* @param[in] isotopeMasses Array with the individual elements isotopic masses
* @param[in] isotopeProbabilities Array with the individual elements isotopic probabilities
* @param[in] p Total coverage of probability space desired, usually close to 1 (e.g. 0.99)
* @param[in] do_p_trim Whether to discard extra configurations that have been computed
*
* @note This constructor is only useful if you need to define non-standard abundances
* of isotopes, for other uses the one accepting EmpiricalFormula is easier to use.
*
**/
IsoSpecTotalProbWrapper(const std::vector<int>& isotopeNumbers,
const std::vector<int>& atomCounts,
const std::vector<std::vector<double> >& isotopeMasses,
const std::vector<std::vector<double> >& isotopeProbabilities,
double p,
bool do_p_trim = false);
// delete copy constructor
IsoSpecTotalProbWrapper(const IsoSpecTotalProbWrapper&) = delete;
/**
* @brief Setup the algorithm to run on an EmpiricalFormula
*
**/
IsoSpecTotalProbWrapper(const EmpiricalFormula& formula, double p, bool do_p_trim = false);
~IsoSpecTotalProbWrapper();
IsotopeDistribution run() final;
protected:
std::unique_ptr<IsoSpec::IsoLayeredGenerator> ILG;
const double target_prob;
const bool do_p_trim;
};
/**
* @brief A non-generator version of IsoSpecThresholdGeneratorWrapper
*
* This is the simplest algorithm - most users will however want to use IsoSpecTotalProbWrapper.
* The reason for it is that when thresholding by peak intensity one has no idea how far the obtained
* spectrum is from a real spectrum. For example, consider human insulin: if the threshold is set at
* 0.1 of the most intense peak, then the peaks above the threshold account for 99.7% of total probability
* for water, 82% for substance P, only 60% for human insulin, and 23% for titin.
* For a threshold of 0.01, the numbers will be: still 99.7% for water, 96% for substance P, 88% for human insulin
* and 72% for titin (it also took 5 minutes on an average notebook computer to process the 17 billion configurations
* involved).
*
* As you can see the threshold does not have a straightforward correlation to the accuracy of the final spectrum
* obtained - and accuracy of final spectrum is often what the user is interested in. The IsoSpecTotalProbGeneratorWrapper
* provides a way to directly parameterize based on the desired accuracy of the final spectrum - and should be used
* instead in most cases. The trade-off is that it's (slightly) slower than Threshold algorithm. This speed gap will
* be dramatically improved with IsoSpec 2.0.
*
* @note The eligible isotopologues are NOT guaranteed to be generated in any particular order.
*/
class OPENMS_DLLAPI IsoSpecThresholdWrapper : public IsoSpecWrapper
{
public:
/**
* @brief Constructor
*
* @param[in] isotopeNumbers A vector of how many isotopes each element has, e.g. [2, 2, 3])
* @param[in] atomCounts How many atoms of each we have [e.g. 12, 6, 6 for Glucose]
* @param[in] isotopeMasses Array with the individual elements isotopic masses
* @param[in] isotopeProbabilities Array with the individual elements isotopic probabilities
* @param[in] threshold Intensity threshold: will only compute peaks above this threshold
* @param[in] absolute Whether the threshold is absolute or relative (relative to the most intense peak)
*
* @note This constructor is only useful if you need to define non-standard abundances
* of isotopes, for other uses the one accepting EmpiricalFormula is easier to use.
*
**/
IsoSpecThresholdWrapper(const std::vector<int>& isotopeNumbers,
const std::vector<int>& atomCounts,
const std::vector<std::vector<double> >& isotopeMasses,
const std::vector<std::vector<double> >& isotopeProbabilities,
double threshold,
bool absolute);
// delelte copy constructor
IsoSpecThresholdWrapper(const IsoSpecThresholdWrapper&) = delete;
/**
* @brief Setup the algorithm to run on an EmpiricalFormula
*
**/
IsoSpecThresholdWrapper(const EmpiricalFormula& formula, double threshold, bool absolute);
~IsoSpecThresholdWrapper();
IsotopeDistribution run() final;
protected:
std::unique_ptr<IsoSpec::IsoThresholdGenerator> ITG;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/ISOTOPEDISTRIBUTION/CoarseIsotopePatternGenerator.h | .h | 20,949 | 385 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Clemens Groepl, Andreas Bertsch, Chris Bielow $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CHEMISTRY/ISOTOPEDISTRIBUTION/IsotopePatternGenerator.h>
#include <OpenMS/CHEMISTRY/ISOTOPEDISTRIBUTION/IsotopeDistribution.h>
#include <set>
namespace OpenMS
{
/**
* @ingroup Chemistry
* @brief Isotope pattern generator for coarse isotope distributions.
*
* This algorithm implements IsotopePatternGenerator and generates
* theoretical pattern distributions for empirical formulas with resolution
* of 1Da. It convolves the empirical abundances of each element in a
* molecular formula, thus producing accurate intensities (probabilities)
* for each isotopic peak. However, it will assume that every isotope has an
* atomic mass that is rounded to the closest integer in Daltons, therefore
* it produces coarse distributions (it does not discriminate between 13C,
* N15 and O18 peaks). For example, for a molecule that contains both
* Carbon and Nitrogen, it will add up the probabilities for 13C and 15N,
* ignoring the fact that their masses are (slightly) different. Therefore,
* the probability distributions generated by the
* CoarseIsotopePatternGenerator are accurate, but the masses (m/z) are only
* approximately accurate. In case you need fine resolution, please
* consider using the FineIsotopePatternGenerator.
*
* The output is a list of pairs containing nominal isotope probabilities
* paired with a number that is either an approximately accurate or rounded
* (integer) mass. The accurate masses assume the nominal isotopes are
* mostly due to (13)Carbon. To return accurate vs rounded masses, use
* setRoundMasses accordingly. The default is to return accurate masses
* (note that setting this option will not influence the probabilities and
* still produce a coarse distributions spaced at ca 1Da). For example,
* using rounded mass, for a C100 molecule, you will get:
*
* @code
* 1200 : 0.341036528
* 1201 : 0.368855864
* 1202 : 0.197477505
* 1203 : 0.0697715357
* @endcode
*
* while accurate mass will produce:
*
* @code
* 1200 : 0.341036528
* 1201.00335 : 0.368855864
* 1202.00671 : 0.197477505
* 1203.01006 : 0.0697715357
* @endcode
*
* The other important value which needs to be set is the max isotope value.
* This value can be set using the setMaxIsotope method. It is an upper
* bound for the number of isotopes which are calculated If e.g., set to 3,
* only the first three isotopes, Monoisotopic mass, +1 and +2 are
* calculated.
*
* @note By default all possible isotopes are calculated, which leads to a large
* number of values, if the mass value is large!
*
* @note If you need fine isotope distributions, consider using the
* FineIsotopePatternGenerator.
*
* See also method run()
**/
class OPENMS_DLLAPI CoarseIsotopePatternGenerator
: public IsotopePatternGenerator
{
public:
CoarseIsotopePatternGenerator(const Size max_isotope = 0, const bool round_masses = false);
~CoarseIsotopePatternGenerator() override;
/// @name Accessors
///@{
/** @brief sets the maximal isotope with @p max_isotope
sets the maximal isotope which is included in the distribution
and used to limit the calculations. This is useful as distributions
with numerous isotopes tend to have a lot of numerical zeros at the end
*/
void setMaxIsotope(const Size& max_isotope);
/// round masses to integer values (true) or return accurate masses (false)
void setRoundMasses(const bool round_masses);
/// returns the currently set maximum isotope
Size getMaxIsotope() const;
/// returns the current value of the flag to return expected masses (true) or atomic numbers (false).
bool getRoundMasses() const;
///@}
/**
* @brief Creates an isotope distribution from an empirical sum formula
*
* Iterates through all elements, convolves them according to the number
* of atoms from that element and sums up the result.
*
* If the EmpiricalFormula has a charge 'q' > 0, then 'q' hydrogen atoms are added
* to the formula to match the result of EmpiricalFormula::getMonoWeight().
* Set `ef.charge = 0` to avoid this behavior.
*
* @throw Exception::Precondition if the formula has a negative charge
**/
IsotopeDistribution run(const EmpiricalFormula& ef) const override;
/**
@brief Estimate Peptide Isotopedistribution from weight and number of isotopes that should be reported
Implementation using the averagine model proposed by Senko et al. in
"Determination of Monoisotopic Masses and Ion Populations for Large Biomolecules from Resolved Isotopic Distributions"
*/
IsotopeDistribution estimateFromPeptideWeight(double average_weight);
/**
@brief Estimate Peptide Isotopedistribution from monoisotopic weight and number of isotopes that should be reported
Implementation using the averagine model proposed by Senko et al. in
"Determination of Monoisotopic Masses and Ion Populations for Large Biomolecules from Resolved Isotopic Distributions"
But this function takes monoisotopic mass. Thus determination of monoisotopic mass is not performed.
*/
IsotopeDistribution estimateFromPeptideMonoWeight(double mono_weight);
/**
@brief Estimate peptide IsotopeDistribution from average weight and exact number of sulfurs
@param[in] average_weight Average weight to estimate an EmpiricalFormula for
@param[in] S The exact number of Sulfurs in this molecule
@pre S <= average_weight / average_weight(sulfur)
@pre average_weight >= 0
*/
IsotopeDistribution estimateFromPeptideWeightAndS(double average_weight, UInt S);
/**
@brief roughly approximate peptide IsotopeDistribution from monoisotopic weight using Poisson distribution.
m/z values approximated by adding one neutron mass (divided by charge) for every peak, starting at the given monoisotopic weight.
Foundation from: Bellew et al, https://dx.doi.org/10.1093/bioinformatics/btl276
This method is around 50 times faster than estimateFromPeptideWeight, but only an approximation. The following are the intensities
of the first 6 peaks generated for a monoisotopic mass of 1000:
estimateFromPeptideWeight: 0.571133000;0.306181000;0.095811100;0.022036900;0.004092170;0.000644568
approximateFromPeptideWeight: 0.573753000;0.318752000;0.088542200;0.016396700;0.002277320;0.000253036
KL divergences of the first 20 intensities of estimateFromPeptideWeight and this approximation range from 4.97E-5 for a
monoisotopic mass of 20 to 0.0144 for a mass of 2500. For comparison, when comparing an observed pattern with a
theoretical ground truth, the observed pattern is said to be an isotopic pattern if the KL between the two is below 0.05
for 2 peaks and below 0.6 for >=6 peaks by Guo Ci Teo et al.
@param[in] mass m/z of monoisotopic peak (with charge = 1) to approximate the distribution of intensities for
@param[in] num_peaks How many peaks should be generated (independent of this->max_isotope)
@param[in] charge Charge of the resulting distribution
*/
static IsotopeDistribution approximateFromPeptideWeight(double mass, UInt num_peaks = 20, UInt charge = 1);
/**
@brief roughly approximate intensity distribution of peptidic isotope patterns from monoisotopic weight using Poisson distribution.
Foundation from: Bellew et al, https://dx.doi.org/10.1093/bioinformatics/btl276
This method is around 100 times faster than estimateFromPeptideWeight, but only an approximation of the intensities.
It does not return IsotopeDistribution but a vector of intensities. For an assessment of accuracy, see approximateFromPeptideWeight.
@param[in] mass m/z of monoisotopic peak (with charge = 1) to approximate the distribution of intensities for
@param[in] num_peaks How many peaks should be generated (independent of this->max_isotope)
*/
static std::vector<double> approximateIntensities(double mass, UInt num_peaks = 20);
/**
@brief Estimate Nucleotide Isotopedistribution from weight and number of isotopes that should be reported
averagine model from Zubarev, R. A.; Demirev, P. A. in
"Isotope depletion of large biomolecules: Implications for molecular mass measurements."
*/
IsotopeDistribution estimateFromRNAWeight(double average_weight);
/**
@brief Estimate Nucleotide Isotopedistribution from monoisotopic weight and number of isotopes that should be reported
averagine model from Zubarev, R. A.; Demirev, P. A. in
"Isotope depletion of large biomolecules: Implications for molecular mass measurements."
*/
IsotopeDistribution estimateFromRNAMonoWeight(double mono_weight);
/**
@brief Estimate Nucleotide Isotopedistribution from weight and number of isotopes that should be reported
averagine model from Zubarev, R. A.; Demirev, P. A. in
"Isotope depletion of large biomolecules: Implications for molecular mass measurements."
*/
IsotopeDistribution estimateFromDNAWeight(double average_weight);
/**
@brief Estimate Isotopedistribution from weight, average composition, and number of isotopes that should be reported
*/
IsotopeDistribution estimateFromWeightAndComp(double average_weight, double C, double H, double N, double O, double S, double P);
/**
@brief Estimate Isotopedistribution from monoisotopic weight, average composition, and number of isotopes that should be reported
*/
IsotopeDistribution estimateFromMonoWeightAndComp(double mono_weight, double C, double H, double N, double O, double S, double P);
/**
@brief Estimate IsotopeDistribution from weight, exact number of sulfurs, and average remaining composition
@param[in] average_weight Average weight to estimate an IsotopeDistribution for
@param[in] S The exact numbers of Sulfurs in this molecule
@param[in] C The approximate relative stoichiometry of Carbons to other elements (excluding Sulfur) in this molecule
@param[in] H The approximate relative stoichiometry of Hydrogens to other elements (excluding Sulfur) in this molecule
@param[in] N The approximate relative stoichiometry of Nitrogens to other elements (excluding Sulfur) in this molecule
@param[in] O The approximate relative stoichiometry of Oxygens to other elements (excluding Sulfur) in this molecule
@param[in] P The approximate relative stoichiometry of Phosphoruses to other elements (excluding Sulfur) in this molecule
@pre S, C, H, N, O, P >= 0
@pre average_weight >= 0
*/
IsotopeDistribution estimateFromWeightAndCompAndS(double average_weight, UInt S, double C, double H, double N, double O, double P);
/**
@brief Estimate peptide fragment IsotopeDistribution from the precursor's average weight,
fragment's average weight, and a list of isolated precursor isotopes.
The max_depth of the isotopic distribution is set to max(precursor_isotopes)+1.
@param[in] average_weight_precursor average weight of the precursor peptide
@param[in] average_weight_fragment average weight of the fragment
@param[in] precursor_isotopes the precursor isotopes that were isolated. 0 corresponds to the mono-isotopic molecule (M0), 1->M1, etc.
@pre average_weight_precursor >= average_weight_fragment
@pre average_weight_fragment > 0
@pre average_weight_precursor > 0
@pre precursor_isotopes.size() > 0
*/
IsotopeDistribution estimateForFragmentFromPeptideWeight(double average_weight_precursor, double average_weight_fragment, const std::set<UInt>& precursor_isotopes);
/**
@brief Estimate peptide fragment IsotopeDistribution from the precursor's average weight,
number of sulfurs in the precursor, fragment's average weight, number of sulfurs in the fragment,
and a list of isolated precursor isotopes.
The max_depth of the isotopic distribution is set to max(precursor_isotopes)+1.
@param[in] average_weight_precursor average weight of the precursor peptide
@param[in] S_precursor The exact number of Sulfurs in the precursor peptide
@param[in] average_weight_fragment average weight of the fragment
@param[in] S_fragment The exact number of Sulfurs in the fragment
@param[in] precursor_isotopes the precursor isotopes that were isolated
@pre S_fragment <= average_weight_fragment / average_weight(sulfur)
@pre S_precursor - S_fragment <= (average_weight_precursor - average_weight_fragment) / average_weight(sulfur)
@pre average_weight_precursor >= average_weight_fragment
@pre average_weight_precursor > 0
@pre average_weight_fragment > 0
@pre precursor_isotopes.size() > 0
*/
IsotopeDistribution estimateForFragmentFromPeptideWeightAndS(double average_weight_precursor, UInt S_precursor, double average_weight_fragment, UInt S_fragment, const std::set<UInt>& precursor_isotopes) const;
/**
@brief Estimate RNA fragment IsotopeDistribution from the precursor's average weight,
fragment's average weight, and a list of isolated precursor isotopes.
The max_depth of the isotopic distribution is set to max(precursor_isotopes)+1.
@param[in] average_weight_precursor average weight of the precursor nucleotide
@param[in] average_weight_fragment average weight of the fragment
@param[in] precursor_isotopes the precursor isotopes that were isolated. 0 corresponds to the mono-isotopic molecule (M0), 1->M1, etc.
@pre average_weight_precursor >= average_weight_fragment
@pre average_weight_precursor > 0
@pre average_weight_fragment > 0
@pre precursor_isotopes.size() > 0
*/
IsotopeDistribution estimateForFragmentFromRNAWeight(double average_weight_precursor, double average_weight_fragment, const std::set<UInt>& precursor_isotopes);
/**
@brief Estimate DNA fragment IsotopeDistribution from the precursor's average weight,
fragment's average weight, and a list of isolated precursor isotopes.
The max_depth of the isotopic distribution is set to max(precursor_isotopes)+1.
@param[in] average_weight_precursor average weight of the precursor nucleotide
@param[in] average_weight_fragment average weight of the fragment
@param[in] precursor_isotopes the precursor isotopes that were isolated. 0 corresponds to the mono-isotopic molecule (M0), 1->M1, etc.
@pre average_weight_precursor >= average_weight_fragment
@pre average_weight_precursor > 0
@pre average_weight_fragment > 0
@pre precursor_isotopes.size() > 0
*/
IsotopeDistribution estimateForFragmentFromDNAWeight(double average_weight_precursor, double average_weight_fragment, const std::set<UInt>& precursor_isotopes);
/**
@brief Estimate fragment IsotopeDistribution from the precursor's average weight,
fragment's average weight, a list of isolated precursor isotopes, and average composition
The max_depth of the isotopic distribution is set to max(precursor_isotopes)+1.
@param[in] average_weight_precursor average weight of the precursor molecule
@param[in] average_weight_fragment average weight of the fragment molecule
@param[in] precursor_isotopes the precursor isotopes that were isolated. 0 corresponds to the mono-isotopic molecule (M0), 1->M1, etc.
@param[in] C The approximate relative stoichiometry of Carbons to other elements in this molecule
@param[in] H The approximate relative stoichiometry of Hydrogens to other elements in this molecule
@param[in] N The approximate relative stoichiometry of Nitrogens to other elements in this molecule
@param[in] O The approximate relative stoichiometry of Oxygens to other elements in this molecule
@param[in] S The approximate relative stoichiometry of Sulfurs to other elements in this molecule
@param[in] P The approximate relative stoichiometry of Phosphoruses to other elements in this molecule
@pre S, C, H, N, O, P >= 0
@pre average_weight_precursor >= average_weight_fragment
@pre average_weight_precursor > 0
@pre average_weight_fragment > 0
@pre precursor_isotopes.size() > 0
*/
IsotopeDistribution estimateForFragmentFromWeightAndComp(double average_weight_precursor, double average_weight_fragment, const std::set<UInt>& precursor_isotopes, double C, double H, double N, double O, double S, double P) const;
/**
@brief Calculate isotopic distribution for a fragment molecule
This calculates the isotopic distribution for a fragment molecule given
the isotopic distribution of the fragment and complementary fragment (as
if they were precursors), and which precursor isotopes were isolated.
@note Do consider normalising the distribution afterwards to get conditional probabilities.
Equations come from Rockwood, AL; Kushnir, MA; Nelson, GJ. in
"Dissociation of Individual Isotopic Peaks: Predicting Isotopic Distributions of Product Ions in MSn"
@param[in] fragment_isotope_dist the isotopic distribution of the fragment (as if it was a precursor).
@param[in] comp_fragment_isotope_dist the isotopic distribution of the complementary fragment (as if it was a precursor).
@param[in] precursor_isotopes a list of which precursor isotopes were isolated. 0 corresponds to the mono-isotopic molecule (M0), 1->M1, etc.
@param[in] fragment_mono_mass the monoisotopic mass of the fragment.
@pre fragment_isotope_dist and comp_fragment_isotope_dist are gapless (no missing isotopes between the min/max isotopes of the dist)
*/
IsotopeDistribution calcFragmentIsotopeDist(const IsotopeDistribution& fragment_isotope_dist, const IsotopeDistribution& comp_fragment_isotope_dist, const std::set<UInt>& precursor_isotopes, const double fragment_mono_mass) const;
CoarseIsotopePatternGenerator& operator=(const CoarseIsotopePatternGenerator& iso);
/// convolves the distributions @p left and @p right and stores the result in @p result
IsotopeDistribution::ContainerType convolve(const IsotopeDistribution::ContainerType& left, const IsotopeDistribution::ContainerType& right) const;
protected:
/// convolves the distribution @p input @p factor times and stores the result in @p result
IsotopeDistribution::ContainerType convolvePow_(const IsotopeDistribution::ContainerType& input, Size factor) const;
/// convolves the distribution @p input with itself and stores the result in @p result
IsotopeDistribution::ContainerType convolveSquare_(const IsotopeDistribution::ContainerType& input) const;
/// converts the masses of distribution @p input from atomic numbers to accurate masses (based on mass delta of C12 vs C13)
IsotopeDistribution::ContainerType correctMass_(const IsotopeDistribution::ContainerType& input, const double mono_weight) const;
/** @brief calculates the fragment distribution for a fragment molecule and stores it in @p result.
@param[in] fragment_isotope_dist the isotopic distribution of the fragment (as if it was a precursor).
@param[in] comp_fragment_isotope_dist the isotopic distribution of the complementary fragment (as if it was a precursor).
@param[in] precursor_isotopes which precursor isotopes were isolated. 0 corresponds to the mono-isotopic molecule (M0), 1->M1, etc.
*/
IsotopeDistribution calcFragmentIsotopeDist_(const IsotopeDistribution::ContainerType& fragment_isotope_dist, const IsotopeDistribution::ContainerType& comp_fragment_isotope_dist, const std::set<UInt>& precursor_isotopes) const;
/// fill a gapped isotope pattern (i.e. certain masses are missing), with zero probability masses
IsotopeDistribution::ContainerType fillGaps_(const IsotopeDistribution::ContainerType& id) const;
/// maximal isotopes which is used to calculate the distribution
Size max_isotope_;
/// flag to determine whether masses should be rounded or not
bool round_masses_;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/ISOTOPEDISTRIBUTION/FineIsotopePatternGenerator.h | .h | 7,249 | 191 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hannes Rost $
// $Authors: Hannes Rost $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CHEMISTRY/ISOTOPEDISTRIBUTION/IsotopePatternGenerator.h>
namespace OpenMS
{
/**
* @ingroup Chemistry
*
* @brief Isotope pattern generator for fine isotope distributions.
*
* This algorithm implements IsotopePatternGenerator and generates
* theoretical pattern distributions for empirical formulas with high
* resolution (while the CoarseIsotopePatternGenerator will generate
* low-resolution patterns). The output is a list of pairs containing
* isotope probabilities paired with the accurate m/z for the analyte
* isotopic composition.
*
* For example, for a C100H202 molecule (at 0.01 threshold), you will get:
*
* @code
* m/z 1403.5806564438 : INT 0.333207070827484
* m/z 1404.5840114438 : INT 0.360387712717056
* m/z 1404.5869331919 : INT 0.00774129061028361
* m/z 1405.5873664438 : INT 0.19294385612011
* m/z 1405.5902881919 : INT 0.00837276969105005
* m/z 1406.5907214438 : INT 0.0681697279214859
* m/z 1406.5936431919 : INT 0.00448260130360723
* m/z 1407.5940764438 : INT 0.0178796537220478
* m/z 1407.5969981919 : INT 0.00158376491162926
* ...
* @endcode
*
* For comparison, the CoarseIsotopePatternGenerator will produce the
* following result for a C100H202 molecule:
*
* @code
* m/z 1403.58 INT: 0.333489
* m/z 1404.58 INT: 0.36844
* m/z 1405.59 INT: 0.201576
* m/z 1406.59 INT: 0.0728113
* m/z 1407.59 INT: 0.0195325
* ...
* @endcode
*
* From the above example, we can see that the CoarseIsotopePatternGenerator
* will generate a single peak at nominal mass 1404 which sums up the
* probability of both the 13C and the 2H (deuterium) peak, while the
* FineIsotopePatternGenerator will generate two peaks at 1404.5840 (for
* 13C) and at 1404.5869 (for 2H). The probabilities of 36.0% and 0.77% add
* up to 36.8% which is the same as the sum reported by the
* CoarseIsotopePatternGenerator for the nominal mass at 1404. Note that for
* the peak at 1405 the FineIsotopePatternGenerator only reports two out of
* the three probabilities due to the chosen probability cutoffs.
*
* One important value to set is the threshold with tells the algorithm when
* to stop calculating isotopic peaks to calculate. The default stop
* condition is to stop when only a small portion (such as 0.01) of the
* total probability is unexplained and the reported values cover most of
* the probability (e.g. 0.99).
*
* Another way to stop the search is when any new peak would be less than
* 0.01 in height (absolute) or when it would be less than 0.01 of the
* highest isotopic peak (relative). This is how the stop_condition
* parameter is interpreted when use_total_prob is set to false.
*
* @note Computation of fine isotope patterns can be slow for large
* molecules, if you don't need fine isotope distributions consider using
* CoarseIsotopePatternGenerator.
*
* @note Consider using IsoSpec directly or the OpenMS IsoSpecWrapper /
* IsoSpecGeneratorWrapper classes defined in IsoSpecWrapper.h for
* increased performance since this class will sort the resuly by m/z
* while the wrapper will not; sorting substantially decreases
* performance.
*
* The computation is based on the IsoSpec algorithm, please cite
*
* @code
* Łącki MK, Startek M, Valkenborg D, Gambin A.
* IsoSpec: Hyperfast Fine Structure Calculator.
* Anal Chem. 2017 Mar 21;89(6):3272-3277. doi: 10.1021/acs.analchem.6b01459.
* @endcode
*
* See also method run()
**/
class OPENMS_DLLAPI FineIsotopePatternGenerator
: public IsotopePatternGenerator
{
public:
/**
* @brief Default Constructor
*
**/
FineIsotopePatternGenerator() = default;
/**
* @brief Constructor
*
* @param[in] stop_condition The total probability (if use_total_prob == true) or
* threshold (if use_total_prob is false) (see class docu)
*
* @param[in] use_total_prob Whether the stop_condition should be interpreted as a
* probability threshold (only configurations with intensity above this
* threshold will be returned) or as a total probability that the distribution
* should cover.
*
* @param[in] absolute Whether threshold is absolute or relative (ignored if use_total_prob is true, see class docu)
*
**/
FineIsotopePatternGenerator(double stop_condition, bool use_total_prob = true, bool absolute = false) :
stop_condition_(stop_condition),
absolute_(absolute),
use_total_prob_(use_total_prob)
{}
/**
* @brief Creates an isotope distribution from an empirical sum formula
*
* Iterates through all elements, convolves them according to the number
* of atoms from that element and sums up the result.
*
* If the EmpiricalFormula has a charge 'q' != 0, then 'q' hydrogen atoms are added
* to the formula to match the result of EmpiricalFormula::getMonoWeight().
* Set `ef.charge = 0` to avoid this behavior.
*
* @note The constructed isotope distribution is sorted by m/z which slows
* down processing, consider using IsoSpec (IsoSpecWrapper /
* IsoSpecGeneratorWrapper) directly for increased performance.
*
* @throw Exception::Precondition if the formula has a negative charge
**/
IsotopeDistribution run(const EmpiricalFormula& ef) const override;
/// Set probability stop condition (lower values generate fewer results)
void setThreshold(double stop_condition)
{
stop_condition_ = stop_condition;
}
/// Get probability stop condition (lower values generate fewer results)
double getThreshold() const
{
return stop_condition_;
}
/// Set whether threshold is absolute or relative probability (ignored if use_total_prob is true, see class docu)
void setAbsolute(bool absolute)
{
absolute_ = absolute;
}
/// Returns whether threshold is absolute or relative probability (ignored if use_total_prob is true, see class docu)
bool getAbsolute() const
{
return absolute_;
}
/// Set whether total probability should be computed (see FineIsotopePatternGenerator() )
void setTotalProbability(bool total)
{
use_total_prob_ = total;
}
/// Returns whether total probability should be computed (see FineIsotopePatternGenerator() )
bool getTotalProbability() const
{
return use_total_prob_;
}
protected:
double stop_condition_ = 0.01;
bool absolute_ = false;
bool use_total_prob_ = true;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/CHEMISTRY/ISOTOPEDISTRIBUTION/IsotopePatternGenerator.h | .h | 2,140 | 61 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Nikos Patikos $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/config.h>
namespace OpenMS
{
class EmpiricalFormula;
class IsotopeDistribution;
/**
@brief Provides an interface for different isotope pattern generator methods.
The IsotopePatternGenerator interface allows the developer integrate various
isotope pattern generator methods in the OpenMS code. It provides a run() method
that generates but does not hold any generated isotope distribution data in
the class. Instead it returns an IsotopeDistribution to the caller.
Currently there are two implementations available:
- CoarseIsotopePatternGenerator: a fast implementation of isotopic
patterns that generates accurate probabilities for each isotopic peak
but ignores the hyperfine isotopic structures (i.e. single peaks will
be generated spaced ca. 1 Da apart, thus aggregating the peaks
generated by 13C, 15N, 18O etc.).
- FineIsotopePatternGenerator: an implementation for generation of fine
resolution (high resolution) isotopic patterns containing the hyperfine
isotopic structure. This will produce individual peaks for each element
(i.e. the isotopic peaks of 13C, 15N, 18O etc. will all be individually
resolved).
*/
class OPENMS_DLLAPI IsotopePatternGenerator
{
public:
IsotopePatternGenerator();
IsotopePatternGenerator(double probability_cutoff);
/**
@brief interface that is being used by the Isotope Pattern Generator methods.
Method that calculates the isotope distribution for the given formula.
*/
virtual IsotopeDistribution run(const EmpiricalFormula&) const = 0;
virtual ~IsotopePatternGenerator();
protected:
double min_prob_;
};
}
| Unknown |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.