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/KERNEL/AreaIterator.h | .h | 9,479 | 306 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg$
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#pragma once
// OpenMS includes
#include <OpenMS/CONCEPT/Types.h>
#include <OpenMS/KERNEL/PeakIndex.h>
#include <OpenMS/KERNEL/RangeManager.h>
// STL includes
#include <iterator>
namespace OpenMS
{
namespace Internal
{
/**
@brief Forward iterator for an area of peaks in an experiment
This iterator allows us to move through the data structure in a linear
manner i.e. we don't need to jump to the next spectrum manually.
Ion mobility can also be filtered for: the low/high range for IM are used to skip over spectra in the given RT range whose drift time
is not within the given range. I.e. the RT range could contain multiple IM frames.
@note This iterator iterates over spectra with same MS level as the MS level of the begin() spectrum in Param! You can explicitly set another MS level as well.
*/
template<class ValueT, class ReferenceT, class PointerT, class SpectrumIteratorT, class PeakIteratorT>
class AreaIterator
{
public:
typedef double CoordinateType;
typedef ValueT PeakType;
typedef SpectrumIteratorT SpectrumIteratorType;
typedef PeakIteratorT PeakIteratorType;
using SpectrumT = typename std::iterator_traits<SpectrumIteratorType>::value_type;
/// Parameters for the AreaIterator
/// Required values must be set in the C'tor. Optional values can be set via member functions (which allow chaining).
class Param
{
friend AreaIterator; // allow access to private members (avoids writing get-accessors)
public:
/**
* \brief C'tor with mandatory parameters
* \param first The very first spectrum of the experiment
* \param begin The first spectrum with a valid RT/IM time
* \param end The last spectrum with a valid RT/IM time
* \param ms_level Only peaks from spectra with this ms_level are used
*/
Param(SpectrumIteratorType first, SpectrumIteratorType begin, SpectrumIteratorType end, uint8_t ms_level) : first_(first), current_scan_(begin), end_scan_(end), ms_level_(ms_level)
{
}
/// return the end-iterator
static Param end()
{
static Param p;
p.is_end_ = true;
return p;
}
/// Assignment operator
Param& operator=(const Param& rhs) = default;
/** @name Named parameter idiom for chaining
*/
//@{
/// low m/z boundary
Param& lowMZ(CoordinateType low_mz)
{
low_mz_ = low_mz;
return *this;
}
/// high m/z boundary
Param& highMZ(CoordinateType high_mz)
{
high_mz_ = high_mz;
return *this;
}
/// low ion mobility boundary
Param& lowIM(CoordinateType low_im)
{
low_im_ = low_im;
return *this;
}
/// high ion mobility boundary
Param& highIM(CoordinateType high_im)
{
high_im_ = high_im;
return *this;
}
/// Only scans of this MS level are iterated over
Param& msLevel(int8_t ms_level)
{
ms_level_ = ms_level;
return *this;
}
//@}
protected:
/// Iterator to the first scan of the map (needed to calculate the index)
SpectrumIteratorType first_;
/// Iterator to the current spectrum
SpectrumIteratorType current_scan_;
/// Past-the-end iterator of spectra
SpectrumIteratorType end_scan_;
/// Iterator to the current peak
PeakIteratorType current_peak_;
/// Past-the-end iterator of peaks in the current spectrum
PeakIteratorType end_peak_;
/* optional parameters */
/// low m/z boundary
CoordinateType low_mz_ = std::numeric_limits<CoordinateType>::lowest();
/// high m/z boundary
CoordinateType high_mz_ = std::numeric_limits<CoordinateType>::max();
/// low mobility boundary
CoordinateType low_im_ = std::numeric_limits<CoordinateType>::lowest();
/// high mobility boundary
CoordinateType high_im_ = std::numeric_limits<CoordinateType>::max();
/// Only scans of this MS level are iterated over
int8_t ms_level_ {};
/// Flag that indicates that this iterator is the end iterator
bool is_end_ = false;
private:
/// only used internally for end()
Param() = default;
};
/** @name Typedefs for STL compliance, these replace std::iterator
*/
//@{
/// The iterator's category type
typedef std::forward_iterator_tag iterator_category;
/// The iterator's value type
typedef ValueT value_type;
/// The reference type as returned by operator*()
typedef ReferenceT reference;
/// The pointer type as returned by operator->()
typedef PointerT pointer;
/// The difference type
typedef unsigned int difference_type;
//@}
/// Constructor for the begin iterator
explicit AreaIterator(const Param& p) : p_(p)
{
nextScan_();
}
/// Default constructor (for the end iterator)
AreaIterator() : p_(Param::end())
{
}
/// Destructor
~AreaIterator() = default;
/// Copy constructor
AreaIterator(const AreaIterator& rhs) = default;
/// Assignment operator
AreaIterator& operator=(const AreaIterator& rhs)
{
p_.is_end_ = rhs.p_.is_end_;
// only copy iterators, if the assigned iterator is not the end iterator
if (!p_.is_end_)
{
p_ = rhs.p_;
}
return *this;
}
/// Test for equality
bool operator==(const AreaIterator& rhs) const
{
// Both end iterators => equal
if (p_.is_end_ && rhs.p_.is_end_)
return true;
// Normal and end iterator => not equal
if (p_.is_end_ ^ rhs.p_.is_end_)
return false;
// Equality of pointed to peak addresses
return &(*(p_.current_peak_)) == &(*(rhs.p_.current_peak_));
}
/// Test for inequality
bool operator!=(const AreaIterator& rhs) const
{
return !(*this == rhs);
}
/// Step forward by one (prefix operator)
AreaIterator& operator++()
{
// no increment if this is the end iterator
if (p_.is_end_)
return *this;
++p_.current_peak_;
// test whether we arrived at the end of the current scan
if (p_.current_peak_ == p_.end_peak_)
{
++p_.current_scan_;
nextScan_();
}
return *this;
}
/// Step forward by one (postfix operator)
AreaIterator operator++(int)
{
AreaIterator tmp(*this);
++(*this);
return tmp;
}
/// Dereferencing of this pointer yields the underlying peak
reference operator*() const
{
return p_.current_peak_.operator*();
}
/// Dereferencing of this pointer yields the underlying peak
pointer operator->() const
{
return p_.current_peak_.operator->();
}
/// returns the retention time of the current scan
CoordinateType getRT() const
{
return p_.current_scan_->getRT();
}
/// returns the ion mobility time of the current scan
CoordinateType getDriftTime() const
{
return p_.current_scan_->getDriftTime();
}
/// returns the current scan into which the iterator points
const SpectrumT& getSpectrum() const
{
return *p_.current_scan_;
}
/// returns the PeakIndex corresponding to the current iterator position
inline PeakIndex getPeakIndex() const
{
if (p_.is_end_)
{
return {};
}
else
{
return PeakIndex(p_.current_scan_ - p_.first_, p_.current_peak_ - p_.current_scan_->begin());
}
}
private:
/// advances the iterator to the next valid peak in the next valid spectrum
void nextScan_()
{
using MSLevelType = decltype(p_.current_scan_->getMSLevel());
RangeMobility mb {p_.low_im_, p_.high_im_};
while (true)
{
// skip over invalid MS levels and Mobility
while (p_.current_scan_ != p_.end_scan_ && (p_.current_scan_->getMSLevel() != (MSLevelType)p_.ms_level_ || !mb.containsMobility(p_.current_scan_->getDriftTime())))
{
++p_.current_scan_;
}
if (p_.current_scan_ == p_.end_scan_)
{
p_.is_end_ = true;
return;
}
p_.current_peak_ = p_.current_scan_->MZBegin(p_.low_mz_);
p_.end_peak_ = p_.current_scan_->MZEnd(p_.high_mz_);
if (p_.current_peak_ != p_.end_peak_)
{
return;
}
++p_.current_scan_;
}
}
/// holds spectra iterators and area limits
Param p_;
};
} // namespace Internal
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/KERNEL/MRMFeature.h | .h | 3,311 | 124 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hannes Roest $
// $Authors: Hannes Roest $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/Feature.h>
#include <OpenMS/ANALYSIS/OPENSWATH/OpenSwathScores.h>
namespace OpenMS
{
/**
@brief A multi-chromatogram MRM feature
An MRM feature contains corresponding features in multiple chromatograms,
it is thus a representation of a peak group. The individual features in
each chromatogram are represented by OpenMS Features.
*/
class OPENMS_DLLAPI MRMFeature :
public Feature
{
public:
///Type definitions
//@{
/// Feature list type
typedef std::vector<Feature> FeatureListType;
//@}
///@name Constructors and Destructor
//@{
/// Default constructor
MRMFeature();
/// Copy constructor
MRMFeature(const MRMFeature &rhs);
/// Move constructor
MRMFeature(MRMFeature &&rhs) = default;
/// Assignment operator
MRMFeature & operator=(const MRMFeature & rhs);
/// Move assignment operator
MRMFeature& operator=(MRMFeature&&) & = default;
/// Destructor
~MRMFeature() override;
//@}
///@name Accessors
//@{
/// get all peakgroup scores
const OpenSwath_Scores & getScores() const;
/// get all peakgroup scores
OpenSwath_Scores & getScores();
/// get a specified feature
Feature & getFeature(const String& key);
/// get a specified feature (const)
const Feature & getFeature(const String& key) const;
/// set all peakgroup scores
void setScores(const OpenSwath_Scores & scores);
/// set a single peakgroup score
void addScore(const String & score_name, double score);
/// Adds an feature from a single chromatogram into the feature.
void addFeature(const Feature & feature, const String& key);
void addFeature(Feature && feature, const String& key);
/// get a list of features
const std::vector<Feature> & getFeatures() const;
/// get a list of IDs of available features
void getFeatureIDs(std::vector<String> & result) const;
/// Adds a precursor feature from a single chromatogram into the feature.
void addPrecursorFeature(const Feature & feature, const String& key);
void addPrecursorFeature(Feature && feature, const String& key);
/// get a list of IDs of available precursor features
void getPrecursorFeatureIDs(std::vector<String> & result) const;
/// get a specified precursor feature
Feature & getPrecursorFeature(const String& key);
/// get a specified precursor feature (const)
const Feature & getPrecursorFeature(const String& key) const;
void IDScoresAsMetaValue(bool decoy, const OpenSwath_Ind_Scores& idscores);
//@}
protected:
FeatureListType features_;
FeatureListType precursor_features_;
/// peak group scores
OpenSwath_Scores pg_scores_;
/// map native ids to the features
std::map<String, int> feature_map_;
/// map native ids to the precursor features
std::map<String, int> precursor_feature_map_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/KERNEL/BinnedSpectrum.h | .h | 6,320 | 184 | // 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, Mathias Walzer $
// --------------------------------------------------------------------------
//
#pragma once
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/KERNEL/MSSpectrum.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <cmath>
// forward decl
namespace Eigen
{
template<typename _Scalar, int _Flags, typename _StorageIndex>
class SparseVector;
}
namespace OpenMS
{
/**
@brief This is a binned representation of a PeakSpectrum
@param[in] sz the size of the bins and
@param[in] sp number of neighboring bins to both sides affected by a peak contribution
@param[in] ps the PeakSpectrum, used to calculate the binned spectrum
sz denotes the size of a bin in @p Th, thereby deciding the number of bins (all of size sz) the spectrum is discretized to.
Each bin will represent a certain @p Th range and the peaks will be put in the respective bins and sum up inside.
sp denotes the number of neighboring bins to the left and the number of neighboring bins to the right a peak is also added to.
E.g. a BinnedSpectrum with binsize of 0.5 @p Th will have a peak at 100 @p Th in bin no. 200, a peak at 100.1 @p Th will be in bin no. 201.
If the binspread is 1, the peak at 100 Th will be added to bin no. 199, 200 and 201.
If the binspread is 2, the peak at 100 @p Th will also be added to bin no. 198 and 202, and so on.
Many operations are provided by the underlying SparseVector implementation:
- bin-wise addition (e.g.: c = a.getBins() + b.getBins())
- bin-wise scaling (e.g.: c = a.getBins() * 5f)
- to get the number of filled bins, call: getBins().nonZeros()
- many more...
See the Eigen SparseVector implementation for details.
Implementation detail: Eigen SparseVectors need to have the same dimensionality. EmptySparseVector provides an empty SparseVector
with compatible dimension to perform all supported operations.
@ingroup SpectraComparison
*/
class OPENMS_DLLAPI BinnedSpectrum
{
// smallest possible m/z value (needs to be >= 1)
static constexpr const float MIN_MZ_ = 1.0;
public:
/** Sensible default values and notes from doi:10.1007/s13361-015-1179-x
* Low-resolution MS/MS data:
* bin width = 1.0005
* offset = 0.4
* spread should be 0
*
* High-resolution MS/MS data:
* bin width = 0.02
* offset = 0.0
* spread should be 0
* Note: in sum scores, intensities from neighboring bins should be considered with half intensity of each flanking bin.
* @todo: Weighted intensity spread is currently not implemented(but could replace the spread parameter).
*/
// default bin width for low-resolution data (adapted from doi:10.1007/s13361-015-1179-x)
static constexpr const float DEFAULT_BIN_WIDTH_LOWRES = 1.0005f;
// default bin width for high-resolution data (adapted from doi:10.1007/s13361-015-1179-x)
static constexpr const float DEFAULT_BIN_WIDTH_HIRES = 0.02f;
/// default bin offset for high-resolution data (adapted from doi:10.1007/s13361-015-1179-x)
static constexpr const float DEFAULT_BIN_OFFSET_HIRES = 0.0f;
/// default bin offset for low-resolution data (adapted from doi:10.1007/s13361-015-1179-x)
static constexpr const float DEFAULT_BIN_OFFSET_LOWRES = 0.4f;
/// typedef for the underlying sparse vector
using SparseVectorType = Eigen::SparseVector<float, 0, int>;
/// the empty SparseVector
// static const SparseVectorType EmptySparseVector;
/// default constructor
// BinnedSpectrum() = delete;
BinnedSpectrum() {};
/// detailed constructor
BinnedSpectrum(const PeakSpectrum& ps, float size, bool unit_ppm, UInt spread, float offset);
/// copy constructor
BinnedSpectrum(const BinnedSpectrum&);
/// destructor
virtual ~BinnedSpectrum();
/// assignment operator
BinnedSpectrum& operator=(const BinnedSpectrum&);
/// equality operator
bool operator==(const BinnedSpectrum& rhs) const;
/// inequality operator
bool operator!=(const BinnedSpectrum& rhs) const;
/// returns the bin intensity at a given m/z position
float getBinIntensity(double mz);
/// return the bin index of a given m/z position
size_t getBinIndex(float mz) const;
/// return the lower m/z of a bin given its index
inline float getBinLowerMZ(size_t i) const
{
if (unit_ppm_)
{
// mz = MIN_MZ_ * (1.0 + bin_size_)^index for index
return float(MIN_MZ_ * pow(1.0 + bin_size_ * 1e-6, i));
}
else
{
return ((static_cast<float>(i) - offset_) * bin_size_);
}
}
/// get the bin size
inline float getBinSize() const { return bin_size_; }
/// get the bin spread
inline size_t getBinSpread() const { return bin_spread_; }
/// immutable access to the bin container
const SparseVectorType* getBins() const;
/// mutable access to the bin container
SparseVectorType* getBins();
/// return offset
inline float getOffset() const { return offset_; }
/// immutable access to precursors
const std::vector<Precursor>& getPrecursors() const;
/// mutable access to precursors
std::vector<Precursor>& getPrecursors();
/// Check if two BinnedSpectrum objects have equally sized bins and offset.
// returns true if bin size, unit and offset are equal, otherwise false
static bool isCompatible(const BinnedSpectrum& a, const BinnedSpectrum& b);
private:
/// the spread to left or right
UInt bin_spread_ {0};
/// the size of each bin
float bin_size_ {0};
/// absolute bin size or relative bin size
bool unit_ppm_ {false};
/// offset of bin start
float offset_ {0};
/// bins
SparseVectorType* bins_ {nullptr};
/// calculate binning of peak spectrum
void binSpectrum_(const PeakSpectrum& ps);
/// precursor information
std::vector<Precursor> precursors_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/KERNEL/MSSpectrum.h | .h | 24,088 | 670 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg$
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/Peak1D.h>
#include <OpenMS/METADATA/SpectrumSettings.h>
#include <OpenMS/KERNEL/RangeManager.h>
#include <OpenMS/METADATA/DataArrays.h>
#include <OpenMS/METADATA/MetaInfoDescription.h>
#include <numeric>
namespace OpenMS
{
enum class DriftTimeUnit;
/**
@brief The representation of a 1D spectrum.
It contains peak data and metadata about specific instrument settings,
acquisition settings, description of the meta values used in the peaks and precursor info
(SpectrumSettings).
Several MSSpectrum instances are contained in a peak map (MSExperiment), which is essentially
a vector of spectra with additional information about the experiment.
Precursor info from SpectrumSettings should only be used if this spectrum is a tandem-MS
spectrum. The precursor spectrum is the first spectrum in MSExperiment, that has a lower
MS-level than the current spectrum.
@note For range operations, see \ref RangeUtils "RangeUtils module"!
@ingroup Kernel
*/
class OPENMS_DLLAPI MSSpectrum final :
private std::vector<Peak1D>,
public RangeManagerContainer<RangeMZ, RangeIntensity, RangeMobility>,
public SpectrumSettings
{
public:
/// Comparator for the retention time.
struct OPENMS_DLLAPI RTLess
{
bool operator()(const MSSpectrum& a, const MSSpectrum& b) const;
};
/// Comparator for the ion mobility.
struct OPENMS_DLLAPI IMLess {
bool operator()(const MSSpectrum& a, const MSSpectrum& b) const;
};
/// Used to remember what subsets in a spectrum are sorted already to allow faster sorting of the spectrum
struct Chunk {
Size start; ///< inclusive
Size end; ///< not inclusive
bool is_sorted; ///< are the Peaks in [start, end) sorted yet?
Chunk(Size p_start, Size p_end, bool p_sorted) : start(p_start), end(p_end), is_sorted(p_sorted)
{
}
};
/**
* @brief Container for organizing and managing multiple chunks in a spectrum.
*
* This structure is used to track multiple chunks (segments) within a spectrum.
* Each chunk represents a portion of the spectrum that may or may not be sorted.
* This information is used to optimize sorting operations on spectra, particularly
* when only parts of the spectrum need to be sorted or have been modified.
*
* @see Chunk
*/
struct Chunks {
public:
Chunks(const MSSpectrum& s) : spec_(s) {}
void add(bool is_sorted)
{
chunks_.emplace_back((chunks_.empty() ? 0 : chunks_.back().end), spec_.size(), is_sorted);
}
std::vector<Chunk>& getChunks()
{
return chunks_;
}
private:
std::vector<Chunk> chunks_;
const MSSpectrum& spec_;
};
///@name Base type definitions
//@{
/// Peak type
typedef OpenMS::Peak1D PeakType;
/// Coordinate (m/z) type
typedef typename PeakType::CoordinateType CoordinateType;
/// Spectrum base type
typedef std::vector<PeakType> ContainerType;
/// RangeManager
typedef RangeManagerContainer<RangeMZ, RangeIntensity, RangeMobility> RangeManagerContainerType;
typedef RangeManager<RangeMZ, RangeIntensity, RangeMobility> RangeManagerType;
/// Float data array vector type
typedef OpenMS::DataArrays::FloatDataArray FloatDataArray ;
typedef std::vector<FloatDataArray> FloatDataArrays;
/// String data array vector type
typedef OpenMS::DataArrays::StringDataArray StringDataArray ;
typedef std::vector<StringDataArray> StringDataArrays;
/// Integer data array vector type
typedef OpenMS::DataArrays::IntegerDataArray IntegerDataArray ;
typedef std::vector<IntegerDataArray> IntegerDataArrays;
//@}
///@name Peak container iterator type definitions
//@{
/// Mutable iterator
typedef typename ContainerType::iterator Iterator;
/// Non-mutable iterator
typedef typename ContainerType::const_iterator ConstIterator;
/// Mutable reverse iterator
typedef typename ContainerType::reverse_iterator ReverseIterator;
/// Non-mutable reverse iterator
typedef typename ContainerType::const_reverse_iterator ConstReverseIterator;
//@}
///@name Export methods from std::vector<Peak1D>
//@{
using ContainerType::operator[];
using ContainerType::begin;
using ContainerType::rbegin;
using ContainerType::end;
using ContainerType::rend;
using ContainerType::cbegin;
using ContainerType::cend;
using ContainerType::resize;
using ContainerType::size;
using ContainerType::push_back;
using ContainerType::emplace_back;
using ContainerType::pop_back;
using ContainerType::empty;
using ContainerType::front;
using ContainerType::back;
using ContainerType::reserve;
using ContainerType::insert;
using ContainerType::erase;
using ContainerType::swap;
using ContainerType::data;
using ContainerType::shrink_to_fit;
using typename ContainerType::iterator;
using typename ContainerType::const_iterator;
using typename ContainerType::size_type;
using typename ContainerType::value_type;
using typename ContainerType::reference;
using typename ContainerType::const_reference;
using typename ContainerType::pointer;
using typename ContainerType::difference_type;
//@}
/// Constructor
MSSpectrum();
/// Constructor from a list of Peak1D, e.g. MSSpectrum spec{ {mz1, int1}, {mz2, int2}, ... };
MSSpectrum(const std::initializer_list<Peak1D>& init);
/// Copy constructor
MSSpectrum(const MSSpectrum& source);
/// Move constructor
MSSpectrum(MSSpectrum&&) = default;
/// Destructor
~MSSpectrum() = default;
/// Assignment operator
MSSpectrum& operator=(const MSSpectrum& source);
/// Move assignment operator
MSSpectrum& operator=(MSSpectrum&&) & = default;
/// Assignment operator
MSSpectrum& operator=(const SpectrumSettings & source);
/// Equality operator
bool operator==(const MSSpectrum& rhs) const;
/// Equality operator
bool operator!=(const MSSpectrum& rhs) const
{
return !(operator==(rhs));
}
// Docu in base class (RangeManager)
void updateRanges() override;
///@name Accessors for meta information
///@{
/// Returns the absolute retention time (in seconds)
double getRT() const;
/// Sets the absolute retention time (in seconds)
void setRT(double rt);
/**
@brief Returns the ion mobility drift time (IMTypes::DRIFTTIME_NOT_SET means it is not set)
@note Drift times may be stored directly as an attribute of the spectrum
(if they relate to the spectrum as a whole). In case of ion mobility
spectra, the drift time of the spectrum will always be set here while the
drift times attribute in the Precursor class may often be unpopulated.
*/
double getDriftTime() const;
/**
@brief Sets the ion mobility drift time
*/
void setDriftTime(double dt);
/**
@brief Returns the ion mobility drift time unit
*/
DriftTimeUnit getDriftTimeUnit() const;
/// returns the ion mobility drift time unit as string
String getDriftTimeUnitAsString() const;
/**
@brief Sets the ion mobility drift time unit
*/
void setDriftTimeUnit(DriftTimeUnit dt);
/**
@brief Returns the MS level.
For survey scans this is 1, for MS/MS scans 2, ...
*/
UInt getMSLevel() const;
/// Sets the MS level.
void setMSLevel(UInt ms_level);
/// Returns the name
const String& getName() const;
/// Sets the name
void setName(const String& name);
//@}
/**
@name Peak data array methods
These methods are used to annotate each peak in a spectrum with meta information.
It is an intermediate way between storing the information in the peak's MetaInfoInterface
and deriving a new peak type with members for this information.
These statements should help you chose which approach to use
- Access to meta info arrays is slower than to a member variable
- Access to meta info arrays is faster than to a %MetaInfoInterface
- Meta info arrays are stored when using mzML format for storing
*/
//@{
/// Returns a const reference to the float meta data arrays
const FloatDataArrays& getFloatDataArrays() const;
/// Returns a mutable reference to the float meta data arrays
FloatDataArrays& getFloatDataArrays()
{
return float_data_arrays_;
}
/// Sets the float meta data arrays
void setFloatDataArrays(const FloatDataArrays& fda);
/// Returns a const reference to the string meta data arrays
const StringDataArrays& getStringDataArrays() const;
/// Returns a mutable reference to the string meta data arrays
StringDataArrays& getStringDataArrays();
/// Sets the string meta data arrays
void setStringDataArrays(const StringDataArrays& sda);
/// Returns a const reference to the integer meta data arrays
const IntegerDataArrays& getIntegerDataArrays() const;
/// Returns a mutable reference to the integer meta data arrays
IntegerDataArrays& getIntegerDataArrays();
/// Sets the integer meta data arrays
void setIntegerDataArrays(const IntegerDataArrays& ida);
//@}
///@name Sorting peaks
//@{
/**
@brief Lexicographically sorts the peaks by their intensity.
Sorts the peaks according to ascending intensity. Meta data arrays will be sorted accordingly.
*/
void sortByIntensity(bool reverse = false);
/**
@brief Lexicographically sorts the peaks by their position.
The spectrum is sorted with respect to position. Meta data arrays will be sorted accordingly.
*/
void sortByPosition();
/**
@brief Sorts the m/z peaks by their ion mobility value (and the accociated IM data arrays accordingly).
Requires a binary data array which is a child of 'MS:1002893 ! ion mobility array' (see getIMData())
@throws Exception::MissingInformation if containsIMData() returns false
*/
void sortByIonMobility();
/**
@brief Sort the spectrum, but uses the fact, that certain chunks are presorted
@param[in] chunks a Chunk is an object that contains the start and end of a sublist of peaks in the spectrum, that is or isn't sorted yet (is_sorted member)
*/
void sortByPositionPresorted(const std::vector<Chunk>& chunks);
/// Checks if all peaks are sorted with respect to ascending m/z
bool isSorted() const;
/// Checks if m/z peaks are sorted by their associated ion mobility value.
/// Requires a binary data array which is a child of 'MS:1002893 ! ion mobility array' (see getIMData())
///
/// @throws Exception::MissingInformation if containsIMData() returns false
bool isSortedByIM() const;
/// Checks if container is sorted by a certain user-defined property.
/// You can pass any lambda function with <tt>[](Size index_1, Size index_2) --> bool</tt>
/// which given two indices into MSSpectrum (either for peaks or data arrays) returns a weak-ordering.
/// (you need to capture the MSSpectrum in the lambda and operate on it, based on the indices)
template<class Predicate>
bool isSorted(const Predicate& lambda) const
{
auto value_2_index_wrapper = [this, &lambda](const value_type& value1, const value_type& value2) {
// translate values into indices (this relies on no copies being made!)
const Size index1 = (&value1) - (&this->front());
const Size index2 = (&value2) - (&this->front());
// just make sure the pointers above are actually pointing to a Peak inside our container
assert(index1 < this->size());
assert(index2 < this->size());
return lambda(index1, index2);
};
return std::is_sorted(this->begin(), this->end(), value_2_index_wrapper);
}
/// Sort by a user-defined property
/// You can pass any @p lambda function with <tt>[](Size index_1, Size index_2) --> bool</tt>
/// which given two indices into MSSpectrum (either for peaks or data arrays) returns a weak-ordering.
/// (you need to capture the MSSpectrum in the lambda and operate on it, based on the indices)
template<class Predicate>
void sort(const Predicate& lambda)
{
std::vector<Size> indices(this->size());
std::iota(indices.begin(), indices.end(), 0);
std::stable_sort(indices.begin(), indices.end(), lambda);
select(indices);
}
//@}
///@name Searching a peak or peak range
///@{
/**
@brief Binary search for the peak nearest to a specific m/z
@param[in] mz The searched for mass-to-charge ratio searched
@return Returns the index of the peak.
@note Make sure the spectrum is sorted with respect to m/z! Otherwise the result is undefined.
@exception Exception::Precondition is thrown if the spectrum is empty (not only in debug mode)
*/
Size findNearest(CoordinateType mz) const;
/**
@brief Binary search for the peak nearest to a specific m/z given a +/- tolerance windows in Th
@param[in] mz The searched for mass-to-charge ratio searched
@param[in] tolerance The non-negative tolerance applied to both sides of mz
@return Returns the index of the peak or -1 if no peak present in tolerance window or if spectrum is empty
@note Make sure the spectrum is sorted with respect to m/z! Otherwise the result is undefined.
@note Peaks exactly on borders are considered in tolerance window.
*/
Int findNearest(CoordinateType mz, CoordinateType tolerance) const;
/**
@brief Search for the peak nearest to a specific m/z given two +/- tolerance windows in Th
@param[in] mz The searched for mass-to-charge ratio searched
@param[in] tolerance_left The non-negative tolerance applied left of mz
@param[in] tolerance_right The non-negative tolerance applied right of mz
@return Returns the index of the peak or -1 if no peak present in tolerance window or if spectrum is empty
@note Make sure the spectrum is sorted with respect to m/z! Otherwise the result is undefined.
@note Peaks exactly on borders are considered in tolerance window.
@note Search for the left border is done using a binary search followed by a linear scan
*/
Int findNearest(CoordinateType mz, CoordinateType tolerance_left, CoordinateType tolerance_right) const;
/**
@brief Search for the peak with highest intensity among the peaks near to a specific m/z given two +/- tolerance windows in Th
@param[in] mz The searched for mass-to-charge ratio searched
@param[in] tolerance_left The non-negative tolerance applied left of mz
@param[in] tolerance_right The non-negative tolerance applied right of mz
@return Returns the index of the peak or -1 if no peak present in tolerance window or if spectrum is empty
@note Make sure the spectrum is sorted with respect to m/z! Otherwise the result is undefined.
@note Peaks exactly on borders are considered in tolerance window.
*/
Int findHighestInWindow(CoordinateType mz, CoordinateType tolerance_left, CoordinateType tolerance_right) const;
/**
@brief Binary search for peak range begin
@note Make sure the spectrum is sorted with respect to m/z! Otherwise the result is undefined.
*/
Iterator MZBegin(CoordinateType mz);
/**
@brief Binary search for peak range begin
@note Make sure the spectrum is sorted with respect to m/z! Otherwise the result is undefined.
*/
Iterator MZBegin(Iterator begin, CoordinateType mz, Iterator end);
/**
@brief Binary search for peak range end (returns the past-the-end iterator)
@note Make sure the spectrum is sorted with respect to m/z. Otherwise the result is undefined.
*/
Iterator MZEnd(CoordinateType mz);
/**
@brief Binary search for peak range end (returns the past-the-end iterator)
@note Make sure the spectrum is sorted with respect to m/z. Otherwise the result is undefined.
*/
Iterator MZEnd(Iterator begin, CoordinateType mz, Iterator end);
/**
@brief Binary search for peak range begin
@note Make sure the spectrum is sorted with respect to m/z! Otherwise the result is undefined.
*/
ConstIterator MZBegin(CoordinateType mz) const;
/**
@brief Binary search for peak range begin
@note Make sure the spectrum is sorted with respect to m/z! Otherwise the result is undefined.
*/
ConstIterator MZBegin(ConstIterator begin, CoordinateType mz, ConstIterator end) const;
/**
@brief Binary search for peak range end (returns the past-the-end iterator)
@note Make sure the spectrum is sorted with respect to m/z. Otherwise the result is undefined.
*/
ConstIterator MZEnd(CoordinateType mz) const;
/**
@brief Binary search for peak range end (returns the past-the-end iterator)
@note Make sure the spectrum is sorted with respect to m/z. Otherwise the result is undefined.
*/
ConstIterator MZEnd(ConstIterator begin, CoordinateType mz, ConstIterator end) const;
/**
@brief Binary search for peak range begin
Alias for MZBegin()
@note Make sure the spectrum is sorted with respect to m/z! Otherwise the result is undefined.
*/
Iterator PosBegin(CoordinateType mz);
/**
@brief Binary search for peak range begin
Alias for MZBegin()
@note Make sure the spectrum is sorted with respect to m/z! Otherwise the result is undefined.
*/
Iterator PosBegin(Iterator begin, CoordinateType mz, Iterator end);
/**
@brief Binary search for peak range begin
Alias for MZBegin()
@note Make sure the spectrum is sorted with respect to m/z! Otherwise the result is undefined.
*/
ConstIterator PosBegin(CoordinateType mz) const;
/**
@brief Binary search for peak range begin
Alias for MZBegin()
@note Make sure the spectrum is sorted with respect to m/z! Otherwise the result is undefined.
*/
ConstIterator PosBegin(ConstIterator begin, CoordinateType mz, ConstIterator end) const;
/**
@brief Binary search for peak range end (returns the past-the-end iterator)
Alias for MZEnd()
@note Make sure the spectrum is sorted with respect to m/z. Otherwise the result is undefined.
*/
Iterator PosEnd(CoordinateType mz);
/**
@brief Binary search for peak range end (returns the past-the-end iterator)
Alias for MZEnd()
@note Make sure the spectrum is sorted with respect to m/z. Otherwise the result is undefined.
*/
Iterator PosEnd(Iterator begin, CoordinateType mz, Iterator end);
/**
@brief Binary search for peak range end (returns the past-the-end iterator)
Alias for MZEnd()
@note Make sure the spectrum is sorted with respect to m/z. Otherwise the result is undefined.
*/
ConstIterator PosEnd(CoordinateType mz) const;
/**
@brief Binary search for peak range end (returns the past-the-end iterator)
Alias for MZEnd()
@note Make sure the spectrum is sorted with respect to m/z. Otherwise the result is undefined.
*/
ConstIterator PosEnd(ConstIterator begin, CoordinateType mz, ConstIterator end) const;
/// do the names of internal float metadata arrays contain any hint of ion mobility data, i.e. they are a child of 'MS:1002893 ! ion mobility array'?
/// (for spectra which represent an IM-frame)
bool containsIMData() const;
/**
@brief Get the Ion mobility data array's @p index and its associated @p unit
This only works for spectra which represent an IM-frame, i.e. they have a float metadata array which is a child of 'MS:1002893 ! ion mobility array'?
Check this first by using `containsIMData()`.
@throws Exception::MissingInformation if IM data is not present
*/
std::pair<Size, DriftTimeUnit> getIMData() const;
/**
@brief Get the spectrum's ion mobility data (if exists) and its associated unit as a pair of {unit, data}
This only works for spectra which represent an IM-frame, i.e. they have a float metadata array which is a child of 'MS:1002893 ! ion mobility array'.
If this is not present, this returns {DriftTimeUnit::NONE, {}}
*/
std::pair<DriftTimeUnit, std::vector<float>> maybeGetIMData() const;
//@}
/**
@brief Clears all data and meta data
Will delete (clear) all peaks contained in the spectrum as well as any
associated data arrays (FloatDataArrays, IntegerDataArrays,
StringDataArrays) by default. If @em clear_meta_data is @em true, then
also all meta data (such as RT, drift time, ms level etc) will be
deleted.
@param[in] clear_meta_data If @em true, all meta data is cleared in addition to the data.
*/
void clear(bool clear_meta_data);
/*
@brief Select a (subset of) spectrum and its data_arrays, only retaining the indices given in @p indices
@param[in] indices Vector of indices to keep
@return Reference to this MSSpectrum
*/
MSSpectrum& select(const std::vector<Size>& indices);
/**
@brief Determine if spectrum is profile or centroided using up to three layers of information.
First, the SpectrumSettings are inquired and the type is returned unless it is unknown.
Second, all data processing entries are searched for a centroiding step.
If that is unsuccessful as well and @p query_data is true, the data is fed into PeakTypeEstimator().
@param [query_data] If SpectrumSettings and DataProcessing information are not sufficient, should the data be queried? (potentially expensive)
@return The spectrum type (centroided, profile or unknown)
*/
SpectrumSettings::SpectrumType getType(const bool query_data) const;
using SpectrumSettings::getType; // expose base class function
/// return the peak with the highest intensity. If the peak is not unique, the first peak in the container is returned.
/// The function works correctly, even if the spectrum is unsorted.
ConstIterator getBasePeak() const;
/// return the peak with the highest intensity. If the peak is not unique, the first peak in the container is returned.
/// The function works correctly, even if the spectrum is unsorted.
Iterator getBasePeak();
/// compute the total ion count (sum of all peak intensities)
PeakType::IntensityType calculateTIC() const;
protected:
/// Retention time
double retention_time_ = -1;
/// Drift time
double drift_time_ = -1;
/// Drift time unit
DriftTimeUnit drift_time_unit_ = DriftTimeUnit::NONE;
/// MS level
UInt ms_level_ = 1;
/// Name
String name_;
/// Float data arrays
FloatDataArrays float_data_arrays_;
/// String data arrays
StringDataArrays string_data_arrays_;
/// Integer data arrays
IntegerDataArrays integer_data_arrays_;
};
inline std::ostream& operator<<(std::ostream& os, const MSSpectrum& spec)
{
os << "-- MSSPECTRUM BEGIN --" << std::endl;
// spectrum settings
os << static_cast<const SpectrumSettings&>(spec);
// peaklist
for (MSSpectrum::ConstIterator it = spec.begin(); it != spec.end(); ++it)
{
os << *it << std::endl;
}
os << "-- MSSPECTRUM END --" << std::endl;
return os;
}
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/KERNEL/ConsensusMap.h | .h | 13,292 | 378 | // 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/UniqueIdInterface.h>
#include <OpenMS/CONCEPT/UniqueIdIndexer.h>
#include <OpenMS/KERNEL/RangeManager.h>
#include <OpenMS/KERNEL/ConsensusFeature.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/METADATA/DocumentIdentifier.h>
#include <OpenMS/METADATA/MetaInfoInterface.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/ID/IdentificationData.h>
#include <OpenMS/CONCEPT/Types.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/DATASTRUCTURES/ExposedVector.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/DATASTRUCTURES/Utils/MapUtilities.h>
#include <OpenMS/OpenMSConfig.h>
#include <map>
#include <vector>
#include <iosfwd>
namespace OpenMS
{
class PeptideIdentification;
class PeptideHit;
class ProteinIdentification;
class DataProcessing;
namespace Logger
{
class LogStream;
}
/**
@brief A container for consensus elements.
A %ConsensusMap is a container holding 2-dimensional consensus elements
(ConsensusFeature) which in turn represent analytes that have been
quantified across multiple LC-MS/MS experiments. Each analyte in a
ConsensusFeature is linked to its original LC-MS/MS run, the links are
maintained by the ConsensusMap class.
The map is implemented as a vector of elements of type ConsensusFeature.
To be consistent, all maps who are referenced by ConsensusFeature objects
(through a unique id) need to be registered in this class.
@ingroup Kernel
*/
class OPENMS_DLLAPI ConsensusMap :
public MetaInfoInterface,
public RangeManagerContainer<RangeRT, RangeMZ, RangeIntensity>,
public DocumentIdentifier,
public ExposedVector<ConsensusFeature>,
public UniqueIdInterface,
public UniqueIdIndexer<ConsensusMap>,
public MapUtilities<ConsensusMap>
{
public:
EXPOSED_VECTOR_INTERFACE(ConsensusFeature)
enum class SplitMeta
{
DISCARD, ///< do not copy any meta values
COPY_ALL, ///< copy all meta values to all feature maps
COPY_FIRST ///< copy all meta values to first feature map
};
/// Description of the columns in a consensus map
struct ColumnHeader :
public MetaInfoInterface
{
/// Default constructor
ColumnHeader() = default;
/// Copy constructor
ColumnHeader(const ColumnHeader&) = default;
/// Copy assignment
ColumnHeader& operator=(const ColumnHeader&) = default;
/// File name of the mzML file
String filename;
/// Label e.g. 'heavy' and 'light' for ICAT, or 'sample1' and 'sample2' for label-free quantitation
String label;
/// @brief Number of elements (features, peaks, ...).
/// This is e.g. used to check for correct element indices when writing a consensus map TODO fix that
Size size = 0;
/// Unique id of the file
UInt64 unique_id = UniqueIdInterface::INVALID;
unsigned getLabelAsUInt(const String& experiment_type) const;
};
///@name Type definitions
//@{
typedef ConsensusFeature FeatureType;
typedef std::map<UInt64, ColumnHeader> ColumnHeaders;
typedef RangeManagerContainer<RangeRT, RangeMZ, RangeIntensity> RangeManagerContainerType;
typedef RangeManager<RangeRT, RangeMZ, RangeIntensity> RangeManagerType;
typedef iterator Iterator;
typedef const_iterator ConstIterator;
typedef reverse_iterator ReverseIterator;
typedef const_reverse_iterator ConstReverseIterator;
//@}
/// Default constructor
ConsensusMap();
/// Copy constructor
ConsensusMap(const ConsensusMap& source);
/// Move constructor
ConsensusMap(ConsensusMap&& source);
/// Destructor
~ConsensusMap() override;
/// Creates a ConsensusMap with n elements
explicit ConsensusMap(size_type n);
/// Assignment operator
ConsensusMap& operator=(const ConsensusMap& source);
/// MoveAssignment operator
ConsensusMap& operator=(ConsensusMap&& source) = default;
/**
@brief Add consensus map entries as new rows.
Consensus elements are merged into one container, simply by appending.
The number of columns (maximum map index) stays the same.
@param[in] rhs The consensus map to be merged.
*/
ConsensusMap& appendRows(const ConsensusMap& rhs);
/**
@brief Add consensus map entries as new columns.
The number of columns (maximum map index) is the sum of both maps.
@param[in] rhs The consensus map to be merged.
*/
ConsensusMap& appendColumns(const ConsensusMap& rhs);
/**
@brief Clears all data and meta data
@param[in] clear_meta_data If @em true, all meta data is cleared in addition to the data.
*/
void clear(bool clear_meta_data = true);
/// Non-mutable access to the file descriptions
const ColumnHeaders& getColumnHeaders() const;
/// Mutable access to the file descriptions
ColumnHeaders& getColumnHeaders();
/// Mutable access to the file descriptions
void setColumnHeaders(const ColumnHeaders& column_description);
/// Non-mutable access to the experiment type
const String& getExperimentType() const;
/// Mutable access to the experiment type
void setExperimentType(const String& experiment_type);
/**
@name Sorting.
These specialized sorting methods are supported in addition to the standard sorting methods
of std::vector. All use stable sorting.
*/
//@{
/// Sorts the peaks according to ascending intensity.
void sortByIntensity(bool reverse = false);
/// Sorts the peaks to RT position.
void sortByRT();
/// Sorts the peaks to m/z position.
void sortByMZ();
/// Lexicographically sorts the peaks by their position (First RT then m/z).
void sortByPosition();
/// Sorts the peaks according to ascending quality.
void sortByQuality(bool reverse = false);
/// Sorts with respect to the size (number of elements)
void sortBySize();
/// Sorts with respect to the sets of maps covered by the consensus features (lexicographically).
void sortByMaps();
/// Sorts PeptideIdentifications of consensus features with respect to their map index.
void sortPeptideIdentificationsByMapIndex();
//@}
// Docu in base class
void updateRanges() override;
/// Swaps the content of this map with the content of @p from
void swap(ConsensusMap& from);
/// non-mutable access to the protein identifications
const std::vector<ProteinIdentification>& getProteinIdentifications() const;
/// mutable access to the protein identifications
std::vector<ProteinIdentification>& getProteinIdentifications();
/// sets the protein identifications
void setProteinIdentifications(const std::vector<ProteinIdentification>& protein_identifications);
/// sets the protein identifications by moving
void setProteinIdentifications(std::vector<ProteinIdentification>&& protein_identifications);
/// non-mutable access to the unassigned peptide identifications
const PeptideIdentificationList& getUnassignedPeptideIdentifications() const;
/// mutable access to the unassigned peptide identifications
PeptideIdentificationList& getUnassignedPeptideIdentifications();
/// sets the unassigned peptide identifications
void setUnassignedPeptideIdentifications(const PeptideIdentificationList& unassigned_peptide_identifications);
/// returns a const reference to the description of the applied data processing
const std::vector<DataProcessing>& getDataProcessing() const;
/// returns a mutable reference to the description of the applied data processing
std::vector<DataProcessing>& getDataProcessing();
/// sets the description of the applied data processing
void setDataProcessing(const std::vector<DataProcessing>& processing_method);
/// set the file paths to the primary MS run (stored in ColumnHeaders)
void setPrimaryMSRunPath(const StringList& s);
/// set the file path to the primary MS run using the mzML annotated in the MSExperiment @p e.
/// If it doesn't exist, fallback to @p s.
/// @param[in] s Fallback if @p e does not have a primary MS runpath
/// @param[in,out] e Use primary MS runpath from this mzML file
void setPrimaryMSRunPath(const StringList& s, MSExperiment & e);
/// returns the MS run path (stored in ColumnHeaders)
void getPrimaryMSRunPath(StringList& toFill) const;
/// Equality operator
bool operator==(const ConsensusMap& rhs) const;
/// Equality operator
bool operator!=(const ConsensusMap& rhs) const;
/**
@brief Applies a member function of Type to the container itself and all consensus features.
The returned values are accumulated.
<b>Example:</b> The following will print the number of features with invalid unique ids
(plus 1 if the container has an invalid UID as well):
@code
ConsensusMap cm;
(...)
std::cout << cm.applyMemberFunction(&UniqueIdInterface::hasInvalidUniqueId) << std::endl;
@endcode
See e.g. UniqueIdInterface for what else can be done this way.
*/
template <typename Type>
Size applyMemberFunction(Size (Type::* member_function)())
{
Size assignments = 0;
assignments += ((*this).*member_function)();
for (Iterator iter = this->begin(); iter != this->end(); ++iter)
{
assignments += ((*iter).*member_function)();
}
return assignments;
}
/// The "const" variant.
template <typename Type>
Size applyMemberFunction(Size (Type::* member_function)() const) const
{
Size assignments = 0;
assignments += ((*this).*member_function)();
for (ConstIterator iter = this->begin(); iter != this->end(); ++iter)
{
assignments += ((*iter).*member_function)();
}
return assignments;
}
/**
@brief checks if the given maps are unique and all FeatureHandles actually refer to a registered map
To avoid inconsistencies in map IDs and make sure the maps are unique in terms of name+label
If you want some verbose output, provide a stream.
@note Alternative to this method we could check the features while they are added to the map directly, but
- currently we can't because the interface is not designed for this (derived from std::vector, no encapsulation)
- we should restrict the user to first fill the list of maps, before any datapoints can be inserted
*/
bool isMapConsistent(Logger::LogStream* stream = nullptr) const;
/**
@brief splits ConsensusMap into its original FeatureMaps
If the ConsensusMap originated from some number of FeatureMaps, those are reconstructed with the information
provided by the map index.
If the ConsensusMap originated from the IsobaricAnalyzer, only Features are separated. All PeptideIdentifications
(assigned and unassigned) are added to the first FeatureMap.
MetaValues of ConsensusFeatures can be copied to all FeatureMaps, just to the first or they can be ignored.
@param[in] mode Decide what to do with the MetaValues annotated at the ConsensusFeatures.
@return FeatureMaps
*/
std::vector<FeatureMap> split(SplitMeta mode = SplitMeta::DISCARD) const;
/// @name Functions for dealing with identifications in new format
///@{
/*!
@brief Return observation matches (e.g. PSMs) from the identification data that are not assigned to any feature in the map
Only top-level features are considered, i.e. no subordinates.
@see BaseFeature::getIDMatches()
*/
std::set<IdentificationData::ObservationMatchRef> getUnassignedIDMatches() const;
/// Immutable access to the contained identification data
const IdentificationData& getIdentificationData() const;
/// Mutable access to the contained identification data
IdentificationData& getIdentificationData();
///@}
protected:
/// Map from index to file description
ColumnHeaders column_description_;
/// type of experiment (label-free, labeled_MS1, labeled_MS2)
String experiment_type_ = "label-free";
/// protein identifications
std::vector<ProteinIdentification> protein_identifications_;
/// unassigned peptide identifications (without feature)
PeptideIdentificationList unassigned_peptide_identifications_;
/// applied data processing
std::vector<DataProcessing> data_processing_;
/// general identification results (peptides/proteins, RNA, compounds)
IdentificationData id_data_;
};
///Print the contents of a ConsensusMap to a stream.
OPENMS_DLLAPI std::ostream& operator<<(std::ostream& os, const ConsensusMap& cons_map);
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/KERNEL/DimMapper.h | .h | 29,165 | 972 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/CONCEPT/CommonEnums.h>
#include <OpenMS/DATASTRUCTURES/DPosition.h>
#include <OpenMS/DATASTRUCTURES/DRange.h>
#include <OpenMS/KERNEL/BaseFeature.h>
#include <OpenMS/KERNEL/MobilityPeak2D.h>
#include <OpenMS/KERNEL/Mobilogram.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/KERNEL/MSSpectrum.h>
#include <OpenMS/KERNEL/Peak1D.h>
#include <OpenMS/KERNEL/Peak2D.h>
#include <OpenMS/KERNEL/RangeManager.h>
#include <array>
#include <memory>
namespace OpenMS
{
/**
@brief A base class for a dimension which represents a certain unit (e.g. RT or m/z).
Derived classes implement virtual functions, which receive a well-defined data type,
e.g. a Feature, and return the appropriate value for their dimension (the DimRT class would return the RT of the feature).
This makes it possible to extract dimensions using a runtime configuration of DimBase instances.
Very useful when mapping units (RT, m/z) to axis when plotting etc.
The reverse (X-Y coordinates to data type, e.g. Peak1D) is also possible using 'from...()' methods
*/
class OPENMS_DLLAPI DimBase
{
public:
using ValueType = double;
using ValueTypes = std::vector<ValueType>;
/// No default c'tor
DimBase() = delete;
/// Custom c'tor with unit
DimBase(DIM_UNIT unit) :
unit_(unit)
{}
/// Assignment operator
DimBase& operator=(const DimBase& rhs) = default;
/// D'tor (needs to be virtual; we are holding pointers to base in DimMapper)
virtual ~DimBase() noexcept = default;
/// Equality
bool operator==(const DimBase& rhs) const
{
return unit_ == rhs.unit_;
}
/// Copy derived objects to avoid slicing when dealing with pointers to DimBase
virtual std::unique_ptr<DimBase> clone() const = 0;
virtual ValueType map(const Peak1D& p) const = 0;
virtual ValueType map(const Peak2D& p) const = 0;
virtual ValueType map(const ChromatogramPeak& p) const = 0;
virtual ValueType map(const MSExperiment::ConstAreaIterator& it) const = 0;
virtual ValueType map(const MobilityPeak1D& p) const = 0;
virtual ValueType map(const MobilityPeak2D& p) const = 0;
/// obtain value from a certain point in a spectrum
virtual ValueType map(const MSSpectrum& spec, const Size index) const = 0;
/// obtain value from a certain point in a chromatogram
virtual ValueType map(const MSChromatogram& chrom, const Size index) const = 0;
/// obtain value from a certain point in a mobilogram
virtual ValueType map(const Mobilogram& mb, const Size index) const = 0;
/// obtain vector of same length as @p spec; one element per peak
/// @throw Exception::InvalidRange if elements do not support the dimension
virtual ValueTypes map(const MSSpectrum& spec) const = 0;
/// obtain vector of same length as @p spec; one element per peak
/// @throw Exception::InvalidRange if elements do not support the dimension
virtual ValueTypes map(const MSChromatogram& chrom) const = 0;
virtual ValueType map(const BaseFeature& bf) const = 0;
virtual ValueType map(const PeptideIdentification& pi) const = 0;
/// Return the min/max (range) for a certain dimension
virtual RangeBase map(const RangeAllType& rm) const = 0;
/// Return the min/max (range) for a certain dimension (i.e. a reference to the base class of @p rm)
virtual RangeBase& map(RangeAllType& rm) const = 0;
/// Set the min/max (range) in @p out for a certain dimension
virtual void setRange(const RangeBase& in, RangeAllType& out) const = 0;
// from XY to a type
/// set the dimension of a Peak1D
virtual void fromXY(const ValueType in, Peak1D& p) const = 0;
/// set the dimension of a ChromatogramPeak
virtual void fromXY(const ValueType in, ChromatogramPeak& p) const = 0;
/// set the dimension of a MobilityPeak1D
virtual void fromXY(const ValueType in, MobilityPeak1D& p) const = 0;
/// set the dimension of a MobilityPeak2D
virtual void fromXY(const ValueType in, MobilityPeak2D& p) const = 0;
/// Name of the dimension, e.g. 'RT [s]'
std::string_view getDimName() const
{
return DIM_NAMES[(int)unit_];
}
/// Name of the dimension, e.g. 'RT'
std::string_view getDimNameShort() const
{
return DIM_NAMES_SHORT[(int)unit_];
}
/// The unit of the dimension
DIM_UNIT getUnit() const
{
return unit_;
}
/**
* \brief Creates a short string representation with "UNIT: value", where value has a predefined precision (see valuePrecision())
* \param value The value of this Dim to format
* \return A formatted string, e.g. "RT: 45.32"
*/
String formattedValue(const ValueType value) const;
/// like formattedValue() but with a custom unit prefix instead of the default one for the dim, e.g. "myText: 45.32"
String formattedValue(ValueType value, const String& prefix) const;
/// return the recommended precision for the current unit (2 digits for RT, 8 for m/z, etc)
int valuePrecision() const;
protected:
DIM_UNIT unit_; ///< the unit of this dimension
};
/**
@brief Dimension implementation for retention time values.
This class implements the DimBase interface for the retention time dimension.
It provides methods to access RT values from various data structures and
convert between RT values and generic dimension values.
@see DimBase
@ingroup Kernel
*/
class OPENMS_DLLAPI DimRT final : public DimBase
{
public:
DimRT() : DimBase(DIM_UNIT::RT) {}
std::unique_ptr<DimBase> clone() const override
{
return std::make_unique<DimRT>();
}
ValueType map(const Peak1D&) const override
{
throw Exception::InvalidRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
ValueType map(const Peak2D& p) const override
{
return p.getRT();
}
ValueType map(const ChromatogramPeak& p) const override
{
return p.getRT();
}
ValueType map(const MSSpectrum& spec, const Size /*index*/) const override
{
return spec.getRT();
}
ValueType map(const MSChromatogram& chrom, const Size index) const override
{
return chrom[index].getRT();
}
ValueType map(const Mobilogram& mb, const Size /*index*/) const override
{
return mb.getRT();
}
ValueTypes map(const MSSpectrum&) const override
{
throw Exception::InvalidRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
ValueTypes map(const MSChromatogram& chrom) const override
{
ValueTypes res;
res.reserve(chrom.size());
for (const auto& p : chrom)
{
res.push_back(p.getRT());
}
return res;
}
ValueType map(const MSExperiment::ConstAreaIterator& it) const override
{
return it.getRT();
}
ValueType map(const MobilityPeak1D&) const override
{
throw Exception::InvalidRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
ValueType map(const MobilityPeak2D&) const override
{
throw Exception::InvalidRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
ValueType map(const BaseFeature& bf) const override
{
return bf.getRT();
}
ValueType map(const PeptideIdentification& pi) const override
{
return pi.getRT();
}
RangeBase map(const RangeAllType& rm) const override
{
return rm.getRangeForDim(MSDim::RT);
}
RangeBase& map(RangeAllType& rm) const override
{
return rm.getRangeForDim(MSDim::RT);
}
void setRange(const RangeBase& in, RangeAllType& out) const override
{
out.RangeRT::operator=(in);
}
/// set the RT of a Peak1D (throws)
void fromXY(const ValueType, Peak1D&) const override
{
throw Exception::InvalidRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
/// set the RT of a ChromatogramPeak
void fromXY(const ValueType in, ChromatogramPeak& p) const override
{
p.setRT(in);
}
/// set the RT of a MobilityPeak1D (throws)
void fromXY(const ValueType, MobilityPeak1D&) const override
{
throw Exception::InvalidRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
/// set the RT of a MobilityPeak2D (throws)
void fromXY(const ValueType, MobilityPeak2D&) const override
{
throw Exception::InvalidRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
};
/**
@brief Dimension implementation for m/z values.
This class implements the DimBase interface for the mass-to-charge ratio dimension.
It provides methods to access m/z values from various data structures and
convert between m/z values and generic dimension values.
@see DimBase
@ingroup Kernel
*/
class OPENMS_DLLAPI DimMZ final : public DimBase
{
public:
DimMZ() : DimBase(DIM_UNIT::MZ) {};
std::unique_ptr<DimBase> clone() const override
{
return std::make_unique<DimMZ>();
}
ValueType map(const Peak1D& p) const override
{
return p.getMZ();
}
ValueType map(const Peak2D& p) const override
{
return p.getMZ();
}
ValueType map(const ChromatogramPeak&) const override
{
throw Exception::InvalidRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
ValueType map(const MSExperiment::ConstAreaIterator& it) const override
{
return it->getMZ();
}
ValueType map(const MobilityPeak1D&) const override
{
throw Exception::InvalidRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
ValueType map(const MobilityPeak2D& p) const override
{
return p.getMZ();
}
ValueType map(const MSSpectrum& spec, const Size index) const override
{
return spec[index].getMZ();
}
ValueType map(const MSChromatogram& chrom, const Size /*index*/) const override
{
return chrom.getPrecursor().getMZ();
}
ValueType map(const Mobilogram& /*mb*/, const Size /*index*/) const override
{
throw Exception::InvalidRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
ValueTypes map(const MSSpectrum& spec) const override
{
ValueTypes res;
res.reserve(spec.size());
for (const auto& p : spec)
{
res.push_back(p.getMZ());
}
return res;
}
ValueTypes map(const MSChromatogram&) const override
{
throw Exception::InvalidRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
ValueType map(const BaseFeature& bf) const override
{
return bf.getMZ();
}
ValueType map(const PeptideIdentification& pi) const override
{
return pi.getMZ();
}
RangeBase map(const RangeAllType& rm) const override
{
return rm.getRangeForDim(MSDim::MZ);
}
RangeBase& map(RangeAllType& rm) const override
{
return rm.getRangeForDim(MSDim::MZ);
}
void setRange(const RangeBase& in, RangeAllType& out) const override
{
out.RangeMZ::operator=(in);
}
/// set the MZ of a Peak1D
void fromXY(const ValueType in, Peak1D& p) const override
{
p.setMZ(in);
}
/// set the MZ of a ChromatogramPeak (throws)
void fromXY(const ValueType, ChromatogramPeak&) const override
{
throw Exception::InvalidRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
/// set the MZ of a MobilityPeak1D (throws)
void fromXY(const ValueType, MobilityPeak1D&) const override
{
throw Exception::InvalidRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
/// set the MZ of a MobilityPeak2D (throws)
void fromXY(const ValueType in, MobilityPeak2D& p) const override
{
p.setMZ(in);
}
};
/**
@brief Dimension implementation for intensity values.
This class implements the DimBase interface for the intensity dimension.
It provides methods to access intensity values from various data structures and
convert between intensity values and generic dimension values.
@see DimBase
@ingroup Kernel
*/
class OPENMS_DLLAPI DimINT final : public DimBase
{
public:
DimINT() : DimBase(DIM_UNIT::INT) {};
std::unique_ptr<DimBase> clone() const override
{
return std::make_unique<DimINT>();
}
ValueType map(const Peak1D& p) const override
{
return p.getIntensity();
}
ValueType map(const Peak2D& p) const override
{
return p.getIntensity();
}
ValueType map(const ChromatogramPeak& p) const override
{
return p.getIntensity();
}
ValueType map(const MSExperiment::ConstAreaIterator& it) const override
{
return it->getIntensity();
}
ValueType map(const MobilityPeak1D& p) const override
{
return p.getIntensity();
}
ValueType map(const MobilityPeak2D& p) const override
{
return p.getIntensity();
}
ValueType map(const MSSpectrum& spec, const Size index) const override
{
return spec[index].getIntensity();
}
ValueType map(const MSChromatogram& chrom, const Size index) const override
{
return chrom[index].getIntensity();
}
ValueType map(const Mobilogram& mb, const Size index) const override
{
return mb[index].getIntensity();
}
ValueTypes map(const MSSpectrum& spec) const override
{
ValueTypes res;
res.reserve(spec.size());
for (const auto& p : spec)
{
res.push_back(p.getIntensity());
}
return res;
}
ValueTypes map(const MSChromatogram& chrom) const override
{
ValueTypes res;
res.reserve(chrom.size());
for (const auto& p : chrom)
{
res.push_back(p.getIntensity());
}
return res;
}
ValueType map(const BaseFeature& bf) const override
{
return bf.getIntensity();
}
ValueType map(const PeptideIdentification&) const override
{
throw Exception::InvalidRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
RangeBase map(const RangeAllType& rm) const override
{
return rm.getRangeForDim(MSDim::INT);
}
RangeBase& map(RangeAllType& rm) const override
{
return rm.getRangeForDim(MSDim::INT);
}
void setRange(const RangeBase& in, RangeAllType& out) const override
{
out.RangeIntensity::operator=(in);
}
/// set the intensity of a Peak1D
void fromXY(const ValueType in, Peak1D& p) const override
{
p.setIntensity(Peak1D::IntensityType(in));
}
/// set the intensity of a ChromatogramPeak
void fromXY(const ValueType in, ChromatogramPeak& p) const override
{
p.setIntensity(ChromatogramPeak::IntensityType(in));
}
/// set the intensity of a MobilityPeak1D
void fromXY(const ValueType in, MobilityPeak1D& p) const override
{
p.setIntensity(MobilityPeak1D::IntensityType(in));
}
/// set the intensity of a MobilityPeak2D
void fromXY(const ValueType in, MobilityPeak2D& p) const override
{
p.setIntensity(MobilityPeak2D::IntensityType(in));
}
};
/**
@brief Dimension implementation for ion mobility values.
This class implements the DimBase interface for the ion mobility dimension.
It provides methods to access ion mobility values from various data structures and
convert between ion mobility values and generic dimension values.
Ion mobility dimensions support different units such as FAIMS compensation voltage,
linear ion mobility spectrometry, and trapped ion mobility spectrometry.
@see DimBase
@ingroup Kernel
*/
class OPENMS_DLLAPI DimIM final : public DimBase
{
public:
DimIM(const DIM_UNIT im_unit) : DimBase(im_unit) {}
std::unique_ptr<DimBase> clone() const override
{
return std::make_unique<DimIM>(*this);
}
ValueType map(const Peak1D&) const override
{
throw Exception::InvalidRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
ValueType map(const Peak2D&) const override
{
throw Exception::InvalidRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
ValueType map(const ChromatogramPeak&) const override
{
throw Exception::InvalidRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
ValueTypes map(const MSSpectrum&) const override
{
throw Exception::InvalidRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
ValueTypes map(const MSChromatogram&) const override
{
throw Exception::InvalidRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
ValueType map(const MSExperiment::ConstAreaIterator& it) const override
{
return it.getDriftTime();
}
ValueType map(const MobilityPeak1D& p) const override
{
return p.getMobility();
}
ValueType map(const MobilityPeak2D& p) const override
{
return p.getMobility();
}
ValueType map(const MSSpectrum& spec, const Size /*index*/) const override
{
return spec.getDriftTime();
}
ValueType map(const MSChromatogram&, const Size) const override
{
throw Exception::InvalidRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
ValueType map(const Mobilogram& mb, const Size index) const override
{
return mb[index].getMobility();
}
ValueType map(const BaseFeature&) const override
{
throw Exception::InvalidRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
ValueType map(const PeptideIdentification&) const override
{
throw Exception::InvalidRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
RangeBase map(const RangeAllType& rm) const override
{
return rm.getRangeForDim(MSDim::IM);
}
RangeBase& map(RangeAllType& rm) const override
{
return rm.getRangeForDim(MSDim::IM);
}
void setRange(const RangeBase& in, RangeAllType& out) const override
{
out.RangeMobility::operator=(in);
}
/// set the IM of a Peak1D (throws)
void fromXY(const ValueType, Peak1D&) const override
{
throw Exception::InvalidRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
/// set the IM of a ChromatogramPeak (throws)
void fromXY(const ValueType, ChromatogramPeak&) const override
{
throw Exception::InvalidRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
/// set the IM of a MobilityPeak1D
void fromXY(const ValueType in, MobilityPeak1D& p) const override
{
p.setMobility(in);
}
/// set the IM of a MobilityPeak2D
void fromXY(const ValueType in, MobilityPeak2D& p) const override
{
p.setMobility(in);
}
};
/// Declare Dimensions for referencing dimensions in plotting etc
/// e.g. Point[X], Point[Y]
/// The order X,Y,Z,... is important here. Some classes rely upon it.
enum class DIM
{
X = 0,
Y = 1,
Z = 2
};
/**
@brief Allows dynamical switching (at runtime) between a dimension (RT, m/z, int, IM, etc)
and X,Y,Z coordinates. You can set either of them, and query the other.
The Mapping is stored internally.
The unit to which the X,Y,Z coordinates currently mapped onto can also be queried (useful for axis labels etc).
Use N_DIM template parameter to determine the number of axis dimensions (1-3 is currently supported). Usually 2 or 3 make sense.
@ingroup Visual
*/
template<int N_DIM>
class DimMapper
{
public:
using Point = DPosition<N_DIM, DimBase::ValueType>;
/// No default c'tor (we need dimensions)
DimMapper() = delete;
/// Custom C'tor with given dimensions to map to (the order is assumed to be X, Y, Z, ...)
DimMapper(const DIM_UNIT (&units)[N_DIM])
:dims_([&]() {
std::array<std::unique_ptr<const DimBase>, N_DIM> dims_tmp;
for (int i = 0; i < N_DIM; ++i)
{
dims_tmp[i] = create_(units[i]);
}
return dims_tmp;
}()) // immediately evaluated lambda to enable 'dims_' to be const
{
static_assert(N_DIM >= 1); // at least one dimension (X)
static_assert(N_DIM <= 3); // at most three (X, Y, Z)
}
/// Copy C'tor
DimMapper(const DimMapper& rhs) // cannot be defaulted due to unique_ptr
{
*this = rhs;
};
/// Assignment operator
DimMapper& operator=(const DimMapper& rhs) // cannot be defaulted due to unique_ptr
{
for (int i = 0; i < N_DIM; ++i) dims_[i] = rhs.dims_[i]->clone();
return *this;
};
/// Equality
bool operator==(const DimMapper& rhs) const
{
bool res {true};
for (int i = 0; i < N_DIM; ++i)
{
res &= (*dims_[i] == *rhs.dims_[i]);
}
return res;
}
/// Inequality
bool operator!=(const DimMapper& rhs) const
{
return !operator==(rhs);
}
/// convert an OpenMS datatype (such as Feature) to an N_DIM-dimensional point
template <typename T>
Point map(const T& data) const
{
Point pr;
for (int i = 0; i < N_DIM; ++i) pr[i] = dims_[i]->map(data);
return pr;
}
/// convert an OpenMS datapoint in a container (such as MSSpectrum) to an N_DIM-dimensional point
template<typename Container>
Point map(const Container& data, const Size index) const
{
Point pr;
for (int i = 0; i < N_DIM; ++i)
pr[i] = dims_[i]->map(data, index);
return pr;
}
/// Convert Range to an N_DIM-dimensional area (min and max for each dimension)
template<typename ...Ranges>
DRange<N_DIM> mapRange(const RangeManager<Ranges...>& ranges) const
{
DRange<N_DIM> res;
RangeAllType all;
all.assign(ranges);
for (int i = 0; i < N_DIM; ++i)
{
RangeBase mm = dims_[i]->map(all);
if (mm.isEmpty()) continue;
res.setDimMinMax(i, {mm.getMin(), mm.getMax()});
}
return res;
}
/// Convert an N_DIM-dimensional area (min and max for each dimension) to a Range.
/// Empty dimensions in the input @p in, will also be made empty in @p output.
/// Dimensions not contained in this DimMapper will remain untouched in @p output
template<typename... Ranges>
void fromXY(const DRange<N_DIM>& in, RangeManager<Ranges...>& output) const
{
for (int i = 0; i < N_DIM; ++i)
{
if (in.isEmpty(i))
dims_[i]->setRange(RangeBase(), output);
else
dims_[i]->setRange({in.minPosition()[i], in.maxPosition()[i]}, output);
}
}
/// Convert an N_DIM-Point to a Range.
/// The range will only span a single value in each dimension covered by this mapper.
/// Dimensions not contained in this DimMapper will remain untouched in @p output
template<typename... Ranges>
void fromXY(const Point& in, RangeManager<Ranges...>& output) const
{
for (int i = 0; i < N_DIM; ++i)
{
dims_[i]->setRange({in[i], in[i]}, output);
}
}
/// Convert an N_DIM-Point to a Peak1D or ChromatogramPeak.
/// Dimensions not contained in this DimMapper will remain untouched in @p out
/// @throw Exception::InvalidRange if DimMapper has a dimension not supported by T
template<typename T>
void fromXY(const Point& in, T& out) const
{
for (int i = 0; i < N_DIM; ++i)
{
dims_[i]->fromXY(in[i], out);
}
}
/// Convert an N_DIM-Point to a Range with all known dimensions.
/// The range will only span a single value in each dimension covered by this mapper.
/// Dimensions not contained in this DimMapper will remain empty.
RangeAllType fromXY(const Point& in) const
{
RangeAllType output;
for (int i = 0; i < N_DIM; ++i)
{
dims_[i]->setRange({in[i], in[i]}, output);
}
return output;
}
/// obtain unit/name for X/Y/Z dimension.
const DimBase& getDim(DIM d) const
{
assert((int)d <= N_DIM);
return *dims_[(int)d];
}
bool hasUnit(DIM_UNIT unit) const
{
for (int i = 0; i < N_DIM; ++i)
{
if (dims_[i]->getUnit() == unit) return true;
}
return false;
}
protected:
/// a minimal factory
static std::unique_ptr<const DimBase> create_(DIM_UNIT u)
{
switch (u)
{
case DIM_UNIT::RT:
return std::make_unique<DimRT>();
case DIM_UNIT::MZ:
return std::make_unique<DimMZ>();
case DIM_UNIT::INT:
return std::make_unique<DimINT>();
case DIM_UNIT::FAIMS_CV:
case DIM_UNIT::IM_MS:
case DIM_UNIT::IM_VSSC:
return std::make_unique<DimIM>(u);
default:
throw Exception::NotImplemented(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
}
std::array<std::unique_ptr<const DimBase>, N_DIM> dims_; ///< mappers for the X,Y,Z... dimension
};
/// The data is stored in two members, one axis-related (X and Y; unit does not matter), and one unit-related (units; no mapping to axis)
/// You can set either, and the other will be updated accordingly as long as you provide a DimMapper which translates between the two representations.
template <int N_DIM>
class Area
{
public:
/// The Area in X,Y,(Z)... dimension (number of dimensions depends on N_DIM)
using AreaXYType = DRange<N_DIM>;
/// No default C'tor
Area() = delete;
/// Custom C'tor with a mapper (non owning pointer)
Area(const DimMapper<N_DIM>* const dims)
: mapper_(dims)
{
}
/// Copy C'tor
Area(const Area& range) = default;
/// Assignment operator - which checks for identical DimMappers and throws otherwise
Area& operator=(const Area& rhs)
{
// check that Dims are identical, otherwise this is very dangerous (the user probably only wanted to update the area, not change its mapping).
if (mapper_ != rhs.mapper_ && *mapper_ != *rhs.mapper_)
{
throw Exception::Precondition(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Assignment of Areas using different mappers!");
}
data_range_ = rhs.data_range_;
visible_area_ = rhs.visible_area_;
return *this;
}
bool operator==(const Area& rhs) const
{
return data_range_ == rhs.data_range_
&& visible_area_ == rhs.visible_area_
&& (*mapper_ == *rhs.mapper_);
}
bool operator!=(const Area& rhs) const
{
return !operator==(rhs);
}
/**
@brief Set the area using unit data (RT, m/z, ...)
@param[in] data Area in units
*/
const Area& setArea(const RangeAllType& data)
{
data_range_ = data;
// update axis view using dims
visible_area_ = mapper_->mapRange(data);
return *this;
}
/**
@brief Set the area using axis data (X and Y)
@param[in] data Area as displayed on the axis
*/
const Area& setArea(const AreaXYType& data)
{
visible_area_ = data;
// update range view from XY area using dims
mapper_->fromXY(visible_area_, data_range_);
return *this;
}
const AreaXYType& getAreaXY() const
{
return visible_area_;
}
const RangeAllType& getAreaUnit() const
{
return data_range_;
}
/**
@brief Clone the current object, set the area of the clone using axis data (X and Y) and return the clone.
@param[in] data New area as displayed on the axis
*/
Area cloneWith(const AreaXYType& data) const
{
Area clone(*this);
clone.setArea(data);
return clone;
}
/**
@brief Clone the current object, set the area of the clone using unit data (RT, m/z, ...) and return the clone.
@param[in] data New area in units
*/
Area cloneWith(const RangeAllType& data) const
{
Area clone(*this);
clone.setArea(data);
return clone;
}
/**
* \brief Push the area into a sandbox (if its outside the sandbox). See UnitRange::pushInto()
* \param sandbox The sandbox which delimits the range of this area
*/
void pushInto(const RangeAllType& sandbox)
{
auto a = data_range_;
a.pushInto(sandbox);
setArea(a);
}
/// empty all dimensions
void clear()
{
setArea(RangeAllType());
}
private:
/* two sides of the same coin... */
RangeAllType data_range_; ///< range in units
AreaXYType visible_area_ = AreaXYType::empty; ///< range in terms of axis (X and Y axis)
/// and a mapper (non-owning pointer) to translate between the two
const DimMapper<N_DIM>* mapper_;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/KERNEL/ChromatogramRangeManager.h | .h | 1,284 | 38 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Administrator $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/RangeManager.h>
namespace OpenMS
{
/**
@brief Range manager for chromatograms
This class manages retention time, m/z, and intensity ranges for multiple chromatograms.
It extends the basic RangeManager to provide specialized functionality for chromatogram data.
The ChromatogramRangeManager is used in conjunction with the SpectrumRangeManager in MSExperiment
to provide separate range tracking for chromatograms and spectra. This separation allows for
more efficient and targeted range operations on specific data types.
@see RangeManager
@see SpectrumRangeManager
@see MSExperiment
@ingroup Kernel
*/
class OPENMS_DLLAPI ChromatogramRangeManager : public RangeManager<RangeRT, RangeIntensity, RangeMZ>
{
public:
/// Base type
using BaseType = RangeManager<RangeRT, RangeIntensity, RangeMZ>;
};
} // namespace OpenMS | Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/KERNEL/RichPeak2D.h | .h | 2,350 | 100 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg$
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/Peak2D.h>
#include <OpenMS/METADATA/MetaInfoInterface.h>
#include <OpenMS/CONCEPT/UniqueIdInterface.h>
namespace OpenMS
{
/**
@brief A 2-dimensional raw data point or peak with meta information.
This data structure is intended for continuous data or peak data.
If you do not need to annotated single peaks with meta data, use Peak2D instead.
@ingroup Kernel
*/
class OPENMS_DLLAPI RichPeak2D :
public Peak2D,
public MetaInfoInterface,
public UniqueIdInterface
{
public:
/// Default constructor
RichPeak2D() :
Peak2D(),
MetaInfoInterface(),
UniqueIdInterface()
{}
/// Copy constructor
RichPeak2D(const RichPeak2D& p) = default;
/// Constructor from Peak2D
explicit RichPeak2D(const Peak2D& p) :
Peak2D(p),
MetaInfoInterface()
{
UniqueIdInterface::clearUniqueId();
}
/// Member constructor
explicit RichPeak2D(const PositionType& pos, const IntensityType in) :
Peak2D(pos, in),
MetaInfoInterface()
{}
/// Move constructor
RichPeak2D(RichPeak2D&& p) = default;
/// Destructor
~RichPeak2D() override
{}
/// Assignment operator
RichPeak2D & operator=(const RichPeak2D& rhs) = default;
/// Move Assignment operator
RichPeak2D & operator=(RichPeak2D&& rhs) & = default;
/// Assignment operator
RichPeak2D & operator=(const Peak2D& rhs)
{
if (this == &rhs) return *this;
Peak2D::operator=(rhs);
clearMetaInfo();
UniqueIdInterface::clearUniqueId();
return *this;
}
/// Equality operator
bool operator==(const RichPeak2D& rhs) const
{
return Peak2D::operator==(rhs) &&
MetaInfoInterface::operator==(rhs) &&
UniqueIdInterface::operator==(rhs);
}
/// Equality operator
bool operator!=(const RichPeak2D& rhs) const
{
return !(operator==(rhs));
}
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/KERNEL/FeatureMap.h | .h | 10,019 | 298 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Marc Sturm, Chris Bielow, Clemens Groepl $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/Feature.h>
#include <OpenMS/KERNEL/RangeManager.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/METADATA/DocumentIdentifier.h>
#include <OpenMS/METADATA/MetaInfoInterface.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <OpenMS/METADATA/ID/IdentificationData.h>
#include <OpenMS/METADATA/ID/Observation.h>
#include <OpenMS/CONCEPT/Types.h>
#include <OpenMS/CONCEPT/UniqueIdInterface.h>
#include <OpenMS/CONCEPT/UniqueIdIndexer.h>
#include <OpenMS/DATASTRUCTURES/ExposedVector.h>
#include <OpenMS/DATASTRUCTURES/Utils/MapUtilities.h>
#include <OpenMS/KERNEL/BaseFeature.h>
#include <OpenMS/OpenMSConfig.h>
#include <exception>
namespace OpenMS
{
class ProteinIdentification;
class PeptideIdentification;
class DataProcessing;
/// summary of the peptide identification assigned to each feature of this map.
/// Each feature contributes one vote (=state)
struct OPENMS_DLLAPI AnnotationStatistics
{
std::vector<Size> states; ///< count each state, indexing by BaseFeature::AnnotationState
AnnotationStatistics();
AnnotationStatistics(const AnnotationStatistics& rhs);
AnnotationStatistics& operator=(const AnnotationStatistics& rhs);
bool operator==(const AnnotationStatistics& rhs) const;
AnnotationStatistics& operator+=(BaseFeature::AnnotationState state);
};
/// Print content of an AnnotationStatistics object to a stream
OPENMS_DLLAPI std::ostream& operator<<(std::ostream& os, const AnnotationStatistics& ann);
/**
@brief A container for features.
A feature map is a container holding features, which represent chemical
entities (peptides, proteins, small molecules etc.) found in an LC-MS/MS
experiment.
Maps are implemented as vectors of features and have basically the same interface
as an STL vector has (model of Random Access Container and Back Insertion Sequence).
Feature maps are typically created from peak data of 2D runs through the FeatureFinder.
@ingroup Kernel
*/
class OPENMS_DLLAPI FeatureMap :
public MetaInfoInterface,
public RangeManagerContainer<RangeRT, RangeMZ, RangeIntensity>,
public DocumentIdentifier,
public ExposedVector<Feature>,
public UniqueIdInterface,
public UniqueIdIndexer<FeatureMap>,
public MapUtilities<FeatureMap>
{
public:
EXPOSED_VECTOR_INTERFACE(Feature)
//@{
typedef RangeManagerContainer<RangeRT, RangeMZ, RangeIntensity> RangeManagerContainerType;
typedef RangeManager<RangeRT, RangeMZ, RangeIntensity> RangeManagerType;
typedef iterator Iterator;
typedef const_iterator ConstIterator;
typedef reverse_iterator ReverseIterator;
typedef const_reverse_iterator ConstReverseIterator;
//@}
/**
@name Constructors and Destructor
*/
//@{
/// Default constructor
FeatureMap();
/// Copy constructor
FeatureMap(const FeatureMap& source);
/// Move constructor
FeatureMap(FeatureMap&& source);
/// Assignment operator
FeatureMap& operator=(const FeatureMap& rhs);
/// Move assignment
//FeatureMap& FeatureMap::operator=(FeatureMap&&);
/// Destructor
~FeatureMap() override;
//@}
/// Equality operator
bool operator==(const FeatureMap& rhs) const;
/// Inequality operator
bool operator!=(const FeatureMap& rhs) const;
/**
@brief Joins two feature maps.
Features are merged into one container (see operator+= for details).
*/
FeatureMap operator+(const FeatureMap& rhs) const;
/**
@brief Add one feature map to another.
Features are merged into one container, simply by appending.
UnassignedPeptides and ProteinIdentifications are appended.
Information on DocumentIdentifier, UniqueIdInterface (of container only)
are reset to default.
For conflicting UID's, new UID's will be assigned.
@param[in] rhs The feature to add to this one.
*/
FeatureMap& operator+=(const FeatureMap& rhs);
/**
@name Sorting.
These simplified sorting methods are supported in addition to
the standard sorting methods of std::vector.
*/
//@{
/// Sorts the peaks according to ascending intensity.
void sortByIntensity(bool reverse = false);
///Sort features by position. Lexicographical comparison (first RT then m/z) is done.
void sortByPosition();
///Sort features by RT position.
void sortByRT();
///Sort features by m/z position.
void sortByMZ();
///Sort features by ascending overall quality.
void sortByOverallQuality(bool reverse = false);
//@}
// Docu in base class
void updateRanges() override;
/// Swaps the feature content (plus its range information) of this map with the content of @p from
void swapFeaturesOnly(FeatureMap& from);
void swap(FeatureMap& from);
/// @name Functions for dealing with identifications in legacy format
///@{
/// non-mutable access to the protein identifications
const std::vector<ProteinIdentification>& getProteinIdentifications() const;
/// mutable access to the protein identifications
std::vector<ProteinIdentification>& getProteinIdentifications();
/// sets the protein identifications
void setProteinIdentifications(const std::vector<ProteinIdentification>& protein_identifications);
/// non-mutable access to the unassigned peptide identifications
const PeptideIdentificationList& getUnassignedPeptideIdentifications() const;
/// mutable access to the unassigned peptide identifications
PeptideIdentificationList& getUnassignedPeptideIdentifications();
/// sets the unassigned peptide identifications
void setUnassignedPeptideIdentifications(const PeptideIdentificationList& unassigned_peptide_identifications);
///@}
/// returns a const reference to the description of the applied data processing
const std::vector<DataProcessing>& getDataProcessing() const;
/// returns a mutable reference to the description of the applied data processing
std::vector<DataProcessing>& getDataProcessing();
/// sets the description of the applied data processing
void setDataProcessing(const std::vector<DataProcessing>& processing_method);
/// set the file path to the primary MS run (usually the mzML file obtained after data conversion from raw files)
void setPrimaryMSRunPath(const StringList& s);
/// set the file path to the primary MS run using the mzML annotated in the MSExperiment @p e.
/// If it doesn't exist, fallback to @p s.
void setPrimaryMSRunPath(const StringList& s, MSExperiment& e);
/// get the file path to the first MS run
void getPrimaryMSRunPath(StringList& toFill) const;
/**
@brief Clears all data and meta data
@param[in] clear_meta_data If @em true, all meta data is cleared in addition to the data.
*/
void clear(bool clear_meta_data = true);
/**
@brief Applies a member function of Type to the container itself and all features (including subordinates).
The returned values are accumulated.
<b>Example:</b> The following will print the number of features with invalid unique ids (plus 1 if the container has an invalid UID as well):
@code
FeatureMap fm;
(...)
std::cout << fm.applyMemberFunction(&UniqueIdInterface::hasInvalidUniqueId) << std::endl;
@endcode
See e.g. UniqueIdInterface for what else can be done this way.
*/
template <typename Type>
Size applyMemberFunction(Size (Type::* member_function)())
{
Size assignments = 0;
assignments += ((*this).*member_function)();
for (Iterator iter = this->begin(); iter != this->end(); ++iter)
{
assignments += iter->applyMemberFunction(member_function);
}
return assignments;
}
/// The "const" variant.
template <typename Type>
Size applyMemberFunction(Size (Type::* member_function)() const) const
{
Size assignments = 0;
assignments += ((*this).*member_function)();
for (ConstIterator iter = this->begin(); iter != this->end(); ++iter)
{
assignments += iter->applyMemberFunction(member_function);
}
return assignments;
}
AnnotationStatistics getAnnotationStatistics() const;
/// @name Functions for dealing with identifications in new format
///@{
/*!
@brief Return observation matches (e.g. PSMs) from the identification data that are not assigned to any feature in the map
Only top-level features are considered, i.e. no subordinates.
@see BaseFeature::getIDMatches()
*/
std::set<IdentificationData::ObservationMatchRef> getUnassignedIDMatches() const;
/// Immutable access to the contained identification data
const IdentificationData& getIdentificationData() const;
/// Mutable access to the contained identification data
IdentificationData& getIdentificationData();
///@}
protected:
/// protein identifications
std::vector<ProteinIdentification> protein_identifications_;
/// peptide identifications not matched to a specific feature
PeptideIdentificationList unassigned_peptide_identifications_;
/// applied data processing
std::vector<DataProcessing> data_processing_;
/// general identification results (peptides/proteins, RNA, compounds)
IdentificationData id_data_;
};
OPENMS_DLLAPI std::ostream& operator<<(std::ostream& os, const FeatureMap& map);
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/KERNEL/MassTrace.h | .h | 9,853 | 357 | // 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, Holger Franken, Chris Bielow $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/Peak2D.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <vector>
#include <list>
#include <map>
namespace OpenMS
{
typedef Peak2D PeakType;
class string;
/** @brief A container type that gathers peaks similar in m/z and moving along retention time.
Depending on the method of extraction a mass trace could virtually
represent a complete extracted ion chromatogram (XIC) or merely a part of
it (e.g., a chromatographic peak). The kernel class provides methods for
computing mass trace characteristics such as its centroid m/z and retention
time. Coeluting mass traces can be further assembled to complete isotope
patterns of peptides/metabolites.
@ingroup Kernel
*/
class OPENMS_DLLAPI MassTrace
{
public:
// must match to names_of_quantmethod[]
enum MT_QUANTMETHOD {
MT_QUANT_AREA = 0, ///< quantify by area
MT_QUANT_MEDIAN, ///< quantify by median of intensities
MT_QUANT_HEIGHT, ///< quantify by peak height
SIZE_OF_MT_QUANTMETHOD
};
static const std::string names_of_quantmethod[SIZE_OF_MT_QUANTMETHOD];
/// converts a string to enum value; returns 'SIZE_OF_MT_QUANTMETHOD' upon error
static MT_QUANTMETHOD getQuantMethod(const String& val);
/** @name Constructors and Destructor
*/
///@{
/// Default constructor
MassTrace() = default;
/// Detailed constructor
/// (useful, since Mass Traces are commonly assembled by prepending and appending -- which is faster using lists)
MassTrace(const std::list<PeakType>& trace_peaks);
/// Detailed constructor for vector
MassTrace(const std::vector<PeakType>& trace_peaks);
/// Destructor
~MassTrace() = default;
/// Copy constructor
MassTrace(const MassTrace &) = default;
/// Assignment operator
MassTrace & operator=(const MassTrace &) = default;
/// Random access operator
PeakType& operator[](const Size & mt_idx);
const PeakType& operator[](const Size & mt_idx) const;
///@}
/** @name Iterators
@brief Enables mutable/immutable access to the mass trace's peaks.
*/
///@{
typedef std::vector<PeakType>::iterator iterator;
typedef std::vector<PeakType>::const_iterator const_iterator;
typedef std::vector<PeakType>::reverse_iterator reverse_iterator;
typedef std::vector<PeakType>::const_reverse_iterator const_reverse_iterator;
iterator begin()
{
return trace_peaks_.begin();
}
iterator end()
{
return trace_peaks_.end();
}
const_iterator begin() const
{
return trace_peaks_.begin();
}
const_iterator end() const
{
return trace_peaks_.end();
}
reverse_iterator rbegin()
{
return trace_peaks_.rbegin();
}
reverse_iterator rend()
{
return trace_peaks_.rend();
}
const_reverse_iterator rbegin() const
{
return trace_peaks_.rbegin();
}
const_reverse_iterator rend() const
{
return trace_peaks_.rend();
}
///@}
/** @name Accessor methods
*/
///@{
/// Returns the number of peaks contained in the mass trace.
Size getSize() const
{
return trace_peaks_.size();
}
/// Gets label of mass trace.
String getLabel() const
{
return label_;
}
/// Sets label of mass trace.
void setLabel(const String & label)
{
label_ = label;
}
/// Returns the centroid m/z.
double getCentroidMZ() const
{
return centroid_mz_;
}
/// Returns the centroid ion mobility.
double getCentroidIM() const
{
return centroid_im_;
}
/// Returns the centroid RT.
double getCentroidRT() const
{
return centroid_rt_;
}
double getCentroidSD() const
{
return centroid_sd_;
}
void setCentroidSD(const double & tmp_sd)
{
centroid_sd_ = tmp_sd;
}
void setCentroidIM(const double & im)
{
centroid_im_ = im;
}
double getFWHM() const
{
return fwhm_;
}
/// Returns the length of the trace (as difference in RT)
double getTraceLength() const
{
double length(0.0);
if (trace_peaks_.size() > 1)
{
length = std::fabs(trace_peaks_.rbegin()->getRT() - trace_peaks_.begin()->getRT());
}
return length;
}
std::pair<Size, Size> getFWHMborders() const
{
return std::make_pair(fwhm_start_idx_, fwhm_end_idx_);
}
/// Gets smoothed intensities (empty if no smoothing was explicitly done beforehand!).
const std::vector<double>& getSmoothedIntensities() const
{
return smoothed_intensities_;
}
/// Set smoothed intensities (smoothing is done externally, e.g. by LowessSmoothing).
void setSmoothedIntensities(const std::vector<double> & db_vec)
{
if (trace_peaks_.size() != db_vec.size())
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Number of smoothed intensities deviates from mass trace size! Aborting...", String(db_vec.size()));
}
smoothed_intensities_ = db_vec;
}
/// Get average scan time of mass trace
double getAverageMS1CycleTime() const
{
if (trace_peaks_.size() <= 1) return 0.0;
return (trace_peaks_.rbegin()->getRT() - trace_peaks_.begin()->getRT()) / (trace_peaks_.size() - 1);
}
///@}
/** @name Computational methods
*/
///@{
/// Sum all non-negative (smoothed!) intensities in the mass trace
double computeSmoothedPeakArea() const;
/// Compute area of peaks in the mass trace
double computePeakArea() const;
/// Sum all peak intensities in the mass trace
double computeIntensitySum() const;
/// Return the index of the mass trace's highest peak within the MassTrace container (based either on raw or smoothed intensities).
Size findMaxByIntPeak(bool use_smoothed_ints = false) const;
/// Estimate FWHM of chromatographic peak in seconds (based on either raw or smoothed intensities).
/// Uses linear interpolation of the two closest points to the half_max intensity in order to get the RT values at exactly the half_max
/// stores result internally, use getFWHM().
double estimateFWHM(bool use_smoothed_ints = false);
/// determine if area or median is used for quantification
void setQuantMethod(MT_QUANTMETHOD method);
/// check if area or median is used for quantification
MT_QUANTMETHOD getQuantMethod() const;
/// Compute chromatographic peak area within the FWHM range.
double computeFwhmAreaSmooth() const;
double computeFwhmArea() const;
// double computeFwhmAreaSmoothRobust() const;
// double computeFwhmAreaRobust() const;
double getIntensity(bool smoothed) const;
double getMaxIntensity(bool smoothed) const;
/// Return the mass trace's convex hull.
ConvexHull2D getConvexhull() const;
///@}
/** @name Update methods for centroid RT and m/z
*/
///@{
void updateSmoothedMaxRT();
/// Compute & update centroid RT as a intensity-weighted mean of RTs.
void updateWeightedMeanRT();
void updateSmoothedWeightedMeanRT();
/// Compute & update centroid RT as median position of intensities.
void updateMedianRT();
/// Compute & update centroid m/z as median of m/z values.
void updateMedianMZ();
/// Compute & update centroid m/z as mean of m/z values.
void updateMeanMZ();
/// Compute & update centroid m/z as weighted mean of m/z values.
void updateWeightedMeanMZ();
/** @brief Compute & update m/z standard deviation of mass trace as weighted mean of m/z values.
Make sure to call update(Weighted)(Mean|Median)MZ() first! <br>
use getCentroidSD() to get result
*/
void updateWeightedMZsd();
///@}
/// Average FWHM of m/z peaks
/// 0 denotes no fwhm meta data computed
double fwhm_mz_avg = 0;
/// Average FWHM of ion mobility peaks
/// 0 denotes no fwhm meta data computed
double fwhm_im_avg = 0;
private:
/// median of trace intensities
double computeMedianIntensity_() const;
/// calculate x coordinate of start/end indexes at half_max
/// calculation is based on (yB - yA) / (xB - xA) = (y_eval - yA) / (xC - xA)
/// solve for xC: xC = xA + ((y_eval - yA) * (xB - xA) / (yB - yA))
double linearInterpolationAtY_(double xA, double xB, double yA, double yB, double y_eval) const;
/// Actual MassTrace container for doing centroid calculation, peak width estimation etc.
std::vector<PeakType> trace_peaks_;
/// Centroid m/z
double centroid_mz_ = 0.0;
/// centroid ion mobility peak
/// 0.0 denotes no im data in the data
double centroid_im_ = 0.0;
/// intensity-weighted STD
double centroid_sd_ = 0.0;
/// Centroid RT
double centroid_rt_ = 0.0;
/// Trace label
String label_;
/// Container for smoothed intensities. Smoothing must be done externally.
std::vector<double> smoothed_intensities_;
double fwhm_ = 0.0; ///< FWHM of RT peak
Size fwhm_start_idx_ = 0; ///< index into 'trace_peaks_' vector (inclusive)
Size fwhm_end_idx_ = 0; ///< index into 'trace_peaks_' vector (inclusive)
/// use area under mass trace or the median of intensities
MT_QUANTMETHOD quant_method_ = MT_QUANT_AREA;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/IONMOBILITY/FAIMSHelper.h | .h | 2,148 | 61 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Eugen Netz $
// $Authors: Eugen Netz $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <set>
namespace OpenMS
{
/**
@brief Helper functions for FAIMS data
FAIMSHelper contains convenience functions to deal with FAIMS
compensation voltages and related data.
*/
class OPENMS_DLLAPI FAIMSHelper
{
public:
virtual ~FAIMSHelper() {}
/**
@brief Get all unique FAIMS compensation voltages (CVs) that occur in a PeakMap
- Scans all spectra in the experiment and collects CVs from spectra whose drift time
unit is DriftTimeUnit::FAIMS_COMPENSATION_VOLTAGE.
- If the data does not contain any FAIMS spectra, an empty set will be returned.
- The sentinel IMTypes::DRIFTTIME_NOT_SET is ignored; a warning is logged if encountered.
@param[in] exp The input experiment
@return Unique FAIMS compensation voltages (in volts)
*/
static std::set<double> getCompensationVoltages(const PeakMap& exp);
/**
@brief Filter peptide identifications by FAIMS compensation voltage
Filters peptide identifications to only include those matching the specified
FAIMS CV. IDs without FAIMS_CV annotation are included for backward compatibility.
@param[in] peptides Input peptide identifications
@param[in] target_cv Target FAIMS compensation voltage to filter for
@param[in] cv_tolerance Tolerance for floating point comparison (default: 0.01)
@return Filtered list of peptide identifications
*/
static PeptideIdentificationList filterPeptidesByFAIMSCV(
const PeptideIdentificationList& peptides,
double target_cv,
double cv_tolerance = 0.01);
};
} //end namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/IONMOBILITY/IMDataConverter.h | .h | 9,523 | 172 | // 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, Chris Bielow $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CONCEPT/CommonEnums.h>
#include <OpenMS/CONCEPT/Types.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/MATH/MathFunctions.h>
#include <tuple>
#include <vector>
#include <utility>
namespace OpenMS
{
// forward declarations
namespace DataArrays
{
class FloatDataArray;
}
enum class DriftTimeUnit;
/**
@brief This class converts PeakMaps and MSSpectra from/to different IM/FAIMS storage models
*/
class OPENMS_DLLAPI IMDataConverter
{
public:
/**
@brief Splits a PeakMap into one PeakMap per FAIMS compensation voltage (CV)
The spectra from the original PeakMap are moved to new PeakMaps, so the original
PeakMap is unusable afterwards (it is moved-from).
Behavior:
- If the dataset contains FAIMS spectra (MS1 with DriftTimeUnit::FAIMS_COMPENSATION_VOLTAGE),
returns a vector of (CV, MSExperiment) pairs, one per unique FAIMS CV. Each experiment
contains all spectra assigned to that CV.
- MS2+ spectra without an explicit FAIMS CV are assigned to the last seen FAIMS CV
(based on run order). Spectra without a prior FAIMS CV context are skipped with a warning.
- If the dataset contains no FAIMS spectra at all, an informational message is logged and a
single-element vector is returned. This element contains the original PeakMap (i.e. no
splitting took place) under a synthetic key (NaN). Callers that specifically work on
FAIMS data should usually check for FAIMS CVs via FAIMSHelper::getCompensationVoltages()
instead of relying on this special case.
@param[in,out] exp The PeakMap (will be moved-from)
@return A vector of (FAIMS compensation voltage (CV), MSExperiment) pairs; for non-FAIMS data,
a single-element vector containing the original, unsplit PeakMap with a NaN CV key
*/
static std::vector<std::pair<double, MSExperiment>> splitByFAIMSCV(PeakMap&& exp);
/**
@brief Split a (TimsTOF) ion mobility frame (i.e. a spectrum concatenated from multiple spectra with different IM values) into separate spectra
The input @p im_frame must have a floatDataArray where IM values are annotated. If not, an exception is thrown.
For the output spectra, the IM value is annotated once in `spec.getDriftTime()` (there is no metadata array which contains IM values, since they are all the same).
Output spectra are sorted by m/z. Ranges of the experiment are updated.
The reverse operation is `reshapeIMFrameToSingle()`.
@param[in] im_frame Concatenated spectrum representing an IM frame
@return IM frame split into spectra (one per distinct IM value), sorted by m/z, with updated ranges
@throws Exception::MissingInformation if @p im_frame does not have IM data in floatDataArrays
*/
static MSExperiment reshapeIMFrameToMany(MSSpectrum im_frame);
/**
@brief Bins the ion mobility range into discrete bins and creates a new MSExperiment for each IM bin.
The IM range (of the whole @p in) is divided into equally spaced IM-bins and the bin center is the new drift time (see `spec.getDriftTime()`).
Usually multiple spectra from an IM frame (with close IM values) fall into the same bin. These spectra are merged using SpectraMerger's block-method.
When merging m/z peaks of two MS spectra with SpectraMerger, parameters `mz_binning_width` and `mz_binning_width_unit` and used internally.
To avoid artifacts at the bin borders, each bin can be extended by `bin_extension_abs` on both sides. The actual overlap between adjacent bins is thus `2*bin_extension_abs`.
@note All MS levels are binned. If you want to bin only a specific MS level, you need to filter the input MSExperiment before calling this function.
@param[in,out] in The PeakMap containing many 'wide' IM-frame spectra (where one spectrum contains multiple IM values).
@param[in] number_of_IM_bins Into how many bins should the ion mobility range be sliced?
@param[in] bin_extension_abs How much should each bin be extended at its borders? (in absolute IM units). The actual overlap between adjacent bins is thus `2*bin_extension_abs`.
@param[in] mz_binning_width The width of the m/z binning window, when merging spectra of the same IM-bin (in Da or ppm, see @p mz_binning_width_unit)
@param[in] mz_binning_width_unit The unit of the m/z binning window (Da or ppm)
@return One MSExperiment per IM-bin and the corresponding binning borders
@throws Exception::InvalidValue if any spectrum in @p in is missing an IM-float data array (see IMTypes::determineIMFormat(), or MSSpectrum::containsIMData())
@throws Exception::InvalidValue if number_of_IM_bins == 0
@throws Exception::InvalidValue if bin_extension_abs < 0
*/
static std::tuple < std::vector<MSExperiment>, Math::BinContainer> splitExperimentByIonMobility(MSExperiment&& in,
UInt number_of_IM_bins,
double bin_extension_abs,
double mz_binning_width,
MZ_UNITS mz_binning_width_unit);
/**
@brief Collapses multiple MS spectra (each with its own drift time) from the same IM-frame into a single MSSpectrum (with an IM-float data array)
Frames are recognized by having the same RT for subsequent spectra. The IM information is taken
from each input spectrum's .getDriftTime().
Multiple frames are allowed.
If the input already contains IM-frames, they are simply copied.
If a spectrum does not have drift time (spec.getDriftTime()), it is simply copied to the output and ignored during the collapsing process.
@param[in] in The input experiment with multiple spectra per frame
@return result The output spectra collapsed to a single spectrum per frame
@note This requires that spectra from the same frame have the same RT ("scan start time")
The reverse operation is `reshapeIMFrameToMany()`.
@throws Exception::InvalidValue if any spectrum has both a single drift time AND a IM-float data array (see IMTypes::determineIMFormat(), or MSSpectrum::containsIMData())
*/
static MSExperiment reshapeIMFrameToSingle(const MSExperiment& in);
/**
@brief Convert from a Unit to a CV term and annotate is as the FDA's name. This is not very accurate (since we cannot decide if its 'raw' or 'binned' IM data),
but it allows to reconstruct the unit from the IM float-data array which is annotated with this term.
<table>
<caption>This is the mapping</caption>
<tr><th>Unit <th>CV term
<tr><td>DriftTimeUnit::MILLISECOND <td>MS:1002816 ! mean ion mobility array
<tr><td>DriftTimeUnit::VSSC <td>MS:1003008 ! raw inverse reduced ion mobility array
</table>
For any other unit (e.g. FAIMS-Compensation voltage) we throw, since the PSI CV does not
(and should not?) have CV terms for other IM units in ion mobility arrays.
@param[out] fda The FDA to be annotated as an IM array
@param[in] unit The unit of the IM measurement
@throws Exception::InvalidValue for unsupported units
*/
static void setIMUnit(DataArrays::FloatDataArray& fda, const DriftTimeUnit unit);
/**
@brief Checks if the @p fda is an ion-mobility array and if so, returns the unit (either MILLISECOND or VSSC, or NONE)
The name of the @p fda should correspond to a value set by setIMUnit(), but all CV names of child terms of
'MS:1002893 ! ion mobility array' are accepted.
<table>
<caption>This is the current mapping (all of which return true)</caption>
<tr><th>CV term <th>Unit
<tr><td>MS:1002816 ! mean ion mobility array <td>DriftTimeUnit::MILLISECOND
<tr><td>MS:1003008 ! raw inverse reduced ion mobility array <td>DriftTimeUnit::VSSC
<tr><td>MS:1002893 ! ion mobility array ** <td>DriftTimeUnit::NONE
</table>
@p **) or a child term, which is not one of the terms used above.
@param[in] fda Input array, which is tested for its name
@param[out] unit If @p fda is an IM array, the @p unit will contain the IM unit (undefined otherwise)
@return True if @p fda is an IM array, false otherwise
*/
static bool getIMUnit(const DataArrays::FloatDataArray& fda, DriftTimeUnit& unit);
};
} //end namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/IONMOBILITY/IMTypes.h | .h | 4,524 | 100 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CONCEPT/CommonEnums.h>
#include <OpenMS/OpenMSConfig.h>
#include <string>
namespace OpenMS
{
class MSExperiment;
class MSSpectrum;
/// Drift time unit for ion mobility
enum class DriftTimeUnit
{
NONE, ///< No unit
MILLISECOND, ///< milliseconds
VSSC, ///< volt-second per square centimeter (i.e. 1/K_0)
FAIMS_COMPENSATION_VOLTAGE,///< compensation voltage
SIZE_OF_DRIFTTIMEUNIT
};
/// Names of IM Units. Should be usable as axis annotation.
OPENMS_DLLAPI extern const std::string NamesOfDriftTimeUnit[(size_t) DriftTimeUnit::SIZE_OF_DRIFTTIMEUNIT];
/// convert an entry in NamesOfDriftTimeUnit[] to DriftTimeUnit enum
/// @throws Exception::InvalidValue if @p dtu_string is not contained in NamesOfDriftTimeUnit[]
OPENMS_DLLAPI DriftTimeUnit toDriftTimeUnit(const std::string& dtu_string);
/// convert a DriftTimeUnit enum to String
/// @throws Exception::InvalidValue if @p value is SIZE_OF_DRIFTTIMEUNIT
OPENMS_DLLAPI const std::string& driftTimeUnitToString(const DriftTimeUnit value);
/// Different ways to represent ion mobility data in a spectrum
/// Note:
/// 1. MIXED is only used for MSExperiment, not for MSSpectrum
/// 2. UNKNOWN should be used if the format is not yet determined.
/// FileHandler or e.g. IM peak picker should ideally set the format a known value.
enum class IMFormat
{
NONE, ///< no ion mobility
CONCATENATED, ///< ion mobility frame is stacked in a single spectrum (i.e. has an IM float data array)
MULTIPLE_SPECTRA,///< ion mobility is recorded as multiple spectra per frame (i.e. has one IM annotation per spectrum)
MIXED, ///< an MSExperiment contains both CONCATENATED and MULTIPLE_SPECTRA
CENTROIDED, ///< ion mobility of peaks after centroiding in IM dimension. Ion mobility is annotated in a single float data array (i.e., each peak might have a different IM value in the data array); identical to CONCATENATED in terms of data layout.
UNKNOWN, ///< ion mobility format not yet determined.
SIZE_OF_IMFORMAT
};
/// Names of IMFormat
OPENMS_DLLAPI extern const std::string NamesOfIMFormat[(size_t) IMFormat::SIZE_OF_IMFORMAT];
/// convert an entry in NamesOfIMFormat[] to IMFormat enum
/// @throws Exception::InvalidValue if @p IM_format is not contained in NamesOfIMFormat[]
OPENMS_DLLAPI IMFormat toIMFormat(const std::string& IM_format);
/// convert an IMFormat enum to String
/// @throws Exception::InvalidValue if @p value is SIZE_OF_IMFORMAT
OPENMS_DLLAPI const std::string& imFormatToString(const IMFormat value);
class OPENMS_DLLAPI IMTypes
{
public:
/// If drift time for a spectrum is unavailable (i.e. not an IM spectrum), it will have this value
inline static constexpr double DRIFTTIME_NOT_SET = -1.0;
/// Checks the all spectra for their type (see overload)
/// and returns the common type (or IMFormat::MIXED if both CONCATENATED and MULTIPLE_SPECTRA are present)
/// If @p exp is empty or contains no IM spectra at all, IMFormat::NONE is returned
/// @throws Exception::InvalidValue if IM values are annotated as single drift time and float array for any single spectrum
static IMFormat determineIMFormat(const MSExperiment& exp);
/**
@brief Checks for existence of a single driftTime (using spec.getDriftTime()) or an ion-mobility float data array (using spec.hasIMData())
If neither is found, IMFormat::NONE is returned.
If a single drift time (== IMFormat::MULTIPLE_SPECTRA) is found, but no unit, a warning is issued.
@throws Exception::InvalidValue if IM values are annotated as single drift time and float array in the given spectrum
*/
static IMFormat determineIMFormat(const MSSpectrum& spec);
/**
* \brief
* \param from Drift unit to convert from
* \return A more general DIM_UNIT (or exception)
* \throws Exception::ConversionError if @p from has invalid value (e.g. 'NONE')
*/
static DIM_UNIT fromIMUnit(const DriftTimeUnit from);
};
};
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/INTERFACES/DataStructures.h | .h | 5,491 | 214 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hannes Roest $
// $Authors: Darren Kessner, Hannes Roest, Witold Wolski$
// --------------------------------------------------------------------------
#pragma once
#include <string>
#include <vector>
#include <memory>
#include <OpenMS/config.h>
namespace OpenMS
{
namespace Interfaces
{
/**
@brief The datastructures used by the OpenSwath interfaces
Many of them are closely related to Proteowizard data structures,
originally written by Darren Kessner and released under the Apache 2.0
licence and can be found in the file pwiz/data/msdata/MSData.hpp.
Original author: Darren Kessner <darren@proteowizard.org>
Copyright 2007 Spielberg Family Center for Applied Proteomics
Cedars-Sinai Medical Center, Los Angeles, California 90048
The following datastructures are used :
- BinaryDataArray : a struct that holds a std::vector<double> with the data
- ChromatogramMeta : meta information of a chromatogram (index)
- Chromatogram : chromatogram data. Contains a vector of pointers to BinaryDataArray,
the first one is time array (RT), the second one is intensity
- SpectrumMeta : meta information of a spectrum (index, identifier, RT, ms_level)
- Spectrum : spectrum data. Contains a vector of pointers to BinaryDataArray,
the first one is mz array, the second one is intensity
*/
/// The structure into which encoded binary data goes.
struct OPENMS_DLLAPI BinaryDataArray
{
/// this optional attribute may reference the 'id' attribute of the appropriate dataProcessing.
//DataProcessingPtr dataProcessingPtr;
/// the binary data.
std::vector<double> data;
};
typedef std::shared_ptr<BinaryDataArray> BinaryDataArrayPtr;
/// Identifying information for a chromatogram
struct OPENMS_DLLAPI ChromatogramMeta
{
/// the zero-based, consecutive index of the chromatogram in the ChromatogramList.
std::size_t index;
/// a unique identifier for this chromatogram.
std::string id;
/// precursor and product m/z
double precursor_isolation_target;
double product_isolation_target;
ChromatogramMeta() :
index()
{
}
};
typedef std::shared_ptr<ChromatogramMeta> ChromatogramMetaPtr;
/// A single chromatogram.
struct OPENMS_DLLAPI Chromatogram
{
/// default length of binary data arrays contained in this element.
std::size_t defaultArrayLength;
private:
/// list of binary data arrays.
std::vector<BinaryDataArrayPtr> binaryDataArrayPtrs;
public:
Chromatogram() :
defaultArrayLength(2),
binaryDataArrayPtrs(defaultArrayLength)
{
initvec();
}
private:
void initvec()
{
for (std::size_t i = 0; i < defaultArrayLength; ++i)
{
BinaryDataArrayPtr empty(new BinaryDataArray);
binaryDataArrayPtrs[i] = empty;
}
}
public:
/// get time array (may be null)
BinaryDataArrayPtr getTimeArray() const
{
return binaryDataArrayPtrs[0];
}
/// set time array
void setTimeArray(BinaryDataArrayPtr data)
{
binaryDataArrayPtrs[0] = data;
}
/// get intensity array (may be null)
BinaryDataArrayPtr getIntensityArray() const
{
return binaryDataArrayPtrs[1];
}
/// set intensity array
void setIntensityArray(BinaryDataArrayPtr data)
{
binaryDataArrayPtrs[1] = data;
}
};
typedef std::shared_ptr<Chromatogram> ChromatogramPtr;
/// Identifying information for a spectrum
struct OPENMS_DLLAPI SpectrumMeta
{
/// the zero-based, consecutive index of the spectrum in the SpectrumList.
size_t index;
/// a unique identifier for this spectrum.
std::string id;
/// retention time information
double RT;
/// ms level
int ms_level;
SpectrumMeta() :
index(0)
{
}
};
typedef std::shared_ptr<SpectrumMeta> SpectrumMetaPtr;
/// The structure that captures the generation of a peak list (including the underlying acquisitions)
struct OPENMS_DLLAPI Spectrum
{
/// default length of binary data arrays contained in this element.
std::size_t defaultArrayLength;
private:
/// list of binary data arrays.
std::vector<BinaryDataArrayPtr> binaryDataArrayPtrs;
public:
Spectrum() :
defaultArrayLength(2),
binaryDataArrayPtrs(defaultArrayLength)
{
initvec();
}
private:
void initvec()
{
for (std::size_t i = 0; i < defaultArrayLength; ++i)
{
BinaryDataArrayPtr empty(new BinaryDataArray);
binaryDataArrayPtrs[i] = empty;
}
}
public:
/// get m/z array (may be null)
BinaryDataArrayPtr getMZArray() const
{
return binaryDataArrayPtrs[0];
}
/// set mz array
void setMZArray(BinaryDataArrayPtr data)
{
binaryDataArrayPtrs[0] = data;
}
/// get intensity array (may be null)
BinaryDataArrayPtr getIntensityArray() const
{
return binaryDataArrayPtrs[1];
}
/// set intensity array
void setIntensityArray(BinaryDataArrayPtr data)
{
binaryDataArrayPtrs[1] = data;
}
};
typedef std::shared_ptr<Spectrum> SpectrumPtr;
} //end namespace Interfaces
} //end namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/INTERFACES/IMSDataConsumer.h | .h | 3,726 | 108 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hannes Roest $
// $Authors: Hannes Roest $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/config.h>
#include <OpenMS/CONCEPT/Types.h>
namespace OpenMS
{
class MSSpectrum;
class MSChromatogram;
class ExperimentalSettings;
namespace Interfaces
{
/**
@brief The interface of a consumer of spectra and chromatograms
The data consumer is able to consume data of type MSSpectrum and
MSChromatogram and process them (it may modify the spectra). The consumer
interface may be used when data is generated sequentially (e.g. by
reading from disc) and needs to be processed as fast as possible without
ever holding the full set of data in memory.
The consumer expects to be informed about the number of spectra and
chromatograms to consume and potentially about the ExperimentalSettings
@a before_consuming any spectra. This can be critical for consumers who
write data to disk. Depending on the implementation, an exception may
occur if the ExperimentalSettings and the size of the experiment are not
set before consuming any spectra.
Implementations in OpenMS can be found in OpenMS/FORMAT/DATAACCESS
@note The member functions setExpectedSize and setExperimentalSettings
are expected to be called before consuming starts.
*/
class OPENMS_DLLAPI IMSDataConsumer
{
public:
typedef MSSpectrum SpectrumType;
typedef MSChromatogram ChromatogramType;
virtual ~IMSDataConsumer() {}
/**
@brief Consume a spectrum
The spectrum will be consumed by the implementation and possibly modified.
@note The implementation might not allow to consume spectra and chromatograms in any order
@param[in,out] s The spectrum to be consumed
*/
virtual void consumeSpectrum(SpectrumType& s) = 0;
/**
@brief Consume a chromatogram
The chromatogram will be consumed by the implementation and possibly modified.
@note The implementation might not allow to consume spectra and chromatograms in any order
@param[in,out] c The chromatogram to be consumed
*/
virtual void consumeChromatogram(ChromatogramType& c) = 0;
/**
@brief Set expected size of spectra and chromatograms to be consumed.
Some implementations might care about the number of spectra and
chromatograms to be consumed and need to be informed about this
(usually before consuming starts).
@note Calling this method is optional but good practice.
@param[in] expectedSpectra Number of spectra expected
@param[in] expectedChromatograms Number of chromatograms expected
*/
virtual void setExpectedSize(size_t expectedSpectra, size_t expectedChromatograms) = 0;
/**
@brief Set experimental settings (meta-data) of the data to be consumed
Some implementations might need to know about the meta-data (or the
context) of the spectra and chromatograms to be consumed. This method
allows them learn this.
@note Calling this method is optional but good practice.
@param[in] exp Experimental settings meta data for the data to be consumed
*/
virtual void setExperimentalSettings(const ExperimentalSettings& exp) = 0;
};
typedef IMSDataConsumer IMSDataConsumer;
} //end namespace Interfaces
} //end namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/INTERFACES/ISpectrumAccess.h | .h | 3,753 | 106 | // 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/INTERFACES/DataStructures.h>
#include <vector>
#include <string>
#include <memory>
namespace OpenMS
{
namespace Interfaces
{
/**
@brief The interface of read-access to a list of spectra
*/
class OPENMS_DLLAPI ISpectraReader
{
public:
virtual ~ISpectraReader() {}
/// Return a pointer to a spectrum at the given id
virtual SpectrumPtr getSpectrumById(int id) const = 0;
/// Return a pointer to a spectrum at the given string id
virtual SpectrumPtr getSpectrumById(const std::string& id) const = 0;
/// Return a vector of ids of spectra that are within RT +/- deltaRT
virtual std::vector<std::size_t> getSpectraByRT(double RT, double deltaRT) const = 0;
/// Returns the number of spectra available
virtual size_t getNrSpectra() const = 0;
/// Returns the meta information for a spectrum
virtual SpectrumMetaPtr getSpectrumMetaById(int id) const = 0;
/*
* Do we need an Iterator here?
* We would have to provide our own iterator wrapper class because we don't
* know whether all the spectra are loaded at any given timepoint
typedef SpectrumPtr const ConstSpectraIterator;
ConstSpectraIterator beginSpectra() const;
ConstSpectraIterator endSpectra() const;
*/
};
typedef std::shared_ptr<ISpectraReader> SpectraReaderPtr;
/**
@brief The interface of read-access to a list of chromatograms
*/
class OPENMS_DLLAPI IChromatogramsReader
{
public:
virtual ~IChromatogramsReader() {}
/// Return a pointer to a chromatogram at the given id
virtual ChromatogramPtr getChromatogramById(int id) const = 0;
/// Return a pointer to a chromatogram at the given string id
virtual ChromatogramPtr getChromatogramById(const std::string& id) const = 0;
/// Return a vector of ids of chromatograms that are within mz +/- deltaMz
virtual std::vector<std::size_t> getChromatogramByPrecursorMZ(double mz, double deltaMZ) const = 0;
/// Returns the number of chromatograms available
virtual std::size_t getNrChromatograms() const = 0;
/// Returns the meta information for a chromatogram
virtual ChromatogramMetaPtr getChromatogramMetaById(int id) const = 0;
/*
* Do we need an Iterator here?
* We would have to provide our own iterator wrapper class because we don't
* know whether all the chromatograms are loaded at any given timepoint
ConstChromatogramIterator beginChromatograms() const;
ConstChromatogramIterator endChromatograms() const;
*/
};
typedef std::shared_ptr<IChromatogramsReader> ChromatogramsReaderPtr;
class OPENMS_DLLAPI ISpectraWriter
{
public:
virtual ~ISpectraWriter() {}
/// Append a spectrum to the end
virtual void appendSpectrum(SpectrumPtr spectrum, bool write_through=false) = 0;
/// write all cached data to disk
virtual void flush() = 0;
};
typedef std::shared_ptr<ISpectraWriter> SpectraWriterPtr;
class OPENMS_DLLAPI IChromatogramsWriter
{
public:
virtual ~IChromatogramsWriter() {}
/// Append a chromatogram to the end
virtual void appendChromatogram(ChromatogramPtr chromatogram, bool write_through=false) = 0;
/// write all cached data to disk
virtual void flush() = 0;
};
typedef std::shared_ptr<IChromatogramsWriter> ChromatogramsWriterPtr;
} //end namespace Interfaces
} //end namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/QC/FeatureSummary.h | .h | 1,524 | 59 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Axel Walter $
// $Authors: Axel Walter $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/QC/QCBase.h>
/**
* @brief Detected Compounds as a Metabolomics QC metric
*
* Simple class to return a summary of detected compounds
* from a featureXML file.
*
*/
namespace OpenMS
{
class OPENMS_DLLAPI FeatureSummary : public QCBase
{
public:
/// Constructor
FeatureSummary() = default;
/// Destructor
virtual ~FeatureSummary() = default;
// stores feature summary values calculated by compute function
struct OPENMS_DLLAPI Result {
UInt feature_count = 0;
float rt_shift_mean = 0;
bool operator==(const Result& rhs) const;
};
/**
@brief computes a summary of a featureXML file
@param[in] feature_map FeatureMap
@return result object with summary values:
number of detected compounds (detected_compounds),
retention time shift mean (rt_shift_mean)
**/
Result compute(const FeatureMap& feature_map);
const String& getName() const override;
QCBase::Status requirements() const override;
private:
const String name_ = "Summary of features from featureXML file";
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/QC/Ms2SpectrumStats.h | .h | 4,019 | 95 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Juliane Schmachtenberg, Chris Bielow $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/MSSpectrum.h>
#include <OpenMS/KERNEL/Peak1D.h>
#include <OpenMS/QC/QCBase.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
namespace OpenMS
{
class FeatureMap;
class MSExperiment;
class PeptideIdentification;
class TransformationDescription;
/**
@brief QC metric to determine the number of MS2 scans per MS1 scan over RT
Ms2SpectrumStats collects data from MS2 scans and stores the result into PeptideIdentifications,
which already exist in the FeatureMap, or are newly created as empty PeptideIdentifications (with no sequence).
The following meta-values are computed:
"ScanEventNumber": consecutive number of each MS2 scan after the preceding MS1 scan
"identified": All PeptideIdentifications of the FeatureMap are marked with '+' and all unidentified MS2-Spectra with '-'.
"ion_injection_time": from MS2 spectrum
"activation_method": from MS2 spectrum
"total_ion_count": summed intensity from MS2 spectrum
"base_peak_intensity": highest intensity from MS2 spectrum
"FWHM": RT peak width for all assigned PIs (if provided)
**/
class OPENMS_DLLAPI Ms2SpectrumStats : public QCBase
{
public:
struct ScanEvent {
ScanEvent(UInt32 sem, bool ms2) : scan_event_number(sem), ms2_presence(ms2)
{
}
UInt32 scan_event_number;
bool ms2_presence;
};
/// Constructor
Ms2SpectrumStats() = default;
/// Destructor
virtual ~Ms2SpectrumStats() = default;
/**
@brief Calculate the ScanEventNumber, find all unidentified MS2-Spectra and add them to unassigned PeptideIdentifications,
write meta values "ScanEventNumber" and "identified" in PeptideIdentification.
@param[in] exp Imported calibrated MzML file as MSExperiment
@param[in,out] features Imported featureXML file after FDR as FeatureMap
@param[in] map_to_spectrum Map to find index of spectrum given by meta value at PepID
@return unassigned peptide identifications newly generated from unidentified MS2-Spectra
@throws MissingInformation If exp is empty
@throws InvalidParameter PeptideID is missing meta value 'spectrum_reference'
**/
PeptideIdentificationList compute(const MSExperiment& exp, FeatureMap& features, const QCBase::SpectraMap& map_to_spectrum);
/// returns the name of the metric
const String& getName() const override;
/// define the required input file: featureXML after FDR (=POSTFDRFEAT), MzML-file (MSExperiment) with all MS2-Spectra (=RAWMZML)
Status requirements() const override;
private:
/// name of the metric
const String name_ = "Ms2SpectrumStats";
/// ms2_included_ contains for every spectrum the information "ScanEventNumber" and presence MS2-scan in PeptideIDs
std::vector<ScanEvent> ms2_included_ {};
/// compute "ScanEventNumber" for every spectrum: MS1=0, MS2=1-n, write into ms2_included_
void setScanEventNumber_(const MSExperiment& exp);
/// set ms2_included_ bool to true, if PeptideID exist and set "ScanEventNumber" for every PeptideID
void setPresenceAndScanEventNumber_(PeptideIdentification& peptide_ID, const MSExperiment& exp, const QCBase::SpectraMap& map_to_spectrum);
/// return all unidentified MS2-Scans as unassignedPeptideIDs, these contain only Information about RT and "ScanEventNumber"
PeptideIdentificationList getUnassignedPeptideIdentifications_(const MSExperiment& exp);
/// calculate highest intensity (base peak intensity)
static MSSpectrum::PeakType::IntensityType getBPI_(const MSSpectrum& spec);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/QC/PSMExplainedIonCurrent.h | .h | 5,610 | 106 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Tom Waschischeck$
// $Authors: Tom Waschischeck$
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/METADATA/ProteinIdentification.h>
#include <OpenMS/QC/QCBase.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <vector>
namespace OpenMS
{
class FeatureMap;
class MSExperiment;
class PeptideIdentification;
class WindowMower;
class OPENMS_DLLAPI PSMExplainedIonCurrent : public QCBase
{
public:
/// Default constructor
PSMExplainedIonCurrent() = default;
/// Destructor
virtual ~PSMExplainedIonCurrent() = default;
/**
* @brief Structure for storing results: average and variance over all PSMs
*/
struct Statistics {
double average_correctness = 0;
double variance_correctness = 0;
};
/**
* @brief computes PSMExplainedIonCurrent (only of the first PeptideHit of each PepID)
*
* To calculate PSMExplainedIonCurrent the theoretical spectrum is generated and matched with the original one.
* After that: PSMExplainedIonCurrent = sum of matched peaks intensity / total intensity
*
* Stores average and variance of PSMExplainedIonCurrent as a struct and stores it in the results vector (can be accessed by getResults()).
* Each PSMExplainedIonCurrent is also stored in the first PeptideHit of the corresponding PeptideIdentification as metavalue "PSM_correctness".
*
* @param[in,out] fmap Input FeatureMap for annotation and data for theoretical spectra
* @param[in] exp Input MSExperiment for MS2 spectra; spectra should be sorted (ascending RT)
* @param[in] map_to_spectrum Map to find index of spectrum given by meta value at PepID
* @param[in] tolerance Search window for matching peaks; distance has to be lower than tolerance value
* @param[in] tolerance_unit Tolerance in ppm or Dalton (if auto was chosen, the unit and value will taken from FeatureMap metadata)
* @throws Exceptions::MissingInformation If fragment mass tolerance is missing in metadata of FeatureMap (& no ToleranceUnit is given)
* @throws Exception::InvalidParameter PeptideID is missing meta value 'spectrum_reference'
* @throws Exception::IllegalArgument Spectrum for a PepID has ms-level of 1
* @throws Exception::MissingInformation If PSMExplainedIonCurrent couldn't be calculated for any spectrum. (i.e. all spectra are: empty, contain only peaks with intensity 0 or the matching pep_id
* has no hits)
* @throws Exception::InvalidParameter If the fragmentation method is not ECD, ETD, CID or HCD
*/
void compute(FeatureMap& fmap, const MSExperiment& exp, const QCBase::SpectraMap& map_to_spectrum, ToleranceUnit tolerance_unit = ToleranceUnit::AUTO, double tolerance = 20);
/**
* @brief computes PSMExplainedIonCurrent (only of the first PeptideHit of each PepID)
*
* Same as above, but with PeptideIdentification + SearchParameter input instead of FeatureMap
*
* @param[in,out] pep_ids Input peptide identifications for annotation and data for theoretical spectra
* @param[in] search_params Input search parameters from ID-search that generated the peptide identifications from @p pep_ids
* @param[in] exp Input MSExperiment for MS2 spectra; spectra should be sorted (ascending RT)
* @param[in] map_to_spectrum Map to find index of spectrum given by meta value at PepID
* @param[in] tolerance Search window for matching peaks; distance has to be lower than tolerance value
* @param[in] tolerance_unit Tolerance in ppm or Dalton (if auto was chosen, the unit and value will taken from FeatureMap metadata)
* @throws Exceptions::MissingInformation If fragment mass tolerance is missing in metadata of FeatureMap (& no ToleranceUnit is given)
* @throws Exception::InvalidParameter PeptideID is missing meta value 'spectrum_reference'
* @throws Exception::IllegalArgument Spectrum for a PepID has ms-level of 1
* @throws Exception::MissingInformation If PSMExplainedIonCurrent couldn't be calculated for any spectrum. (i.e. all spectra are: empty, contain only peaks with intensity 0 or the matching pep_id
* has no hits)
* @throws Exception::InvalidParameter If the fragmentation method is not ECD, ETD, CID or HCD
*/
void compute(PeptideIdentificationList& pep_ids, const ProteinIdentification::SearchParameters& search_params, const MSExperiment& exp, const QCBase::SpectraMap& map_to_spectrum,
ToleranceUnit tolerance_unit = ToleranceUnit::AUTO, double tolerance = 20);
/// returns the name of the metric
const String& getName() const override;
/// returns results
const std::vector<Statistics>& getResults() const;
/**
* @brief Returns the input data requirements of the compute(...) function
* @return Status for RAWMZML and POSTFDRFEAT
*/
QCBase::Status requirements() const override;
private:
/// container that stores results
std::vector<Statistics> results_ {};
static double annotatePSMExplainedIonCurrent_(PeptideIdentification& pep_id, const MSExperiment& exp, const QCBase::SpectraMap& map_to_spectrum, WindowMower& filter,
PSMExplainedIonCurrent::ToleranceUnit tolerance_unit, double tolerance);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/QC/MissedCleavages.h | .h | 2,935 | 75 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Swenja Wagner, Patricia Scheil $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CHEMISTRY/ProteaseDigestion.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <OpenMS/METADATA/ProteinIdentification.h>
#include <OpenMS/QC/QCBase.h>
#include <map>
#include <vector>
namespace OpenMS
{
class FeatureMap;
/**
* @brief This class is a metric for the QualityControl TOPP Tool.
*
* This class counts the number of MissedCleavages per PeptideIdentification given a FeatureMap
* and returns an agglomeration statistic (observed counts).
* Additionally the PeptideHits in the FeatureMap are augmented with MetaInformation:
* - 'missed_cleavages'
* - 'FWHM' (from feature's 'FWHM' or 'model_FWHM')
* - 'mass' (experimental mass of peptide)
*/
class OPENMS_DLLAPI MissedCleavages : public QCBase
{
private:
typedef std::map<UInt32, UInt32> MapU32;
/// collects number of missed cleavages from PeptideIdentification in a result map (missed cleavages: occurences)
void get_missed_cleavages_from_peptide_identification_(const ProteaseDigestion& digestor, MapU32& result, const UInt32& max_mc, PeptideIdentification& pep_id);
public:
/// constructor
MissedCleavages() = default;
/// destructor
virtual ~MissedCleavages() = default;
/**
* @brief Counts the number of missed cleavages per PeptideIdentification.
*
* The result is a key/value map: \#missed_cleavages --> counts
* Additionally the first PeptideHit in each PeptideIdentification of the FeatureMap is annotated with metavalue 'missed_cleavages'.
* The protease and digestion parameters are taken from the first ProteinIdentication (and SearchParameter therein) within the FeatureMap itself.
*
* @param[in,out] fmap FeatureMap with Peptide and ProteinIdentifications
*/
void compute(FeatureMap& fmap);
void compute(std::vector<ProteinIdentification>& prot_ids, PeptideIdentificationList& pep_ids);
/// returns the name of the metric
const String& getName() const override;
/// returns the result as maps of number of missed_cleavages to counts; one map for each call to compute(...)
const std::vector<std::map<UInt32, UInt32>>& getResults() const;
/**
* @brief Returns the input data requirements of the compute(...) function
* @return Status for POSTFDRFEAT;
*/
QCBase::Status requirements() const override;
private:
/// container that stores results
std::vector<std::map<UInt32, UInt32>> mc_result_;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/QC/RTAlignment.h | .h | 2,214 | 66 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Juliane Schmachtenberg, Chris Bielow $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/QC/QCBase.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
namespace OpenMS
{
class FeatureMap;
class PeptideIdentification;
class TransformationDescription;
/**
@brief Take the original retention time before map alignment and use the alignment's trafoXML
for calculation of the new alignment retention times.
Sets meta values "rt_raw" and "rt_align" in PeptideIdentifications of the featureMap's PepIDs.
It does <b>not</b> change the RT of the features.
**/
class OPENMS_DLLAPI RTAlignment : public QCBase
{
public:
/// Constructor
RTAlignment() = default;
/// Destructor
virtual ~RTAlignment() = default;
/**
@brief Calculates retention time after map alignment
and sets meta values "rt_raw" and "rt_align" in all PepIDs (on features and all unassigned PepIDs)
@param[in,out] fm FeatureMap to receive the new metavalues
@param[in] trafo Transformation information to get needed data from
**/
void compute(FeatureMap& fm, const TransformationDescription& trafo) const;
/**
@brief Calculates retention time after map alignment
and sets meta values "rt_raw" and "rt_align" in all PepIDs
@param[in,out] ids PepIDs to receive the new metavalues
@param[in] trafo Transformation information to get needed data from
**/
void compute(PeptideIdentificationList& ids, const TransformationDescription& trafo) const;
/// returns the name of the metric
const String& getName() const override;
/// define the required input file: featureXML before map alignment (=POSTFDRFEAT), trafoXML after map alignment (=TRAFOALIGN)
Status requirements() const override;
private:
/// name of the metric
const String name_ = "RTAlignment";
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/QC/IdentificationSummary.h | .h | 2,635 | 78 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Axel Walter $
// $Authors: Axel Walter $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <OpenMS/METADATA/ProteinIdentification.h>
#include <OpenMS/QC/QCBase.h>
#include <vector>
/**
* @brief Detected Proteins/Peptides as a Proteomics QC metric
*
* Simple class to return a summary of detected proteins/peptides
* from a given idXML file.
*
*/
namespace OpenMS
{
class OPENMS_DLLAPI IdentificationSummary : public QCBase
{
public:
/// Constructor
IdentificationSummary() = default;
/// Destructor
virtual ~IdentificationSummary() = default;
// small struct for unique peptide / protein identifications (considering sequence only)
// count: number of unique identifications, fdr_threshold: significance threshold if score type is FDR, else -1
struct OPENMS_DLLAPI UniqueID {
UInt count = 0;
float fdr_threshold = -1.0;
};
// stores identification summary values calculated by compute function
struct OPENMS_DLLAPI Result {
UInt peptide_spectrum_matches = 0;
UniqueID unique_peptides;
UniqueID unique_proteins;
float missed_cleavages_mean = 0;
double protein_hit_scores_mean = 0;
double peptide_length_mean = 0;
bool operator==(const Result& rhs) const;
};
/**
@brief computes a summary of an idXML file
@param[in] prot_ids vector with ProteinIdentifications
@param[in] pep_ids vector with PeptideIdentifications
@return result object with summary values:
total number of PSM (peptide_spectrum_matches),
number of identified peptides with given FDR threshold (unique_peptides),
number of identified proteins with given FDR threshold (unique_proteins),
missed cleavages mean (missed_cleavages_mean),
identification score mean of protein hits (protein_hit_scores_mean),
identified peptide lengths mean (peptide_length_mean)
**/
Result compute(std::vector<ProteinIdentification>& prot_ids, PeptideIdentificationList& pep_ids);
const String& getName() const override;
QCBase::Status requirements() const override;
private:
const String name_ = "Summary of detected Proteins and Peptides from idXML file";
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/QC/FWHM.h | .h | 1,750 | 53 | // 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/QC/QCBase.h>
namespace OpenMS
{
class FeatureMap;
/**
@brief QC metric calculating (un)calibrated m/z error
The metric sets m/z-values of the original experiment and the calculated reference m/z-values, uncalibrated m/z error (ppm)
and calibrated m/z error (ppm) as metavalues of all PeptideIdentifications in a FeatureMap.
For full functionality a PeakMap/MSExperiment with original m/z-values before m/z calibration generated by InternalCalibration has to be given.
It's also possible to use this without an MzML File, but then only uncalibrated m/z error (ppm) will be reported.
A FeatureMap after FDR is always required.
**/
class OPENMS_DLLAPI FWHM : public QCBase
{
public:
/// Constructor
FWHM() = default;
/// Destructor
virtual ~FWHM() = default;
/**
@brief Moves FWHM metavalues from the feature to all its PeptideIdentifications (since that's were mzTab takes it from if we want to preserve Raw file origin)
A warning is issued on the commandline if a feature does not have either 'FWHM' or 'model_FWHM' as metavalue.
@param[in,out] features FeatureMap with features which have metavalue 'FWHM' or 'model_FWHM'
**/
void compute(FeatureMap& features);
const String& getName() const override;
Status requirements() const override;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/QC/QCBase.h | .h | 3,593 | 126 | // 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, Tom Waschischeck $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CONCEPT/Types.h>
#include <OpenMS/DATASTRUCTURES/FlagSet.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <algorithm>
#include <map>
namespace OpenMS
{
class MSExperiment;
class ConsensusMap;
/**
* @brief This class serves as an abstract base class for all QC classes.
*
* It contains the important feature of encoding the input requirements
* for a certain QC.
*/
class OPENMS_DLLAPI QCBase
{
public:
/**
* @brief Enum to encode a file type as a bit.
*/
enum class Requires : UInt64 // 64 bit unsigned type for bitwise and/or operations (see below)
{
NOTHING, //< default, does not require anything
RAWMZML, //< mzML file is required
POSTFDRFEAT, //< Features with FDR-filtered pepIDs
PREFDRFEAT, //< Features with unfiltered pepIDs
CONTAMINANTS, //< Contaminant Database
TRAFOALIGN, //< transformationXMLs for RT-alignment
ID, //< idXML with protein IDs
SIZE_OF_REQUIRES
};
/// strings corresponding to enum Requires
static const std::string names_of_requires[];
enum class ToleranceUnit
{
AUTO,
PPM,
DA,
SIZE_OF_TOLERANCEUNIT
};
/// strings corresponding to enum ToleranceUnit
static const std::string names_of_toleranceUnit[];
/**
* @brief Map to find a spectrum via its NativeID
*/
class OPENMS_DLLAPI SpectraMap
{
public:
/// Constructor
SpectraMap() = default;
/// CTor which allows immediate indexing of an MSExperiment
explicit SpectraMap(const MSExperiment& exp);
/// Destructor
~SpectraMap() = default;
/// calculate a new map, delete the old one
void calculateMap(const MSExperiment& exp);
/// get index from identifier
/// @throws Exception::ElementNotFound if @p identifier is unknown
UInt64 at(const String& identifier) const;
/// clear the map
void clear();
/// check if empty
bool empty() const;
/// get size of map
Size size() const;
private:
std::map<String, UInt64> nativeid_to_index_; //< nativeID to index
};
using Status = FlagSet<Requires>;
/**
* @brief Returns the name of the metric
*/
virtual const String& getName() const = 0;
/**
*@brief Returns the input data requirements of the compute(...) function
*/
virtual Status requirements() const = 0;
/// tests if a metric has the required input files
/// gives a warning with the name of the metric that can not be performed
bool isRunnable(const Status& s) const;
/// check if the IsobaricAnalyzer TOPP tool was used to create this ConsensusMap
static bool isLabeledExperiment(const ConsensusMap& cm);
/// does the container have a PeptideIdentification in its members or as unassignedPepID ?
template<typename MAP>
static bool hasPepID(const MAP& fmap)
{
if (!fmap.getUnassignedPeptideIdentifications().empty())
return true;
return std::any_of(fmap.cbegin(), fmap.cend(), [](const auto& f) { return !f.getPeptideIdentifications().empty(); });
}
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/QC/MQMsmsExporter.h | .h | 4,050 | 99 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow$
// $Authors: Hendrik Beschorner, Lenny Kovac, Virginia Rossow$
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/QC/MQExporterHelper.h>
#include <fstream>
#include <OpenMS/KERNEL/ConsensusFeature.h>
#include <OpenMS/KERNEL/ConsensusMap.h>
#include <OpenMS/KERNEL/Feature.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/MATH/MathFunctions.h>
/**
@brief Builds a MaxQuant msms.txt
This class is closely related to QualityControl, it creates an msms.txt similar
to a MaxQuant msms.txt. But not all columns of a MaxQuant file get exported.
By the construction of an object, the column names of the msms values are added to the msms.txt.
For the construction a valid path is needed (check out constructor) where the msms.txt can be stored.
To fill the output msms.txt with data from the MS/MS run use the exportFeatureMap function,
it needs a FeatureMap and the matching ConsensusMap as an input.
To check if the created msms.txt is writable use the function isValid.
@ingroup Metadata
*/
class OPENMS_DLLAPI MQMsms
{
private:
std::fstream file_; ///< Stream where the data is added to create msms.txt
OpenMS::Size id_ = 0; ///< number of rows in msms.txt to give each row a specific id
OpenMS::String filename_; ///< path and name of the msms.txt
/**
@brief Writes the header of msms.txt (Names of columns)
*/
void exportHeader_();
/**
@brief Export one Feature as a row in msms.txt
If the feature has no PepID's or the corresponding CF has no PepIDs,
no row will be exported
@param[in] f Feature to extract evidence data
@param[in] cmap ConsensusMap to extract msms data if Feature has no valid PeptideIdentifications
@param[in] c_feature_number Index of corresponding ConsensusFeature in ConsensusMap
@param[in] raw_file is specifying the raw_file the feature belongs to
@param[in] UIDs UIDs of all PeptideIdentifications of the ConsensusMap
@param[in] mp_f Mapping between the FeatureMap and ProteinIdentifications for the UID
from PeptideIdenfitication::buildUIDfromAllPepIds
@param[in] exp MS Experiment holds evidence data to extract
@param[in] prot_map Mapping a protein_accession to its description(proteinname, genename...)
*/
void exportRowFromFeature_(const OpenMS::Feature& f,
const OpenMS::ConsensusMap& cmap,
const OpenMS::Size c_feature_number,
const OpenMS::String& raw_file,
const std::multimap<OpenMS::String, std::pair<OpenMS::Size, OpenMS::Size>>& UIDs,
const OpenMS::ProteinIdentification::Mapping& mp_f,
const OpenMS::MSExperiment& exp = {},
const std::map<OpenMS::String,OpenMS::String>& prot_map = {});
public:
/**
@brief Creates MQMsms object and msms.txt in given path
If the path for the constructor is empty (path not valid), no msms.txt is created.
If the creation of the fstream object is successful a constant header is added to the msms.txt
If the path does not exist, it will be created
@throw Exception::FileNotWritable if msms.txt could not be created
@param[in] path that is the path where msms.txt has to be stored
*/
explicit MQMsms(const OpenMS::String& path);
/**
@brief Closes f_stream
*/
~MQMsms();
void exportFeatureMap(const OpenMS::FeatureMap& feature_map, const OpenMS::ConsensusMap& cmap,
const OpenMS::MSExperiment& exp, const std::map<OpenMS::String,OpenMS::String>& prot_map = {});
}; | Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/QC/Ms2IdentificationRate.h | .h | 5,211 | 126 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow$
// $Authors: Patricia Scheil, Swenja Wagner$
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/QC/QCBase.h>
#include <OpenMS/CONCEPT/Types.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <string>
#include <vector>
namespace OpenMS
{
class FeatureMap;
class MSExperiment;
class MzTabMetaData;
class PeptideIdentification;
/**
@brief This class is a metric for the QualityControl-ToppTool.
This class computes the MS2 Identification Rate (as \#identified PSMs divided by total number of MS2 scans) given a FeatureMap and an MSExperiment.
Only pep-ids with FDR metavalue 'target_decoy' equal to 'target' are counted, unless assume_all_target flag is set (assumes all pep-ids are target peptides)
*/
class OPENMS_DLLAPI Ms2IdentificationRate : public QCBase
{
public:
/// Structure for storing results
struct IdentificationRateData {
Size num_peptide_identification = 0;
Size num_ms2_spectra = 0;
double identification_rate = 0.;
};
private:
/// name of the metric
const String name_ = "Ms2IdentificationRate";
/// container that stores results
std::vector<IdentificationRateData> rate_result_;
/// returns number of all ms2 spectra in an MSExperiment
Size getMS2Count_(const MSExperiment& exp);
/*
* @brief Checks pepID for target/decoy
*
* Only checks the first (!) hit, all other hits are ignored
* Is static so that it can be used with MapUtilities::applyFunctionOnPeptideIDs() without creating a new object for each ID
*
* @param[in] id pepID to be checked
* @param[in] all_targets always returns true (if the hits aren't empty)
* @return true/false
* @throws MissingInformation if target/decoy annotation is missing
*/
static bool isTargetPeptide_(const PeptideIdentification& id, bool all_targets);
/*
* @brief Calculates id-rate and writes the result into a IdentificationRateData object which is appended to rate_result_
*
* @param[in] ms2_spectra_count number of found ms2 spectra
* @param[in] pep_ids_count number of found (target) peptide identifications
*/
void writeResults_(Size pep_ids_count, Size ms2_spectra_count);
public:
/// Default constructor
Ms2IdentificationRate() = default;
/// Destructor
virtual ~Ms2IdentificationRate() = default;
/**
* @brief computes Ms2 Identification Rate with FeatureMap
*
* stores results as a struct in a vector
* Only pep-ids with target/decoy annotation as 'target' are counted, unless force_index flag is set (assumes all pep-ids are target peptides)
*
* @param[in] feature_map Input FeatureMap with target/decoy annotation
* @param[in] exp MSExperiment for counting number of MS2 spectra
* @param[in] assume_all_target Count all(!) PepIDs towards number of identified MS2 spectra (ignore target/decoy information if any)
* @exception MissingInformation is thrown if the mzML is empty
* @exception MissingInformation is thrown if the experiment doesn't contain MS2 spectra
* @exception Precondition is thrown if there are more identifications than MS2 spectra
*/
void compute(const FeatureMap& feature_map, const MSExperiment& exp, bool assume_all_target = false);
/**
* @brief computes Ms2 Identification Rate with PeptideIdentifications
*
* stores results as a struct in a vector
* Only pep-ids with target/decoy annotation as 'target' are counted, unless force_index flag is set (assumes all pep-ids are target peptides)
*
* @param[in] pep_ids Input PeptideIdentifications with target/decoy annotation
* @param[in] exp MSExperiment for counting number of MS2 spectra
* @param[in] assume_all_target Count all(!) PepIDs towards number of identified MS2 spectra (ignore target/decoy information if any)
* @exception MissingInformation is thrown if the mzML is empty
* @exception MissingInformation is thrown if the experiment doesn't contain MS2 spectra
* @exception Precondition is thrown if there are more identifications than MS2 spectra
*/
void compute(const PeptideIdentificationList& pep_ids, const MSExperiment& exp, bool assume_all_target = false);
/// returns the name of the metric
const String& getName() const override;
/// returns results
const std::vector<IdentificationRateData>& getResults() const;
/**
* @brief Returns the input data requirements of the compute(...) function
* @return Status for RAWMZML and POSTFDRFEAT
*/
QCBase::Status requirements() const override;
void addMetaDataMetricsToMzTab(MzTabMetaData& meta) const;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/QC/DBSuitability.h | .h | 24,838 | 484 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Tom Waschischeck $
// $Authors: Tom Waschischeck $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CONCEPT/Types.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/FORMAT/FASTAFile.h>
#include <OpenMS/METADATA/ProteinIdentification.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <cfloat>
#include <vector>
#include <boost/regex.hpp>
namespace OpenMS
{
class ParamXMLFile;
class PeptideIdentification;
class PeptideHit;
class MSExperiment;
/**
* @brief This class holds the functionality of calculating the database suitability.
*
* To calculate the suitability of a database for a specific mzML for identification search, it
* is vital to perform a combined deNovo+database identification search. Meaning that the database
* should be appended with an additional entry derived from concatenated deNovo sequences from said mzML.
* Currently only Comet search is supported.
*
* This class will calculate q-values by itself and will throw an error if any q-value calculation was done beforehand.
*
* The algorithm parameters can be set using setParams().
*
* Allows for multiple usage of the compute function. The result of each call is stored internally in a vector.
* Therefore old results will not be overridden by a new call. This vector then can be returned using getResults().
*
* This class serves as the library representation of @ref TOPP_DatabaseSuitability
*/
class OPENMS_DLLAPI DBSuitability:
public DefaultParamHandler
{
public:
/// struct to store results
struct OPENMS_DLLAPI SuitabilityData
{
/// number of times the top hit is considered to be a deNovo hit
Size num_top_novo = 0;
/// number of times the top hit is considered to be a database hit
Size num_top_db = 0;
/// number of times a deNovo hit scored on top of a database hit
Size num_interest = 0;
/// number of times a deNovo hit scored on top of a database hit,
/// but their score difference was small enough, that it was still counted as a database hit
Size num_re_ranked = 0;
/// the cut-off that was used to determine when a score difference was "small enough"
/// this is normalized by mw
double cut_off = DBL_MAX;
/// the suitability of the database used for identification search, calculated with:
/// \#db_hits / (\#db_hits + \#deNovo_hit)
/// can reach from 0 -> the database was not at all suited to 1 -> the perfect database was used
///
/// Preliminary tests have shown that databases of the right organism or close related organisms
/// score around 0.9 to 0.95, organisms from the same class can still score around 0.8, organisms
/// from the same phylum score around 0.5 to 0.6 and after that it quickly falls to suitabilities
/// of 0.15 or even 0.05.
/// Note that these test were only performed for one mzML and your results might differ.
double suitability = 0;
/// the suitability if re-ranking would have been turned off
/// if re-ranking is actually turned off, this will be the same as the normal suitability
double suitability_no_rerank = 0;
/// the suitability after correcting the top deNovo hits, if re-ranking would have been disabled
double suitability_corr_no_rerank = 0;
// resets all members to their defaults
void clear();
/// apply a correction factor to the already calculated suitability
/// only works if num_top_db and num_top_novo contain a non-zero value
void setCorrectionFactor(double factor);
double getCorrectionFactor() const;
double getCorrectedNovoHits() const;
double getCorrectedSuitability() const;
/**
* @brief Returns a SuitabilityData object containing the data if re-ranking didn't happen
*
* Cases that are re-ranked are already counted. To get the 'no re-ranking' data these cases need to be
* subtracted from the number of top database hits and added to the number of top deNovo hits.
*
* @returns simulated suitability data where re-ranking didn't happen
*/
SuitabilityData simulateNoReRanking() const;
private:
/// \#IDs with only deNovo search / \#IDs with only database search
/// used for correcting the number of deNovo hits
/// worse databases will have less IDs than good databases
/// this punishes worse databases more than good ones and will result in
/// a worse suitability
double corr_factor = -1;
/// number of top deNovo hits multiplied by the correction factor
double num_top_novo_corr = 0;
/// the suitability after correcting the top deNovo hits to impact worse databases more
///
/// The corrected suitability has a more linear behaviour. It basicly translates to the ratio
/// of the theoretical perfect database the used database corresponds to. (i.e. a corrected
/// suitability of 0.5 means the used database contains half the proteins of the 'perfect' database)
double suitability_corr = 0;
};
/// Constructor
/// Settings are initialized with their default values:
/// no_rerank = false, reranking_cutoff_percentile = 1, FDR = 0.01
DBSuitability();
/// Destructor
~DBSuitability() override = default;
/// To test private member functions
friend class DBSuitability_friend;
/**
* @brief Computes suitability of a database used to search a mzML
*
* Top deNovo and top database hits from a combined deNovo+database search
* are counted. The ratio of db hits vs all hits yields the suitability.
* To re-rank cases, where a de novo peptide scores just higher than
* the database peptide, a decoy cut-off is calculated. This functionality
* can be turned off. This will result in an underestimated suitability,
* but it can solve problems like different search engines or to few decoy hits.
*
* Parameters can be set using the functionality of DefaultParamHandler.
* Parameters are:
* no_rerank - re-ranking can be turned off with this (will be set automatically
* if no cross correlation score is found)
* reranking_cutoff_percentile - percentile that determines which cut-off will be returned
* FDR - q-value that should be filtered for
* Preliminary tests have shown that database suitability
* is rather stable across common FDR thresholds from 0 - 5 %
* keep_search_files - temporary files created for and by the internal ID search are kept
* disable_correction - disables corrected suitability calculations
* force - forces re-ranking to be done even without a cross correlation score,
* in which case the default main score is used
*
* The calculated suitability is then tried to be corrected. For this a correction factor for the number of found top
* deNovo hits is calculated.
* This is done by perfoming an additional combined identification search with a smaller sample of the database.
* It was observed that the number of top deNovo and db hits behave linear according to the sampling ratio of the
* database. This can be used to extrapolate the number of database hits that would be needed to get a suitability
* of 1. This number in combination with the maximum number of deNovo hits (found with an identification search
* where only deNovo is used as a database) can be used to calculate a correction factor like this:
* \#database hits for suitability of 1 / \#maximum deNovo hits
* This formula can be simplified in a way that the maximum number of deNovo hits isn't needed:
* - (database hits slope) / deNovo hits slope
* Both of these values can easily be calculated with the original suitability data in conjunction with the one sampled search.
*
* Correcting the number of found top deNovo hits with this factor results in them being more comparable to the top
* database hits. This in return results in a more linear behaviour of the suitability according to the sampling ratio.
* The corrected suitability reflects what sampling ratio your database represents regarding to the theoretical 'perfect'
* database. Or in other words: Your database needs to be (1 - corrected suitability) bigger to get a suitability of 1.
*
* Both the original suitability as well as the corrected one are reported in the result.
*
* Since q-values need to be calculated the identifications are taken by copy.
* Since decoys need to be calculated for the fasta input those are taken by copy as well.
*
* Result is appended to the result member. This allows for multiple usage.
*
* @param[in] pep_ids vector containing pepIDs with target/decoy annotation coming from a deNovo+database
* identification search without FDR
* (Comet is recommended - to use other search engines either disable reranking or set the '-force' flag)
* vector is modified internally, and is thus copied
* @param[in] exp MSExperiment that was searched to produce the identifications
* given in @p pep_ids
* @param[in] original_fasta FASTAEntries of the database used for the ID search (without decoys)
* @param[in] novo_fasta FASTAEntry derived from deNovo peptides
* @param[in] search_params SearchParameters object containing information which adapter
* was used with which settings for the identification search
* that resulted in @p pep_ids
* @throws MissingInformation if no target/decoy annotation is found on @p pep_ids
* @throws MissingInformation if no xcorr is found,
* this happens when another adapter than CometAdapter was used
* @throws Precondition if a q-value is found in @p pep_ids
*/
void compute(PeptideIdentificationList&& pep_ids, const MSExperiment& exp, const std::vector<FASTAFile::FASTAEntry>& original_fasta, const std::vector<FASTAFile::FASTAEntry>& novo_fasta, const ProteinIdentification::SearchParameters& search_params);
/**
* @brief Returns results calculated by this metric
*
* The returned vector contains one DBSuitabilityData object for each time compute was called.
* Each of these objects contains the suitability information that was extracted from the
* identifications used for the corresponding call of compute.
*
* @returns DBSuitabilityData objects in a vector
*/
const std::vector<SuitabilityData>& getResults() const;
private:
/// result vector
std::vector<SuitabilityData> results_;
/// pattern for finding a decoy string
const boost::regex decoy_pattern_;
/**
* @brief Calculates the xcorr difference between the top two hits marked as decoy
*
* Searches for the top two decoys hits and returns their score difference.
* By default the xcorr from Comet is used. If no xcorr can be found and the 'force' flag is set
* the main score from the peptide hit is used, else an error is thrown.
*
* If there aren't two decoys, DBL_MAX is returned.
*
* @param[in] pep_id pepID from where the decoy difference will be calculated
* @returns xcorr difference
* @throws MissingInformation if no target/decoy annotation is found
* @throws MissingInformation if no xcorr is found
*/
double getDecoyDiff_(const PeptideIdentification& pep_id) const;
/**
* @brief Calculates a xcorr cut-off based on decoy hits
*
* Decoy differences of all N pepIDs are calculated. The (1-reranking_cutoff_percentile)*N highest
* one is returned.
* It is assumed that this difference accounts for 'reranking_cutoff_percentile' of the re-ranking cases.
*
* @param[in] pep_ids vector containing the pepIDs
* @param[in] reranking_cutoff_percentile percentile that determines which cut-off will be returned
* @returns xcorr cut-off
* @throws IllegalArgument if reranking_cutoff_percentile isn't in range [0,1]
* @throws IllegalArgument if reranking_cutoff_percentile is too low for a decoy cut-off to be calculated
* @throws MissingInformation if no more than 20 % of the peptide IDs have two decoys in their top ten peptide hits
*/
double getDecoyCutOff_(const PeptideIdentificationList& pep_ids, double reranking_cutoff_percentile) const;
/**
* @brief Tests if a PeptideHit is considered a deNovo hit
*
* To test this the function looks into the protein accessions.
* If only the deNovo protein is found, 'true' is returned.
* If at least one database protein is found, 'false' is returned.
*
* This function also uses boost::regex_search to make sure the deNovo accession doesn't contain a decoy string.
* This is needed for 'target+decoy' hits.
*
* @param[in] hit PepHit in question
* @returns true/false
*/
bool isNovoHit_(const PeptideHit& hit) const;
/**
* @brief Tests if a PeptideHit has a score better than the given threshold
*
* @param[in] hit PepHit in question
* @param[in] threshold threshold to check against
* @param[in] higher_score_better true/false depending if a higher or a lower score is better
* @returns true/false
*/
bool checkScoreBetterThanThreshold_(const PeptideHit& hit, double threshold, bool higher_score_better) const;
/**
* @brief Looks through meta values of SearchParameters to find out which search adapter was used
*
* Checks for the following adapters:
* CometAdapter, MSGFPlusAdapter, MSFraggerAdapter
*
* @param[in] meta_values SearchParameters object, since the adapters write their parameters here
* @returns A pair containing the name of the adapter and the parameters used to run it
* @throws MissingInformation if none of the adapters above is found in the meta values
*/
std::pair<String, Param> extractSearchAdapterInfoFromMetaValues_(const ProteinIdentification::SearchParameters& meta_values) const;
/**
* @brief Writes parameters into a given file
*
* @param[in] parameters parameters to write
* @param[in] filename name of the file where the parameters should be written to
* @throws UnableToCreateFile if filename isn't writable
*/
void writeIniFile_(const Param& parameters, const String& filename) const;
/**
* @brief Executes the workflow from search adapter, followed by PeptideIndexer and finishes with FDR
*
* Which adapter should run with which parameters can be controlled.
* Make sure the search adapter you wish to use is built on your system and the executable is on your PATH variable.
*
* Indexing and FDR are always done the same way.
*
* The inputs are stored in temporary files to execute the Adapter.
* (MSExperiment -> .mzML, vector<FASTAEntry> -> .fasta, Param -> .INI)
*
* @param[in] exp MSExperiment that will be searched
* @param[in] fasta_data represents the database that should be used to search
* @param[in] adapter_name name of the adapter to search with
* @param[in,out] parameters parameters for the adapter
* @returns peptide identifications with annotated q-values
* @throws MissingInformation if no adapter name is given
* @throws InvalidParameter if a not supported adapter name is given
* @throws InternalToolError if any error occures while running the adapter
* @throws InternalToolError if any error occures while running PeptideIndexer functionalities
* @throws InvalidParameter if the needed FDR parameters are not found
*/
PeptideIdentificationList runIdentificationSearch_(const MSExperiment& exp, const std::vector<FASTAFile::FASTAEntry>& fasta_data, const String& adapter_name, Param& parameters) const;
/**
* @brief Creates a subsampled fasta with the given subsampling rate
*
* The subsampling is based on the number of amino acides and not on the number of fasta entries.
*
* @param[in] fasta_data fasta of which the subsampling should be done
* @param[in] subsampling_rate subsampling rate to be used [0,1]
* @returns fasta entries with total number of AA = original number of AA * subsampling_rate
* @throws IllegalArgument if subsampling rate is not between 0 and 1
*/
std::vector<FASTAFile::FASTAEntry> getSubsampledFasta_(const std::vector<FASTAFile::FASTAEntry>& fasta_data, double subsampling_rate) const;
/**
* @brief Calculates all suitability data from a combined deNovo+database search
*
* Counts top database and top deNovo hits.
*
* Calculates a decoy score cut-off to compare high scoring deNovo hits with lower scoring database hits.
* If the score difference is smaller than the cut-off the database hit is counted and the deNovo hit ignored.
*
* Suitability is calculated: # database hits / # all hits
*
* @param[in] pep_ids peptide identifications coming from the combined search, each peptide identification should be sorted
* @param[out] data SuitabilityData object where the result should be written into
* @throws MissingInformation if no target/decoy annotation is found on @p pep_ids
* @throws MissingInformation if no xcorr is found,
* this happens when another adapter than CometAdapter was used
*/
void calculateSuitability_(const PeptideIdentificationList& pep_ids, SuitabilityData& data) const;
/**
* @brief Calculates and appends decoys to a given vector of FASTAEntry
*
* Each sequence is digested with Trypsin. The resulting peptides are reversed and appended to one another.
* This results in the decoy sequences.
* The identifier is given a 'DECOY_' prefix.
*
* @param[in,out] fasta reference to fasta vector where the decoys are needed
*/
void appendDecoys_(std::vector<FASTAFile::FASTAEntry>& fasta) const;
/**
* @brief Returns the cross correlation score normalized by MW (if existing), else if the 'force' flag is set the current main score is returned
*
* @param[in] pep_hit PeptideHit of which the score is needed
* @returns cross correlation score normalized by MW or current score
* @throws MissingInformation if no xcorr is found and 'force' flag isn't set
*/
double extractScore_(const PeptideHit& pep_hit) const;
/**
* @brief Calculates the correction factor from two suitability calculations
*
* Two suitability calculations need to be done for this. One with the original data and one with data from a search with a sampled database.
* The number of db hits and deNovo hits behaves linear. The two searches can than be used to calculate the
* corresponding linear functions.
* The factor is calculated with the negative ratio of the db slope and the deNovo slope.
*
* @param[in] data suitability data from the original search
* @param[in] data_sampled vector of suitability data from the sampled search(s)
* @param[in] sampling_rate the sampling rate used for sampled db [0,1)
* @returns correction factor
*/
double calculateCorrectionFactor_(const SuitabilityData& data, const SuitabilityData& data_sampled, double sampling_rate) const;
/**
* @brief Determines the number of unique proteins found in the protein accessions of PeptideIdentifications
*
* @param[in] peps vector of PeptideIdentifications
* @param[in] number_of_hits the number of hits to search in (if this is bigger than the actual number of hits all hits are looked at)
* @returns number of unique protein accessions
* @throws MissingInformation if no target/decoy annotation is found on @p peps
*/
UInt numberOfUniqueProteins_(const PeptideIdentificationList& peps, UInt number_of_hits = 1) const;
/**
* @brief Finds the SuitabilityData object with the median number of de novo hits
*
* If the median isn't distinct (e.g. two entries could be considered median) the upper one is chosen.
*
* @param[in] data vector of SuitabilityData objects
* @returns index to object with median number of de novo hits
*/
Size getIndexWithMedianNovoHits_(const std::vector<SuitabilityData>& data) const;
/**
* @brief Extracts the worst score that still passes a FDR (q-value) threshold
*
* This can be used to 'convert' a FDR threshold to a threshold for the desired score (score and FDR need to be dependent)
*
* @param[in] pep_ids vector of PeptideIdentifications
* @param[in] FDR FDR threshold, hits with a worse q-value score aren't looked at
* @param[in] score_name name of the score to search for
* The score name doesn't need to be the exact metavalue name, but a metavalue key should contain it.
* i.e. "e-value" as metavalue "e-value_score"
* @param[in] higher_score_better true/false depending if a higher or lower score (@p score_name) is better
* @returns the worst score that is still in the FDR threshold
*
* @throws IllegalArgument if @p score_name isn't found in the metavalues
* @throws Precondition if main score of @p pep_ids isn't 'q-value'
*/
double getScoreMatchingFDR_(const PeptideIdentificationList& pep_ids, double FDR, const String& score_name, bool higher_score_better) const;
};
// friend class to test private member functions
class DBSuitability_friend
{
public:
DBSuitability_friend() = default;
~DBSuitability_friend() = default;
std::vector<FASTAFile::FASTAEntry> getSubsampledFasta(const std::vector<FASTAFile::FASTAEntry>& fasta_data, double subsampling_rate)
{
return suit_.getSubsampledFasta_(fasta_data, subsampling_rate);
}
void appendDecoys(std::vector<FASTAFile::FASTAEntry>& fasta)
{
suit_.appendDecoys_(fasta);
}
double calculateCorrectionFactor(const DBSuitability::SuitabilityData& data, const DBSuitability::SuitabilityData& data_sampled, double sampling_rate)
{
return suit_.calculateCorrectionFactor_(data, data_sampled, sampling_rate);
}
UInt numberOfUniqueProteins(const PeptideIdentificationList& peps, UInt number_of_hits = 1)
{
return suit_.numberOfUniqueProteins_(peps, number_of_hits);
}
Size getIndexWithMedianNovoHits(const std::vector<DBSuitability::SuitabilityData>& data)
{
return suit_.getIndexWithMedianNovoHits_(data);
}
double getScoreMatchingFDR(const PeptideIdentificationList& pep_ids, double FDR, String score_name, bool higher_score_better)
{
return suit_.getScoreMatchingFDR_(pep_ids, FDR, score_name, higher_score_better);
}
/* Not tested:
getDecoyDiff_, getDecoyCutOff_, isNovoHit_, checkScoreBetterThanThreshold_
Reason: These functions are essential to the normal suitability calculation and if something would not work, the test for 'compute' would fail.
extractSearchAdapterInfoFromMetaValues_, writeIniFile_, extractScore_
Reason: These functions are very straightforeward.
runIdentificationSearch_
Reason: This function simulates a whole workflow and testing it would be to complicated.
*/
private:
DBSuitability suit_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/QC/MQEvidenceExporter.h | .h | 4,491 | 110 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow$
// $Authors: Valentin Noske, Vincent Musch$
// --------------------------------------------------------------------------
#pragma once
#include <fstream>
#include <OpenMS/KERNEL/ConsensusFeature.h>
#include <OpenMS/KERNEL/ConsensusMap.h>
#include <OpenMS/KERNEL/Feature.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/QC/MQExporterHelper.h>
#include <map>
class OPENMS_DLLAPI MQEvidence
/**
@brief Builds a MaxQuant Evidence.txt
This class is closely related to QualityControl, it creates an evidence.txt similar
to a MaxQuant evidence.txt. But not all columns of a MaxQuant file get exported.
By the construction of an object, the column names of the evidence values are added to the evidence.txt.
For the construction a valid path is needed (check out constructor) where the evidence.txt can be stored.
To fill the output evidence.txt with data from the MS/MS run use the exportFeatureMap function,
it needs a FeatureMap and the matching ConsensusMap as an input.
To check if the created evidence.txt is writable use the function isValid.
@ingroup Metadata
*/
{
private:
std::fstream file_; ///< Stream where the data is added to create evidence.txt
OpenMS::Size id_ = 0; ///< number of rows in evidence.txt to give each row a specific id
OpenMS::String filename_; ///< path and name of the evidence.txt
/**
@brief Writes the header of evidence.txt (Names of columns)
*/
void exportHeader_();
/**
@brief Export one Feature as a row in MQEvidence.txt
If the feature has no PepID's or the corresponding CF has no PepIDs,
no row will be exported
@param[in] f Feature to extract evidence data
@param[in] cmap ConsensusMap to extract evidence data if Feature has no valid PeptideIdentifications
@param[in] c_feature_number Index of corresponding ConsensusFeature in ConsensusMap
@param[in] raw_file is specifying the raw_file the feature belongs to
@param[in] UIDs UIDs of all PeptideIdentifications of the ConsensusMap
@param[in] mp_f Mapping between the FeatureMap and ProteinIdentifications for the UID
from PeptideIdenfitication::buildUIDfromAllPepIds
@param[in] exp MS Experiment holds evidence data to extract
@param[in] prot_map Mapping a protein_accession to its description(proteinname, genename...)
*/
void exportRowFromFeature_(
const OpenMS::Feature& f,
const OpenMS::ConsensusMap& cmap,
const OpenMS::Size c_feature_number,
const OpenMS::String& raw_file,
const std::multimap<OpenMS::String, std::pair<OpenMS::Size, OpenMS::Size>>& UIDs,
const OpenMS::ProteinIdentification::Mapping& mp_f,
const OpenMS::MSExperiment& exp= {},
const std::map<OpenMS::String,OpenMS::String>& prot_map = {});
public:
/**
@brief Creates MQEvidence object and evidence.txt in given path
If the path for the constructor is empty (path not valid), no evidence.txt is created.
If the creation of the fstream object is successful a constant header is added to the evidence.txt
If the path does not exist, it will be created
@throw Exception::FileNotWritable if evidence.txt could not be created
@param[in] path that is the path where evidence.txt has to be stored
*/
explicit MQEvidence(const OpenMS::String& path);
/**
@brief Closes f_stream
*/
~MQEvidence();
/**
@brief Exports a FeatureMap to the evidence.txt
Exports one row per feature from the FeatureMap to the evidence.txt file.
@throw Exception::FileNotWritable if evidence.txt is not writable
@throw Exception::MissingInformation if Feature_map has no corresponding ConsensusFeature
@param[in] feature_map which contains Features to extract evidence data
@param[in] cmap ConsensusMap to extract evidence data if Feature has no valid PeptideIdentifications
@param[in] exp MS Experiment holds evidence data to extract
@param[in] prot_map Mapping a protein_accession to its description(proteinname, genename...)
*/
void exportFeatureMap(
const OpenMS::FeatureMap& feature_map,
const OpenMS::ConsensusMap& cmap,
const OpenMS::MSExperiment& exp= {},
const std::map<OpenMS::String,OpenMS::String>& prot_map = {});
}; | Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/QC/SpectrumCount.h | .h | 1,119 | 47 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Axel Walter $
// $Authors: Axel Walter $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/QC/QCBase.h>
/**
* @brief Number of MS spectra per MS level (SpectrumCount) as a QC metric
*/
namespace OpenMS
{
class MSExperiment;
class OPENMS_DLLAPI SpectrumCount : public QCBase
{
public:
/// Constructor
SpectrumCount() = default;
/// Destructor
virtual ~SpectrumCount() = default;
/**
@brief Compute number of spectra per MS level and returns them in a map
@param[in] exp MSExperiment containing the spectra to be counted
@return SpectrumCount
**/
std::map<Size, UInt> compute(const MSExperiment& exp);
const String& getName() const override;
QCBase::Status requirements() const override;
private:
const String name_ = "SpectrumCount";
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/QC/FragmentMassError.h | .h | 6,604 | 114 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow$
// $Authors: Patricia Scheil, Swenja Wagner$
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/METADATA/ProteinIdentification.h>
#include <OpenMS/QC/QCBase.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <vector>
namespace OpenMS
{
class FeatureMap;
class MSExperiment;
class PeptideIdentification;
class WindowMower;
class OPENMS_DLLAPI FragmentMassError : public QCBase
{
public:
/// Default constructor
FragmentMassError() = default;
/// Destructor
virtual ~FragmentMassError() = default;
/**
* @brief Structure for storing results: average and variance of all FragmentMassErrors in ppm
*/
struct Statistics {
double average_ppm = 0;
double variance_ppm = 0;
};
/**
* @brief computes FragmentMassError (FME) in ppm and Dalton (only of the first PeptideHit of each PepID)
*
* Stores average FME over all spectra (one for each PeptideIdentification) and its variance in ppm as a struct in a vector.
* Each FME (in ppm) is stored at the first PeptideHit of the corresponding PeptideIdentification as metavalue Constants::UserParam::FRAGMENT_ERROR_PPM_METAVALUE_USERPARAM
* and contains the FME for each peak in the corresponding spectrum.
* Same is done for the FME in Da - as metavalue Constants::UserParam::FRAGMENT_ERROR_DA_METAVALUE_USERPARAM.
* For both tolerance units the variance of FMEs over the spectrum is also stored as a metavalue with the extension "_variance" to the metavalue name.
* Note: Variance will not be written if 1 or less FMEs were calculated.
* Note: If the metavalues already exist, they will be overwritten.
*
* @param[in,out] fmap Input FeatureMap for annotation and data for theoretical spectra
* @param[in] exp Input MSExperiment for MS2 spectra; spectra should be sorted (ascending RT)
* @param[in] map_to_spectrum Map to find index of spectrum given by meta value at PepID
* @param[in] tolerance_unit Tolerance in ppm or Dalton (if auto was chosen, the unit and value will taken from FeatureMap metadata)
* @param[in] tolerance Search window for matching peaks; distance has to be lower than tolerance value (Will be overwritten if tolerance_unit AUTO is chosen)
* @throws Exceptions::MissingInformation If fragment mass tolerance is missing in metadata of FeatureMap
* @throws Exception::InvalidParameter PeptideID is missing meta value 'spectrum_reference'
* @throws Exception::IllegalArgument Spectrum for a PepID has ms-level of 1
* @throws Exception::MissingInformation If no fragmentation method given in a MS2 precursor
* @throws Exception::InvalidParameter If the fragmentation method is not ECD, ETD, CID or HCD
*/
void compute(FeatureMap& fmap, const MSExperiment& exp, const QCBase::SpectraMap& map_to_spectrum, ToleranceUnit tolerance_unit = ToleranceUnit::AUTO, double tolerance = 20);
/**
* @brief computes FragmentMassError (FME) in ppm and Dalton (only of the first PeptideHit of each PepID)
*
* Stores average FME over all spectra and its variance in ppm as a struct in a vector.
* Each FME (in ppm) is stored at the first PeptideHit of the corresponding PeptideIdentification as metavalue Constants::UserParam::FRAGMENT_ERROR_PPM_METAVALUE_USERPARAM
* and contains the FME for each peak in the corresponding spectrum.
* Same is done for the FME in Da - as metavalue Constants::UserParam::FRAGMENT_ERROR_DA_METAVALUE_USERPARAM.
* For both tolerance units the variance of FMEs over the spectrum is also stored as a metavalue with the extension "_variance" to the metavalue name.
* Note: Variance will not be written if 1 or less FMEs were calculated.
* Note: If the metavalues already exist, they will be overwritten.
*
* @param[in,out] pep_ids Input vector of peptide identifications for annotation and data for theoretical spectra
* @param[in] search_params Input search parameters (corresponding to ID search that generated @p pep_ids) for finding fragment mass tolerance and unit automatically
* @param[in] exp Input MSExperiment for MS2 spectra; spectra should be sorted (ascending RT)
* @param[in] map_to_spectrum Map to find index of spectrum given by meta value at PepID
* @param[in] tolerance_unit Tolerance in ppm or Dalton (if auto was chosen, the unit and value will taken from FeatureMap metadata)
* @param[in] tolerance Search window for matching peaks; distance has to be lower than tolerance value (Will be overwritten if tolerance_unit AUTO is chosen)
* @throws Exceptions::MissingInformation If fragment mass tolerance is missing in @p search_params
* @throws Exception::InvalidParameter PeptideID is missing meta value 'spectrum_reference'
* @throws Exception::IllegalArgument Spectrum for a PepID has ms-level of 1
* @throws Exception::MissingInformation If no fragmentation method given in a MS2 precursor
* @throws Exception::InvalidParameter If the fragmentation method is not ECD, ETD, CID or HCD
*/
void compute(PeptideIdentificationList& pep_ids, const ProteinIdentification::SearchParameters& search_params, const MSExperiment& exp, const QCBase::SpectraMap& map_to_spectrum,
ToleranceUnit tolerance_unit = ToleranceUnit::AUTO, double tolerance = 20);
/// returns the name of the metric
const String& getName() const override;
/// returns results
const std::vector<Statistics>& getResults() const;
/**
* @brief Returns the input data requirements of the compute(...) function
* @return Status for RAWMZML and POSTFDRFEAT
*/
QCBase::Status requirements() const override;
private:
/// container that stores results
std::vector<Statistics> results_;
static void calculateFME_(PeptideIdentification& pep_id, const MSExperiment& exp, const QCBase::SpectraMap& map_to_spectrum, bool& print_warning, double tolerance,
FragmentMassError::ToleranceUnit tolerance_unit, double& accumulator_ppm, UInt32& counter_ppm, WindowMower& window_mower_filter);
static void calculateVariance_(FragmentMassError::Statistics& result, const PeptideIdentification& pep_id, const UInt num_ppm);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/QC/MzCalibration.h | .h | 2,666 | 67 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Juliane Schmachtenberg $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/QC/QCBase.h>
namespace OpenMS
{
class FeatureMap;
class MSExperiment;
class PeptideIdentification;
/**
@brief QC metric calculating (un)calibrated m/z error
The metric sets m/z-values of the original experiment and the calculated reference m/z-values, uncalibrated m/z error (ppm)
and calibrated m/z error (ppm) as metavalues of all PeptideIdentifications in a FeatureMap.
For full functionality a PeakMap/MSExperiment with original m/z-values before m/z calibration generated by InternalCalibration has to be given.
It's also possible to use this without an MzML File, but then only uncalibrated m/z error (ppm) will be reported.
A FeatureMap after FDR is always required.
**/
class OPENMS_DLLAPI MzCalibration : public QCBase
{
public:
/// Constructor
MzCalibration();
/// Destructor
virtual ~MzCalibration() = default;
/**
* @brief Writes results as meta values to the PeptideIdentification of the given FeatureMap
* @param[in,out] features FeatureMap with m/z-values of PeptideIdentification after calibration, meta values are added here
* @param[in] exp PeakMap of the original experiment. Can be empty (i.e. not available).
* @param[in] map_to_spectrum Map to find index of spectrum given by meta value at PepID
* @throws Exception::InvalidParameter PeptideID is missing meta value 'spectrum_reference'
* @throws Exception::IllegalArgument Spectrum for a PepID has MSLevel of 1
* @throws Exception::MissingInformation Meta value 'mz_raw' missing from MSExperiment
**/
void compute(FeatureMap& features, const MSExperiment& exp, const QCBase::SpectraMap& map_to_spectrum);
/// define the required input files
/// only FeatureXML after FDR is ultimately necessary
Status requirements() const override;
/// Returns the name of the metric.
const String& getName() const override;
private:
/// calculate the m/z values and m/z errors and add them to the PeptideIdentification
void addMzMetaValues_(PeptideIdentification& peptide_ID, const MSExperiment& exp, const QCBase::SpectraMap& map_to_spectrum);
double mz_raw_;
double mz_ref_;
bool no_mzml_;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/QC/MQExporterHelper.h | .h | 6,410 | 158 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow$
// $Authors: Virginia Rossow, Lenny Kovac, Hendrik Beschorner$
// --------------------------------------------------------------------------
#pragma once
#include <fstream>
#include <OpenMS/KERNEL/ConsensusFeature.h>
#include <OpenMS/KERNEL/ConsensusMap.h>
#include <OpenMS/KERNEL/Feature.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/MATH/MathFunctions.h>
class OPENMS_DLLAPI MQExporterHelper
/**
@brief Helper class for common functions and NON trivial values needed for exporting MaxQuant outputs
@ingroup Metadata
*/
{
public:
struct MQCommonOutputs
{
std::stringstream modifications;
char acetyl;
std::stringstream oxidation;
std::stringstream gene_names;
std::stringstream protein_names;
std::stringstream msms_mz;
std::stringstream mass_error_ppm;
std::stringstream mass_error_da;
std::stringstream uncalibrated_mass_error_ppm;
std::stringstream uncalibrated_mass_error_da;
std::stringstream uncalibrated_calibrated_mz_ppm;
std::stringstream uncalibrated_calibrated_mz_mda;
std::stringstream base_peak_fraction;
// common columns in msms and evividence exporter
//file_ << "Sequence" << "\t"; maybe, relativ trivial
//file_ << "Length" << "\t";
//file_ << "Modifications" << "\t"; implementieren
// file_ << "Modified sequence" << "\t"; implementieren
//file_ << "Acetyl (Protein N-term)" << "\t"; implementieren
//file_ << "Oxidation (M)" << "\t"; implementieren
//file_ << "Missed cleavages" << "\t"; trivial
//file_ << "Proteins" << "\t"; trivial
//file_ << "Gene Names" << "\t"; // in progress, aber implementieren
//file_ << "Protein Names" << "\t"; // in progress, aber implementieren
//file_ << "Type" << "\t"; TODO different type
//file_ << "Raw file" << "\t"; trivial
//file_ << "MS/MS m/z" << "\t"; implementieren TODO is m/z in MSMS MS/MS m/z
//file_ << "Charge" << "\t"; trivial
//file_ << "m/z" << "\t"; trivial TODO
//file_ << "Mass" << "\t"; trivial
//file_ << "Mass Error [ppm]" << "\t"; vielleicht, beim einen halt noch calibrated dabei
//file_ << "Mass Error [Da]" << "\t"; vielleicht, beim einen halt noch calibrated dabei
//file_ << "Retention time" << "\t"; trivial
//file_ << "Fraction of total spectrum" << "\t"; trivial
//file_ << "Base peak fraction" << "\t"; trvial
//file_ << "PEP" << "\t"; trivial
//file_ << "MS/MS Scan Number" << "\t"; trivial
//file_ << "Score" << "\t"; trivial
//file_ << "Delta score" << "\t"; trivial
//file_ << "Reverse" << "\t";
//file_ << "id" << "\t"; ?
//file_ << "Protein group IDs" << "\n"; trivial
explicit MQCommonOutputs(
const OpenMS::Feature& f,
const OpenMS::ConsensusMap& cmap,
const OpenMS::Size c_feature_number,
const std::multimap<OpenMS::String, std::pair<OpenMS::Size, OpenMS::Size>>& UIDs,
const OpenMS::ProteinIdentification::Mapping& mp_f,
const OpenMS::MSExperiment& exp,
const std::map<OpenMS::String,OpenMS::String>& prot_mapper);
};
/**
@brief Extract a gene name from a protein description by looking for the substring 'GN='
If no such substring exists, an empty string is returned.
*/
static OpenMS::String extractGeneName(const OpenMS::String& prot_description);
/**
@brief Returns a unique ID (number) for each distinct protein accession, or creates a new ID by augmenting the given database.
Obtains a unique, consecutive number for each distinct protein, which can
be used as a protein ID in the MaxQuant output files (in lack of a proper
proteingroup ID which maps to proteinGroups.txt)
@param[in,out] database A map from accession to ID (which can be augmented by this function)
@param[in] protein_accession The protein accession which needs translation to an ID
@return The ID for the @p protein_accession
*/
static OpenMS::Size proteinGroupID_(std::map<OpenMS::String, OpenMS::Size>& database,
const OpenMS::String& protein_accession);
/**
@brief Creates map that has the information which FeatureUID is mapped to which ConsensusFeature in ConsensusMap
@throw Exception::Precondition if FeatureHandle exists twice in ConsensusMap
@param[in] cmap ConsensusMap that includes ConsensusFeatures
@return Returns map, the index is a FeatureID, the value is the index of the ConsensusFeature
in the vector of ConsensusMap
*/
static std::map<OpenMS::Size, OpenMS::Size> makeFeatureUIDtoConsensusMapIndex_(const OpenMS::ConsensusMap& cmap);
/**
@brief Checks if Feature has valid PeptideIdentifications
If there are no PeptideIdentifications or the best hit of the Feature cannot be found in corresponding ConsensusFeature,
the functions returns false to show that something went wrong.
@param[in] f Feature to extract PeptideIdentifications
@param[in] c_feature_number Index of corresponding ConsensusFeature in ConsensusMap
@param[in] UIDs UIDs of all PeptideIdentifications of the ConsensusMap
@param[in] mp_f Mapping between the FeatureMap and ProteinIdentifications for the UID
@return Returns true if the PeptideIdentifications exist and are valid
*/
static bool hasValidPepID_(
const OpenMS::Feature& f,
const OpenMS::Size c_feature_number,
const std::multimap<OpenMS::String, std::pair<OpenMS::Size, OpenMS::Size>>& UIDs,
const OpenMS::ProteinIdentification::Mapping& mp_f);
/**
@brief Checks if ConsensusFeature has valid PeptideIdentifications
If there are no PeptideIdentifications,
the functions returns false to show that something went wrong.
@param[in] cf is used to extract PeptideIdentifications
@return Returns true if the ConsensusFeature has any PepIDs; otherwise false
*/
static bool hasPeptideIdentifications_(const OpenMS::ConsensusFeature& cf);
/**
@brief Checks if file is writable
(i.e. the path in the ctor was not empty and could be created)
@return Returns true if file is writable
*/
static bool isValid(const std::string& filename_);
}; | Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/QC/TIC.h | .h | 2,373 | 77 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Tom Waschischeck $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/QC/QCBase.h>
/**
* @brief Total Ion Count (TIC) as a QC metric
*
* Simple class to calculate the TIC of an MSExperiment.
* Allows for multiple usage, because each calculated TIC is
* stored internally. Those results can then be returned using
* getResults().
*
*/
namespace OpenMS
{
class MzTabMetaData;
class MSExperiment;
class MSChromatogram;
class OPENMS_DLLAPI TIC : public QCBase
{
public:
/// Constructor
TIC() = default;
/// Destructor
virtual ~TIC() = default;
// stores TIC values calculated by compute function
struct OPENMS_DLLAPI Result {
std::vector<UInt> intensities; // TIC intensities
std::vector<float> relative_intensities;
std::vector<float> retention_times; // TIC RTs in seconds
UInt area = 0; // Area under TIC
UInt fall = 0; // MS1 signal fall (10x) count
UInt jump = 0; // MS1 signal jump (10x) count
bool operator==(const Result& rhs) const;
};
/**
@brief Compute Total Ion Count and applies the resampling algorithm, if a bin size in RT seconds greater than 0 is given.
All MS1 TICs within a bin are summed up.
@param[in] exp Peak map to compute the MS1 tick from
@param[in] bin_size RT bin size in seconds
@param[in] ms_level MS level of spectra for calculation
@return result struct with with computed QC metrics: intensities, RTs (in seconds), area under TIC, 10x MS1 signal fall, 10x MS1 signal jump
**/
Result compute(const MSExperiment& exp, float bin_size = 0, UInt ms_level = 1);
const String& getName() const override;
const std::vector<MSChromatogram>& getResults() const;
QCBase::Status requirements() const override;
/// append QC data for given metrics to mzTab's MTD section
void addMetaDataMetricsToMzTab(MzTabMetaData& meta, std::vector<Result>& tics);
private:
const String name_ = "TIC";
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/QC/PeptideMass.h | .h | 1,114 | 46 | // 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/QC/QCBase.h>
namespace OpenMS
{
class FeatureMap;
/**
@brief QC metric calculating theoretical mass of a peptide sequence
Each PeptideHit in the FeatureMap will be annotated with its theoretical mass as metavalue 'mass'
**/
class OPENMS_DLLAPI PeptideMass : public QCBase
{
public:
/// Constructor
PeptideMass() = default;
/// Destructor
virtual ~PeptideMass() = default;
/**
@brief Sets the 'mass' metavalue to all PeptideHits by computing the theoretical mass
@param[in,out] features FeatureMap with PeptideHits
**/
void compute(FeatureMap& features);
const String& getName() const override;
Status requirements() const override;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/QC/Contaminants.h | .h | 4,220 | 106 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Dominik Schmitz, Chris Bielow$
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/FORMAT/FASTAFile.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/QC/QCBase.h>
#include <unordered_set>
namespace OpenMS
{
/**
* @brief This class is a metric for the QualityControl TOPP tool.
*
* This class checks whether a peptide is a contaminant (given a protein DB) and adds that result as metavalue "is_contaminant"
* to the first hit of each PeptideIdentification.
*/
class OPENMS_DLLAPI Contaminants : public QCBase
{
public:
/// structure for storing results
struct ContaminantsSummary {
///(\#contaminants in assigned/ \#peptides in assigned)
double assigned_contaminants_ratio;
///(\#contaminants in unassigned/ \#peptides in unassigned)
double unassigned_contaminants_ratio;
///(\#all contaminants/ \#peptides in all)
double all_contaminants_ratio;
///(intensity of contaminants in assigned/ intensity of peptides in assigned)
double assigned_contaminants_intensity_ratio;
///(features without peptideidentification or with peptideidentifications but without hits; all features)
std::pair<Int64, Int64> empty_features;
};
/// Constructor
Contaminants() = default;
/// Destructor
virtual ~Contaminants() = default;
/**
* @brief Checks if the peptides are in the contaminant database.
*
* "is_contaminant" metavalue is added to the first hit of each PeptideIdentification of each feature
* and to the first hit of all unsigned PeptideIdentifications.
* The enzyme and number of missed cleavages used to digest the given protein DB is taken
* from the ProteinIdentification[0].getSearchParameters() within the given FeatureMap.
*
* @param[in,out] features Input FeatureMap with peptideidentifications of features
* @param[in] contaminants Vector of FASTAEntries that need to be digested to check whether a peptide is a contaminant or not
* @exception Exception::MissingInformation if the contaminants database is empty
* @exception Exception::MissingInformation if no enzyme is given
* @exception Exception::MissingInformation if proteinidentification of FeatureMap is empty
* @warning LOG_WARN if the FeatureMap is empty
*/
void compute(FeatureMap& features, const std::vector<FASTAFile::FASTAEntry>& contaminants);
/// returns the name of the metric
const String& getName() const override;
/// returns results
const std::vector<Contaminants::ContaminantsSummary>& getResults();
/**
* @brief Returns the input data requirements of the compute(...) function
* @return Status for POSTFDRFEAT and CONTAMINANTS
*/
Status requirements() const override;
private:
/// name of the metric
const String name_ = "Contaminants";
/// container that stores results
std::vector<Contaminants::ContaminantsSummary> results_;
/// unordered set that contains the contaminant sequences
std::unordered_set<String> digested_db_;
/**
* @brief
* checks if the peptide is in the contaminant database
* @param[in] key String that will be the key for searching in the unordered set
* @param[in,out] pep_hit PeptideHit to store the result "is_contaminant = 0/1"
* @param[in,out] total counter of all checked peptides
* @param[in,out] cont counter of all checked peptides that are contaminants
* @param[in,out] sum_total intensity of all checked peptides
* @param[in,out] sum_cont intensity of all checked peptides that are contaminants
* @param[in] intensity intensity of current peptide
*/
void compare_(const String& key, PeptideHit& pep_hit, Int64& total, Int64& cont, double& sum_total, double& sum_cont, double intensity);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/PeptideHit.h | .h | 15,714 | 459 | // 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 <iosfwd>
#include <vector>
#include <functional>
#include <OpenMS/CONCEPT/Types.h>
#include <OpenMS/CONCEPT/Constants.h>
#include <OpenMS/CONCEPT/HashUtils.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/METADATA/MetaInfoInterface.h>
#include <OpenMS/CHEMISTRY/AASequence.h>
#include <OpenMS/METADATA/PeptideEvidence.h>
namespace OpenMS
{
class PeptideHit;
using SpectrumMatch = PeptideHit; // better name that might become the default in future version
/**
@brief Represents a single spectrum match (candidate) for a specific tandem mass spectrum (MS/MS).
Stores the primary information about a potential match, including:
- The sequence (potentially with modifications) using AASequence.
- The primary score assigned by the identification algorithm (e.g., search engine).
- The rank of this hit compared to other hits for the same spectrum (stored as a meta value with key "rank").
- The precursor charge state assumed for this match.
- Evidence linking the peptide sequence to specific protein sequences (PeptideEvidence).
- Optional annotations mapping fragment ions in the MS/MS spectrum to interpretations (PeakAnnotation).
- Optional secondary scores from post-processing tools (PepXMLAnalysisResult).
Objects are typically contained within a PeptideIdentification object, which represents
all hits found for a single spectrum. Inherits from MetaInfoInterface, allowing
arbitrary metadata (key-value pairs) to be attached.
@deprecated Use SpectrumMatch instead. PeptideHit may be removed in a future OpenMS version.
@see PeptideIdentification, AASequence, PeptideEvidence, PeakAnnotation, PepXMLAnalysisResult, MetaInfoInterface
@ingroup Metadata
*/
class OPENMS_DLLAPI PeptideHit :
public MetaInfoInterface
{
public:
/// Enum for target/decoy annotation
enum class TargetDecoyType
{
TARGET, ///< Only matches target proteins
DECOY, ///< Only matches decoy proteins
TARGET_DECOY, ///< Matches BOTH target and decoy proteins
UNKNOWN ///< Target/decoy status is unknown (meta value not set)
};
/**
* @brief Contains annotations of a peak
The mz and intensity values contain the same information as a spectrum
would have about the peaks, and can be used to map the additional
information to the correct peak or reconstruct the annotated spectrum.
Additionally the charge of the peak and an arbitrary string annotation
can be stored.
The string annotation can be e.g. a fragment type like "y3".
This information can be used e.g. to label peaks in TOPPView.
The specific application in OpenProXL uses a more complex syntax to
define the larger number of different ion types found in XL-MS data.
In the example "[alpha|ci$y3-H2O-NH3]" "alpha" or "beta" determines on
which of the two peptides the fragmentation occurred, "ci" or "xi"
determines whether the cross-link and with it the other peptide is
contained in the fragment, and the last part is the ion type with the
fragmentation position (index) and losses. The separators "|" and "$"
are used to separate the parts easily when parsing the annotation.
*/
struct OPENMS_DLLAPI PeakAnnotation
{
String annotation = ""; // e.g. [alpha|ci$y3-H2O-NH3]
int charge = 0;
double mz = -1.;
double intensity = 0.;
bool operator<(const PeptideHit::PeakAnnotation& other) const;
bool operator==(const PeptideHit::PeakAnnotation& other) const;
static void writePeakAnnotationsString_(String& annotation_string, std::vector<PeptideHit::PeakAnnotation> annotations);
};
public:
/// @name Comparators for PeptideHit and ProteinHit
//@{
/// Greater predicate for scores of hits
class OPENMS_DLLAPI ScoreMore
{
public:
template <typename Arg>
bool operator()(const Arg& a, const Arg& b)
{
return a.getScore() > b.getScore();
}
};
/// Lesser predicate for scores of hits
class OPENMS_DLLAPI ScoreLess
{
public:
template <typename Arg>
bool operator()(const Arg& a, const Arg& b)
{
return a.getScore() < b.getScore();
}
};
/// Lesser predicate for scores of hits
class OPENMS_DLLAPI RankLess
{
public:
template <typename Arg>
bool operator()(const Arg& a, const Arg& b)
{
return a.getRank() < b.getRank();
}
};
//@}
/// @name Hash functors for PeptideHit
//@{
/**
* @brief Hash functor for PeptideHit based on sequence and charge.
*
* This hasher computes a portable hash based on the peptide sequence
* (including modifications) and charge state. This represents the
* "identity" of a peptide hit for most practical purposes.
*
* @note This hash is NOT consistent with operator== which also compares
* score, rank, evidences, annotations, and meta info. Use this
* hasher when you want to identify unique peptides by sequence+charge.
*
* Example usage:
* @code
* std::unordered_set<PeptideHit, PeptideHit::SequenceChargeHash, PeptideHit::SequenceChargeEqual> unique_hits;
* @endcode
*/
class OPENMS_DLLAPI SequenceChargeHash
{
public:
std::size_t operator()(const PeptideHit& hit) const noexcept
{
std::size_t seed = std::hash<AASequence>{}(hit.getSequence());
OpenMS::hash_combine(seed, OpenMS::hash_int(hit.getCharge()));
return seed;
}
};
/**
* @brief Equality functor for PeptideHit based on sequence and charge.
*
* Companion to SequenceChargeHash for use in unordered containers.
*/
class OPENMS_DLLAPI SequenceChargeEqual
{
public:
bool operator()(const PeptideHit& a, const PeptideHit& b) const noexcept
{
return a.getSequence() == b.getSequence() && a.getCharge() == b.getCharge();
}
};
//@}
/// Lesser predicate for (modified) sequence of hits
class OPENMS_DLLAPI SequenceLessComparator
{
template <typename Arg>
bool operator()(const Arg& a, const Arg& b)
{
if (a.getSequence().toString() < b.getSequence().toString()) return true;
return false;
}
};
//@}
/// Analysis Result (containing search engine / prophet results)
class OPENMS_DLLAPI PepXMLAnalysisResult
{
public:
String score_type; /// e.g. peptideprophet / interprophet
bool higher_is_better{}; /// is higher score better ?
double main_score{}; /// posterior probability for example
std::map<String, double> sub_scores; /// additional scores attached to the original, aggregated score
bool operator==(const PepXMLAnalysisResult& rhs) const
{
return score_type == rhs.score_type
&& higher_is_better == rhs.higher_is_better
&& main_score == rhs.main_score
&& sub_scores == rhs.sub_scores;
}
};
/** @name Constructors and Assignment
*/
//@{
/// Default constructor
PeptideHit();
/// Values constructor that copies sequence
PeptideHit(double score,
UInt rank,
Int charge,
const AASequence& sequence);
/// Values constructor that moves sequence R-value
PeptideHit(double score,
UInt rank,
Int charge,
AASequence&& sequence);
/// Copy constructor
PeptideHit(const PeptideHit& source);
/// Move constructor
PeptideHit(PeptideHit&&) noexcept;
/// Destructor
virtual ~PeptideHit();
/// Assignment operator
PeptideHit& operator=(const PeptideHit& source);
/// Move assignment operator
PeptideHit& operator=(PeptideHit&&) noexcept;
//@}
/// Equality operator
bool operator==(const PeptideHit& rhs) const;
/// Inequality operator
bool operator!=(const PeptideHit& rhs) const;
/** @name Accessors
*/
//@{
/// returns the peptide sequence
const AASequence& getSequence() const;
/// returns the mutable peptide sequence
AASequence& getSequence();
/// sets the peptide sequence
void setSequence(const AASequence& sequence);
/// sets the peptide sequence
void setSequence(AASequence&& sequence);
/// returns the charge of the peptide
Int getCharge() const;
/// sets the charge of the peptide
void setCharge(Int charge);
/// returns information on peptides (potentially) identified by this PSM
const std::vector<PeptideEvidence>& getPeptideEvidences() const;
/// set information on peptides (potentially) identified by this PSM
void setPeptideEvidences(const std::vector<PeptideEvidence>& peptide_evidences);
void setPeptideEvidences(std::vector<PeptideEvidence>&& peptide_evidences);
/// adds information on a peptide that is (potentially) identified by this PSM
void addPeptideEvidence(const PeptideEvidence& peptide_evidence);
/// returns the PSM score
double getScore() const;
/// sets the PSM score
void setScore(double score);
/// set information on (search engine) sub scores associated with this PSM (only used by pepXML)
void setAnalysisResults(const std::vector<PepXMLAnalysisResult>& aresult);
/// add information on (search engine) sub scores associated with this PSM (only used by pepXML)
void addAnalysisResults(const PepXMLAnalysisResult& aresult);
/// returns information on (search engine) sub scores associated with this PSM (only used by pepXML)
std::vector<PepXMLAnalysisResult> getAnalysisResults() const;
/// returns the PSM rank
UInt getRank() const;
/// sets the PSM rank (0 = top hit)
void setRank(UInt newrank);
/// returns the fragment annotations
std::vector<PeptideHit::PeakAnnotation>& getPeakAnnotations();
const std::vector<PeptideHit::PeakAnnotation>& getPeakAnnotations() const;
/// sets the fragment annotations
void setPeakAnnotations(std::vector<PeptideHit::PeakAnnotation> frag_annotations);
/**
* @brief Returns true if this hit is annotated as mapping to decoy sequences only.
* Returns false for TargetDecoyType::TARGET and TargetDecoyType::TARGET_DECOY.
* Note: an unknown/unannotated state (TargetDecoyType::UNKNOWN) will yield false.
*/
bool isDecoy() const;
/** @brief Sets the target/decoy type for this peptide hit
*
* This method provides a type-safe way to annotate peptide hits with their
* target/decoy status. Use TARGET_DECOY for peptides that match both target
* and decoy protein sequences (these are treated as targets in FDR calculations).
* Note: UNKNOWN should only be used in special cases where the status needs to
* be explicitly marked as unknown.
*
* @param[in] type The target/decoy classification:
* - TARGET: Only matches target proteins
* - DECOY: Only matches decoy proteins
* - TARGET_DECOY: Matches both target and decoy proteins
* - UNKNOWN: Target/decoy status is unknown (explicit unknown state)
*/
void setTargetDecoyType(TargetDecoyType type);
/** @brief Returns the target/decoy type for this peptide hit
*
* This method performs case-insensitive parsing of the "target_decoy" meta value
* and returns the corresponding enum value. Returns UNKNOWN if the meta value
* does not exist.
*
* @return The target/decoy classification:
* - TARGET: Only matches target proteins
* - DECOY: Only matches decoy proteins
* - TARGET_DECOY: Matches both target and decoy proteins
* - UNKNOWN: Target/decoy status not set (meta value missing)
*/
TargetDecoyType getTargetDecoyType() const;
//@}
/// extracts the set of non-empty protein accessions from peptide evidences
std::set<String> extractProteinAccessionsSet() const;
protected:
AASequence sequence_;
/// the score of the peptide hit
double score_{};
/// the charge of the peptide
Int charge_{};
/// information on the potential peptides observed through this PSM.
std::vector<PeptideEvidence> peptide_evidences_;
/// annotations of fragments in the corresponding spectrum
std::vector<PeptideHit::PeakAnnotation> fragment_annotations_;
private:
/// Get the number of analysis results stored as meta values (only for pepXML results)
size_t getNumberOfAnalysisResultsFromMetaValues_() const;
/// Extract analysis results from meta values (only for pepXML results)
std::vector<PepXMLAnalysisResult> extractAnalysisResultsFromMetaValues_() const;
};
/// Stream operator
OPENMS_DLLAPI std::ostream& operator<< (std::ostream& stream, const PeptideHit& hit);
} // namespace OpenMS
// Hash function specialization for PeptideHit::PeakAnnotation
namespace std
{
/**
* @brief Hash function for OpenMS::PeptideHit::PeakAnnotation.
*
* Computes a hash by combining annotation (via fnv1a_hash_string),
* charge, mz, and intensity fields using hash_combine.
*
* @note Hash is consistent with operator==.
*/
template<>
struct hash<OpenMS::PeptideHit::PeakAnnotation>
{
std::size_t operator()(const OpenMS::PeptideHit::PeakAnnotation& pa) const noexcept
{
std::size_t seed = OpenMS::fnv1a_hash_string(pa.annotation);
OpenMS::hash_combine(seed, OpenMS::hash_int(pa.charge));
OpenMS::hash_combine(seed, OpenMS::hash_float(pa.mz));
OpenMS::hash_combine(seed, OpenMS::hash_float(pa.intensity));
return seed;
}
};
} // namespace std
// Hash function specialization for PeptideHit
namespace std
{
/**
* @brief Hash function for OpenMS::PeptideHit.
*
* Computes a hash consistent with operator==, which compares:
* - MetaInfoInterface (all meta values)
* - sequence_ (AASequence)
* - score_ (double)
* - rank (stored as meta value)
* - charge_ (int)
* - peptide_evidences_ (vector<PeptideEvidence>)
* - fragment_annotations_ (vector<PeakAnnotation>)
*
* @note Hash is consistent with operator==.
*/
template<>
struct hash<OpenMS::PeptideHit>
{
std::size_t operator()(const OpenMS::PeptideHit& hit) const noexcept
{
// Start with MetaInfoInterface hash (includes rank which is stored as meta value)
std::size_t seed = std::hash<OpenMS::MetaInfoInterface>{}(hit);
// Hash sequence
OpenMS::hash_combine(seed, std::hash<OpenMS::AASequence>{}(hit.getSequence()));
// Hash score
OpenMS::hash_combine(seed, OpenMS::hash_float(hit.getScore()));
// Note: rank is NOT hashed separately - it's included via MetaInfoInterface above
// (rank is stored as meta value "rank" when non-zero)
// Hash charge
OpenMS::hash_combine(seed, OpenMS::hash_int(hit.getCharge()));
// Hash peptide evidences
for (const auto& pe : hit.getPeptideEvidences())
{
OpenMS::hash_combine(seed, std::hash<OpenMS::PeptideEvidence>{}(pe));
}
// Hash fragment annotations
for (const auto& fa : hit.getPeakAnnotations())
{
OpenMS::hash_combine(seed, std::hash<OpenMS::PeptideHit::PeakAnnotation>{}(fa));
}
return seed;
}
};
} // namespace std
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/CVTermListInterface.h | .h | 3,774 | 129 | // 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/METADATA/MetaInfoInterface.h>
#include <OpenMS/METADATA/CVTerm.h>
#include <OpenMS/CONCEPT/HashUtils.h>
#include <map>
namespace OpenMS
{
class CVTermList;
/**
@brief Interface to the controlled vocabulary term list
This class is an interface to CVTermList, providing the same interface
and it can be used instead (direct plug-in). It can be used to inherit
from instead of CVTermList. The advantage is that this class only stores
a single pointer to a CVTermList which may be more efficient for an empty
list than storing the whole object.
@ingroup Metadata
*/
class OPENMS_DLLAPI CVTermListInterface :
public MetaInfoInterface
{
public:
/** @name Constructors and Assignment
*/
//@{
// Constructor
CVTermListInterface();
/// Copy constructor
CVTermListInterface(const CVTermListInterface & rhs);
/// Move constructor
CVTermListInterface(CVTermListInterface&&) noexcept;
// Destructor (non virtual)
~CVTermListInterface();
/// Assignment operator
CVTermListInterface & operator=(const CVTermListInterface & rhs);
/// Move assignment operator
CVTermListInterface& operator=(CVTermListInterface&&) noexcept;
//@}
/// equality operator
bool operator==(const CVTermListInterface& rhs) const;
/// inequality operator
bool operator!=(const CVTermListInterface& rhs) const;
void replaceCVTerms(std::map<String, std::vector<CVTerm> > & cv_terms);
/// sets the CV terms
void setCVTerms(const std::vector<CVTerm>& terms);
/// replaces the specified CV term
void replaceCVTerm(const CVTerm& cv_term);
/// replaces the specified CV terms using the given accession number
void replaceCVTerms(const std::vector<CVTerm>& cv_terms, const String& accession);
/// replaces all cv terms with a map (can be obtained via getCVTerms)
void replaceCVTerms(const std::map<String, std::vector<CVTerm> >& cv_term_map);
/// merges the given map into the member map, no duplicate checking
void consumeCVTerms(const std::map<String, std::vector<CVTerm> >& cv_term_map);
/// returns the accession string of the term
const std::map<String, std::vector<CVTerm> >& getCVTerms() const;
/// adds a CV term
void addCVTerm(const CVTerm& term);
/// checks whether the term has a value
bool hasCVTerm(const String& accession) const;
bool empty() const;
private:
void createIfNotExists_();
CVTermList* cvt_ptr_;
};
} // namespace OpenMS
// Hash function specialization for CVTermListInterface
namespace std
{
/**
* @brief Hash function for CVTermListInterface.
*
* Hashes based on all CV terms stored in the interface.
* Iterates through the map of accession -> vector<CVTerm>.
*/
template<>
struct hash<OpenMS::CVTermListInterface>
{
std::size_t operator()(const OpenMS::CVTermListInterface& iface) const noexcept
{
std::size_t seed = 0;
for (const auto& entry : iface.getCVTerms())
{
// Hash the accession string
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(entry.first));
// Hash each CV term in the vector
for (const auto& term : entry.second)
{
OpenMS::hash_combine(seed, std::hash<OpenMS::CVTerm>{}(term));
}
}
return seed;
}
};
} // namespace std
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/MetaInfo.h | .h | 7,269 | 210 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#pragma once
#include <vector>
#include <OpenMS/CONCEPT/Types.h>
#include <OpenMS/CONCEPT/HashUtils.h>
#include <OpenMS/METADATA/MetaInfoRegistry.h>
#include <OpenMS/DATASTRUCTURES/DataValue.h>
#include <boost/container/flat_map.hpp>
#include <functional>
namespace OpenMS
{
class String;
/**
@brief A Type-Name-Value tuple class.
MetaInfo maps an index (an integer corresponding to a string) to
DataValue objects. The mapping of strings to the index is performed by
the MetaInfoRegistry, which can be accessed by the method registry().
There are two versions of nearly all members. One which operates with a
string name and another one which operates on an index. The index version
is always faster, as it does not need to look up the index corresponding
to the string in the MetaInfoRegistry.
If you wish to add a MetaInfo member to a class, consider deriving that
class from MetaInfoInterface, instead of simply adding MetaInfo as
member. MetaInfoInterface implements a full interface to a MetaInfo
member and is more memory efficient if no meta info gets added.
@ingroup Metadata
*/
class OPENMS_DLLAPI MetaInfo
{
public:
/// Internal map type (UInt key to DataValue)
using MapType = boost::container::flat_map<UInt, DataValue>;
/// Mutable iterator type
using iterator = MapType::iterator;
/// Const iterator type
using const_iterator = MapType::const_iterator;
/// Constructor
MetaInfo() = default;
/// Copy constructor
MetaInfo(const MetaInfo&) = default;
/// Move constructor
MetaInfo(MetaInfo&&) = default;
/// Destructor
~MetaInfo();
/// Assignment operator
MetaInfo& operator=(const MetaInfo&) = default;
/// Move assignment operator
MetaInfo& operator=(MetaInfo&&) & = default;
/// Equality operator
bool operator==(const MetaInfo& rhs) const;
/// Equality operator
bool operator!=(const MetaInfo& rhs) const;
/**
* @brief Merge another MetaInfo into this one.
*
* All entries from @p rhs are added to this MetaInfo.
* If an entry with the same index already exists, it will be overwritten
* with the value from @p rhs.
*
* Uses an O(n+m) two-way merge algorithm since the underlying flat_map is sorted.
*
* @param rhs The MetaInfo to merge from.
* @return Reference to this object.
*/
MetaInfo& operator+=(const MetaInfo& rhs);
/// Returns the value corresponding to a string, or a default value (default: DataValue::EMPTY) if not found
const DataValue& getValue(const String& name, const DataValue& default_value = DataValue::EMPTY) const;
/// Returns the value corresponding to an index, or a default value (default: DataValue::EMPTY) if not found
const DataValue& getValue(UInt index, const DataValue& default_value = DataValue::EMPTY) const;
/// Returns whether an entry with the given name exists
bool exists(const String& name) const;
/// Returns whether an entry with the given index exists
bool exists(UInt index) const;
/// Sets the DataValue corresponding to a name
void setValue(const String& name, const DataValue& value);
/// Sets the DataValue corresponding to an index
void setValue(UInt index, const DataValue& value);
/// Removes the DataValue corresponding to @p name if it exists
void removeValue(const String& name);
/// Removes the DataValue corresponding to @p index if it exists
void removeValue(UInt index);
/// Returns a reference to the MetaInfoRegistry
static MetaInfoRegistry& registry();
/// Fills the given vector with a list of all keys for which a value is set
void getKeys(std::vector<String>& keys) const;
/// Fills the given vector with a list of all keys for which a value is set
void getKeys(std::vector<UInt>& keys) const;
/// Returns if the MetaInfo is empty
bool empty() const;
/// Removes all meta values
void clear();
/// @name Iterator access
/// @brief Provides iterator access to the underlying index-to-value map.
/// Iterators dereference to std::pair<UInt, DataValue> where the first element
/// is the registry index and the second is the associated value.
/// The iteration order is sorted by index (ascending).
///@{
/**
* @brief Returns a const iterator to the beginning of the meta info entries.
* @return const_iterator pointing to the first index-value pair, or end() if empty.
*/
const_iterator begin() const { return index_to_value_.begin(); }
/**
* @brief Returns a const iterator to the end of the meta info entries.
* @return const_iterator pointing past the last index-value pair.
*/
const_iterator end() const { return index_to_value_.end(); }
/**
* @brief Returns a const iterator to the beginning of the meta info entries.
* @return const_iterator pointing to the first index-value pair, or cend() if empty.
*/
const_iterator cbegin() const { return index_to_value_.cbegin(); }
/**
* @brief Returns a const iterator to the end of the meta info entries.
* @return const_iterator pointing past the last index-value pair.
*/
const_iterator cend() const { return index_to_value_.cend(); }
/**
* @brief Returns a mutable iterator to the beginning of the meta info entries.
* @return iterator pointing to the first index-value pair, or end() if empty.
* @note Modifying the key (first element) may invalidate the sorted order invariant.
*/
iterator begin() { return index_to_value_.begin(); }
/**
* @brief Returns a mutable iterator to the end of the meta info entries.
* @return iterator pointing past the last index-value pair.
*/
iterator end() { return index_to_value_.end(); }
///@}
/**
* @brief Returns the number of meta value entries.
* @return The count of index-value pairs stored.
*/
Size size() const { return index_to_value_.size(); }
private:
/// Static MetaInfoRegistry
static MetaInfoRegistry registry_;
/// The actual mapping of indexes to values
MapType index_to_value_;
// Grant access to hash implementation
friend struct std::hash<MetaInfo>;
};
} // namespace OpenMS
// Hash function specialization for MetaInfo
namespace std
{
template<>
struct hash<OpenMS::MetaInfo>
{
std::size_t operator()(const OpenMS::MetaInfo& mi) const noexcept
{
std::size_t seed = 0;
// Hash each key-value pair in sorted order (flat_map is already sorted by key)
for (const auto& [key, value] : mi.index_to_value_)
{
OpenMS::hash_combine(seed, OpenMS::hash_int(key));
OpenMS::hash_combine(seed, std::hash<OpenMS::DataValue>{}(value));
}
return seed;
}
};
} // namespace std
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/ProteinModificationSummary.h | .h | 1,784 | 48 | // 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 <map>
#include <OpenMS/CHEMISTRY/ResidueModification.h>
namespace OpenMS
{
/**
* @brief Map a protein position to all observed modifications and associated statistics
*
* For example, allows storing that position 10 in the protein carries Oxidation (M)
* and was observed in 123 PSMs.
* Note: Implementation uses a std::map, thus accessing a location not present in the map
* with operator[] will value construct an empty map at that location. Like with std::maps
* check first if the key exists.
*/
struct OPENMS_DLLAPI ProteinModificationSummary
{
/// basic modification statistic
struct OPENMS_DLLAPI Statistics
{
bool operator==(const Statistics& rhs) const;
size_t count = 0; ///< total number of PSMs supporting the modification at this position
double frequency = 0.0; ///< PSMs with modification / total number of PSMs
double FLR = 0.0; ///< false localization rate
double probability = 0.0; ///< (localization) probability
};
/// comparison operator
bool operator==(const ProteinModificationSummary& rhs) const;
using ModificationsToStatistics = std::map<const ResidueModification*, Statistics>;
using AALevelModificationSummary = std::map<size_t, ModificationsToStatistics>;
/// position -> modification -> statistic (counts, etc.)
AALevelModificationSummary AALevelSummary;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/Instrument.h | .h | 5,244 | 154 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/METADATA/MetaInfoInterface.h>
#include <OpenMS/METADATA/IonSource.h>
#include <OpenMS/METADATA/MassAnalyzer.h>
#include <OpenMS/METADATA/IonDetector.h>
#include <OpenMS/METADATA/Software.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
#include <vector>
namespace OpenMS
{
/**
@brief Description of a MS instrument
It contains information like vendor, model, ion source(s), mass analyzer(s), and ion detector(s).
The parts (IonSource, MassAnalyzer, IonDetector) all have a @em order member.
The order can be ignored, as long the instrument has this default setup:
- one ion source
- one or many mass analyzers
- one ion detector
For more complex instruments, the order should be defined.
@ingroup Metadata
*/
class OPENMS_DLLAPI Instrument :
public MetaInfoInterface
{
public:
/// ion optics type
enum class IonOpticsType
{
UNKNOWN, ///< unknown
MAGNETIC_DEFLECTION, ///< magnetic deflection
DELAYED_EXTRACTION, ///< delayed extraction
COLLISION_QUADRUPOLE, ///< collision quadrupole
SELECTED_ION_FLOW_TUBE, ///< selected ion flow tube
TIME_LAG_FOCUSING, ///< time lag focusing
REFLECTRON, ///< reflectron
EINZEL_LENS, ///< einzel lens
FIRST_STABILITY_REGION, ///< first stability region
FRINGING_FIELD, ///< fringing field
KINETIC_ENERGY_ANALYZER, ///< kinetic energy analyzer
STATIC_FIELD, ///< static field
SIZE_OF_IONOPTICSTYPE
};
/// Names of inlet types
static const std::string NamesOfIonOpticsType[static_cast<size_t>(IonOpticsType::SIZE_OF_IONOPTICSTYPE)];
/// returns all ion optics type names known to OpenMS
static StringList getAllNamesOfIonOpticsType();
/// Constructor
Instrument();
/// Copy constructor
Instrument(const Instrument &) = default;
/// Move constructor
Instrument(Instrument&&) = default;
/// Destructor
~Instrument();
/// Assignment operator
Instrument & operator=(const Instrument &) = default;
/// Move assignment operator
Instrument& operator=(Instrument&&) & = default;
/// Equality operator
bool operator==(const Instrument & rhs) const;
/// Equality operator
bool operator!=(const Instrument & rhs) const;
/// returns the name of the instrument
const String & getName() const;
/// sets the name of the instrument
void setName(const String & name);
/// returns the instrument vendor
const String & getVendor() const;
/// sets the instrument vendor
void setVendor(const String & vendor);
/// returns the instrument model
const String & getModel() const;
/// sets the instrument model
void setModel(const String & model);
/// returns a description of customizations
const String & getCustomizations() const;
/// sets a description of customizations
void setCustomizations(const String & customizations);
/// returns a const reference to the ion source list
const std::vector<IonSource> & getIonSources() const;
/// returns a mutable reference to the ion source list
std::vector<IonSource> & getIonSources();
/// sets the ion source list
void setIonSources(const std::vector<IonSource> & ion_sources);
/// returns a const reference to the mass analyzer list
const std::vector<MassAnalyzer> & getMassAnalyzers() const;
/// returns a mutable reference to the mass analyzer list
std::vector<MassAnalyzer> & getMassAnalyzers();
/// sets the mass analyzer list
void setMassAnalyzers(const std::vector<MassAnalyzer> & mass_analyzers);
/// returns a const reference to the ion detector list
const std::vector<IonDetector> & getIonDetectors() const;
/// returns a mutable reference to the ion detector list
std::vector<IonDetector> & getIonDetectors();
/// sets the ion detector list
void setIonDetectors(const std::vector<IonDetector> & ion_detectors);
/// returns a const reference to the instrument software
const Software & getSoftware() const;
/// returns a mutable reference to the instrument software
Software & getSoftware();
/// sets the instrument software
void setSoftware(const Software & software);
/// returns the ion optics type
IonOpticsType getIonOptics() const;
/// sets the ion optics type
void setIonOptics(IonOpticsType ion_optics);
protected:
String name_;
String vendor_;
String model_;
String customizations_;
std::vector<IonSource> ion_sources_;
std::vector<MassAnalyzer> mass_analyzers_;
std::vector<IonDetector> ion_detectors_;
Software software_;
IonOpticsType ion_optics_;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/Precursor.h | .h | 11,236 | 283 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Mathias Walzer $
// $Authors: Marc Sturm, Mathias Walzer $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/Peak1D.h>
#include <OpenMS/METADATA/CVTermList.h>
#include <OpenMS/CONCEPT/Constants.h>
#include <OpenMS/CONCEPT/HashUtils.h>
#include <OpenMS/IONMOBILITY/IMTypes.h>
#include <functional>
#include <set>
namespace OpenMS
{
/**
@brief Precursor meta information.
This class contains precursor information:
- isolation window
- activation
- selected ion (m/z, intensity, charge, possible charge states)
- ion mobility drift time
@ingroup Metadata
*/
class OPENMS_DLLAPI Precursor :
public CVTermList,
public Peak1D
{
public:
/// Constructor
Precursor() = default;
/// Copy constructor
Precursor(const Precursor&) = default;
// note: we implement the move constructor ourselves due to a bug in MSVS
// 2015/2017 which cannot produce a default move constructor for classes
// that contain STL containers (other than vector).
/// Move constructor
Precursor(Precursor&&) noexcept;
/// Destructor
~Precursor() override = default;
/// Assignment operator
Precursor& operator=(const Precursor&) = default;
/// Move assignment operator
Precursor& operator=(Precursor&&) & = default;
/// Method of activation
enum class ActivationMethod
{
CID, ///< Collision-induced dissociation (MS:1000133) (also CAD; parent term, but unless otherwise stated often used as synonym for trap-type CID)
PSD, ///< Post-source decay
PD, ///< Plasma desorption
SID, ///< Surface-induced dissociation
BIRD, ///< Blackbody infrared radiative dissociation
ECD, ///< Electron capture dissociation (MS:1000250)
IMD, ///< Infrared multiphoton dissociation
SORI, ///< Sustained off-resonance irradiation
HCID, ///< High-energy collision-induced dissociation
LCID, ///< Low-energy collision-induced dissociation
PHD, ///< Photodissociation
ETD, ///< Electron transfer dissociation
ETciD, ///< Electron transfer and collision-induced dissociation (MS:1003182)
EThcD, ///< Electron transfer and higher-energy collision dissociation (MS:1002631)
PQD, ///< Pulsed q dissociation (MS:1000599)
TRAP, ///< trap-type collision-induced dissociation (MS:1002472)
HCD, ///< beam-type collision-induced dissociation (MS:1000422)
INSOURCE, ///< in-source collision-induced dissociation (MS:1001880)
LIFT, ///< Bruker proprietary method (MS:1002000)
SIZE_OF_ACTIVATIONMETHOD
};
/// Names of activation methods
static const std::string NamesOfActivationMethod[static_cast<size_t>(ActivationMethod::SIZE_OF_ACTIVATIONMETHOD)];
static const std::string NamesOfActivationMethodShort[static_cast<size_t>(ActivationMethod::SIZE_OF_ACTIVATIONMETHOD)];
/// returns all activation method full names (e.g., "Collision-induced dissociation") known to OpenMS
static StringList getAllNamesOfActivationMethods();
/// returns all activation method abbreviations (e.g., "CID") known to OpenMS
static StringList getAllShortNamesOfActivationMethods();
/// convert an ActivationMethod enum to its full name string
/// @throws Exception::InvalidValue if @p m is SIZE_OF_ACTIVATIONMETHOD
static const std::string& activationMethodToString(ActivationMethod m);
/// convert an ActivationMethod enum to its short (abbreviated) name string
/// @throws Exception::InvalidValue if @p m is SIZE_OF_ACTIVATIONMETHOD
static const std::string& activationMethodToShortString(ActivationMethod m);
/// convert a string (full name or short name) to an ActivationMethod enum
/// @throws Exception::InvalidValue if @p name is not found in NamesOfActivationMethod or NamesOfActivationMethodShort
static ActivationMethod toActivationMethod(const std::string& name);
/// Equality operator
bool operator==(const Precursor & rhs) const;
/// Equality operator
bool operator!=(const Precursor & rhs) const;
/// returns a const reference to the activation methods
const std::set<ActivationMethod>& getActivationMethods() const;
/// returns a mutable reference to the activation methods
std::set<ActivationMethod>& getActivationMethods();
/// Returns the full names (e.g., "Collision-induced dissociation") of the activation methods set on this instance
StringList getActivationMethodsAsString() const;
/// Returns the abbreviations (e.g., "CID") of the activation methods set on this instance
StringList getActivationMethodsAsShortString() const;
/// sets the activation methods
void setActivationMethods(const std::set<ActivationMethod> & activation_methods);
/// returns the activation energy (in electronvolt)
double getActivationEnergy() const;
/// sets the activation energy (in electronvolt)
void setActivationEnergy(double activation_energy);
/**
* @brief Returns the lower offset from the target m/z
*
* @note This is an offset relative to the target m/z. The start of the
* mass isolation window should thus be computed as:
*
* p.getMZ() - p.getIsolationWindowLowerOffset()
*
* @return the lower offset from the target m/z
*/
double getIsolationWindowLowerOffset() const;
/// sets the lower offset from the target m/z
void setIsolationWindowLowerOffset(double bound);
/**
* @brief Returns the upper offset from the target m/z
*
* @note This is an offset relative to the target m/z. The end of the mass
* isolation window should thus be computed as:
*
* p.getMZ() + p.getIsolationWindowUpperOffset()
*
* @return the upper offset from the target m/z
*/
double getIsolationWindowUpperOffset() const;
/// sets the upper offset from the target m/z
void setIsolationWindowUpperOffset(double bound);
/**
@brief Returns the ion mobility drift time in milliseconds (-1 means it is not set)
@note It is possible for the spectrum to not have a Precursor but still
have a drift time, please check getDriftTime of MSSpectrum first and only
use this function if you need find-grained access to individual precursors.
*/
double getDriftTime() const;
/// sets the ion mobility drift time in milliseconds
void setDriftTime(double drift_time);
/**
@brief Returns the ion mobility drift time unit
*/
DriftTimeUnit getDriftTimeUnit() const;
/**
@brief Sets the ion mobility drift time unit
*/
void setDriftTimeUnit(DriftTimeUnit dt);
/**
* @brief Returns the lower offset from the target ion mobility in milliseconds
*
* @note This is an offset relative to the target ion mobility. The start
* of the ion mobility isolation window should thus be computed as:
*
* p.getDriftTime() + p.getDriftTimeWindowLowerOffset()
*
* @return the lower offset from the target ion mobility
*/
double getDriftTimeWindowLowerOffset() const;
/// sets the lower offset from the target ion mobility
void setDriftTimeWindowLowerOffset(double drift_time);
/**
* @brief Returns the upper offset from the target ion mobility in milliseconds
*
* @note This is an offset relative to the target ion mobility. The end
* of the ion mobility isolation window should thus be computed as:
*
* p.getDriftTime() + p.getDriftTimeWindowUpperOffset()
*
* @return the upper offset from the target ion mobility
*/
double getDriftTimeWindowUpperOffset() const;
/// sets the upper offset from the target ion mobility
void setDriftTimeWindowUpperOffset(double drift_time);
/// Non-mutable access to the charge
Int getCharge() const;
/// Mutable access to the charge
void setCharge(Int charge);
/// Mutable access to possible charge states
std::vector<Int>& getPossibleChargeStates();
/// Non-mutable access to possible charge states
const std::vector<Int>& getPossibleChargeStates() const;
/// Sets the possible charge states
void setPossibleChargeStates(const std::vector<Int> & possible_charge_states);
/// Returns the uncharged mass of the precursor, if charge is unknown, i.e. 0, our best guess is doubly charged
inline double getUnchargedMass() const
{
int c = charge_;
(c == 0) ? c = 2 : c = charge_;
return getMZ() * c - c * Constants::PROTON_MASS_U;
}
protected:
std::set<ActivationMethod> activation_methods_;
double activation_energy_{};
double window_low_{};
double window_up_{};
double drift_time_{-1};
double drift_window_low_{};
double drift_window_up_{};
DriftTimeUnit drift_time_unit_{DriftTimeUnit::NONE};
Int charge_{};
std::vector<Int> possible_charge_states_;
};
} // namespace OpenMS
// Hash function specialization for Precursor
namespace std
{
template<>
struct hash<OpenMS::Precursor>
{
std::size_t operator()(const OpenMS::Precursor& p) const noexcept
{
// Hash Peak1D base class
std::size_t seed = std::hash<OpenMS::Peak1D>{}(p);
// Hash CVTermList base class
OpenMS::hash_combine(seed, std::hash<OpenMS::CVTermList>{}(p));
// Hash activation_methods_ (std::set is ordered, deterministic iteration)
for (const auto& method : p.getActivationMethods())
{
OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(method)));
}
// Hash double fields
OpenMS::hash_combine(seed, OpenMS::hash_float(p.getActivationEnergy()));
OpenMS::hash_combine(seed, OpenMS::hash_float(p.getIsolationWindowLowerOffset()));
OpenMS::hash_combine(seed, OpenMS::hash_float(p.getIsolationWindowUpperOffset()));
OpenMS::hash_combine(seed, OpenMS::hash_float(p.getDriftTime()));
OpenMS::hash_combine(seed, OpenMS::hash_float(p.getDriftTimeWindowLowerOffset()));
OpenMS::hash_combine(seed, OpenMS::hash_float(p.getDriftTimeWindowUpperOffset()));
// Hash drift_time_unit_ (enum class)
OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(p.getDriftTimeUnit())));
// Hash charge_
OpenMS::hash_combine(seed, OpenMS::hash_int(p.getCharge()));
// Hash possible_charge_states_
for (const auto& charge : p.getPossibleChargeStates())
{
OpenMS::hash_combine(seed, OpenMS::hash_int(charge));
}
return seed;
}
};
} // namespace std
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/CVTerm.h | .h | 5,104 | 207 | // 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/DATASTRUCTURES/DataValue.h>
#include <OpenMS/CONCEPT/HashUtils.h>
namespace OpenMS
{
/**
@brief Representation of controlled vocabulary term
This class simply stores a CV term, its value and unit if necessary.
Representation of a CV term used by CVMappings
@ingroup Metadata
*/
class OPENMS_DLLAPI CVTerm
{
public:
struct Unit
{
/// Default constructor
Unit() = default;
Unit(const String& p_accession, const String& p_name, const String& p_cv_ref) :
accession(p_accession),
name(p_name),
cv_ref(p_cv_ref)
{
}
/// Copy constructor
Unit(const Unit &) = default;
/// Move constructor
Unit(Unit&&) = default;
/// Destructor
virtual ~Unit()
{
}
/// Assignment operator
Unit& operator=(const Unit&) = default;
/// Move assignment operator
Unit& operator=(Unit&&)& = default;
bool operator==(const Unit& rhs) const
{
return accession == rhs.accession &&
name == rhs.name &&
cv_ref == rhs.cv_ref;
}
bool operator!=(const Unit& rhs) const
{
return !(*this == rhs);
}
String accession;
String name;
String cv_ref;
};
/// Default constructor
CVTerm() = default;
/// Detailed constructor
CVTerm(const String& accession, const String& name = "", const String& cv_identifier_ref = "", const String& value = "", const Unit& unit = Unit());
/// Copy constructor
CVTerm(const CVTerm&) = default;
/// Move constructor
CVTerm(CVTerm&&) = default;
/// Destructor
virtual ~CVTerm();
/// Assignment operator
CVTerm& operator=(const CVTerm&) = default;
/// Move assignment operator
CVTerm& operator=(CVTerm&&)& = default;
/** @name Accessors
*/
//@{
/// sets the accession string of the term
void setAccession(const String& accession);
/// returns the accession string of the term
const String& getAccession() const;
/// sets the name of the term
void setName(const String& name);
/// returns the name of the term
const String& getName() const;
/// sets the cv identifier reference string, e.g. UO for unit obo
void setCVIdentifierRef(const String& cv_identifier_ref);
/// returns the cv identifier reference string
const String& getCVIdentifierRef() const;
/// set the value of the term
void setValue(const DataValue& value);
/// returns the value of the term
const DataValue& getValue() const;
/// sets the unit of the term
void setUnit(const Unit& unit);
/// returns the unit
const Unit& getUnit() const;
//@}
/** @name Predicates
*/
//@{
/// equality operator
bool operator==(const CVTerm& rhs) const;
/// inequality operator
bool operator!=(const CVTerm& rhs) const;
/// checks whether the term has a value
bool hasValue() const;
/// checks whether the term has a unit
bool hasUnit() const;
//}
protected:
String accession_;
String name_;
String cv_identifier_ref_;
Unit unit_;
DataValue value_;
};
} // namespace OpenMS
// Hash function specializations for CVTerm and CVTerm::Unit
namespace std
{
/**
* @brief Hash function for CVTerm::Unit.
*
* Hashes based on accession, name, and cv_ref fields.
*/
template<>
struct hash<OpenMS::CVTerm::Unit>
{
std::size_t operator()(const OpenMS::CVTerm::Unit& unit) const noexcept
{
std::size_t seed = 0;
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(unit.accession));
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(unit.name));
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(unit.cv_ref));
return seed;
}
};
/**
* @brief Hash function for CVTerm.
*
* Hashes based on all fields: accession, name, cv_identifier_ref, unit, and value.
* This is consistent with operator== which compares all fields.
*/
template<>
struct hash<OpenMS::CVTerm>
{
std::size_t operator()(const OpenMS::CVTerm& term) const noexcept
{
std::size_t seed = 0;
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(term.getAccession()));
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(term.getName()));
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(term.getCVIdentifierRef()));
OpenMS::hash_combine(seed, std::hash<OpenMS::CVTerm::Unit>{}(term.getUnit()));
OpenMS::hash_combine(seed, std::hash<OpenMS::DataValue>{}(term.getValue()));
return seed;
}
};
} // namespace std
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/ContactPerson.h | .h | 2,684 | 94 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/METADATA/MetaInfoInterface.h>
namespace OpenMS
{
/**
@brief Contact person information
@ingroup Metadata
*/
class OPENMS_DLLAPI ContactPerson :
public MetaInfoInterface
{
public:
/// Constructor
ContactPerson() = default;
/// Copy constructor
ContactPerson(const ContactPerson &) = default;
/// Move constructor
ContactPerson(ContactPerson&&) = default;
/// Destructor
~ContactPerson() = default;
/// Assignment operator
ContactPerson & operator=(const ContactPerson &) = default;
/// Move assignment operator
ContactPerson& operator=(ContactPerson&&) & = default;
/// Equality operator
bool operator==(const ContactPerson & rhs) const;
/// Equality operator
bool operator!=(const ContactPerson & rhs) const;
/// returns the first name of the person
const String & getFirstName() const;
/// sets the first name of the person
void setFirstName(const String & name);
/// returns the last name of the person
const String & getLastName() const;
/// sets the last name of the person
void setLastName(const String & name);
/// sets the full name of the person (gets split into first and last name internally)
void setName(const String & name);
/// returns the affiliation
const String & getInstitution() const;
/// sets the affiliation
void setInstitution(const String & institution);
/// returns the email address
const String & getEmail() const;
/// sets the email address
void setEmail(const String & email);
/// returns the email address
const String & getURL() const;
/// sets the email address
void setURL(const String & email);
/// returns the address
const String & getAddress() const;
/// sets the address
void setAddress(const String & email);
/// returns miscellaneous info about the contact person
const String & getContactInfo() const;
/// sets miscellaneous info about the contact person
void setContactInfo(const String & contact_info);
protected:
String first_name_;
String last_name_;
String institution_;
String email_;
String contact_info_;
String url_;
String address_;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/AcquisitionInfo.h | .h | 2,290 | 80 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/METADATA/Acquisition.h>
#include <OpenMS/METADATA/MetaInfoInterface.h>
#include <vector>
namespace OpenMS
{
/**
@brief Description of the combination of raw data to a single spectrum
Specification for combining raw scans ( Acquisition ) into a single spectrum.
A list of acquisitions from the original raw file can be specified.
@ingroup Metadata
*/
class OPENMS_DLLAPI AcquisitionInfo :
private std::vector<Acquisition>,
public MetaInfoInterface
{
private:
typedef std::vector<Acquisition> ContainerType;
public:
/// Constructor
AcquisitionInfo() = default;
/// Copy constructor
AcquisitionInfo(const AcquisitionInfo&) = default;
/// Move constructor
AcquisitionInfo(AcquisitionInfo&&) = default;
/// Destructor
~AcquisitionInfo() = default;
/// Assignment operator
AcquisitionInfo& operator=(const AcquisitionInfo&) = default;
/// Move assignment operator
AcquisitionInfo& operator=(AcquisitionInfo&&) & = default;
/// Equality operator
bool operator==(const AcquisitionInfo& rhs) const;
/// Equality operator
bool operator!=(const AcquisitionInfo& rhs) const;
/// returns the method of combination
const String& getMethodOfCombination() const;
/// sets the method of combination
void setMethodOfCombination(const String& method_of_combination);
///@name Export methods from private base std::vector<Acquisition>
//@{
using ContainerType::operator[];
using ContainerType::begin;
using ContainerType::end;
using ContainerType::size;
using ContainerType::push_back;
using ContainerType::empty;
using ContainerType::back;
using ContainerType::insert;
using ContainerType::resize;
using ContainerType::iterator;
using ContainerType::const_iterator;
//@}
protected:
String method_of_combination_;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/SpectrumNativeIDParser.h | .h | 5,365 | 129 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Hendrik Weisser, Timo Sachsenberg $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/OpenMSConfig.h>
#include <boost/regex.hpp>
namespace OpenMS
{
/**
@brief Parser for extracting scan numbers from spectrum native IDs
This class provides static functions for parsing native ID strings from various
mass spectrometry file formats. Native IDs are vendor-specific identifiers that
encode information such as scan numbers, file indices, and experiment numbers.
@par Supported Native ID Formats
The parser supports the following native ID formats based on CV (Controlled Vocabulary)
accessions from the PSI-MS ontology:
| CV Accession | Vendor/Format | Native ID Pattern | Example |
|--------------|---------------|-------------------|---------|
| MS:1000768 | Thermo | scan=NUMBER | scan=42 |
| MS:1000769 | Waters | function=X process=Y scan=NUMBER | function=2 process=1 scan=100 |
| MS:1000770 | WIFF (AB Sciex) | sample=X period=Y cycle=Z experiment=W | sample=1 period=1 cycle=42 experiment=1 |
| MS:1000771 | Bruker/Agilent | scan=NUMBER | scan=42 |
| MS:1000772 | Bruker BAF | scan=NUMBER | scan=42 |
| MS:1000773 | Bruker FID | file=NUMBER | file=42 |
| MS:1000774 | Index-based | index=NUMBER | index=42 (returns 43) |
| MS:1000775 | Single peak list | file=NUMBER | file=42 |
| MS:1000776 | Thermo/Bruker TDF | scan=NUMBER | scan=42 |
| MS:1000777 | Generic spectrum | spectrum=NUMBER | spectrum=42 |
| MS:1001508 | Agilent MassHunter | scanId=NUMBER | scanId=42 |
| MS:1001530 | Numeric-only | NUMBER | 42 |
@par Usage Examples
@code
// Extract scan number using CV accession
Int scan = SpectrumNativeIDParser::extractScanNumber("scan=42", "MS:1000768"); // returns 42
// Get regex pattern from native ID format
String regex = SpectrumNativeIDParser::getRegExFromNativeID("scan=123"); // returns "scan=(?<GROUP>\d+)"
// Check if string is a native ID
bool is_native = SpectrumNativeIDParser::isNativeID("scan=123"); // returns true
@endcode
@see SpectrumLookup
*/
class OPENMS_DLLAPI SpectrumNativeIDParser
{
public:
/**
@brief Extract the scan number from the native ID of a spectrum using a regular expression
@param[in] native_id Spectrum native ID string
@param[in] scan_regexp Regular expression to use (must contain the named group "?<SCAN>")
@param[in] no_error Suppress the exception on failure and return -1 instead
@throw Exception::ParseError if the scan number could not be extracted (unless @p no_error is set)
@return Scan number of the spectrum (or -1 on failure to extract)
@note The regular expression must contain a capture group, and the last matching
subgroup is used as the scan number.
*/
static Int extractScanNumber(const String& native_id,
const boost::regex& scan_regexp,
bool no_error = false);
/**
@brief Extract the scan number from the native ID using a CV accession
@param[in] native_id Spectrum native ID string
@param[in] native_id_type_accession CV accession specifying the native ID format
(e.g., "MS:1000768" for Thermo, "MS:1000770" for WIFF)
@return Scan number of the spectrum (or -1 on failure to extract)
@note For WIFF files (MS:1000770), the return value is computed as cycle * 1000 + experiment.
@note For index-based native IDs (MS:1000774), the return value is index + 1 for pepXML compatibility.
*/
static Int extractScanNumber(const String& native_id,
const String& native_id_type_accession);
/**
@brief Determine the regular expression to extract scan/index numbers from native IDs
@param[in] native_id A native ID string to analyze
@return Regular expression string with named group `(?<GROUP>\d+)` that matches
the scan or index number in the native ID
This function examines the prefix of the native ID to determine the appropriate
regular expression pattern:
- `scan=`, `controllerType=`, `function=` → `scan=(?<GROUP>\d+)`
- `index=` → `index=(?<GROUP>\d+)`
- `scanId=`, `scanID=` → `scanId=(?<GROUP>\d+)` or `scanID=(?<GROUP>\d+)`
- `spectrum=` → `spectrum=(?<GROUP>\d+)`
- `file=` → `file=(?<GROUP>\d+)`
- Plain number → `(?<GROUP>\d+)`
*/
static std::string getRegExFromNativeID(const String& native_id);
/**
@brief Check if a spectrum identifier is a native ID from a vendor file
@param[in] id Spectrum identifier string to check
@return True if the string matches a known native ID prefix pattern
Recognized prefixes: scan=, scanId=, scanID=, controllerType=, function=, sample=, index=, spectrum=, file=
*/
static bool isNativeID(const String& id);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/MetaInfoDescription.h | .h | 2,464 | 72 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#pragma once
#include <compare>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/METADATA/DataProcessing.h>
#include <OpenMS/METADATA/MetaInfoInterface.h>
namespace OpenMS
{
/**
@brief Description of the meta data arrays of MSSpectrum.
@ingroup Metadata
*/
class OPENMS_DLLAPI MetaInfoDescription :
public MetaInfoInterface
{
public:
/// Constructor
MetaInfoDescription() = default;
/// Copy constructor
MetaInfoDescription(const MetaInfoDescription &) = default;
/// Move constructor
MetaInfoDescription(MetaInfoDescription&&) = default;
/// Destructor
~MetaInfoDescription();
/// Assignment operator
MetaInfoDescription & operator=(const MetaInfoDescription &) = default;
/// Move assignment operator
MetaInfoDescription& operator=(MetaInfoDescription&&) & = default;
/// Equality operator
bool operator==(const MetaInfoDescription & rhs) const;
/// Less than operator
bool operator<(const MetaInfoDescription & rhs) const;
/// Less than or equal operator
bool operator<=(const MetaInfoDescription & rhs) const;
/// Greater than operator
bool operator>(const MetaInfoDescription & rhs) const;
/// Greater than or equal operator
bool operator>=(const MetaInfoDescription & rhs) const;
/// Not equal operator
bool operator!=(const MetaInfoDescription & rhs) const;
/// returns the name of the peak annotations
const String & getName() const;
/// sets the name of the peak annotations
void setName(const String & name);
/// returns a const reference to the description of the applied processing
const std::vector<ConstDataProcessingPtr> & getDataProcessing() const;
/// returns a mutable reference to the description of the applied processing
std::vector<DataProcessingPtr> & getDataProcessing();
/// sets the description of the applied processing
void setDataProcessing(const std::vector<DataProcessingPtr> & data_processing);
protected:
String name_;
std::vector<DataProcessingPtr> data_processing_;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/ChromatogramSettings.h | .h | 11,655 | 286 | // 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/METADATA/InstrumentSettings.h>
#include <OpenMS/METADATA/AcquisitionInfo.h>
#include <OpenMS/METADATA/SourceFile.h>
#include <OpenMS/METADATA/Precursor.h>
#include <OpenMS/METADATA/Product.h>
#include <OpenMS/METADATA/DataProcessing.h>
#include <OpenMS/CONCEPT/HashUtils.h>
#include <functional>
#include <map>
#include <vector>
namespace OpenMS
{
/**
@brief Representation of chromatogram settings, e.g. SRM/MRM chromatograms
It contains the metadata about chromatogram specific instrument settings,
acquisition settings, description of the meta values used in the peaks and precursor info.
@ingroup Metadata
*/
class OPENMS_DLLAPI ChromatogramSettings :
public MetaInfoInterface
{
public:
/// List of chromatogram names, e.g., SELECTED_REACTION_MONITORING_CHROMATOGRAM.
/// Actual names can be accessed using the ChromatogramNames[] array
enum class ChromatogramType
{
MASS_CHROMATOGRAM = 0,
TOTAL_ION_CURRENT_CHROMATOGRAM,
SELECTED_ION_CURRENT_CHROMATOGRAM,
BASEPEAK_CHROMATOGRAM,
SELECTED_ION_MONITORING_CHROMATOGRAM,
SELECTED_REACTION_MONITORING_CHROMATOGRAM,
ELECTROMAGNETIC_RADIATION_CHROMATOGRAM,
ABSORPTION_CHROMATOGRAM,
EMISSION_CHROMATOGRAM,
SIZE_OF_CHROMATOGRAM_TYPE // last entry!
};
/// Names of chromatogram types corresponding to enum ChromatogramType
static const char * const ChromatogramNames[static_cast<size_t>(ChromatogramType::SIZE_OF_CHROMATOGRAM_TYPE)+1]; // avoid string[], since it gets copied onto heap on initialization
/// Constructor
ChromatogramSettings();
/// Copy constructor
ChromatogramSettings(const ChromatogramSettings &) = default;
/// Move constructor
ChromatogramSettings(ChromatogramSettings&&) = default;
/// Destructor
virtual ~ChromatogramSettings();
// Assignment operator
ChromatogramSettings & operator=(const ChromatogramSettings &) = default;
/// Move assignment operator
ChromatogramSettings& operator=(ChromatogramSettings&&) & = default;
/// Equality operator
bool operator==(const ChromatogramSettings & rhs) const;
/// Equality operator
bool operator!=(const ChromatogramSettings & rhs) const;
/// returns the native identifier for the spectrum, used by the acquisition software.
const String & getNativeID() const;
/// sets the native identifier for the spectrum, used by the acquisition software.
void setNativeID(const String & native_id);
/// returns the free-text comment
const String & getComment() const;
/// sets the free-text comment
void setComment(const String & comment);
/// returns a const reference to the instrument settings of the current spectrum
const InstrumentSettings & getInstrumentSettings() const;
/// returns a mutable reference to the instrument settings of the current spectrum
InstrumentSettings & getInstrumentSettings();
/// sets the instrument settings of the current spectrum
void setInstrumentSettings(const InstrumentSettings & instrument_settings);
/// returns a const reference to the acquisition info
const AcquisitionInfo & getAcquisitionInfo() const;
/// returns a mutable reference to the acquisition info
AcquisitionInfo & getAcquisitionInfo();
/// sets the acquisition info
void setAcquisitionInfo(const AcquisitionInfo & acquisition_info);
/// returns a const reference to the source file
const SourceFile & getSourceFile() const;
/// returns a mutable reference to the source file
SourceFile & getSourceFile();
/// sets the source file
void setSourceFile(const SourceFile & source_file);
/// returns a const reference to the precursors
const Precursor & getPrecursor() const;
/// returns a mutable reference to the precursors
Precursor & getPrecursor();
/// sets the precursors
void setPrecursor(const Precursor & precursor);
/// returns a const reference to the products
const Product & getProduct() const;
/// returns a mutable reference to the products
Product & getProduct();
/// sets the products
void setProduct(const Product & product);
/// returns the chromatogram type, e.g. a SRM chromatogram
ChromatogramType getChromatogramType() const;
/// sets the chromatogram type
void setChromatogramType(ChromatogramType type);
/// sets the description of the applied processing
void setDataProcessing(const std::vector< DataProcessingPtr > & data_processing);
/// returns a mutable reference to the description of the applied processing
std::vector< DataProcessingPtr > & getDataProcessing();
/// returns a const reference to the description of the applied processing
const std::vector< std::shared_ptr<const DataProcessing > > getDataProcessing() const;
protected:
String native_id_;
String comment_;
InstrumentSettings instrument_settings_;
SourceFile source_file_;
AcquisitionInfo acquisition_info_;
Precursor precursor_;
Product product_;
std::vector< DataProcessingPtr > data_processing_;
ChromatogramType type_;
};
///Print the contents to a stream.
OPENMS_DLLAPI std::ostream & operator<<(std::ostream & os, const ChromatogramSettings & spec);
} // namespace OpenMS
// Hash function specialization for ChromatogramSettings
namespace std
{
/**
* @brief Hash function for OpenMS::ChromatogramSettings.
*
* Hashes all fields used in operator==:
* - MetaInfoInterface (base class - meta values)
* - native_id_ (string)
* - comment_ (string)
* - instrument_settings_ (scan mode, zoom scan, polarity, scan windows, and MetaInfo)
* - acquisition_info_ (method of combination, acquisitions, and MetaInfo)
* - source_file_ (file properties and CVTermList)
* - precursor_ (activation methods, windows, drift time, charge, and Peak1D/CVTermList)
* - product_ (uses std::hash<Product>)
* - data_processing_ (software, actions, completion time for each element)
* - type_ (chromatogram type enum)
*
* @note This hash implementation hashes the key identifying fields of nested types
* and includes MetaInfoInterface. Consistent with operator==.
*/
template<>
struct hash<OpenMS::ChromatogramSettings>
{
std::size_t operator()(const OpenMS::ChromatogramSettings& cs) const noexcept
{
std::size_t seed = 0;
// Hash native_id_ and comment_
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(cs.getNativeID()));
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(cs.getComment()));
// Hash instrument_settings_
const auto& is = cs.getInstrumentSettings();
OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(is.getScanMode())));
OpenMS::hash_combine(seed, OpenMS::hash_int(is.getZoomScan() ? 1 : 0));
OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(is.getPolarity())));
// Hash scan windows
const auto& scan_windows = is.getScanWindows();
OpenMS::hash_combine(seed, OpenMS::hash_int(scan_windows.size()));
for (const auto& sw : scan_windows)
{
OpenMS::hash_combine(seed, OpenMS::hash_float(sw.begin));
OpenMS::hash_combine(seed, OpenMS::hash_float(sw.end));
}
// Hash acquisition_info_
const auto& ai = cs.getAcquisitionInfo();
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(ai.getMethodOfCombination()));
OpenMS::hash_combine(seed, OpenMS::hash_int(ai.size()));
for (const auto& acq : ai)
{
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(acq.getIdentifier()));
}
// Hash source_file_
const auto& sf = cs.getSourceFile();
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(sf.getNameOfFile()));
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(sf.getPathToFile()));
OpenMS::hash_combine(seed, OpenMS::hash_float(static_cast<double>(sf.getFileSize())));
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(sf.getFileType()));
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(sf.getChecksum()));
OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(sf.getChecksumType())));
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(sf.getNativeIDType()));
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(sf.getNativeIDTypeAccession()));
// Hash precursor_
const auto& prec = cs.getPrecursor();
// Hash activation methods
const auto& am = prec.getActivationMethods();
OpenMS::hash_combine(seed, OpenMS::hash_int(am.size()));
for (const auto& method : am)
{
OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(method)));
}
OpenMS::hash_combine(seed, OpenMS::hash_float(prec.getActivationEnergy()));
OpenMS::hash_combine(seed, OpenMS::hash_float(prec.getIsolationWindowLowerOffset()));
OpenMS::hash_combine(seed, OpenMS::hash_float(prec.getIsolationWindowUpperOffset()));
OpenMS::hash_combine(seed, OpenMS::hash_float(prec.getDriftTime()));
OpenMS::hash_combine(seed, OpenMS::hash_float(prec.getDriftTimeWindowLowerOffset()));
OpenMS::hash_combine(seed, OpenMS::hash_float(prec.getDriftTimeWindowUpperOffset()));
OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(prec.getDriftTimeUnit())));
OpenMS::hash_combine(seed, OpenMS::hash_int(prec.getCharge()));
// Hash possible charge states
const auto& pcs = prec.getPossibleChargeStates();
OpenMS::hash_combine(seed, OpenMS::hash_int(pcs.size()));
for (const auto& charge : pcs)
{
OpenMS::hash_combine(seed, OpenMS::hash_int(charge));
}
// Hash Peak1D part (MZ and intensity)
OpenMS::hash_combine(seed, OpenMS::hash_float(prec.getMZ()));
OpenMS::hash_combine(seed, OpenMS::hash_float(prec.getIntensity()));
// Hash product_ using existing std::hash<Product>
OpenMS::hash_combine(seed, std::hash<OpenMS::Product>{}(cs.getProduct()));
// Hash data_processing_
const auto dp = cs.getDataProcessing();
OpenMS::hash_combine(seed, OpenMS::hash_int(dp.size()));
for (const auto& proc_ptr : dp)
{
if (proc_ptr)
{
// Hash software using std::hash<Software>
OpenMS::hash_combine(seed, std::hash<OpenMS::Software>{}(proc_ptr->getSoftware()));
// Hash processing actions
const auto& actions = proc_ptr->getProcessingActions();
OpenMS::hash_combine(seed, OpenMS::hash_int(actions.size()));
for (const auto& action : actions)
{
OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(action)));
}
// Hash completion time using std::hash<DateTime>
OpenMS::hash_combine(seed, std::hash<OpenMS::DateTime>{}(proc_ptr->getCompletionTime()));
}
}
// Hash type_
OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(cs.getChromatogramType())));
// Hash MetaInfoInterface base class
OpenMS::hash_combine(seed, std::hash<OpenMS::MetaInfoInterface>{}(cs));
return seed;
}
};
} // namespace std
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/ExperimentalSettings.h | .h | 4,335 | 124 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/METADATA/Sample.h>
#include <OpenMS/METADATA/MetaInfoInterface.h>
#include <OpenMS/METADATA/HPLC.h>
#include <OpenMS/METADATA/SourceFile.h>
#include <OpenMS/METADATA/ContactPerson.h>
#include <OpenMS/METADATA/Instrument.h>
#include <OpenMS/METADATA/DocumentIdentifier.h>
#include <OpenMS/METADATA/ProteinIdentification.h>
#include <vector>
namespace OpenMS
{
/**
@brief Description of the experimental settings
These settings are valid for the whole experiment.
See SpectrumSettings for settings which are specific to an MSSpectrum.
See ChromatogramSettings for settings which are specific to an MSChromatogram.
@ingroup Metadata
*/
class OPENMS_DLLAPI ExperimentalSettings :
public MetaInfoInterface,
public DocumentIdentifier
{
public:
/// Constructor
ExperimentalSettings() = default;
/// Copy constructor
ExperimentalSettings(const ExperimentalSettings &) = default;
/// Move constructor
ExperimentalSettings(ExperimentalSettings &&) = default;
/// Destructor
~ExperimentalSettings() override;
/// Assignment operator
ExperimentalSettings & operator=(const ExperimentalSettings &) = default;
/// Move assignment operator
ExperimentalSettings & operator=(ExperimentalSettings &&) = default;
/// Equality operator
bool operator==(const ExperimentalSettings & rhs) const;
/// Equality operator
bool operator!=(const ExperimentalSettings & rhs) const;
/// returns a const reference to the sample description
const Sample & getSample() const;
/// returns a mutable reference to the sample description
Sample & getSample();
/// sets the sample description
void setSample(const Sample & sample);
/// returns a const reference to the source data file
const std::vector<SourceFile> & getSourceFiles() const;
/// returns a mutable reference to the source data file
std::vector<SourceFile> & getSourceFiles();
/// sets the source data file
void setSourceFiles(const std::vector<SourceFile> & source_files);
/// returns a const reference to the list of contact persons
const std::vector<ContactPerson> & getContacts() const;
/// returns a mutable reference to the list of contact persons
std::vector<ContactPerson> & getContacts();
/// sets the list of contact persons
void setContacts(const std::vector<ContactPerson> & contacts);
/// returns a const reference to the MS instrument description
const Instrument & getInstrument() const;
/// returns a mutable reference to the MS instrument description
Instrument & getInstrument();
/// sets the MS instrument description
void setInstrument(const Instrument & instrument);
/// returns a const reference to the description of the HPLC run
const HPLC & getHPLC() const;
/// returns a mutable reference to the description of the HPLC run
HPLC & getHPLC();
/// sets the description of the HPLC run
void setHPLC(const HPLC & hplc);
/// returns the date the experiment was performed
const DateTime & getDateTime() const;
/// sets the date the experiment was performed
void setDateTime(const DateTime & date);
/// returns the free-text comment
const String & getComment() const;
/// sets the free-text comment
void setComment(const String & comment);
/// returns fraction identifier
const String & getFractionIdentifier() const;
/// sets the fraction identifier
void setFractionIdentifier(const String & fraction_identifier);
protected:
Sample sample_;
std::vector<SourceFile> source_files_;
std::vector<ContactPerson> contacts_;
Instrument instrument_;
HPLC hplc_;
DateTime datetime_;
String comment_;
String fraction_identifier_;
};
///Print the contents to a stream.
OPENMS_DLLAPI std::ostream & operator<<(std::ostream & os, const ExperimentalSettings & exp);
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/HPLC.h | .h | 2,555 | 95 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CONCEPT/Types.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/METADATA/Gradient.h>
namespace OpenMS
{
/**
@brief Representation of a HPLC experiment
It contains the description of instrument, the settings and the gradient.
@ingroup Metadata
*/
class OPENMS_DLLAPI HPLC
{
public:
/// Constructor
HPLC();
/// Copy constructor
HPLC(const HPLC &) = default;
/// Move constructor
HPLC(HPLC&&) = default;
/// Destructor
~HPLC();
/// Assignment operator
HPLC & operator=(const HPLC &) = default;
/// Move assignment operator
HPLC& operator=(HPLC&&) & = default;
/// Equality operator
bool operator==(const HPLC & source) const;
/// Equality operator
bool operator!=(const HPLC & source) const;
/// returns a const reference to the instrument name
const String & getInstrument() const;
/// sets the instrument name
void setInstrument(const String & instrument);
/// returns a const reference to the column description
const String & getColumn() const;
/// sets the column description
void setColumn(const String & column);
/// returns the temperature (in degree C)
Int getTemperature() const;
/// sets the temperature (in degree C)
void setTemperature(Int temperature);
/// returns the pressure (in bar)
UInt getPressure() const;
/// sets the pressure (in bar)
void setPressure(UInt pressure);
/// returns the flux (in microliter/sec)
UInt getFlux() const;
/// sets the flux (in microliter/sec)
void setFlux(UInt flux);
/// returns the comments
String getComment() const;
/// sets the comments
void setComment(String comment);
/// returns a const reference to the used gradient
const Gradient & getGradient() const;
/// returns a mutable reference to the used gradient
Gradient & getGradient();
/// sets the used gradient
void setGradient(const Gradient & gradient);
protected:
String instrument_;
String column_;
Int temperature_;
Int pressure_;
Int flux_;
String comment_;
Gradient gradient_;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/ProteinIdentification.h | .h | 25,656 | 609 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Nico Pfeifer, Chris Bielow $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <OpenMS/METADATA/ProteinHit.h>
#include <OpenMS/METADATA/MetaInfoInterface.h>
#include <OpenMS/DATASTRUCTURES/DateTime.h>
#include <OpenMS/CHEMISTRY/DigestionEnzymeProtein.h>
#include <OpenMS/CHEMISTRY/EnzymaticDigestion.h>
#include <OpenMS/METADATA/DataArrays.h>
#include <OpenMS/CONCEPT/Constants.h>
#include <OpenMS/CONCEPT/HashUtils.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
#include <functional>
#include <set>
namespace OpenMS
{
class MSExperiment;
class PeptideIdentification;
class PeptideEvidence;
class ConsensusMap;
/**
@brief Representation of a protein identification run
This class stores the general information and the protein hits of a protein identification run.
The actual peptide hits are stored in PeptideIdentification instances that are part of spectra or features.
In order to be able to connect the ProteinIdentification and the
corresponding peptide identifications, both classes have a string
identifier. We recommend using the search engine name and the date as
identifier.
Setting this identifier is especially important when there are several
protein identification runs for a map, i.e. several ProteinIdentification
instances.
@todo Add MetaInfoInterface to modifications => update IdXMLFile and ProteinIdentificationVisualizer (Andreas)
@ingroup Metadata
*/
class OPENMS_DLLAPI ProteinIdentification :
public MetaInfoInterface
{
public:
/// Hit type definition
typedef ProteinHit HitType;
/// two way mapping from ms-run-path to protID|pepID-identifier
struct Mapping
{
std::map<String, StringList> identifier_to_msrunpath;
std::map<StringList, String> runpath_to_identifier;
Mapping() = default;
explicit Mapping(const std::vector<ProteinIdentification>& prot_ids)
{
create(prot_ids);
}
void create(const std::vector<ProteinIdentification>& prot_ids)
{
identifier_to_msrunpath.clear();
runpath_to_identifier.clear();
StringList filenames;
for (const ProteinIdentification& prot_id : prot_ids)
{
prot_id.getPrimaryMSRunPath(filenames);
if (filenames.empty())
{
throw Exception::MissingInformation(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "No MS run path annotated in ProteinIdentification.");
}
identifier_to_msrunpath[prot_id.getIdentifier()] = filenames;
const auto& it = runpath_to_identifier.find(filenames);
if (it != runpath_to_identifier.end())
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"Multiple protein identifications with the same ms-run-path in Consensus/FeatureXML. Check input!\n",
ListUtils::concatenate(filenames, ","));
}
runpath_to_identifier[filenames] = prot_id.getIdentifier();
}
}
String getPrimaryMSRunPath(const PeptideIdentification& pepid) const
{
// if a merge index n is annotated, we use the filename annotated at index n in the protein identification, otherwise the one at index 0
size_t merge_index = pepid.getMetaValue(Constants::UserParam::ID_MERGE_INDEX, 0);
const auto& filenames = identifier_to_msrunpath.at(pepid.getIdentifier());
return (merge_index < filenames.size()) ? filenames[merge_index] : ""; // return filename or empty string if missing
}
};
/**
@brief Bundles multiple (e.g. indistinguishable) proteins in a group
*/
class OPENMS_DLLAPI ProteinGroup
{
public:
/// Float data array vector type
typedef OpenMS::DataArrays::FloatDataArray FloatDataArray ;
typedef std::vector<FloatDataArray> FloatDataArrays;
/// String data array vector type
typedef OpenMS::DataArrays::StringDataArray StringDataArray ;
typedef std::vector<StringDataArray> StringDataArrays;
/// Integer data array vector type
typedef OpenMS::DataArrays::IntegerDataArray IntegerDataArray ;
typedef std::vector<IntegerDataArray> IntegerDataArrays;
/// Probability of this group
double probability;
/// Accessions of (indistinguishable) proteins that belong to the same group
std::vector<String> accessions;
ProteinGroup();
/// Equality operator
bool operator==(const ProteinGroup& rhs) const;
/*
@brief Comparison operator (for sorting)
This operator is intended for sorting protein groups in a "best first"
manner. That means higher probabilities are "less" than lower
probabilities (!); smaller groups are "less" than larger groups;
everything else being equal, accessions are compared lexicographically.
*/
bool operator<(const ProteinGroup& rhs) const;
/// Float data arrays
/**
@name data array methods
These methods are used to annotate protein group meta information.
These statements should help you chose which approach to use
- Access to meta info arrays is slower than to a member variable
- Access to meta info arrays is faster than to a %MetaInfoInterface
- Meta info arrays are stored when using mzML format for storing
*/
//@{
/// Returns a const reference to the float meta data arrays
const FloatDataArrays& getFloatDataArrays() const;
/// Returns a mutable reference to the float meta data arrays
FloatDataArrays& getFloatDataArrays()
{
return float_data_arrays_;
}
/// Sets the float meta data arrays
void setFloatDataArrays(const FloatDataArrays& fda);
/// Returns a const reference to the string meta data arrays
const StringDataArrays& getStringDataArrays() const;
/// Returns a mutable reference to the string meta data arrays
StringDataArrays& getStringDataArrays();
/// Sets the string meta data arrays
void setStringDataArrays(const StringDataArrays& sda);
/// Returns a const reference to the integer meta data arrays
const IntegerDataArrays& getIntegerDataArrays() const;
/// Returns a mutable reference to the integer meta data arrays
IntegerDataArrays& getIntegerDataArrays();
/// Sets the integer meta data arrays
void setIntegerDataArrays(const IntegerDataArrays& ida);
/// Returns a mutable reference to the first integer meta data array with the given name
inline IntegerDataArray& getIntegerDataArrayByName(String name)
{
return *std::find_if(integer_data_arrays_.begin(), integer_data_arrays_.end(),
[&name](const IntegerDataArray& da) { return da.getName() == name; } );
}
/// Returns a mutable reference to the first string meta data array with the given name
inline StringDataArray& getStringDataArrayByName(String name)
{
return *std::find_if(string_data_arrays_.begin(), string_data_arrays_.end(),
[&name](const StringDataArray& da) { return da.getName() == name; } );
}
/// Returns a mutable reference to the first float meta data array with the given name
inline FloatDataArray& getFloatDataArrayByName(String name)
{
return *std::find_if(float_data_arrays_.begin(), float_data_arrays_.end(),
[&name](const FloatDataArray& da) { return da.getName() == name; } );
}
/// Returns a const reference to the first integer meta data array with the given name
inline const IntegerDataArray& getIntegerDataArrayByName(String name) const
{
return *std::find_if(integer_data_arrays_.begin(), integer_data_arrays_.end(),
[&name](const IntegerDataArray& da) { return da.getName() == name; } );
}
/// Returns a const reference to the first string meta data array with the given name
inline const StringDataArray& getStringDataArrayByName(String name) const
{
return *std::find_if(string_data_arrays_.begin(), string_data_arrays_.end(),
[&name](const StringDataArray& da) { return da.getName() == name; } );
}
/// Returns a const reference to the first float meta data array with the given name
inline const FloatDataArray& getFloatDataArrayByName(String name) const
{
return *std::find_if(float_data_arrays_.begin(), float_data_arrays_.end(),
[&name](const FloatDataArray& da) { return da.getName() == name; } );
}
private:
/// Float data arrays
FloatDataArrays float_data_arrays_;
/// String data arrays
StringDataArrays string_data_arrays_;
/// Integer data arrays
IntegerDataArrays integer_data_arrays_;
};
/// Peak mass type
enum class PeakMassType
{
MONOISOTOPIC,
AVERAGE,
SIZE_OF_PEAKMASSTYPE
};
/// Names corresponding to peak mass types
static const std::string NamesOfPeakMassType[static_cast<size_t>(PeakMassType::SIZE_OF_PEAKMASSTYPE)];
/// returns all peak mass type names known to OpenMS
static StringList getAllNamesOfPeakMassType();
/// Search parameters of the DB search
struct OPENMS_DLLAPI SearchParameters :
public MetaInfoInterface
{
String db; ///< The used database
String db_version; ///< The database version
String taxonomy; ///< The taxonomy restriction
String charges; ///< The allowed charges for the search
PeakMassType mass_type; ///< Mass type of the peaks
std::vector<String> fixed_modifications; ///< Used fixed modifications
std::vector<String> variable_modifications; ///< Allowed variable modifications
UInt missed_cleavages; ///< The number of allowed missed cleavages
double fragment_mass_tolerance; ///< Mass tolerance of fragment ions (Dalton or ppm)
bool fragment_mass_tolerance_ppm; ///< Mass tolerance unit of fragment ions (true: ppm, false: Dalton)
double precursor_mass_tolerance; ///< Mass tolerance of precursor ions (Dalton or ppm)
bool precursor_mass_tolerance_ppm; ///< Mass tolerance unit of precursor ions (true: ppm, false: Dalton)
Protease digestion_enzyme; ///< The cleavage site information in details (from ProteaseDB)
EnzymaticDigestion::Specificity enzyme_term_specificity; ///< The number of required cutting-rule matching termini during search (none=0, semi=1, or full=2)
SearchParameters();
/// Copy constructor
SearchParameters(const SearchParameters&) = default;
/// Move constructor
SearchParameters(SearchParameters&&) = default;
/// Destructor
~SearchParameters() = default;
/// Assignment operator
SearchParameters& operator=(const SearchParameters&) = default;
/// Move assignment operator
SearchParameters& operator=(SearchParameters&&)& = default;
bool operator==(const SearchParameters& rhs) const;
bool operator!=(const SearchParameters& rhs) const;
/// returns the charge range from the search engine settings as a pair of ints
std::pair<int,int> getChargeRange() const;
/// Tests if these search engine settings are mergeable with @p sp
/// depending on the given @p experiment_type.
/// Modifications are compared as sets. Databases based on filename.
/// "labeled_MS1" experiments additionally allow different modifications.
bool mergeable(const ProteinIdentification::SearchParameters& sp, const String& experiment_type) const;
private:
int getChargeValue_(String& charge_str) const;
};
/** @name Constructors, destructors, assignment operator <br> */
//@{
/// Default constructor
ProteinIdentification();
/// Copy constructor
ProteinIdentification(const ProteinIdentification&) = default;
/// Move constructor
ProteinIdentification(ProteinIdentification&&) = default;
/// Destructor
virtual ~ProteinIdentification();
/// Assignment operator
ProteinIdentification& operator=(const ProteinIdentification&) = default;
/// Move assignment operator
ProteinIdentification& operator=(ProteinIdentification&&) = default;
/// Equality operator
bool operator==(const ProteinIdentification& rhs) const;
/// Inequality operator
bool operator!=(const ProteinIdentification& rhs) const;
//@}
///@name Protein hit information (public members)
//@{
/// Returns the protein hits
const std::vector<ProteinHit>& getHits() const;
/// Returns the protein hits (mutable)
std::vector<ProteinHit>& getHits();
/// Appends a protein hit
void insertHit(const ProteinHit& input);
/// Appends a protein hit
void insertHit(ProteinHit&& input);
/**
@brief Sets the protein hits
@note This may invalidate (indistinguishable) protein groups! If necessary, use e.g. @p IDFilter::updateProteinGroups to update the groupings.
*/
void setHits(const std::vector<ProteinHit>& hits);
/// Finds a protein hit by accession (returns past-the-end iterator if not found)
std::vector<ProteinHit>::iterator findHit(const String& accession);
/// Returns the protein groups
const std::vector<ProteinGroup>& getProteinGroups() const;
/// Returns the protein groups (mutable)
std::vector<ProteinGroup>& getProteinGroups();
/// Appends a new protein group
void insertProteinGroup(const ProteinGroup& group);
/// Returns the indistinguishable proteins
const std::vector<ProteinGroup>& getIndistinguishableProteins() const;
/// Returns the indistinguishable proteins (mutable)
std::vector<ProteinGroup>& getIndistinguishableProteins();
/// Appends new indistinguishable proteins
void insertIndistinguishableProteins(const ProteinGroup& group);
/// Appends singleton groups (with the current score) for every yet ungrouped protein hit
void fillIndistinguishableGroupsWithSingletons();
/// Returns the protein significance threshold value
double getSignificanceThreshold() const;
/// Sets the protein significance threshold value
void setSignificanceThreshold(double value);
/// Returns the protein score type
const String& getScoreType() const;
/// Sets the protein score type
void setScoreType(const String& type);
/// Returns true if a higher score represents a better score
bool isHigherScoreBetter() const;
/// Sets the orientation of the score (is higher better?)
void setHigherScoreBetter(bool higher_is_better);
/// Sorts the protein hits according to their score
void sort();
/**
@brief Compute the coverage (in percent) of all ProteinHits given PeptideHits
@throws Exception::MissingInformation if ProteinsHits do not have sequence information
Does not return anything but stores the coverage inside the ProteinHit objects
*/
void computeCoverage(const PeptideIdentificationList& pep_ids);
void computeCoverage(const ConsensusMap& cmap, bool use_unassigned_ids);
//@}
/**
@brief Compute the modifications of all ProteinHits given PeptideHits
For every protein accession, the pair of position and modification is returned.
Because fixed modifications might not be of interest, a list can be provided to skip those.
*/
void computeModifications(
const PeptideIdentificationList& pep_ids,
const StringList& skip_modifications);
void computeModifications(
const ConsensusMap& cmap,
const StringList& skip_modifications,
bool use_unassigned_ids);
///@name General information
//@{
/// Returns the date of the protein identification run
const DateTime& getDateTime() const;
/// Sets the date of the protein identification run
void setDateTime(const DateTime& date);
/// Sets the search engine type
void setSearchEngine(const String& search_engine);
/// Returns the type of search engine used
const String& getSearchEngine() const;
/// Return the type of search engine that was first applied (e.g., before percolator or consensusID) or "Unknown"
const String getOriginalSearchEngineName() const;
/// Sets the search engine version
void setSearchEngineVersion(const String& search_engine_version);
/// Returns the search engine version
const String& getSearchEngineVersion() const;
/// Sets the inference engine type
void setInferenceEngine(const String& search_engine);
/// Returns the type of search engine used
const String getInferenceEngine() const;
/// Sets the search engine version
void setInferenceEngineVersion(const String& inference_engine_version);
/// Returns the search engine version
const String getInferenceEngineVersion() const;
/// Sets the search parameters
void setSearchParameters(const SearchParameters& search_parameters);
/// Sets the search parameters (move)
void setSearchParameters(SearchParameters&& search_parameters);
/// Returns the search parameters
const SearchParameters& getSearchParameters() const;
/// Returns the search parameters (mutable)
SearchParameters& getSearchParameters();
/// Returns the identifier
const String& getIdentifier() const;
/// Sets the identifier
void setIdentifier(const String& id);
/**
Set the file paths to the primary MS runs (usually the mzML files obtained after data conversion from raw files)
@param[in] s The file paths
@param[in] raw Store paths to the raw files (or equivalent) rather than mzMLs
*/
void setPrimaryMSRunPath(const StringList& s, bool raw = false);
/// set the file path to the primary MS run but try to use the mzML annotated in the MSExperiment.
void setPrimaryMSRunPath(const StringList& s, MSExperiment& e);
void addPrimaryMSRunPath(const String& s, bool raw = false);
void addPrimaryMSRunPath(const StringList& s, bool raw = false);
/**
Get the file paths to the primary MS runs
@param[out] output The file paths
@param[in] raw Get raw files (or equivalent) instead of mzMLs
*/
void getPrimaryMSRunPath(StringList& output, bool raw = false) const;
/// get the number of primary MS runs involve in this ID run
Size nrPrimaryMSRunPaths(bool raw = false) const;
/// Checks if this object has inference data. Looks for "InferenceEngine" metavalue.
/// If not, falls back to old behaviour of reading the search engine name.
bool hasInferenceData() const;
/// Checks if the search engine name matches an inference engine known to OpenMS.
bool hasInferenceEngineAsSearchEngine() const;
/// Checks if the peptide IDs of this IDRun are mergeable with another @p id_run
/// given an @p experiment_type .
/// Checks search engine and search engine settings.
bool peptideIDsMergeable(const ProteinIdentification& id_run, const String& experiment_type) const;
/// Collects all search engine settings registered for the given search engine @p se.
/// If @p se is empty, the main search engine is used, otherwise it will also search the metavalues.
std::vector<std::pair<String,String>> getSearchEngineSettingsAsPairs(const String& se = "") const;
//@}
/// Copies only metadata (no protein hits or protein groups)
void copyMetaDataOnly(const ProteinIdentification&);
protected:
///@name General information (search engine, parameters and database)
//@{
String id_;
String search_engine_;
String search_engine_version_;
SearchParameters search_parameters_;
DateTime date_;
//@}
///@name Protein hit information (protected members)
//@{
String protein_score_type_;
bool higher_score_better_;
std::vector<ProteinHit> protein_hits_;
std::vector<ProteinGroup> protein_groups_;
/// Indistinguishable proteins: @p accessions[0] is "group leader", @p probability is meaningless
std::vector<ProteinGroup> indistinguishable_proteins_;
double protein_significance_threshold_;
//@}
private:
void computeCoverageFromEvidenceMapping_(const std::unordered_map<String, std::set<PeptideEvidence>>& map);
void fillEvidenceMapping_(std::unordered_map<String, std::set<PeptideEvidence> >& map_acc_2_evidence,
const PeptideIdentificationList& pep_ids) const;
void fillModMapping_(const PeptideIdentificationList& pep_ids, const StringList& skip_modifications,
std::unordered_map<String, std::set<std::pair<Size, ResidueModification>>>& prot2mod) const;
};
} //namespace OpenMS
// Hash function specializations
namespace std
{
/// std::hash specialization for ProteinIdentification::ProteinGroup
template<>
struct hash<OpenMS::ProteinIdentification::ProteinGroup>
{
std::size_t operator()(const OpenMS::ProteinIdentification::ProteinGroup& pg) const noexcept
{
std::size_t seed = OpenMS::hash_float(pg.probability);
for (const auto& acc : pg.accessions)
{
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(acc));
}
return seed;
}
};
/// std::hash specialization for ProteinIdentification::SearchParameters
template<>
struct hash<OpenMS::ProteinIdentification::SearchParameters>
{
std::size_t operator()(const OpenMS::ProteinIdentification::SearchParameters& sp) const noexcept
{
std::size_t seed = OpenMS::fnv1a_hash_string(sp.db);
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(sp.db_version));
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(sp.taxonomy));
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(sp.charges));
OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(sp.mass_type)));
// Hash fixed_modifications
for (const auto& mod : sp.fixed_modifications)
{
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(mod));
}
// Hash variable_modifications
for (const auto& mod : sp.variable_modifications)
{
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(mod));
}
OpenMS::hash_combine(seed, OpenMS::hash_int(sp.missed_cleavages));
OpenMS::hash_combine(seed, OpenMS::hash_float(sp.fragment_mass_tolerance));
OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(sp.fragment_mass_tolerance_ppm)));
OpenMS::hash_combine(seed, OpenMS::hash_float(sp.precursor_mass_tolerance));
OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(sp.precursor_mass_tolerance_ppm)));
// Hash digestion_enzyme using the base class hash
OpenMS::hash_combine(seed, std::hash<OpenMS::DigestionEnzyme>{}(sp.digestion_enzyme));
OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(sp.enzyme_term_specificity)));
// Hash MetaInfoInterface base class
OpenMS::hash_combine(seed, std::hash<OpenMS::MetaInfoInterface>{}(sp));
return seed;
}
};
/// std::hash specialization for ProteinIdentification
template<>
struct hash<OpenMS::ProteinIdentification>
{
std::size_t operator()(const OpenMS::ProteinIdentification& pi) const noexcept
{
// Hash identifier and search engine info
std::size_t seed = OpenMS::fnv1a_hash_string(pi.getIdentifier());
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(pi.getSearchEngine()));
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(pi.getSearchEngineVersion()));
// Hash SearchParameters
OpenMS::hash_combine(seed, std::hash<OpenMS::ProteinIdentification::SearchParameters>{}(pi.getSearchParameters()));
// Hash DateTime
OpenMS::hash_combine(seed, std::hash<OpenMS::DateTime>{}(pi.getDateTime()));
// Hash protein_hits
for (const auto& hit : pi.getHits())
{
OpenMS::hash_combine(seed, OpenMS::hash_float(hit.getScore()));
OpenMS::hash_combine(seed, OpenMS::hash_int(hit.getRank()));
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(hit.getAccession()));
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(hit.getSequence()));
OpenMS::hash_combine(seed, OpenMS::hash_float(hit.getCoverage()));
}
// Hash protein_groups
for (const auto& group : pi.getProteinGroups())
{
OpenMS::hash_combine(seed, std::hash<OpenMS::ProteinIdentification::ProteinGroup>{}(group));
}
// Hash indistinguishable_proteins
for (const auto& group : pi.getIndistinguishableProteins())
{
OpenMS::hash_combine(seed, std::hash<OpenMS::ProteinIdentification::ProteinGroup>{}(group));
}
// Hash score type and threshold
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(pi.getScoreType()));
OpenMS::hash_combine(seed, OpenMS::hash_float(pi.getSignificanceThreshold()));
OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(pi.isHigherScoreBetter())));
// Hash MetaInfoInterface base class
OpenMS::hash_combine(seed, std::hash<OpenMS::MetaInfoInterface>{}(pi));
return seed;
}
};
} // namespace std
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/MassAnalyzer.h | .h | 15,875 | 438 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CONCEPT/Types.h>
#include <OpenMS/CONCEPT/HashUtils.h>
#include <OpenMS/METADATA/MetaInfoInterface.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
#include <functional>
namespace OpenMS
{
/**
@brief Description of a mass analyzer (part of a MS Instrument)
@ingroup Metadata
*/
class OPENMS_DLLAPI MassAnalyzer :
public MetaInfoInterface
{
public:
/// analyzer type
enum class AnalyzerType
{
ANALYZERNULL, ///< Unknown
QUADRUPOLE, ///< Quadrupole
PAULIONTRAP, ///< Quadrupole ion trap / Paul ion trap
RADIALEJECTIONLINEARIONTRAP, ///< Radial ejection linear ion trap
AXIALEJECTIONLINEARIONTRAP, ///< Axial ejection linear ion trap
TOF, ///< Time-of-flight
SECTOR, ///< Magnetic sector
FOURIERTRANSFORM, ///< Fourier transform ion cyclotron resonance mass spectrometer
IONSTORAGE, ///< Ion storage
ESA, ///< Electrostatic energy analyzer
IT, ///< Ion trap
SWIFT, ///< Stored waveform inverse fourier transform
CYCLOTRON, ///< Cyclotron
ORBITRAP, ///< Orbitrap
LIT, ///< Linear ion trap
SIZE_OF_ANALYZERTYPE
};
/// Names of the analyzer types
static const std::string NamesOfAnalyzerType[static_cast<size_t>(AnalyzerType::SIZE_OF_ANALYZERTYPE)];
/**
@brief resolution method
Which of the available standard measures is used to define whether two peaks are separate
*/
enum class ResolutionMethod
{
RESMETHNULL, ///< Unknown
FWHM, ///< Full width at half max
TENPERCENTVALLEY, ///< Ten percent valley
BASELINE, ///< Baseline
SIZE_OF_RESOLUTIONMETHOD
};
/// Names of resolution methods
static const std::string NamesOfResolutionMethod[static_cast<size_t>(ResolutionMethod::SIZE_OF_RESOLUTIONMETHOD)];
/// Resolution type
enum class ResolutionType
{
RESTYPENULL, ///< Unknown
CONSTANT, ///< Constant
PROPORTIONAL, ///< Proportional
SIZE_OF_RESOLUTIONTYPE
};
/// Names of resolution type
static const std::string NamesOfResolutionType[static_cast<size_t>(ResolutionType::SIZE_OF_RESOLUTIONTYPE)];
/// direction of scanning
enum class ScanDirection
{
SCANDIRNULL, ///< Unknown
UP, ///< Up
DOWN, ///< Down
SIZE_OF_SCANDIRECTION
};
/// Names of direction of scanning
static const std::string NamesOfScanDirection[static_cast<size_t>(ScanDirection::SIZE_OF_SCANDIRECTION)];
///Scan law
enum class ScanLaw
{
SCANLAWNULL, ///< Unknown
EXPONENTIAL, ///< Unknown
LINEAR, ///< Linear
QUADRATIC, ///< Quadratic
SIZE_OF_SCANLAW
};
/// Names of scan laws
static const std::string NamesOfScanLaw[static_cast<size_t>(ScanLaw::SIZE_OF_SCANLAW)];
///Reflectron state
enum class ReflectronState
{
REFLSTATENULL, ///< Unknown
ON, ///< On
OFF, ///< Off
NONE, ///< None
SIZE_OF_REFLECTRONSTATE
};
/// Names of reflectron states
static const std::string NamesOfReflectronState[static_cast<size_t>(ReflectronState::SIZE_OF_REFLECTRONSTATE)];
/**
@brief Returns all analyzer type names known to OpenMS
@return List of all analyzer type names
*/
static StringList getAllNamesOfAnalyzerType();
/**
@brief Returns all resolution method names known to OpenMS
@return List of all resolution method names
*/
static StringList getAllNamesOfResolutionMethod();
/**
@brief Returns all resolution type names known to OpenMS
@return List of all resolution type names
*/
static StringList getAllNamesOfResolutionType();
/**
@brief Returns all scan direction names known to OpenMS
@return List of all scan direction names
*/
static StringList getAllNamesOfScanDirection();
/**
@brief Returns all scan law names known to OpenMS
@return List of all scan law names
*/
static StringList getAllNamesOfScanLaw();
/**
@brief Returns all reflectron state names known to OpenMS
@return List of all reflectron state names
*/
static StringList getAllNamesOfReflectronState();
/**
@brief Convert an AnalyzerType enum to its string representation
@param type The analyzer type enum value to convert
@return Reference to the string representation
@throws Exception::InvalidValue if @p type is SIZE_OF_ANALYZERTYPE
*/
static const std::string& analyzerTypeToString(AnalyzerType type);
/**
@brief Convert a string to an AnalyzerType enum
@param name The string name to convert
@return The corresponding AnalyzerType enum value
@throws Exception::InvalidValue if @p name is not found in NamesOfAnalyzerType[]
*/
static AnalyzerType toAnalyzerType(const std::string& name);
/**
@brief Convert a ResolutionMethod enum to its string representation
@param method The resolution method enum value to convert
@return Reference to the string representation
@throws Exception::InvalidValue if @p method is SIZE_OF_RESOLUTIONMETHOD
*/
static const std::string& resolutionMethodToString(ResolutionMethod method);
/**
@brief Convert a string to a ResolutionMethod enum
@param name The string name to convert
@return The corresponding ResolutionMethod enum value
@throws Exception::InvalidValue if @p name is not found in NamesOfResolutionMethod[]
*/
static ResolutionMethod toResolutionMethod(const std::string& name);
/**
@brief Convert a ResolutionType enum to its string representation
@param type The resolution type enum value to convert
@return Reference to the string representation
@throws Exception::InvalidValue if @p type is SIZE_OF_RESOLUTIONTYPE
*/
static const std::string& resolutionTypeToString(ResolutionType type);
/**
@brief Convert a string to a ResolutionType enum
@param name The string name to convert
@return The corresponding ResolutionType enum value
@throws Exception::InvalidValue if @p name is not found in NamesOfResolutionType[]
*/
static ResolutionType toResolutionType(const std::string& name);
/**
@brief Convert a ScanDirection enum to its string representation
@param direction The scan direction enum value to convert
@return Reference to the string representation
@throws Exception::InvalidValue if @p direction is SIZE_OF_SCANDIRECTION
*/
static const std::string& scanDirectionToString(ScanDirection direction);
/**
@brief Convert a string to a ScanDirection enum
@param name The string name to convert
@return The corresponding ScanDirection enum value
@throws Exception::InvalidValue if @p name is not found in NamesOfScanDirection[]
*/
static ScanDirection toScanDirection(const std::string& name);
/**
@brief Convert a ScanLaw enum to its string representation
@param law The scan law enum value to convert
@return Reference to the string representation
@throws Exception::InvalidValue if @p law is SIZE_OF_SCANLAW
*/
static const std::string& scanLawToString(ScanLaw law);
/**
@brief Convert a string to a ScanLaw enum
@param name The string name to convert
@return The corresponding ScanLaw enum value
@throws Exception::InvalidValue if @p name is not found in NamesOfScanLaw[]
*/
static ScanLaw toScanLaw(const std::string& name);
/**
@brief Convert a ReflectronState enum to its string representation
@param state The reflectron state enum value to convert
@return Reference to the string representation
@throws Exception::InvalidValue if @p state is SIZE_OF_REFLECTRONSTATE
*/
static const std::string& reflectronStateToString(ReflectronState state);
/**
@brief Convert a string to a ReflectronState enum
@param name The string name to convert
@return The corresponding ReflectronState enum value
@throws Exception::InvalidValue if @p name is not found in NamesOfReflectronState[]
*/
static ReflectronState toReflectronState(const std::string& name);
/// Constructor
MassAnalyzer();
/// Copy constructor
MassAnalyzer(const MassAnalyzer &) = default;
/// Move constructor
MassAnalyzer(MassAnalyzer&&) = default;
/// Destructor
~MassAnalyzer();
/// Assignment operator
MassAnalyzer & operator=(const MassAnalyzer&) = default;
/// Move assignment operator
MassAnalyzer& operator=(MassAnalyzer&&) & = default;
/// Equality operator
bool operator==(const MassAnalyzer & rhs) const;
/// Equality operator
bool operator!=(const MassAnalyzer & rhs) const;
/// returns the analyzer type
AnalyzerType getType() const;
/// sets the analyzer type
void setType(AnalyzerType type);
/// returns the method used for determination of the resolution
ResolutionMethod getResolutionMethod() const;
/// sets the method used for determination of the resolution
void setResolutionMethod(ResolutionMethod resolution_method);
/// returns the resolution type
ResolutionType getResolutionType() const;
/// sets the resolution type
void setResolutionType(ResolutionType resolution_type);
/// returns the direction of scanning
ScanDirection getScanDirection() const;
/// sets the direction of scanning
void setScanDirection(ScanDirection scan_direction);
/// returns the scan law
ScanLaw getScanLaw() const;
/// sets the scan law
void setScanLaw(ScanLaw scan_law);
/// returns the reflectron state (for TOF)
ReflectronState getReflectronState() const;
/// sets the reflectron state (for TOF)
void setReflectronState(ReflectronState reflecton_state);
/**
@brief returns the resolution
The maximum m/z value at which two peaks can be resolved, according to one of the standard measures
*/
double getResolution() const;
/// sets the resolution
void setResolution(double resolution);
/// returns the mass accuracy i.e. how much the theoretical mass may differ from the measured mass (in ppm)
double getAccuracy() const;
/// sets the accuracy i.e. how much the theoretical mass may differ from the measured mass (in ppm)
void setAccuracy(double accuracy);
/// returns the scan rate (in s)
double getScanRate() const;
/// sets the scan rate (in s)
void setScanRate(double scan_rate);
/// returns the scan time for a single scan (in s)
double getScanTime() const;
/// sets the scan time for a single scan (in s)
void setScanTime(double scan_time);
/// returns the path length for a TOF mass analyzer (in meter)
double getTOFTotalPathLength() const;
/// sets the path length for a TOF mass analyzer (in meter)
void setTOFTotalPathLength(double TOF_total_path_length);
/// returns the isolation width i.e. in which m/z range the precursor ion is selected for MS to the n (in m/z)
double getIsolationWidth() const;
/// sets the isolation width i.e. in which m/z range the precursor ion is selected for MS to the n (in m/z)
void setIsolationWidth(double isolation_width);
/// returns the final MS exponent
Int getFinalMSExponent() const;
/// sets the final MS exponent
void setFinalMSExponent(Int final_MS_exponent);
/// returns the strength of the magnetic field (in T)
double getMagneticFieldStrength() const;
/// sets the strength of the magnetic field (in T)
void setMagneticFieldStrength(double magnetic_field_strength);
/**
@brief returns the position of this part in the whole Instrument.
Order can be ignored, as long the instrument has this default setup:
- one ion source
- one or many mass analyzers
- one ion detector
For more complex instruments, the order should be defined.
*/
Int getOrder() const;
/// sets the order
void setOrder(Int order);
protected:
AnalyzerType type_;
ResolutionMethod resolution_method_;
ResolutionType resolution_type_;
ScanDirection scan_direction_;
ScanLaw scan_law_;
ReflectronState reflectron_state_;
double resolution_;
double accuracy_;
double scan_rate_;
double scan_time_;
double TOF_total_path_length_;
double isolation_width_;
Int final_MS_exponent_;
double magnetic_field_strength_;
Int order_;
};
} // namespace OpenMS
namespace std
{
/**
* @brief Hash function for OpenMS::MassAnalyzer.
*
* Computes a hash based on all fields compared in operator==:
* - All enum fields (type, resolution_method, resolution_type, scan_direction, scan_law, reflectron_state)
* - All double fields (resolution, accuracy, scan_rate, scan_time, TOF_total_path_length, isolation_width, magnetic_field_strength)
* - All integer fields (final_MS_exponent, order)
*
* @note MetaInfoInterface is included in operator== but excluded from hash computation
* since meta info is typically auxiliary data that varies frequently. This satisfies
* the hash contract: if hash(a) != hash(b), then a != b. The reverse implication
* (equal hashes imply equal objects) is not required for hash functions.
*/
template<>
struct hash<OpenMS::MassAnalyzer>
{
std::size_t operator()(const OpenMS::MassAnalyzer& ma) const noexcept
{
std::size_t seed = 0;
// Hash enum fields (cast to underlying integer type)
OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(ma.getType())));
OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(ma.getResolutionMethod())));
OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(ma.getResolutionType())));
OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(ma.getScanDirection())));
OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(ma.getScanLaw())));
OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(ma.getReflectronState())));
// Hash double fields
OpenMS::hash_combine(seed, OpenMS::hash_float(ma.getResolution()));
OpenMS::hash_combine(seed, OpenMS::hash_float(ma.getAccuracy()));
OpenMS::hash_combine(seed, OpenMS::hash_float(ma.getScanRate()));
OpenMS::hash_combine(seed, OpenMS::hash_float(ma.getScanTime()));
OpenMS::hash_combine(seed, OpenMS::hash_float(ma.getTOFTotalPathLength()));
OpenMS::hash_combine(seed, OpenMS::hash_float(ma.getIsolationWidth()));
OpenMS::hash_combine(seed, OpenMS::hash_float(ma.getMagneticFieldStrength()));
// Hash integer fields
OpenMS::hash_combine(seed, OpenMS::hash_int(ma.getFinalMSExponent()));
OpenMS::hash_combine(seed, OpenMS::hash_int(ma.getOrder()));
return seed;
}
};
} // namespace std
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/ScanWindow.h | .h | 1,276 | 50 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/METADATA/MetaInfoInterface.h>
namespace OpenMS
{
/**
@brief Scan window description
@ingroup Metadata
*/
struct OPENMS_DLLAPI ScanWindow :
public MetaInfoInterface
{
/// Default constructor
ScanWindow() = default;
/// Copy constructor
ScanWindow(const ScanWindow &) = default;
/// Move constructor
ScanWindow(ScanWindow&&) = default;
/// Destructor
~ScanWindow() = default;
/// Equality operator
bool operator==(const ScanWindow & source) const;
/// Equality operator
bool operator!=(const ScanWindow & source) const;
/// Assignment operator
ScanWindow & operator=(const ScanWindow &) = default;
/// Move assignment operator
ScanWindow& operator=(ScanWindow&&) & = default;
/// Begin of the window
double begin = 0.0;
/// End of the window
double end = 0.0;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/MetaInfoInterface.h | .h | 6,800 | 187 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#pragma once
#include <vector>
#include <OpenMS/CONCEPT/Types.h>
#include <OpenMS/CONCEPT/HashUtils.h>
#include <OpenMS/METADATA/MetaInfoRegistry.h>
#include <OpenMS/METADATA/MetaInfo.h>
#include <OpenMS/DATASTRUCTURES/DataValue.h>
namespace OpenMS
{
class String;
/**
@brief Interface for classes that can store arbitrary meta information
(Type-Name-Value tuples).
MetaInfoInterface is a base class for all classes that use one MetaInfo
object as member. If you want to add meta information to a class, let it
publicly inherit the MetaInfoInterface. Meta information is an array of
Type-Name-Value tuples.
@ingroup Metadata
*/
class OPENMS_DLLAPI MetaInfoInterface
{
public:
/**
* @brief Const iterator type for iterating over meta info entries.
*
* Dereferences to std::pair<UInt, DataValue> where the first element is
* the registry index and the second is the associated DataValue.
*/
using MetaInfoConstIterator = MetaInfo::const_iterator;
/// Constructor
MetaInfoInterface() = default;
/// Copy constructor
MetaInfoInterface(const MetaInfoInterface& rhs);
/// Move constructor
MetaInfoInterface(MetaInfoInterface&&) noexcept;
/// Destructor
~MetaInfoInterface();
/// Assignment operator
MetaInfoInterface& operator=(const MetaInfoInterface& rhs);
/// Move assignment operator
MetaInfoInterface& operator=(MetaInfoInterface&&) noexcept;
/// Swap contents
void swap(MetaInfoInterface& rhs);
/// Equality operator
bool operator==(const MetaInfoInterface& rhs) const;
/// Equality operator
bool operator!=(const MetaInfoInterface& rhs) const;
/// Returns the value corresponding to a string, or DataValue::EMPTY if not found
const DataValue& getMetaValue(const String& name) const;
/// Returns the value corresponding to a string, or a default value (e.g.: DataValue::EMPTY) if not found
DataValue getMetaValue(const String& name, const DataValue& default_value) const; // Note: return needs to be by value to prevent life-time issues at caller site (e.g. if he passes a temporary to default-value)
/// Returns the value corresponding to the index, or DataValue::EMPTY if not found
const DataValue& getMetaValue(UInt index) const;
/// Returns the value corresponding to the index, or a default value (e.g.: DataValue::EMPTY) if not found
DataValue getMetaValue(UInt index, const DataValue& default_value) const; // Note: return needs to be by value to prevent life-time issues at caller site
/// Returns whether an entry with the given name exists
bool metaValueExists(const String& name) const;
/// Returns whether an entry with the given index exists
bool metaValueExists(UInt index) const;
/// Sets the DataValue corresponding to a name
void setMetaValue(const String& name, const DataValue& value);
/// Sets the DataValue corresponding to an index
void setMetaValue(UInt index, const DataValue& value);
/// Removes the DataValue corresponding to @p name if it exists
void removeMetaValue(const String& name);
/// Removes the DataValue corresponding to @p index if it exists
void removeMetaValue(UInt index);
/// Copy all meta values from @p from to this object (both named String and indexed UInt keys).
/// Existing entries with the same key are overwritten; others are preserved.
void addMetaValues(const MetaInfoInterface& from);
/// Returns a reference to the MetaInfoRegistry
static MetaInfoRegistry& metaRegistry();
/// Fills the given vector with a list of all keys for which a value is set
void getKeys(std::vector<String>& keys) const;
/// Fills the given vector with a list of all keys for which a value is set
void getKeys(std::vector<UInt>& keys) const;
/// Returns if the MetaInfo is empty
bool isMetaEmpty() const;
/// Removes all meta values
void clearMetaInfo();
/// @name Iterator access for meta info
/// @brief Provides read-only iterator access to the underlying meta info entries.
/// Iterators dereference to std::pair<UInt, DataValue> where the first element
/// is the registry index and the second is the associated value.
/// If no meta info exists (null internal pointer), an empty range is returned.
///@{
/**
* @brief Returns a const iterator to the beginning of the meta info entries.
*
* If no meta info exists (object was never assigned any meta values),
* returns an iterator equal to metaEnd() (empty range).
*
* @return MetaInfoConstIterator pointing to the first index-value pair.
*/
MetaInfoConstIterator metaBegin() const;
/**
* @brief Returns a const iterator to the end of the meta info entries.
*
* @return MetaInfoConstIterator pointing past the last index-value pair.
*/
MetaInfoConstIterator metaEnd() const;
/**
* @brief Returns the number of meta info entries.
*
* @return The count of meta value entries, or 0 if no meta info exists.
*/
Size metaSize() const;
///@}
protected:
/// Creates the MetaInfo object if it does not exist
inline void createIfNotExists_();
/// Pointer to the MetaInfo object
MetaInfo* meta_ = nullptr;
};
} // namespace OpenMS
// Hash function specialization for MetaInfoInterface
namespace std
{
/**
* @brief Hash function for MetaInfoInterface.
*
* Hashes based on all meta info key-value pairs using order-independent
* accumulation. Uses direct iterator access for O(n) complexity without
* allocating intermediate vectors.
*
* @note Uses additive accumulation (commutative) so equal MetaInfoInterface
* objects produce equal hashes regardless of internal storage order.
*/
template<>
struct hash<OpenMS::MetaInfoInterface>
{
std::size_t operator()(const OpenMS::MetaInfoInterface& meta) const noexcept
{
std::size_t hash = 0;
// Iterate directly over the underlying flat_map entries
for (auto it = meta.metaBegin(); it != meta.metaEnd(); ++it)
{
std::size_t pair_hash = OpenMS::hash_int(static_cast<int64_t>(it->first));
OpenMS::hash_combine(pair_hash, std::hash<OpenMS::DataValue>{}(it->second));
hash += pair_hash; // Order-independent accumulation
}
return hash;
}
};
} // namespace std
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/InstrumentSettings.h | .h | 4,483 | 124 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/METADATA/ScanWindow.h>
#include <OpenMS/METADATA/IonSource.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
namespace OpenMS
{
/**
@brief Description of the settings a MS Instrument was run with.
@ingroup Metadata
*/
class OPENMS_DLLAPI InstrumentSettings :
public MetaInfoInterface
{
public:
/// scan mode
enum class ScanMode
{
UNKNOWN, ///< Unknown scan method
MASSSPECTRUM, ///< general spectrum type
MS1SPECTRUM, ///< full scan mass spectrum, is a "mass spectrum" @n Synonyms: 'full spectrum', 'Q1 spectrum', 'Q3 spectrum', 'Single-Stage Mass Spectrometry'
MSNSPECTRUM, ///< MS2+ mass spectrum, is a "mass spectrum"
SIM, ///< Selected ion monitoring scan @n Synonyms: 'Multiple ion monitoring scan', 'SIM scan', 'MIM scan'
SRM, ///< Selected reaction monitoring scan @n Synonyms: 'Multiple reaction monitoring scan', 'SRM scan', 'MRM scan'
CRM, ///< Consecutive reaction monitoring scan @n Synonyms: 'CRM scan'
CNG, ///< Constant neutral gain scan @n Synonyms: 'CNG scan'
CNL, ///< Constant neutral loss scan @n Synonyms: 'CNG scan'
PRECURSOR, ///< Precursor ion scan
EMC, ///< Enhanced multiply charged scan
TDF, ///< Time-delayed fragmentation scan
EMR, ///< Electromagnetic radiation scan @n Synonyms: 'EMR spectrum'
EMISSION, ///< Emission scan
ABSORPTION, ///< Absorption scan
SIZE_OF_SCANMODE
};
/// Names of scan modes
static const std::string NamesOfScanMode[static_cast<size_t>(ScanMode::SIZE_OF_SCANMODE)];
/**
@brief Returns all scan mode names known to OpenMS
@return List of all scan mode names
*/
static StringList getAllNamesOfScanMode();
/**
@brief Convert a ScanMode enum to its string representation
@param mode The scan mode enum value to convert
@return Reference to the string representation
@throws Exception::InvalidValue if @p mode is SIZE_OF_SCANMODE
*/
static const std::string& scanModeToString(ScanMode mode);
/**
@brief Convert a string to a ScanMode enum
@param name The string name to convert
@return The corresponding ScanMode enum value
@throws Exception::InvalidValue if @p name is not found in NamesOfScanMode[]
*/
static ScanMode toScanMode(const std::string& name);
/// Constructor
InstrumentSettings();
/// Copy constructor
InstrumentSettings(const InstrumentSettings &) = default;
/// Move constructor
InstrumentSettings(InstrumentSettings&&) = default;
/// Destructor
~InstrumentSettings();
/// Assignment operator
InstrumentSettings & operator=(const InstrumentSettings &) = default;
/// Move assignment operator
InstrumentSettings& operator=(InstrumentSettings&&) & = default;
/// Equality operator
bool operator==(const InstrumentSettings & rhs) const;
/// Equality operator
bool operator!=(const InstrumentSettings & rhs) const;
/// returns the scan mode
ScanMode getScanMode() const;
/// sets the scan mode
void setScanMode(ScanMode scan_mode);
/// return if this scan is a zoom (enhanced resolution) scan
bool getZoomScan() const;
/// sets if this scan is a zoom (enhanced resolution) scan
void setZoomScan(bool zoom_scan);
/// returns the polarity
IonSource::Polarity getPolarity() const;
/// sets the polarity
void setPolarity(IonSource::Polarity polarity);
/// returns a const reference to the m/z scan windows
const std::vector<ScanWindow> & getScanWindows() const;
/// returns a mutable reference to the m/z scan windows
std::vector<ScanWindow> & getScanWindows();
/// sets the m/z scan windows
void setScanWindows(std::vector<ScanWindow> scan_windows);
protected:
ScanMode scan_mode_;
bool zoom_scan_;
IonSource::Polarity polarity_;
std::vector<ScanWindow> scan_windows_;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/ProteinHit.h | .h | 8,007 | 262 | // 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 <iosfwd>
#include <vector>
#include <functional>
#include <set>
#include <map>
#include <OpenMS/CHEMISTRY/ResidueModification.h>
#include <OpenMS/CONCEPT/HashUtils.h>
#include <OpenMS/CONCEPT/Types.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/METADATA/MetaInfoInterface.h>
namespace OpenMS
{
/**
@brief Representation of a protein hit
It contains the fields score, score_type, rank, accession,
sequence and coverage.
@ingroup Metadata
*/
class OPENMS_DLLAPI ProteinHit :
public MetaInfoInterface
{
public:
/// Enum for target/decoy annotation
enum class TargetDecoyType
{
TARGET, ///< Target protein
DECOY, ///< Decoy protein
UNKNOWN ///< Target/decoy status is unknown (meta value not set)
};
static const double COVERAGE_UNKNOWN; // == -1
/// @name Hashes for ProteinHit
//@{
/// Hash of a ProteinHit based on its accession only!
class OPENMS_DLLAPI ProteinHitAccessionHash
{
public:
size_t operator()(const ProteinHit & p)
{
return std::hash<std::string>{}(p.getAccession());
}
};
class OPENMS_DLLAPI ProteinHitPtrAccessionHash
{
public:
size_t operator()(const ProteinHit * p)
{
return std::hash<std::string>{}(p->getAccession());
}
};
//@}
/// @name Comparators ProteinHit
//@{
/// Greater predicate for scores of hits
class OPENMS_DLLAPI ScoreMore
{
public:
template<typename Arg>
bool operator()(const Arg& a, const Arg& b) const
{
return std::make_tuple(a.getScore(), a.getAccession()) > std::make_tuple(b.getScore(), b.getAccession());
}
};
/// Lesser predicate for scores of hits
class OPENMS_DLLAPI ScoreLess
{
public:
template <typename Arg>
bool operator()(const Arg & a, const Arg & b) const
{
return std::make_tuple(a.getScore(), a.getAccession()) < std::make_tuple(b.getScore(), b.getAccession());
}
};
//@}
/** @name Constructors and Destructor */
//@{
/// Default constructor
ProteinHit();
/// Values constructor
ProteinHit(double score, UInt rank, String accession, String sequence);
/// Copy constructor
ProteinHit(const ProteinHit &) = default;
/// Move constructor
ProteinHit(ProteinHit&&) = default;
//@}
/// Assignment operator
ProteinHit & operator=(const ProteinHit &) = default;
/// Move assignment operator
ProteinHit& operator=(ProteinHit&&) = default; // TODO: add noexcept (gcc 4.8 bug)
/// Assignment for MetaInfo
ProteinHit & operator=(const MetaInfoInterface & source);
/// Equality operator
bool operator==(const ProteinHit & rhs) const;
/// Inequality operator
bool operator!=(const ProteinHit & rhs) const;
/** @name Accessors */
//@{
/// returns the score of the protein hit
double getScore() const;
/// returns the rank of the protein hit
UInt getRank() const;
/// returns the protein sequence
const String & getSequence() const;
/// returns the accession of the protein
const String & getAccession() const;
/// returns the description of the protein
String getDescription() const;
/// returns the coverage (in percent) of the protein hit based upon matched peptides
double getCoverage() const;
/// sets the score of the protein hit
void setScore(const double score);
/// sets the rank
void setRank(UInt newrank);
/// sets the protein sequence
void setSequence(const String & sequence);
void setSequence(String && sequence);
/// sets the accession of the protein
void setAccession(const String & accession);
/// sets the description of the protein
void setDescription(const String & description);
/// sets the coverage (in percent) of the protein hit based upon matched peptides
void setCoverage(const double coverage);
/// returns the set of modified protein positions
const std::set<std::pair<Size, ResidueModification> >& getModifications() const;
/// sets the set of modified protein positions
void setModifications(std::set<std::pair<Size, ResidueModification> >& mods);
/// returns true if this is a decoy hit (false for TARGET and UNKNOWN)
bool isDecoy() const;
/** @brief Sets the target/decoy type for this protein hit
*
* This method provides a type-safe way to annotate protein hits with their
* target/decoy status.
*
* @param[in] type The target/decoy classification:
* - TARGET: Target protein
* - DECOY: Decoy protein
* - UNKNOWN: Target/decoy status is unknown; the "target_decoy" meta value is removed
*/
void setTargetDecoyType(TargetDecoyType type);
/** @brief Returns the target/decoy type for this protein hit
*
* This method performs case-insensitive parsing of the "target_decoy" meta value
* and returns the corresponding enum value. Returns UNKNOWN if the meta value
* does not exist.
*
* @return The target/decoy classification:
* - TARGET: Target protein
* - DECOY: Decoy protein
* - UNKNOWN: Target/decoy status not set (meta value missing)
*/
TargetDecoyType getTargetDecoyType() const;
//@}
protected:
double score_; ///< the score of the protein hit
UInt rank_; ///< the position(rank) where the hit appeared in the hit list
String accession_; ///< the protein identifier
String sequence_; ///< the amino acid sequence of the protein hit
double coverage_; ///< coverage of the protein based upon the matched peptide sequences
std::set<std::pair<Size, ResidueModification> > modifications_; ///< modified positions in a protein
};
/// Stream operator
OPENMS_DLLAPI std::ostream& operator<< (std::ostream& stream, const ProteinHit& hit);
} // namespace OpenMS
// Hash function specialization for ProteinHit
namespace std
{
/**
* @brief Hash function for OpenMS::ProteinHit.
*
* Computes a hash based on all fields used in operator==:
* - score (double)
* - rank (UInt)
* - accession (String)
* - sequence (String)
* - coverage (double)
* - modifications (set of position-modification pairs)
*
* @note MetaInfoInterface is not included in the hash for performance reasons.
* This means two ProteinHit objects that differ only in meta values will
* have the same hash but compare unequal with operator==. This is valid
* as the hash contract only requires that equal objects have equal hashes.
*/
template<>
struct hash<OpenMS::ProteinHit>
{
std::size_t operator()(const OpenMS::ProteinHit& hit) const noexcept
{
std::size_t seed = OpenMS::hash_float(hit.getScore());
OpenMS::hash_combine(seed, OpenMS::hash_int(hit.getRank()));
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(hit.getAccession()));
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(hit.getSequence()));
OpenMS::hash_combine(seed, OpenMS::hash_float(hit.getCoverage()));
// Hash modifications (set of pairs: position + ResidueModification)
for (const auto& mod_pair : hit.getModifications())
{
OpenMS::hash_combine(seed, OpenMS::hash_int(mod_pair.first)); // position (Size)
// Use getFullId() for the modification, consistent with AASequence hashing
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(mod_pair.second.getFullId()));
}
return seed;
}
};
} // namespace std
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/PeptideIdentificationList.h | .h | 3,956 | 113 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Timo Sachsenberg $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/DATASTRUCTURES/ExposedVector.h>
namespace OpenMS
{
/**
@brief Container for peptide identifications from multiple spectra.
This class represents a collection of PeptideIdentification objects, typically
originating from multiple spectra within a single identification run or experiment.
PeptideIdentificationList is commonly used in scenarios where multiple spectra
have been searched against a database, resulting in a list of identifications that
need to be processed together. Examples include:
- Storing all peptide identifications from an LC-MS/MS run
- Collecting identifications for protein inference algorithms
- Aggregating results from multiple search engines
- Managing identifications in feature mapping workflows
Note: The class uses composition over inheritance (via ExposedVector) to avoid the
well-known pitfalls of inheriting directly from STL containers
Usage example:
@code
PeptideIdentificationList peptide_ids;
// Add identifications from search results
PeptideIdentification id1, id2;
id1.setRT(1234.5);
id1.setMZ(567.8);
peptide_ids.push_back(id1);
peptide_ids.push_back(id2);
// Process all identifications
for (auto& id : peptide_ids)
{
// Apply filtering, scoring, etc.
IDFilter::keepNBestHits(id, 5);
}
// Use with algorithms that operate on collections
IDFilter::keepNBestHits(peptide_ids, 1);
BasicProteinInferenceAlgorithm algo;
algo.run(peptide_ids, protein_ids);
@endcode
The container provides full vector-like functionality including element access,
iteration, size management, and all standard algorithms.
@see PeptideIdentification, ProteinIdentification, IDFilter, BasicProteinInferenceAlgorithm, ExposedVector
@ingroup Metadata
*/
class OPENMS_DLLAPI PeptideIdentificationList : public ExposedVector<PeptideIdentification>
{
public:
EXPOSED_VECTOR_INTERFACE(PeptideIdentification)
/// @name Additional constructors for std::vector compatibility
//@{
/// Constructor from std::vector
PeptideIdentificationList(const std::vector<PeptideIdentification>& vec)
: ExposedVector<PeptideIdentification>(vec.begin(), vec.end()) {}
/// Move constructor from std::vector
PeptideIdentificationList(std::vector<PeptideIdentification>&& vec)
: ExposedVector<PeptideIdentification>(std::make_move_iterator(vec.begin()),
std::make_move_iterator(vec.end())) {}
/// Constructor from initializer list
PeptideIdentificationList(std::initializer_list<PeptideIdentification> init)
: ExposedVector<PeptideIdentification>(init.begin(), init.end()) {}
//@}
/// @name Assignment operators for std::vector compatibility
//@{
/// Assignment from std::vector
PeptideIdentificationList& operator=(const std::vector<PeptideIdentification>& vec)
{
assign(vec.begin(), vec.end());
return *this;
}
/// Move assignment from std::vector
PeptideIdentificationList& operator=(std::vector<PeptideIdentification>&& vec)
{
data_ = std::move(vec);
return *this;
}
/// Assignment from initializer list
PeptideIdentificationList& operator=(std::initializer_list<PeptideIdentification> init)
{
assign(init.begin(), init.end());
return *this;
}
//@}
};
} //namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/Acquisition.h | .h | 1,614 | 57 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/METADATA/MetaInfoInterface.h>
namespace OpenMS
{
/**
@brief Information about one raw data spectrum that was combined with several
other raw data spectra.
Although this class is basically a string value, it is needed to store important meta info for each raw data scan.
@ingroup Metadata
*/
class OPENMS_DLLAPI Acquisition :
public MetaInfoInterface
{
public:
/// Constructor
Acquisition() = default;
/// Copy constructor
Acquisition(const Acquisition &) = default;
/// Move constructor
Acquisition(Acquisition&&) = default;
/// Destructor
~Acquisition() = default;
/// Assignment operator
Acquisition & operator=(const Acquisition &) = default;
/// Move assignment operator
Acquisition& operator=(Acquisition&&) & = default;
/// Equality operator
bool operator==(const Acquisition & rhs) const;
/// Equality operator
bool operator!=(const Acquisition & rhs) const;
/// return the identifier/index/number of the acquisition
const String & getIdentifier() const;
/// sets the index/number of the scan
void setIdentifier(const String & identifier);
protected:
String identifier_;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/CVTermList.h | .h | 4,444 | 150 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Mathias Walzer $
// $Authors: Andreas Bertsch, Mathias Walzer $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/METADATA/CVTerm.h>
#include <OpenMS/METADATA/MetaInfoInterface.h>
#include <OpenMS/CONCEPT/HashUtils.h>
#include <map>
namespace OpenMS
{
/**
@brief Representation of controlled vocabulary term list
This class should be used to inherit from, to allow to add
an arbitrary number of CV terms to the inherited class
@ingroup Metadata
*/
///Representation of a CV term used by CVMappings
class OPENMS_DLLAPI CVTermList :
public MetaInfoInterface
{
public:
/// Defaults constructor
CVTermList() = default;
/// Copy constructor
CVTermList(const CVTermList&) = default;
// note: we implement the move constructor ourselves due to a bug in MSVS
// 2015/2017 which cannot produce a default move constructor for classes
// that contain STL containers (other than vector).
/// Move constructor
CVTermList(CVTermList&&) noexcept;
/// Destructor
virtual ~CVTermList();
/// Assignment operator
CVTermList& operator=(const CVTermList& rhs) & = default;
/// Move assignment operator
CVTermList& operator=(CVTermList&&) & = default;
/** @name Accessors
*/
//@{
/// sets the CV terms
void setCVTerms(const std::vector<CVTerm>& terms);
/// replaces the specified CV term
void replaceCVTerm(const CVTerm& cv_term);
/// replaces the specified CV terms using the given accession number
void replaceCVTerms(const std::vector<CVTerm>& cv_terms, const String& accession);
/// replaces all cv terms with a map (can be obtained via getCVTerms)
void replaceCVTerms(const std::map<String, std::vector<CVTerm> >& cv_term_map);
/// merges the given map into the member map, no duplicate checking
void consumeCVTerms(const std::map<String, std::vector<CVTerm> >& cv_term_map);
/// returns the accession string of the term
const std::map<String, std::vector<CVTerm> >& getCVTerms() const;
/// adds a CV term
void addCVTerm(const CVTerm& term);
/// checks whether the spellings of the CV terms stored are correct
//bool checkCVTerms(const ControlledVocabulary& cv) const;
/// corrects the CVTerm names, according to the loaded CV
//void correctCVTermNames();
//@}
/** @name Predicates
*/
//@{
/// equality operator
bool operator==(const CVTermList& cv_term_list) const;
/// inequality operator
bool operator!=(const CVTermList& cv_term_list) const;
/// checks whether the term has a value
bool hasCVTerm(const String& accession) const;
/// checks whether the stored terms fulfill a given CVMappingRule
/// TODO : implement
//bool checkCVTerms(const CVMappingRule & rule, const ControlledVocabulary & cv) const;
/// return true if no terms are available
bool empty() const;
//}
protected:
std::map<String, std::vector<CVTerm> > cv_terms_;
};
} // namespace OpenMS
// Hash function specialization for CVTermList
namespace std
{
/**
* @brief Hash function for CVTermList.
*
* Hashes based on the MetaInfoInterface base class and all CV terms.
* Iterates through the map of accession -> vector<CVTerm>.
*
* @note std::map iteration order is deterministic (sorted by key), so
* equal CVTermList objects will produce identical hash values without
* explicit sorting.
*/
template<>
struct hash<OpenMS::CVTermList>
{
std::size_t operator()(const OpenMS::CVTermList& list) const noexcept
{
// Start with MetaInfoInterface base class hash
std::size_t seed = std::hash<OpenMS::MetaInfoInterface>{}(list);
// Hash all CV terms
for (const auto& entry : list.getCVTerms())
{
// Hash the accession string
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(entry.first));
// Hash each CV term in the vector
for (const auto& term : entry.second)
{
OpenMS::hash_combine(seed, std::hash<OpenMS::CVTerm>{}(term));
}
}
return seed;
}
};
} // namespace std
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/IonSource.h | .h | 11,141 | 284 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/METADATA/MetaInfoInterface.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
#include <OpenMS/CONCEPT/HashUtils.h>
#include <functional>
namespace OpenMS
{
/**
@brief Description of an ion source (part of a MS Instrument)
@ingroup Metadata
*/
class OPENMS_DLLAPI IonSource :
public MetaInfoInterface
{
public:
/// inlet type
enum class InletType
{
INLETNULL, ///< Unknown
DIRECT, ///< Direct
BATCH, ///< Batch (e.g. in MALDI)
CHROMATOGRAPHY, ///< Chromatography (liquid)
PARTICLEBEAM, ///< Particle beam
MEMBRANESEPARATOR, ///< Membrane separator
OPENSPLIT, ///< Open split
JETSEPARATOR, ///< Jet separator
SEPTUM, ///< Septum
RESERVOIR, ///< Reservoir
MOVINGBELT, ///< Moving belt
MOVINGWIRE, ///< Moving wire
FLOWINJECTIONANALYSIS, ///< Flow injection analysis
ELECTROSPRAYINLET, ///< Electro spray
THERMOSPRAYINLET, ///< Thermo spray
INFUSION, ///< Infusion
CONTINUOUSFLOWFASTATOMBOMBARDMENT, ///< Continuous flow fast atom bombardment
INDUCTIVELYCOUPLEDPLASMA, ///< Inductively coupled plasma
MEMBRANE, ///< Membrane inlet
NANOSPRAY, ///< Nanospray inlet
SIZE_OF_INLETTYPE
};
/// Names of inlet types
static const std::string NamesOfInletType[static_cast<size_t>(InletType::SIZE_OF_INLETTYPE)];
/// ionization method
enum class IonizationMethod
{
IONMETHODNULL, ///< Unknown
ESI, ///< electrospray ionisation
EI, ///< electron ionization
CI, ///< chemical ionisation
FAB, ///< fast atom bombardment
TSP, ///< thermospray
LD, ///< laser desorption
FD, ///< field desorption
FI, ///< flame ionization
PD, ///< plasma desorption
SI, ///< secondary ion MS
TI, ///< thermal ionization
API, ///< atmospheric pressure ionisation
ISI, ///<
CID, ///< collision induced decomposition
CAD, ///< collision activated decomposition
HN, ///<
APCI, ///< atmospheric pressure chemical ionization
APPI, ///< atmospheric pressure photo ionization
ICP, ///< inductively coupled plasma
NESI, ///< Nano electrospray ionization
MESI, ///< Micro electrospray ionization
SELDI, ///< Surface enhanced laser desorption ionization
SEND, ///< Surface enhanced neat desorption
FIB, ///< Fast ion bombardment
MALDI, ///< Matrix-assisted laser desorption ionization
MPI, ///< Multiphoton ionization
DI, ///< desorption ionization
FA, ///< flowing afterglow
FII, ///< field ionization
GD_MS, ///< glow discharge ionization
NICI, ///< negative ion chemical ionization
NRMS, ///< neutralization reionization mass spectrometry
PI, ///< photoionization
PYMS, ///< pyrolysis mass spectrometry
REMPI, ///< resonance enhanced multiphoton ionization
AI, ///< adiabatic ionization
ASI, ///< associative ionization
AD, ///< autodetachment
AUI, ///< autoionization
CEI, ///< charge exchange ionization
CHEMI, ///< chemi-ionization
DISSI, ///< dissociative ionization
LSI, ///< liquid secondary ionization
PEI, ///< penning ionization
SOI, ///< soft ionization
SPI, ///< spark ionization
SUI, ///< surface ionization
VI, ///< vertical ionization
AP_MALDI, ///< atmospheric pressure matrix-assisted laser desorption ionization
SILI, ///< desorption/ionization on silicon
SALDI, ///< surface-assisted laser desorption ionization
SIZE_OF_IONIZATIONMETHOD
};
/// Names of ionization methods
static const std::string NamesOfIonizationMethod[static_cast<size_t>(IonizationMethod::SIZE_OF_IONIZATIONMETHOD)];
/// Polarity of the ion source
enum class Polarity
{
POLNULL, ///< Unknown
POSITIVE, ///< Positive polarity
NEGATIVE, ///< Negative polarity
SIZE_OF_POLARITY
};
/// Names of polarity of the ion source
static const std::string NamesOfPolarity[static_cast<size_t>(Polarity::SIZE_OF_POLARITY)];
/**
@brief Returns all inlet type names known to OpenMS
@note For performance-critical code that repeatedly accesses these names,
cache the returned list to avoid repeated allocations.
*/
static StringList getAllNamesOfInletType();
/**
@brief Returns all ionization method names known to OpenMS
@note For performance-critical code that repeatedly accesses these names,
cache the returned list to avoid repeated allocations.
*/
static StringList getAllNamesOfIonizationMethod();
/**
@brief Returns all polarity names known to OpenMS
@note For performance-critical code that repeatedly accesses these names,
cache the returned list to avoid repeated allocations.
*/
static StringList getAllNamesOfPolarity();
/**
@brief Convert an InletType enum to its string representation
@param type The inlet type enum value to convert
@return Reference to the string representation
@throws Exception::InvalidValue if @p type is SIZE_OF_INLETTYPE
*/
static const std::string& inletTypeToString(InletType type);
/**
@brief Convert a string to an InletType enum
@param name The string name to convert
@return The corresponding InletType enum value
@throws Exception::InvalidValue if @p name is not found in NamesOfInletType[]
*/
static InletType toInletType(const std::string& name);
/**
@brief Convert an IonizationMethod enum to its string representation
@param method The ionization method enum value to convert
@return Reference to the string representation
@throws Exception::InvalidValue if @p method is SIZE_OF_IONIZATIONMETHOD
*/
static const std::string& ionizationMethodToString(IonizationMethod method);
/**
@brief Convert a string to an IonizationMethod enum
@param name The string name to convert
@return The corresponding IonizationMethod enum value
@throws Exception::InvalidValue if @p name is not found in NamesOfIonizationMethod[]
*/
static IonizationMethod toIonizationMethod(const std::string& name);
/**
@brief Convert a Polarity enum to its string representation
@param polarity The polarity enum value to convert
@return Reference to the string representation
@throws Exception::InvalidValue if @p polarity is SIZE_OF_POLARITY
*/
static const std::string& polarityToString(Polarity polarity);
/**
@brief Convert a string to a Polarity enum
@param name The string name to convert
@return The corresponding Polarity enum value
@throws Exception::InvalidValue if @p name is not found in NamesOfPolarity[]
*/
static Polarity toPolarity(const std::string& name);
/// Constructor
IonSource();
/// Copy constructor
IonSource(const IonSource &) = default;
/// Move constructor
IonSource(IonSource&&) = default;
/// Destructor
~IonSource();
/// Assignment operator
IonSource & operator=(const IonSource &) = default;
/// Move assignment operator
IonSource& operator=(IonSource&&) & = default;
/// Equality operator
bool operator==(const IonSource & rhs) const;
/// Equality operator
bool operator!=(const IonSource & rhs) const;
/// returns the inlet type
InletType getInletType() const;
/// sets the inlet type
void setInletType(InletType inlet_type);
/// returns the ionization method
IonizationMethod getIonizationMethod() const;
/// sets the ionization method
void setIonizationMethod(IonizationMethod ionization_type);
/// returns the ionization mode
Polarity getPolarity() const;
/// sets the ionization mode
void setPolarity(Polarity polarity);
/**
@brief returns the position of this part in the whole Instrument.
Order can be ignored, as long the instrument has this default setup:
- one ion source
- one or many mass analyzers
- one ion detector
For more complex instruments, the order should be defined.
*/
Int getOrder() const;
/// sets the order
void setOrder(Int order);
protected:
InletType inlet_type_;
IonizationMethod ionization_method_;
Polarity polarity_;
Int order_;
};
} // namespace OpenMS
// Hash function specialization for IonSource
namespace std
{
template<>
struct hash<OpenMS::IonSource>
{
std::size_t operator()(const OpenMS::IonSource& is) const noexcept
{
// Hash all fields used in operator==: order_, inlet_type_, ionization_method_, polarity_, and MetaInfoInterface
std::size_t seed = OpenMS::hash_int(is.getOrder());
OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(is.getInletType())));
OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(is.getIonizationMethod())));
OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(is.getPolarity())));
// Hash MetaInfoInterface base class (handles both UInt and String keys)
OpenMS::hash_combine(seed, std::hash<OpenMS::MetaInfoInterface>{}(is));
return seed;
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/ExperimentalDesign.h | .h | 15,026 | 323 | // 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/String.h>
#include <OpenMS/METADATA/ProteinIdentification.h>
#include <vector>
#include <map>
#include <set>
namespace OpenMS
{
class ConsensusMap;
class FeatureMap;
/**
@brief Representation of an experimental design in OpenMS. Instances can be loaded with
the ExperimentalDesignFile class.
Experimental designs can be provided in two formats: the one-table format and the two-table format.
The one-table format is simpler but slightly more redundant.
The one-table format consists of mandatory (file columns) and optional sample metadata (sample columns).
The mandatory file columns are Fraction_Group, Fraction, Spectra_Filepath and Label.
These columns capture the mapping of quantitative values to files for label-free and multiplexed experiments
and enables fraction-aware data processing.
- Fraction_Group: a numeric identifier that indicates which fractions are grouped together. Please do NOT
reuse the same identifiers across samples! Assign identifiers continuously.
- Fraction: a numeric identifier that indicates which fraction was measured in this file.
In the case of unfractionated data, the fraction identifier is 1 for all samples.
Make sure the same identifiers are used across different Fraction_Groups, as this
determines which fractions correspond to each other.
- Label: a numeric identifier for the label. 1 for label-free, 1 and 2 for SILAC light/heavy, e.g., 1-10 for TMT10Plex
- Spectra_Filepath: a filename or path as string representation (e.g., SILAC_file.mzML)
For processing with MSstats, the optional sample columns are typically MSstats_Condition and MSstats_BioReplicate with an additional MSstats_Mixture
column in the case of TMT labeling.
They capture the experimental factors and conditions associated with a sample.
- MSstats_Condition: a string that indicates the condition (e.g., control or 1000 mMol). Will be forwarded to MSstats and
can then be used to specify test contrasts.
- MSstats_BioReplicate: a string identifier to indicate biological replication of a sample.
Entries with the same Sample/Condition/BioReplicate but different Filepath (and therefore FractionGroup number)
will be treated as technical replicates.
- MSstats_Mixture: (for TMT labeling only): a string identifier to indicate the mixture of samples labeled with different TMT reagents, which can be analyzed in
a single mass spectrometry experiment. E.g., same samples labeled with different TMT reagents have a different mixture identifier.
Technical replicates need to have the same mixture identifier.
For details on the MSstats columns please refer to the MSstats manual for details
(https://www.bioconductor.org/packages/release/bioc/vignettes/MSstats/inst/doc/MSstats.html).
| Fraction_Group | Fraction | Spectra_Filepath | Label | MSstats_Condition | MSstats_BioReplicate |
|----------------|----------|---------------------------|-------|--------------------|------------------------|
| 1 | 1 | UPS1_12500amol_R1.mzML | 1 | 12500 amol | 1 |
| 2 | 1 | UPS1_12500amol_R2.mzML | 1 | 12500 amol | 2 |
| 3 | 1 | UPS1_12500amol_R3.mzML | 1 | 12500 amol | 3 |
| ... | ... | ... | ... | ... | ... |
| 22 | 1 | UPS1_500amol_R1.mzML | 1 | 500 amol | 1 |
| 23 | 1 | UPS1_500amol_R2.mzML | 1 | 500 amol | 2 |
| 24 | 1 | UPS1_500amol_R3.mzML | 1 | 500 amol | 3 |
Alternatively, the experimental design can be specified with a file consisting of two tables
whose headers are separated by a blank line.
The two tables are:
- The file section table and the sample section table.
- The file section consists of columns `Fraction_Group`, `Fraction`, `Spectra_Filepath`, `Label`, and `Sample`
File section:
| Fraction_Group | Fraction | Spectra_Filepath | Label | Sample |
|----------------|----------|---------------------------|-------|--------|
| 1 | 1 | UPS1_12500amol_R1.mzML | 1 | 1 |
| 2 | 1 | UPS1_12500amol_R2.mzML | 1 | 2 |
| ... | ... | ... | ... | ... |
| 22 | 1 | UPS1_500amol_R1.mzML | 1 | 22 |
Sample section:
| Sample | MSstats_Condition | MSstats_BioReplicate |
|--------|--------------------|------------------------|
| 1 | 12500 amol | 1 |
| 2 | 12500 amol | 2 |
| ... | ... | ... |
| 22 | 500 amol | 3 |
@ingroup Metadata
**/
class OPENMS_DLLAPI ExperimentalDesign
{
public:
/// MSFileSectionEntry links single quant. values back the MS file
/// It supports:
/// - multiplexed/labeled data via specification of the quantified label
/// - multiple fractions via specification of the:
/// - fraction index (e.g., 1..10 if ten fractions were measured)
/// - fraction_group to trace which fractions belong together
class OPENMS_DLLAPI MSFileSectionEntry
{
public:
MSFileSectionEntry() = default;
unsigned fraction_group = 1; ///< fraction group id
unsigned fraction = 1; ///< fraction 1..m, mandatory, 1 if not set
std::string path = "UNKNOWN_FILE"; ///< file name, mandatory
unsigned label = 1; ///< the label (e.g.,: 1 for label-free, 1..8 for TMT8plex)
unsigned sample = 0; ///< zero-based index for the sample section contents; allows grouping by sample
String sample_name = "0"; ///< sample name for access of the sample row by string, not index
};
class OPENMS_DLLAPI SampleSection
{
public:
SampleSection() = default;
SampleSection(
const std::vector< std::vector < String > >& content,
const std::map< String, Size >& sample_to_rowindex,
const std::map< String, Size >& columnname_to_columnindex
);
// Get set of all samples that are present in the sample section
std::set< String > getSamples() const;
// Add a sample as the last row
void addSample(const String& sample, const std::vector<String>& content = {});
// TODO should it include the Sample ID column or not??
// Get set of all factors (column names) that were defined for the sample section
std::set< String > getFactors() const;
// Checks whether sample section has row for a sample number
bool hasSample(const String& sample) const;
// Checks whether Sample Section has a specific factor (i.e. column name)
bool hasFactor(const String &factor) const;
// Returns value of factor for given sample and factor name
String getFactorValue(const String& sample_name, const String &factor) const;
// Returns value of factor for given sample index and factor name
String getFactorValue(unsigned sample_idx, const String &factor) const;
// Returns column index of factor
Size getFactorColIdx(const String &factor) const;
// Returns the name/ID of the sample. Not necessarily the row index
String getSampleName(unsigned sample_row) const;
// Returns the row index in the sample section for a sample name/ID
unsigned getSampleRow(const String& sample) const;
/// returns the number of entries in content_ member
Size getContentSize() const;
private:
// The entries of the Sample Section, filled while parsing
// the Experimental Design File
std::vector< std::vector < String > > content_;
// Maps the Sample Entry name to the row where the sample
// appears in the Sample section, its sample index
std::map< String, Size > sample_to_rowindex_;
// Maps the column name of the SampleSection to the
// Index of the column
std::map< String, Size > columnname_to_columnindex_;
};
using MSFileSection = std::vector<MSFileSectionEntry>;
// Experimental Design c'tors
ExperimentalDesign() = default;
ExperimentalDesign(const MSFileSection& msfile_section, const SampleSection& sample_section);
const MSFileSection& getMSFileSection() const;
void setMSFileSection(const MSFileSection& msfile_section);
// Returns the Sample Section of the experimental design file
const ExperimentalDesign::SampleSection& getSampleSection() const;
void setSampleSection(const SampleSection& sample_section);
/// returns a map from a sample section row to sample id for clustering
/// duplicate sample rows (e.g. to find all fractions of the same "sample")
std::map<std::vector<String>, std::set<String>> getUniqueSampleRowToSampleMapping() const;
/// uses getUniqueSampleRowToSampleMapping to get the reversed map
/// mapping sample ID to a real unique sample
std::map<String, unsigned> getSampleToPrefractionationMapping() const;
/// return fraction index to file paths (ordered by fraction_group)
//TODO this probably needs a basename parameter to be fully compatible with the other mappings!! Implicit full path.
std::map<unsigned int, std::vector<String> > getFractionToMSFilesMapping() const;
/// return vector of filepath/label combinations that share the same conditions after removing
/// replicate columns in the sample section (e.g. for merging across replicates)
//TODO this probably needs a basename parameter to be fully compatible with the other mappings!! Implicit full path.
std::vector<std::vector<std::pair<String, unsigned>>> getConditionToPathLabelVector() const;
/// return a condition (unique combination of sample section values except replicate) to Sample index mapping
std::map<std::vector<String>, std::set<unsigned>> getConditionToSampleMapping() const;
/*
* The (Path, Label) tuples in the experimental design have to be unique, so we can map them
* uniquely to the sample number, fraction number, and fraction_group number
*/
/// return <file_path, label> to prefractionation mapping (a prefractionation group is a unique combination of
/// all columns in the sample section, except for replicates.
std::map< std::pair< String, unsigned >, unsigned> getPathLabelToPrefractionationMapping(bool use_basename_only) const;
/// return <file_path, label> to condition mapping (a condition is a unique combination of all columns in the
/// sample section, except for replicates.
std::map< std::pair< String, unsigned >, unsigned> getPathLabelToConditionMapping(bool use_basename_only) const;
/// return Sample name to condition mapping (a condition is a unique combination of all columns in the
/// sample section, except for replicates. Numbering of conditions is alphabetical due to map.
std::map<String, unsigned> getSampleToConditionMapping() const;
/// return <file_path, label> to sample index mapping
std::map< std::pair< String, unsigned >, unsigned> getPathLabelToSampleMapping(bool use_basename_only) const;
/// return <file_path, label> to fraction mapping
std::map< std::pair< String, unsigned >, unsigned> getPathLabelToFractionMapping(bool use_basename_only) const;
/// return <file_path, label> to fraction_group mapping
std::map< std::pair< String, unsigned >, unsigned> getPathLabelToFractionGroupMapping(bool use_basename_only) const;
// @return the number of samples measured (= highest sample index)
unsigned getNumberOfSamples() const;
// @return the number of fractions (= highest fraction index)
unsigned getNumberOfFractions() const;
// @return the number of labels per file
unsigned getNumberOfLabels() const;
// @return the number of MS files (= fractions * fraction groups)
unsigned getNumberOfMSFiles() const;
// @return the number of fraction_groups
// Allows to group fraction ids and source files
unsigned getNumberOfFractionGroups() const;
// @return sample index (depends on fraction_group and label)
unsigned getSample(unsigned fraction_group, unsigned label = 1);
/// @return whether we have a fractionated design
// This is the case if we have at least one fraction group with >= 2 fractions
bool isFractionated() const;
/// filters the MSFileSection to only include a given subset of files whose basenames
/// are given with @p bns
/// @return number of files that have been filtered
Size filterByBasenames(const std::set<String>& bns);
/// @returns whether all fraction groups have the same number of fractions
bool sameNrOfMSFilesPerFraction() const;
/// Extract experimental design from consensus map
static ExperimentalDesign fromConsensusMap(const ConsensusMap& c);
/// Extract experimental design from feature map
static ExperimentalDesign fromFeatureMap(const FeatureMap& f);
/// Extract experimental design from identifications
static ExperimentalDesign fromIdentifications(const std::vector<ProteinIdentification>& proteins);
//TODO create another overload here, that takes two enums outerVec and innerVec with entries Replicate, Fraction, Sample
private:
// MS filename column, optionally trims to basename
std::vector< String > getFileNames_(bool basename) const;
// returns label column
std::vector<unsigned> getLabels_() const;
// returns fraction column
std::vector<unsigned> getFractions_() const;
/// Generic Mapper (Path, Label) -> f(row)
std::map< std::pair< String, unsigned >, unsigned> pathLabelMapper_(
bool,
unsigned (*f)(const ExperimentalDesign::MSFileSectionEntry&)) const;
// sort to obtain the default order
void sort_();
template<typename T>
static void errorIfAlreadyExists(std::set<T> &container, T &item, const String &message);
// basic consistency checks
void isValid_();
MSFileSection msfile_section_;
SampleSection sample_section_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/SpectrumLookup.h | .h | 11,580 | 304 | // 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/CONCEPT/LogStream.h>
#include <OpenMS/KERNEL/MSSpectrum.h>
#include <OpenMS/METADATA/SpectrumNativeIDParser.h>
#include <boost/regex.hpp>
namespace OpenMS
{
/**
@brief Helper class for looking up spectra based on different attributes
This class provides functions for looking up spectra that are stored in a vector (e.g. MSExperiment::getSpectra()) by index, retention time, native ID, scan number (extracted from the native ID), or by a reference string containing any of the previous information ("spectrum reference").
@par Spectrum reference formats
Formats for spectrum references are defined by regular expressions, that must contain certain fields (named groups, i.e. "(?<GROUP>...)") referring to usable information.
The following named groups are recognized and can be used to look up spectra:
@li @c INDEX0: spectrum index, i.e. position in the vector of spectra, counting from zero
@li @c INDEX1: spectrum index, i.e. position in the vector of spectra, counting from one
@li @c ID: spectrum native ID
@li @c SCAN: scan number (extracted from the native ID)
@li @c RT: retention time
@par
For example, if the format of a spectrum reference is "scan=123", where 123 is the scan number, the expression "scan=(?<SCAN>\\d+)" can be used to extract that number, allowing look-up of the corresponding spectrum.
@par
Reference formats are registered via addReferenceFormat().
Several possible formats can be added and will be tried in order by the function findByReference().
@par Native ID Parsing
For standalone parsing of spectrum native IDs (without spectrum lookup), use SpectrumNativeIDParser directly:
@code
// Extract scan number from native ID using CV accession
Int scan = SpectrumNativeIDParser::extractScanNumber("scan=42", "MS:1000768");
// Check if a string is a native ID
if (SpectrumNativeIDParser::isNativeID(spectrum_id))
{
String regex = SpectrumNativeIDParser::getRegExFromNativeID(spectrum_id);
// use regex for further processing...
}
@endcode
@see SpectrumMetaDataLookup, SpectrumNativeIDParser
*/
class OPENMS_DLLAPI SpectrumLookup
{
public:
/// Default regular expression for extracting scan numbers from spectrum native IDs
static const String& default_scan_regexp;
/// Possible formats of spectrum references, defined as regular expressions
std::vector<boost::regex> reference_formats;
/// Tolerance for look-up by retention time
double rt_tolerance;
/// Constructor
SpectrumLookup();
/// Destructor
virtual ~SpectrumLookup();
/// Check if any spectra were set
bool empty() const;
/**
@brief Read and index spectra for later look-up
@tparam SpectrumContainer Spectrum container class, must support @p size and @p operator[]
@param[in] spectra Container of spectra
@param[in] scan_regexp Regular expression for matching scan numbers in spectrum native IDs (must contain the named group "?<SCAN>")
@throw Exception::IllegalArgument if @p scan_regexp does not contain "?<SCAN>" (and is not empty)
Spectra are indexed by retention time, native ID and scan number. In all cases it is expected that the value for each spectrum will be unique.
Setting @p scan_regexp to the empty string ("") disables extraction of scan numbers; look-ups by scan number will fail in that case.
*/
template <typename SpectrumContainer>
void readSpectra(const SpectrumContainer& spectra,
const String& scan_regexp = default_scan_regexp)
{
rts_.clear();
ids_.clear();
scans_.clear();
n_spectra_ = spectra.size();
setScanRegExp_(scan_regexp);
for (Size i = 0; i < n_spectra_; ++i)
{
const MSSpectrum& spectrum = spectra[i];
const String& native_id = spectrum.getNativeID();
Int scan_no = -1;
if (!scan_regexp.empty())
{
scan_no = extractScanNumber(native_id, scan_regexp_, true);
if (scan_no < 0)
{
OPENMS_LOG_WARN << "Warning: Could not extract scan number from spectrum native ID '" + native_id + "' using regular expression '" + scan_regexp + "'. Look-up by scan number may not work properly." << std::endl;
}
}
addEntry_(i, spectrum.getRT(), scan_no, native_id);
}
}
/**
@brief Look up spectrum by retention time (RT).
@param[in] rt Retention time to look up
@throw Exception::ElementNotFound if no matching spectrum was found
@return Index of the spectrum that matched
There is a tolerance for matching of RT values defined by SpectrumLookup::rt_tolerance. The spectrum with the closest match within that tolerance is returned (if any).
*/
Size findByRT(double rt) const;
/**
@brief Look up spectrum by native ID.
@param[in] native_id Native ID to look up
@throw Exception::ElementNotFound if no matching spectrum was found
@return Index of the spectrum that matched
*/
Size findByNativeID(const String& native_id) const;
/**
@brief Look up spectrum by index (position in the vector of spectra).
@param[in] index Index to look up
@param[in] count_from_one Do indexes start counting at one (default: zero)?
@throw Exception::ElementNotFound if no matching spectrum was found
@return Index of the spectrum that matched
*/
Size findByIndex(Size index, bool count_from_one = false) const;
/**
@brief Look up spectrum by scan number (extracted from the native ID).
@param[in] scan_number Scan number to look up
@throw Exception::ElementNotFound if no matching spectrum was found
@return Index of the spectrum that matched
*/
Size findByScanNumber(Size scan_number) const;
/**
@brief Look up spectrum by reference.
@param[in] spectrum_ref Spectrum reference to parse
@throw Exception::ElementNotFound if no matching spectrum was found
@throw Exception::ParseError if the reference could not be parsed (no reference format matched)
@return Index of the spectrum that matched
The regular expressions in SpectrumLookup::reference_formats are matched against the spectrum reference in order. The first one that matches is used to look up the spectrum.
*/
Size findByReference(const String& spectrum_ref) const;
/**
@brief Register a possible format for a spectrum reference
@param[in] regexp Regular expression defining the format
@throw Exception::IllegalArgument if @p regexp does not contain any of the recognized named groups
The regular expression defining the reference format must contain one or more of the recognized named groups defined in SpectrumLookup::regexp_names_.
*/
void addReferenceFormat(const String& regexp);
/**
@brief Extract the scan number from the native ID of a spectrum
@param[in] native_id Spectrum native ID
@param[in] scan_regexp Regular expression to use (must contain the named group "?<SCAN>")
@param[in] no_error Suppress the exception on failure
@throw Exception::ParseError if the scan number could not be extracted (unless @p no_error is set)
@return Scan number of the spectrum (or -1 on failure to extract)
@deprecated Use SpectrumNativeIDParser::extractScanNumber() instead for better discoverability.
@see SpectrumNativeIDParser::extractScanNumber()
*/
static Int extractScanNumber(const String& native_id,
const boost::regex& scan_regexp,
bool no_error = false);
/**
@brief Extract the scan number from the native ID using a CV accession
@param[in] native_id Spectrum native ID
@param[in] native_id_type_accession CV accession specifying the native ID format
@return Scan number of the spectrum (or -1 on failure to extract)
@deprecated Use SpectrumNativeIDParser::extractScanNumber() instead for better discoverability.
@see SpectrumNativeIDParser::extractScanNumber()
*/
static Int extractScanNumber(const String& native_id,
const String& native_id_type_accession);
/**
@brief Determine the RegEx string to extract scan/index number from native IDs. Can be used for extractScanNumber
@param[in] native_id Native ID string to analyze
@return Regular expression string with named group
@deprecated Use SpectrumNativeIDParser::getRegExFromNativeID() instead for better discoverability.
@see SpectrumNativeIDParser::getRegExFromNativeID()
*/
static std::string getRegExFromNativeID(const String& native_id);
/**
@brief Simple prefix check if a spectrum identifier @p id is a nativeID from a vendor file.
@param[in] id Spectrum identifier to check
@return True if the string matches a known native ID prefix pattern
@deprecated Use SpectrumNativeIDParser::isNativeID() instead for better discoverability.
@see SpectrumNativeIDParser::isNativeID()
*/
static bool isNativeID(const String& id);
protected:
/// Named groups recognized in regular expression
static const String& regexp_names_;
Size n_spectra_; ///< Number of spectra
boost::regex scan_regexp_; ///< Regular expression to extract scan numbers
std::vector<String> regexp_name_list_; ///< Named groups in vector format
std::map<double, Size> rts_; ///< Mapping: RT -> spectrum index
std::map<String, Size> ids_; ///< Mapping: native ID -> spectrum index
std::map<Size, Size> scans_; ///< Mapping: scan number -> spectrum index
/**
@brief Add a look-up entry for a spectrum
@param[in] index Spectrum index (position in the vector)
@param[in] rt Retention time
@param[in] scan_number Scan number
@param[in] native_id Native ID
*/
void addEntry_(Size index, double rt, Int scan_number,
const String& native_id);
/**
@brief Look up spectrum by regular expression match
@param[in] spectrum_ref Spectrum reference that was parsed
@param[in] regexp Regular expression used for parsing
@param[in] match Regular expression match
@throw Exception::ElementNotFound if no matching spectrum was found
@return Index of the spectrum that matched
*/
Size findByRegExpMatch_(const String& spectrum_ref, const String& regexp,
const boost::smatch& match) const;
/**
@brief Set the regular expression for extracting scan numbers from spectrum native IDs
@param[in] scan_regexp Regular expression to use (must contain the named group "?<SCAN>")
*/
void setScanRegExp_(const String& scan_regexp);
private:
/// Copy constructor (not implemented)
SpectrumLookup(const SpectrumLookup&);
/// Assignment operator (not implemented).
SpectrumLookup& operator=(const SpectrumLookup&);
};
} //namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/DataArrays.h | .h | 5,174 | 174 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg$
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/METADATA/MetaInfoDescription.h>
#include <OpenMS/CONCEPT/Helpers.h> // for ADL version of <=> for STL containers
#include <compare>
namespace OpenMS
{
namespace DataArrays
{
/// Float data array class
class FloatDataArray :
public MetaInfoDescription,
public std::vector<float>
{
using std::vector<float>::vector; // to allow for aggregate initialization of FloatDataArray
public:
/// Less than operator
bool operator<(const FloatDataArray& rhs) const
{
const MetaInfoDescription& lhs_meta = *this;
const MetaInfoDescription& rhs_meta = rhs;
if (lhs_meta != rhs_meta)
return lhs_meta < rhs_meta;
return static_cast<const std::vector<float>&>(*this) < static_cast<const std::vector<float>&>(rhs);
}
/// Less than or equal operator
bool operator<=(const FloatDataArray& rhs) const
{
return *this < rhs || *this == rhs;
}
/// Greater than operator
bool operator>(const FloatDataArray& rhs) const
{
return !(*this <= rhs);
}
/// Greater than or equal operator
bool operator>=(const FloatDataArray& rhs) const
{
return !(*this < rhs);
}
/// Not equal operator
bool operator!=(const FloatDataArray& rhs) const
{
return !(*this == rhs);
}
/// Equality operator
bool operator==(const FloatDataArray& rhs) const
{
return static_cast<const MetaInfoDescription&>(*this) == static_cast<const MetaInfoDescription&>(rhs) &&
static_cast<const std::vector<float>&>(*this) == static_cast<const std::vector<float>&>(rhs);
}
};
/// Integer data array class
class IntegerDataArray :
public MetaInfoDescription,
public std::vector<Int>
{
using std::vector<int>::vector; // to allow for aggregate initialization of IntegerDataArray
public:
/// Less than operator
bool operator<(const IntegerDataArray& rhs) const
{
const MetaInfoDescription& lhs_meta = *this;
const MetaInfoDescription& rhs_meta = rhs;
if (lhs_meta != rhs_meta)
return lhs_meta < rhs_meta;
return static_cast<const std::vector<Int>&>(*this) < static_cast<const std::vector<Int>&>(rhs);
}
/// Less than or equal operator
bool operator<=(const IntegerDataArray& rhs) const
{
return *this < rhs || *this == rhs;
}
/// Greater than operator
bool operator>(const IntegerDataArray& rhs) const
{
return !(*this <= rhs);
}
/// Greater than or equal operator
bool operator>=(const IntegerDataArray& rhs) const
{
return !(*this < rhs);
}
/// Not equal operator
bool operator!=(const IntegerDataArray& rhs) const
{
return !(*this == rhs);
}
/// Equality operator
bool operator==(const IntegerDataArray& rhs) const
{
return static_cast<const MetaInfoDescription&>(*this) == static_cast<const MetaInfoDescription&>(rhs) &&
static_cast<const std::vector<Int>&>(*this) == static_cast<const std::vector<Int>&>(rhs);
}
};
/// String data array class
class StringDataArray :
public MetaInfoDescription,
public std::vector<String>
{
using std::vector<String>::vector; // to allow for aggregate initialization of StringDataArray
public:
/// Less than operator
bool operator<(const StringDataArray& rhs) const
{
const MetaInfoDescription& lhs_meta = *this;
const MetaInfoDescription& rhs_meta = rhs;
if (lhs_meta != rhs_meta)
return lhs_meta < rhs_meta;
return static_cast<const std::vector<String>&>(*this) < static_cast<const std::vector<String>&>(rhs);
}
/// Less than or equal operator
bool operator<=(const StringDataArray& rhs) const
{
return *this < rhs || *this == rhs;
}
/// Greater than operator
bool operator>(const StringDataArray& rhs) const
{
return !(*this <= rhs);
}
/// Greater than or equal operator
bool operator>=(const StringDataArray& rhs) const
{
return !(*this < rhs);
}
/// Not equal operator
bool operator!=(const StringDataArray& rhs) const
{
return !(*this == rhs);
}
/// Equality operator
bool operator==(const StringDataArray& rhs) const
{
return static_cast<const MetaInfoDescription&>(*this) == static_cast<const MetaInfoDescription&>(rhs) &&
static_cast<const std::vector<String>&>(*this) == static_cast<const std::vector<String>&>(rhs);
}
};
}
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/Sample.h | .h | 4,151 | 125 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/METADATA/MetaInfoInterface.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
namespace OpenMS
{
/**
@brief Meta information about the sample
It contains basic descriptions like name, number (i.e. order number), mass,
volume, concentration, state and a comment.
A Sample can be composed of other samples.
@ingroup Metadata
*/
class OPENMS_DLLAPI Sample :
public MetaInfoInterface
{
public:
///state of aggregation of the sample
enum class SampleState {SAMPLENULL, SOLID, LIQUID, GAS, SOLUTION, EMULSION, SUSPENSION, SIZE_OF_SAMPLESTATE};
/// Names of sample states
static const std::string NamesOfSampleState[static_cast<size_t>(SampleState::SIZE_OF_SAMPLESTATE)];
/// returns all sample state names known to OpenMS
static StringList getAllNamesOfSampleState();
/// convert a SampleState enum to String
/// @throws Exception::InvalidValue if @p state is SIZE_OF_SAMPLESTATE
static const std::string& sampleStateToString(SampleState state);
/// convert an entry in NamesOfSampleState[] to SampleState enum
/// @throws Exception::InvalidValue if @p name is not contained in NamesOfSampleState[]
static SampleState toSampleState(const std::string& name);
/// Default constructor
Sample();
/// Copy constructor
Sample(const Sample & source);
/// Move constructor
Sample(Sample&&) = default;
/// Destructor
~Sample();
/// Assignment operator
Sample & operator=(const Sample & source);
/// Move assignment operator
Sample& operator=(Sample&&) & = default;
/// Equality operator
bool operator==(const Sample & rhs) const;
/// returns the sample name (default: "")
const String & getName() const;
/// sets the sample name
void setName(const String & name);
/// returns the sample name (default: "")
const String & getOrganism() const;
/// sets the sample name
void setOrganism(const String & organism);
/// returns the sample number (default: "")
const String & getNumber() const;
/// sets the sample number (e.g. sample ID)
void setNumber(const String & number);
/// returns the comment (default: "")
const String & getComment() const;
/// sets the comment (may contain newline characters)
void setComment(const String & comment);
/// returns the state of aggregation (default: SAMPLENULL)
SampleState getState() const;
/// sets the state of aggregation
void setState(SampleState state);
/// returns the mass (in gram) (default: 0.0)
double getMass() const;
/// sets the mass (in gram)
void setMass(double mass);
/// returns the volume (in ml) (default: 0.0)
double getVolume() const;
/// sets the volume (in ml)
void setVolume(double volume);
/// returns the concentration (in g/l) (default: 0.0)
double getConcentration() const;
/// sets the concentration (in g/l)
void setConcentration(double concentration);
/// returns a mutable reference to the vector of subsamples that were combined to create this sample
std::vector<Sample> & getSubsamples();
/// returns a const reference to the vector of subsamples that were combined to create this sample
const std::vector<Sample> & getSubsamples() const;
/// sets the vector of subsamples that were combined to create this sample
void setSubsamples(const std::vector<Sample> & subsamples);
protected:
String name_;
String number_;
String comment_;
String organism_;
SampleState state_;
double mass_;
double volume_;
double concentration_;
std::vector<Sample> subsamples_;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/AbsoluteQuantitationStandards.h | .h | 4,003 | 109 | // 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>
#include <OpenMS/KERNEL/FeatureMap.h>
namespace OpenMS
{
/**
@brief AbsoluteQuantitationStandards is a class to handle the relationship between
runs, components, and their actual concentrations.
A mapping between a run, the components in the run, and the actual concentration
of the components in the run are required to build a calibration curve that is
required for absolute quantitation.
*/
class OPENMS_DLLAPI AbsoluteQuantitationStandards
{
public:
/// Constructor
AbsoluteQuantitationStandards() = default;
/// Destructor
~AbsoluteQuantitationStandards() = default;
/// Structure to map runs to components to known concentrations.
struct runConcentration
{
String sample_name;
String component_name;
String IS_component_name;
double actual_concentration;
double IS_actual_concentration;
String concentration_units;
double dilution_factor;
};
/// Structure to hold a single component and its corresponding known concentration.
struct featureConcentration
{
Feature feature;
Feature IS_feature;
double actual_concentration;
double IS_actual_concentration;
String concentration_units;
double dilution_factor;
};
/**
@brief Method to map runs to components to known concentrations.
@warning The method checks for the FeatureMaps' sample names with FeatureMap::getPrimaryMSRunPath()
@param[in] run_concentrations A list of runConcentration structs (e.g., from file upload).
@param[in] feature_maps The method maps to these features.
@param[out] components_to_concentrations A map that links run data to feature data.
*/
void mapComponentsToConcentrations(
const std::vector<AbsoluteQuantitationStandards::runConcentration>& run_concentrations,
const std::vector<FeatureMap>& feature_maps,
std::map<String, std::vector<AbsoluteQuantitationStandards::featureConcentration>>& components_to_concentrations
) const;
/**
@brief Get the feature concentrations from a single component.
This method internally calls `mapComponentsToConcentrations()`, but takes in consideration only those
elements of `run_concentrations` that have the passed `component_name`.
@warning The method checks for the FeatureMaps' sample names with FeatureMap::getPrimaryMSRunPath()
@param[in] run_concentrations A list of runConcentration structs (e.g., from file upload).
@param[in] feature_maps The method maps to these features.
@param[in] component_name Only runConcentration with this name will be considered.
@param[out] feature_concentrations The list of feature concentrations found.
*/
void getComponentFeatureConcentrations(
const std::vector<AbsoluteQuantitationStandards::runConcentration>& run_concentrations,
const std::vector<FeatureMap>& feature_maps,
const String& component_name,
std::vector<AbsoluteQuantitationStandards::featureConcentration>& feature_concentrations
) const;
private:
/**
@brief Finds a feature for a given component name.
@param[in] feature_map The container of features.
@param[in] component_name The feature must have this name as its "native_id".
@param[out] feature_found If found, the feature is saved in this parameter.
*/
bool findComponentFeature_(
const FeatureMap& feature_map,
const String& component_name,
Feature& feature_found
) const;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/SourceFile.h | .h | 3,213 | 108 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/METADATA/CVTermList.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
namespace OpenMS
{
/**
@brief Description of a file location, used to store the origin of (meta) data.
@ingroup Metadata
*/
class OPENMS_DLLAPI SourceFile :
public CVTermList
{
public:
///Type of the checksum
enum class ChecksumType
{
UNKNOWN_CHECKSUM, ///< Unknown checksum type
SHA1, ///< Secure Hash Algorithm-1
MD5, ///< Message-Digest algorithm 5
SIZE_OF_CHECKSUMTYPE
};
/// Names of checksum types
static const std::string NamesOfChecksumType[static_cast<size_t>(ChecksumType::SIZE_OF_CHECKSUMTYPE)];
/// returns all checksum type names known to OpenMS
static StringList getAllNamesOfChecksumType();
/// Constructor
SourceFile();
/// Copy constructor
SourceFile(const SourceFile&) = default;
/// Move constructor
SourceFile(SourceFile&&) = default;
/// Destructor
~SourceFile() override;
/// Assignment operator
SourceFile& operator=(const SourceFile&) = default;
/// Move assignment operator
SourceFile& operator=(SourceFile&&) = default;
/// Equality operator
bool operator==(const SourceFile& rhs) const;
/// Equality operator
bool operator!=(const SourceFile& rhs) const;
/// returns the file name
const String& getNameOfFile() const;
/// sets the file name
void setNameOfFile(const String& name_of_file);
/// returns the file path
const String& getPathToFile() const;
/// sets the file path
void setPathToFile(const String& path_path_to_file);
/// returns the file size in MB
float getFileSize() const;
/// sets the file size in MB
void setFileSize(float file_size);
/// returns the file type
const String& getFileType() const;
/// sets the file type
void setFileType(const String& file_type);
/// returns the file's checksum
const String& getChecksum() const;
/// sets the file's checksum
void setChecksum(const String& checksum, ChecksumType type);
/// returns the checksum type
ChecksumType getChecksumType() const;
/// Returns the native ID type of the spectra
const String& getNativeIDType() const;
/// Sets the native ID type of the spectra
void setNativeIDType(const String& type);
/// Returns the nativeID of the spectra
const String& getNativeIDTypeAccession() const;
/// Sets the native ID of the spectra
void setNativeIDTypeAccession(const String& accesssion);
protected:
String name_of_file_;
String path_to_file_;
double file_size_;
String file_type_;
String checksum_;
ChecksumType checksum_type_ = SourceFile::ChecksumType::UNKNOWN_CHECKSUM;
String native_id_type_;
String native_id_type_accession_;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/SpectrumMetaDataLookup.h | .h | 14,745 | 342 | // 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/METADATA/SpectrumLookup.h>
#include <OpenMS/FORMAT/FileHandler.h>
#include <OpenMS/KERNEL/MSSpectrum.h>
#include <OpenMS/METADATA/ProteinIdentification.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <limits> // for "quiet_NaN"
namespace OpenMS
{
/**
@brief Helper class for looking up spectrum meta data
The class deals with meta data of spectra and provides functions for the extraction and look-up of this data.
A common use case for this functionality is importing peptide/protein
identification results from search engine-specific file formats, where some
meta information may have to be looked up in the raw data (primarily
retention times).
One example of this is in the function addMissingRTsToPeptideIDs().
Meta data of a spectra is stored in SpectrumMetaDataLookup::SpectrumMetaData structures.
In order to control which meta data to extract/look-up, flags
(SpectrumMetaDataLookup::MetaDataFlags) are used.
Meta data can be extracted from spectra or from spectrum reference strings.
The format of a spectrum reference is defined via a regular expression
containing named groups (format "(?<GROUP>...)" for the different data
items.
The table below illustrates the different meta data types and how they are represented.
<CENTER>
<table>
<tr>
<td ALIGN="center" BGCOLOR="#EBEBEB"> @p SpectrumMetaData member </td>
<td ALIGN="center" BGCOLOR="#EBEBEB"> @p MetaDataFlags flag </td>
<td ALIGN="center" BGCOLOR="#EBEBEB"> Reg. exp. group </td>
<td ALIGN="center" BGCOLOR="#EBEBEB"> Comment (*: undefined for MS1 spectra)</td>
</tr>
<tr>
<td ALIGN="center"> @p rt </td>
<td ALIGN="center"> @p MDF_RT </td>
<td ALIGN="center"> @p RT </td>
<td ALIGN="center"> Retention time of the spectrum </td>
</tr>
<tr>
<td ALIGN="center"> @p precursor_rt </td>
<td ALIGN="center"> @p MDF_PRECURSORRT </td>
<td ALIGN="center"> @p PRECRT </td>
<td ALIGN="center"> Retention time of the precursor spectrum* </td>
</tr>
<tr>
<td ALIGN="center"> @p precursor_mz </td>
<td ALIGN="center"> @p MDF_PRECURSORMZ </td>
<td ALIGN="center"> @p MZ </td>
<td ALIGN="center"> Mass-to-charge ratio of the precursor ion* </td>
</tr>
<tr>
<td ALIGN="center"> @p precursor_charge </td>
<td ALIGN="center"> @p MDF_PRECURSORCHARGE </td>
<td ALIGN="center"> @p CHARGE </td>
<td ALIGN="center"> Charge of the precursor ion* </td>
</tr>
<tr>
<td ALIGN="center"> @p ms_level </td>
<td ALIGN="center"> @p MDF_MSLEVEL </td>
<td ALIGN="center"> @p LEVEL </td>
<td ALIGN="center"> MS level (1 for survey scan, 2 for fragment scan, etc.) </td>
</tr>
<tr>
<td ALIGN="center"> @p scan_number </td>
<td ALIGN="center"> @p MDF_SCANNUMBER </td>
<td ALIGN="center"> @p SCAN </td>
<td ALIGN="center"> Scan number (extracted from the native ID) </td>
</tr>
<tr>
<td ALIGN="center"> @p native_id </td>
<td ALIGN="center"> @p MDF_NATIVEID </td>
<td ALIGN="center"> @p ID </td>
<td ALIGN="center"> Native ID of the spectrum </td>
</tr>
<tr>
<td ALIGN="center"></td>
<td ALIGN="center"> @p MDF_ALL </td>
<td ALIGN="center"></td>
<td ALIGN="center"> Shortcut for "all flags set" </td>
</tr>
<tr>
<td ALIGN="center"></td>
<td ALIGN="center"></td>
<td ALIGN="center"> @p INDEX0 </td>
<td ALIGN="center"> Only for look-up: index (vector pos.) counting from 0 </td>
</tr>
<tr>
<td ALIGN="center"></td>
<td ALIGN="center"></td>
<td ALIGN="center"> @p INDEX1 </td>
<td ALIGN="center"> Only for look-up: index (vector pos.) counting from 1 </td>
</tr>
</table>
</CENTER>
@see OpenMS::SpectrumLookup
*/
class OPENMS_DLLAPI SpectrumMetaDataLookup: public SpectrumLookup
{
public:
/// Bit mask for which meta data to extract from a spectrum
typedef unsigned char MetaDataFlags;
/// Possible meta data to extract from a spectrum.
/// Note that the static variables need to be put on separate lines due to a compiler bug in VS
static const MetaDataFlags MDF_RT = 1;
static const MetaDataFlags MDF_PRECURSORRT = 2;
static const MetaDataFlags MDF_PRECURSORMZ = 4;
static const MetaDataFlags MDF_PRECURSORCHARGE = 8;
static const MetaDataFlags MDF_MSLEVEL = 16;
static const MetaDataFlags MDF_SCANNUMBER = 32;
static const MetaDataFlags MDF_NATIVEID = 64;
static const MetaDataFlags MDF_ALL = 127;
/// Meta data of a spectrum
struct SpectrumMetaData
{
double rt; ///< Retention time
double precursor_rt; ///< Precursor retention time
double precursor_mz; ///< Precursor mass-to-charge ratio
Int precursor_charge; ///< Precursor charge
Size ms_level; ///< MS level
Int scan_number; ///< Scan number
String native_id; ///< Native ID
/// Constructor
SpectrumMetaData():
rt(std::numeric_limits<double>::quiet_NaN()),
precursor_rt(std::numeric_limits<double>::quiet_NaN()),
precursor_mz(std::numeric_limits<double>::quiet_NaN()),
precursor_charge(0), ms_level(0), scan_number(-1), native_id("")
{
}
/// Copy constructor
SpectrumMetaData(const SpectrumMetaData &) = default;
/// Move constructor
SpectrumMetaData(SpectrumMetaData&&) = default;
/// Destructor
~SpectrumMetaData() = default;
/// Assignment operator
SpectrumMetaData & operator=(const SpectrumMetaData &) = default;
/// Move assignment operator
SpectrumMetaData& operator=(SpectrumMetaData&&) & = default;
};
/// Constructor
SpectrumMetaDataLookup(): SpectrumLookup()
{}
/// Destructor
~SpectrumMetaDataLookup() override {}
/**
@brief Read spectra and store their meta data
@tparam SpectrumContainer Spectrum container class, must support @p size and @p operator[]
@param[in] spectra Container of spectra
@param[in] scan_regexp Regular expression for matching scan numbers in spectrum native IDs (must contain the named group "?<SCAN>")
@param[in] get_precursor_rt Assign precursor retention times? (This relies on all precursor spectra being present and in the right order.)
@throw Exception::IllegalArgument if @p scan_regexp does not contain "?<SCAN>" (and is not empty)
*/
template <typename SpectrumContainer>
void readSpectra(const SpectrumContainer& spectra,
const String& scan_regexp = default_scan_regexp,
bool get_precursor_rt = false)
{
// If class SpectrumContainer is e.g. OnDiscMSExperiment, reading each
// spectrum is expensive. Thus, to avoid iterating over all spectra twice,
// we do not call "SpectrumLookup::readSpectra" here:
n_spectra_ = spectra.size();
metadata_.reserve(n_spectra_);
setScanRegExp_(scan_regexp);
// mapping: MS level -> RT of previous spectrum of that level
std::map<Size, double> precursor_rts;
for (Size i = 0; i < n_spectra_; ++i)
{
const MSSpectrum& spectrum = spectra[i];
SpectrumMetaData meta;
getSpectrumMetaData(spectrum, meta, scan_regexp_, precursor_rts);
if (get_precursor_rt) precursor_rts[meta.ms_level] = meta.rt;
addEntry_(i, meta.rt, meta.scan_number, meta.native_id);
metadata_.push_back(meta);
}
}
/**
* @brief set spectra_data from read SpectrumContainer origin (i.e. filename)
*
* @param[in] spectra_data the name (and path) of the origin of the read SpectrumContainer
*/
void setSpectraDataRef(const String& spectra_data)
{
this->spectra_data_ref = spectra_data;
}
/**
@brief Look up meta data of a spectrum
@param[in] index Index of the spectrum
@param[out] meta Meta data output
*/
void getSpectrumMetaData(Size index, SpectrumMetaData& meta) const;
/**
@brief Extract meta data from a spectrum
@param[in] spectrum Spectrum input
@param[out] meta Meta data output
@param[in] scan_regexp Regular expression for extracting scan number from spectrum native ID
@param[in] precursor_rts RTs of potential precursor spectra of different MS levels
Scan number and precursor RT, respectively, are only extracted if @p scan_regexp/@p precursor_rts are not empty.
*/
static void getSpectrumMetaData(
const MSSpectrum& spectrum, SpectrumMetaData& meta,
const boost::regex& scan_regexp = boost::regex(),
const std::map<Size, double>& precursor_rts = (std::map<Size, double>()));
/**
@brief Extract meta data via a spectrum reference
@param[in] spectrum_ref Spectrum reference to parse
@param[out] meta Meta data output
@param[in] flags What meta data to extract
@throw Exception::ElementNotFound if a spectrum look-up was necessary, but no matching spectrum was found
This function is a combination of getSpectrumMetaData() and SpectrumLookup::findByReference(). However, the spectrum is only looked up if necessary, i.e. if the required meta data - as defined by @p flags - cannot be extracted from the spectrum reference itself.
*/
void getSpectrumMetaData(const String& spectrum_ref, SpectrumMetaData& meta,
MetaDataFlags flags = MDF_ALL) const;
/**
@brief Add missing retention time (RT) values to peptide identifications based on raw data
@param[in,out] peptides Peptide IDs with or without RT values
@param[in] exp The MSExperiment object representing the raw data file (e.g., mzML) used to look up RT values.
@return True if all peptide IDs could be annotated successfully (including if all already had RT values), false otherwise.
*/
static bool addMissingRTsToPeptideIDs(PeptideIdentificationList& peptides, const MSExperiment& exp);
/**
* @brief Adds missing ion mobility information to peptide identifications.
*
* This function adds missing ion mobility (IM) information to the peptide identifications.
* The missing IM information is retrieved from the MSExperiment.
*
* @param[in,out] peptides The vector of peptide identifications to update.
* @param[in] exp The MSExperiment object representing the raw data file (e.g., mzML) used to look up IM values.
*
* @return True if all missing IM information was successfully added to the peptide identifications, false otherwise.
*/
static bool addMissingIMToPeptideIDs(PeptideIdentificationList& peptides,
const MSExperiment& exp);
/**
* @brief Adds FAIMS compensation voltage information to peptide identifications.
*
* This function adds FAIMS compensation voltage (CV) information to the peptide identifications
* by looking up the corresponding spectrum and extracting the FAIMS CV.
*
* Both MS1 and MS2 spectra can have explicit FAIMS CV annotations (DriftTimeUnit::FAIMS_COMPENSATION_VOLTAGE).
* For MS2 spectra without explicit FAIMS CV, the function falls back to the last seen FAIMS CV
* from a preceding spectrum in run order.
*
* @param[in,out] peptides The vector of peptide identifications to update.
* @param[in] exp The MSExperiment object representing the raw data file (e.g., mzML) used to look up FAIMS CV values.
*
* @return True if FAIMS data was present and at least some IDs were annotated, false if no FAIMS data present.
*/
static bool addMissingFAIMSToPeptideIDs(PeptideIdentificationList& peptides,
const MSExperiment& exp);
/**
* @brief Add missing "spectrum_reference"s to peptide identifications based on raw data
*
* @param[in,out] peptides Peptide IDs with or without spectrum_reference
* @param[in] filename the name of the mz_file from which to draw spectrum_references
* @param[in] stop_on_error Stop when an ID could not be matched to a spectrum (or keep going)?
* @param[in] override_spectra_data if given ProteinIdentifications should be updated with new "spectra_data" values from SpectrumMetaDataLookup
* @param[in] override_spectra_references if given PeptideIdentifications with existing spectrum_reference should be updated from SpectrumMetaDataLookup
* @param[in,out] proteins Protein IDs corresponding to the Peptide IDs
*
* @return True if all peptide IDs could be annotated successfully (including if all already had "spectrum_reference" values), false otherwise.
*
* Look-up works by matching RT of a peptide identification with the given spectra. Matched spectra 'native ID' will be annotated to the identification. All spectrum_references are updated/added.
*/
static bool addMissingSpectrumReferences(PeptideIdentificationList& peptides,
const String& filename,
bool stop_on_error = false,
bool override_spectra_data = false,
bool override_spectra_references = false,
std::vector<ProteinIdentification> proteins = std::vector<ProteinIdentification>());
protected:
std::vector<SpectrumMetaData> metadata_; ///< Meta data for spectra
String spectra_data_ref;
private:
/// Copy constructor (not implemented)
SpectrumMetaDataLookup(const SpectrumMetaDataLookup&);
/// Assignment operator (not implemented)
SpectrumMetaDataLookup& operator=(const SpectrumMetaDataLookup&);
};
} //namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/PeptideIdentification.h | .h | 11,370 | 284 | // 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/METADATA/PeptideHit.h>
#include <OpenMS/METADATA/MetaInfoInterface.h>
#include <OpenMS/METADATA/ProteinHit.h>
#include <OpenMS/CONCEPT/HashUtils.h>
#include <functional>
#include <string>
#include <map>
namespace OpenMS
{
class ConsensusMap;
class PeptideIdentification;
using SpectrumIdentification = PeptideIdentification; // better name that might become the default in future version
/**
@brief Represents the set of candidates (SpectrumMatches) identified for a single precursor spectrum.
Typically encapsulates the results of searching one specific MS/MS spectrum
against a sequence database or spectral library. It primarily holds a list of PeptideHit objects,
each representing a potential match to the spectrum.
Crucially, a PeptideIdentification is typically associated with a parent ProteinIdentification
object. This parent object contains global information about the entire identification run,
such as the search parameters, database used, and the overall set of identified proteins. The
link between a PeptideIdentification and its parent ProteinIdentification is established
via a shared identifier string (see getIdentifier() and setIdentifier()). Multiple
PeptideIdentification instances (one per spectrum analyzed) can belong to the same
ProteinIdentification run.
Each PeptideIdentification stores the precursor ion's retention time (RT) and mass-to-charge
ratio (m/z) corresponding to the spectrum that was identified. This information (retrieved via
getRT() and getMZ()) is essential for mapping these identifications back to experimental data,
such as peaks in an MSExperiment, features in a FeatureMap, or consensus features in a
ConsensusMap. The IDMapper class is often used for this purpose.
The class also stores information about the scoring system used (getScoreType(),
isHigherScoreBetter()) and an optional significance threshold (getSignificanceThreshold())
for the peptide hits. The significance threshold is stored as a meta value with the key
Constants::UserParam::SIGNIFICANCE_THRESHOLD.
PeptideIdentification inherits from MetaInfoInterface, allowing arbitrary metadata (key-value pairs)
to be attached.
@deprecated Use SpectrumIdentification instead. PeptideIdentification may be removed in a future OpenMS version.
@see PeptideHit, ProteinIdentification, IDMapper, MetaInfoInterface
@ingroup Metadata
*/
class OPENMS_DLLAPI PeptideIdentification :
public MetaInfoInterface
{
public:
///Hit type definition
typedef PeptideHit HitType;
/// @name Constructors, destructor, operators
//@{
/// default constructor
PeptideIdentification();
/// destructor
virtual ~PeptideIdentification() noexcept;
/// copy constructor
PeptideIdentification(const PeptideIdentification&) = default;
/// Move constructor
PeptideIdentification(PeptideIdentification&&) noexcept = default;
/// Assignment operator
PeptideIdentification& operator=(const PeptideIdentification&) = default;
/// Move assignment operator
PeptideIdentification& operator=(PeptideIdentification&&) = default; // TODO: add noexcept (gcc 4.8 bug)
/// Equality operator
bool operator==(const PeptideIdentification& rhs) const;
/// Inequality operator
bool operator!=(const PeptideIdentification& rhs) const;
//@}
/// returns the RT of the MS2 spectrum where the identification occurred
double getRT() const;
/// sets the RT of the MS2 spectrum where the identification occurred
void setRT(double rt);
/// shortcut for isnan(getRT())
bool hasRT() const;
/// returns the MZ of the MS2 spectrum
double getMZ() const;
/// sets the MZ of the MS2 spectrum
void setMZ(double mz);
/// shortcut for isnan(getRT())
bool hasMZ() const;
/// returns the peptide hits as const
const std::vector<PeptideHit>& getHits() const;
/// returns the peptide hits
std::vector<PeptideHit>& getHits();
/// Appends a peptide hit
void insertHit(const PeptideHit& hit);
/// Appends a peptide hit
void insertHit(PeptideHit&& hit);
/// Sets the peptide hits
void setHits(const std::vector<PeptideHit>& hits);
void setHits(std::vector<PeptideHit>&& hits);
/// returns the peptide significance threshold value (stored as a meta value)
double getSignificanceThreshold() const;
/// setting of the peptide significance threshold value (stored as a meta value)
void setSignificanceThreshold(double value);
/// returns the peptide score type
const String& getScoreType() const;
/// sets the peptide score type
void setScoreType(const String& type);
/// returns the peptide score orientation
bool isHigherScoreBetter() const;
/// sets the peptide score orientation
void setHigherScoreBetter(bool value);
/// Returns the identifier which links this PI to its corresponding ProteinIdentification
const String& getIdentifier() const;
/// sets the identifier which links this PI to its corresponding ProteinIdentification
void setIdentifier(const String& id);
/// returns the base name which links to underlying peak map
String getBaseName() const;
/// sets the base name which links to underlying peak map
void setBaseName(const String& base_name);
/// returns the experiment label for this identification
const String getExperimentLabel() const;
/// sets the experiment label for this identification
void setExperimentLabel(const String& type);
/// returns the spectrum reference for this identification. Currently it should
/// almost always be the full native vendor ID.
// TODO make a mandatory data member, add to idXML schema, think about storing the
// extracted spectrum "number" only!
String getSpectrumReference() const;
/// sets the spectrum reference for this identification. Currently it should
/// almost always be the full native vendor ID.
void setSpectrumReference(const String& ref);
// Returns a higher or lower comparator based on @p higher_score_better_
static std::function<bool(const PeptideHit&, const PeptideHit&)> getScoreComparator(bool higher_score_better);
/**
@brief Sorts the hits by score
Sorting takes the score orientation (@p higher_score_better_) into account, i.e. after sorting, the best-scoring hit is the first.
*/
void sort();
/// Returns if this PeptideIdentification result is empty
bool empty() const;
/// returns all peptide hits which reference to a given protein accession (i.e. filter by protein accession)
static std::vector<PeptideHit> getReferencingHits(const std::vector<PeptideHit>&, const std::set<String>& accession);
/**
@brief Builds MultiMap over all PI's via their UID (as obtained from buildUIDFromPepID()),
which is mapped to a index of PI therein, i.e. cm[p.first].getPeptideIdentifications()[p.second];
@param[in] cmap All PI's of the CMap are enumerated and their UID -> pair mapping is computed
@return Returns the MultiMap
*/
static std::multimap<String, std::pair<Size, Size>> buildUIDsFromAllPepIDs(const ConsensusMap &cmap);
/**
@brief Builds UID from PeptideIdentification
The UID can be formed in two ways.
Either it is composed of the map_index and the spectrum-reference
or of the ms_run_path and the spectrum_references, if the path is unique.
The parts of the UID are separated by '|'.
@throw Exception::MissingInformation if Spectrum reference missing at PeptideIdentification
@throw Exception::MissingInformation if Multiple files in a run, but no map_index in PeptideIdentification found
@param[in] pep_id PeptideIdentification for which the UID is computed
@param[in] identifier_to_msrunpath Mapping required to build UID. Can be obtained from
ProteinIdentification::Mapping::identifier_to_msrunpath which can be created
from the corresponding ProtID's
@return Returns the UID for PeptideIdentification
*/
static String buildUIDFromPepID(const PeptideIdentification& pep_id,
const std::map<String, StringList>& identifier_to_msrunpath);
protected:
String id_; ///< Identifier by which ProteinIdentification and PeptideIdentification are matched
std::vector<PeptideHit> hits_; ///< A list containing the peptide hits
String score_type_; ///< The score type (Mascot, Sequest, e-value, p-value)
bool higher_score_better_; ///< The score orientation
double mz_;
double rt_;
};
} //namespace OpenMS
// Hash function specialization for PeptideIdentification
namespace std
{
/**
* @brief Hash function for OpenMS::PeptideIdentification.
*
* Computes a hash consistent with operator==, which compares:
* - MetaInfoInterface (all meta values)
* - id_ (string identifier)
* - hits_ (vector of PeptideHit)
* - getSignificanceThreshold() (stored as meta value)
* - score_type_ (string)
* - higher_score_better_ (bool)
* - getExperimentLabel() (stored as meta value)
* - getBaseName() (stored as meta value)
* - mz_ (double, with NaN handling)
* - rt_ (double, with NaN handling)
*
* @note Hash is consistent with operator==.
*/
template<>
struct hash<OpenMS::PeptideIdentification>
{
std::size_t operator()(const OpenMS::PeptideIdentification& pi) const noexcept
{
// Start with MetaInfoInterface hash (includes significance_threshold, experiment_label, base_name)
std::size_t seed = std::hash<OpenMS::MetaInfoInterface>{}(pi);
// Hash identifier
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(pi.getIdentifier()));
// Hash all peptide hits
for (const auto& hit : pi.getHits())
{
OpenMS::hash_combine(seed, std::hash<OpenMS::PeptideHit>{}(hit));
}
// Hash score type
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(pi.getScoreType()));
// Hash higher_score_better
OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(pi.isHigherScoreBetter())));
// Hash mz (with NaN handling - NaN values hash to same value)
if (pi.hasMZ())
{
OpenMS::hash_combine(seed, OpenMS::hash_float(pi.getMZ()));
}
else
{
// Hash a sentinel value for NaN (consistent with operator== which treats NaN==NaN as true)
OpenMS::hash_combine(seed, OpenMS::hash_int(0xDEADBEEF));
}
// Hash rt (with NaN handling)
if (pi.hasRT())
{
OpenMS::hash_combine(seed, OpenMS::hash_float(pi.getRT()));
}
else
{
// Hash a different sentinel value for NaN RT
OpenMS::hash_combine(seed, OpenMS::hash_int(0xCAFEBABE));
}
return seed;
}
};
} // namespace std
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/Gradient.h | .h | 3,143 | 106 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <vector>
namespace OpenMS
{
/**
@brief Representation of a HPLC gradient
It consists of several eluents and timepoints.
Linear behaviour between timepoints is assumed.
@ingroup Metadata
*/
class OPENMS_DLLAPI Gradient
{
public:
/// Constructor
Gradient() = default;
/// Copy constructor
Gradient(const Gradient &) = default;
/// Move constructor
Gradient(Gradient&&) = default;
/// Destructor
~Gradient();
/// Assignment operator
Gradient & operator=(const Gradient &) = default;
/// Move assignment operator
Gradient& operator=(Gradient&&) & = default;
/// Equality operator
bool operator==(const Gradient & source) const;
/// Equality operator
bool operator!=(const Gradient & source) const;
/**
@brief Adds an eluent at the end of the eluent array
@exception Exception::InvalidValue is thrown if the same eluent name is used twice.
*/
void addEluent(const String & eluent);
/// removes all eluents
void clearEluents();
/// returns a const reference to the list of eluents
const std::vector<String> & getEluents() const;
/**
@brief Adds a timepoint at the end of the timepoint array
@exception Exception::OutOfRange is thrown if the new timepoint is before the last timepoint.
*/
void addTimepoint(Int timepoint);
/// removes all timepoints
void clearTimepoints();
/// returns a const reference to the list of timepoints
const std::vector<Int> & getTimepoints() const;
/**
@brief sets the percentage of eluent @p eluent at timepoint @p timepoint
@exception Exception::InvalidValue is thrown if the eluent, timepoint or percentage is invalid.
*/
void setPercentage(const String & eluent, Int timepoint, UInt percentage);
/**
@brief returns a const reference to the percentages
First dimension of the vector is the eluents, second dimension is the timepoints.
*/
const std::vector<std::vector<UInt> > & getPercentages() const;
/**
@brief returns the percentage of an @p eluent at a @p timepoint
@exception Exception::InvalidValue is thrown if the eluent or timepoint is invalid.
*/
UInt getPercentage(const String & eluent, Int timepoint) const;
/// sets all percentage values to 0
void clearPercentages();
/// checks if the percentages of all timepoints add up to 100%
bool isValid() const;
protected:
std::vector<String> eluents_;
std::vector<Int> times_;
// first dimension is eluents, second is times
std::vector<std::vector<UInt> > percentages_;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/DocumentIdentifier.h | .h | 2,608 | 97 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: $
// --------------------------------------------------------------------------
#pragma once
// OpenMS
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/FORMAT/FileTypes.h>
namespace OpenMS
{
/**
@brief Manage source document information.
This class stored information about the source document.
Primarily this is the document id e.g. a LSID.
For source files additional information can be stored:
- file name
- file type
@ingroup Metadata
*/
class OPENMS_DLLAPI DocumentIdentifier
{
public:
/** @name Constructors and Destructors
*/
//@{
/// Default constructor
DocumentIdentifier();
/// Copy constructor
DocumentIdentifier(const DocumentIdentifier &) = default;
/// Move constructor
DocumentIdentifier(DocumentIdentifier&&) = default;
/// Destructor
virtual ~DocumentIdentifier();
/// Assignment operator
DocumentIdentifier & operator=(const DocumentIdentifier &) = default;
/// Move assignment operator
DocumentIdentifier& operator=(DocumentIdentifier&&) & = default;
/// Equality operator
bool operator==(const DocumentIdentifier & rhs) const;
//@}
/** @name Acessors
*/
//@{
/// set document identifier (e.g. an LSID)
void setIdentifier(const String & id);
/// retrieve document identifier (e.g. an LSID)
const String & getIdentifier() const;
/// exchange content with @p from
void swap(DocumentIdentifier & from);
/// set the file_name_ according to absolute path of the file loaded from preferably done whilst loading
void setLoadedFilePath(const String & file_name);
/// get the file_name_ which is the absolute path to the file loaded from
const String & getLoadedFilePath() const;
/// set the file_type according to the type of the file loaded from (see FileHandler::Type) preferably done whilst loading
void setLoadedFileType(const String & file_name);
/// get the file_type (e.g. featureXML, consensusXML, mzData, mzXML, mzML, ...) of the file loaded from
const FileTypes::Type & getLoadedFileType() const;
//@}
protected:
/// the ID (e.g. LSID)
String id_;
/// the path to the loaded file
String file_path_;
/// the type of the loaded file
FileTypes::Type file_type_;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/Product.h | .h | 2,566 | 94 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/METADATA/CVTermList.h>
#include <OpenMS/CONCEPT/HashUtils.h>
#include <functional>
namespace OpenMS
{
/**
@brief Product meta information.
This class describes the product isolation window for special scan types, such as MRM.
@ingroup Metadata
*/
class OPENMS_DLLAPI Product :
public CVTermList
{
public:
/// Constructor
Product() = default;
/// Copy constructor
Product(const Product &) = default;
/// Move constructor
Product(Product&&) = default;
/// Destructor
~Product() override = default;
/// Assignment operator
Product & operator=(const Product &) = default;
/// Move assignment operator
Product& operator=(Product&&) & = default;
/// Equality operator
bool operator==(const Product & rhs) const;
/// Equality operator
bool operator!=(const Product & rhs) const;
/// returns the target m/z
double getMZ() const;
/// sets the target m/z
void setMZ(double mz);
/// returns the lower offset from the target m/z
double getIsolationWindowLowerOffset() const;
/// sets the lower offset from the target m/z
void setIsolationWindowLowerOffset(double bound);
/// returns the upper offset from the target m/z
double getIsolationWindowUpperOffset() const;
/// sets the upper offset from the target m/z
void setIsolationWindowUpperOffset(double bound);
protected:
double mz_ = 0.0;
double window_low_ = 0.0;
double window_up_ = 0.0;
};
} // namespace OpenMS
namespace std
{
/**
* @brief Hash function for OpenMS::Product.
*
* Hashes mz, isolation window offsets, and the CVTermList base class.
* Consistent with operator==.
*/
template<>
struct hash<OpenMS::Product>
{
std::size_t operator()(const OpenMS::Product& p) const noexcept
{
std::size_t seed = OpenMS::hash_float(p.getMZ());
OpenMS::hash_combine(seed, OpenMS::hash_float(p.getIsolationWindowLowerOffset()));
OpenMS::hash_combine(seed, OpenMS::hash_float(p.getIsolationWindowUpperOffset()));
OpenMS::hash_combine(seed, std::hash<OpenMS::CVTermList>{}(p));
return seed;
}
};
} // namespace std
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/MetaInfoRegistry.h | .h | 4,476 | 159 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hendrik Weisser $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#pragma once
#include <map>
#include <string>
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/CONCEPT/Types.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <unordered_map>
#ifdef OPENMS_COMPILER_MSVC
#pragma warning( push )
#pragma warning( disable : 4251 ) // disable MSVC dll-interface warning
#endif
namespace OpenMS
{
/**
@brief Registry which assigns unique integer indices to strings.
When registering a new name an index >= 1024 is assigned.
Indices from 1 to 1023 are reserved for fast access and will never change:<BR>
1 - isotopic_range<BR>
2 - cluster_id<BR>
3 - label<BR>
4 - icon<BR>
5 - color<BR>
6 - RT<BR>
7 - MZ<BR>
8 - predicted_RT<BR>
9 - predicted_RT_p_value<BR>
10 - spectrum_reference<BR>
11 - ID<BR>
12 - low_quality<BR>
13 - charge<BR>
@ingroup Metadata
*/
class OPENMS_DLLAPI MetaInfoRegistry
{
public:
/// Default constructor
MetaInfoRegistry();
/// Copy constructor
MetaInfoRegistry(const MetaInfoRegistry& rhs);
/// Destructor
~MetaInfoRegistry();
/// Assignment operator
MetaInfoRegistry& operator=(const MetaInfoRegistry& rhs);
/**
Registers a string, stores its description and unit, and returns the corresponding index.
If the string is already registered, it returns the index of the string.
*/
UInt registerName(const String& name, const String& description = "", const String& unit = "");
/**
@brief Sets the description (String), corresponding to an index
@exception Exception::InvalidValue is thrown for unregistered indices
*/
void setDescription(UInt index, const String& description);
/**
@brief Sets the description (String), corresponding to a name
@exception Exception::InvalidValue is thrown for unregistered names
*/
void setDescription(const String& name, const String& description);
/**
@brief Sets the unit (String), corresponding to an index
@exception Exception::InvalidValue is thrown for unregistered indices
*/
void setUnit(UInt index, const String& unit);
/**
@brief Sets the unit (String), corresponding to a name
@exception Exception::InvalidValue is thrown for unregistered names
*/
void setUnit(const String& name, const String& unit);
/**
Returns the integer index corresponding to a string. If the string is not
registered, returns UInt(-1) (= UINT_MAX).
*/
UInt getIndex(const String& name) const;
/**
@brief Returns the corresponding name to an index
@exception Exception::InvalidValue is thrown for unregistered indices
*/
String getName(UInt index) const;
/**
@brief returns the description of an index
@exception Exception::InvalidValue is thrown for unregistered indices
*/
String getDescription(UInt index) const;
/**
@brief returns the description of a name
@exception Exception::InvalidValue is thrown for unregistered names
*/
String getDescription(const String& name) const;
/**
@brief returns the unit of an index
@exception Exception::InvalidValue is thrown for unregistered indices
*/
String getUnit(UInt index) const;
/**
@brief returns the unit of a name
@exception Exception::InvalidValue is thrown for unregistered names
*/
String getUnit(const String& name) const;
private:
/// internal counter, that stores the next index to assign
UInt next_index_;
using MapString2IndexType = std::unordered_map<std::string, UInt>;
using MapIndex2StringType = std::unordered_map<UInt, std::string>;
/// map from name to index
MapString2IndexType name_to_index_;
/// map from index to name
MapIndex2StringType index_to_name_;
/// map from index to description
MapIndex2StringType index_to_description_;
/// map from index to unit
MapIndex2StringType index_to_unit_;
};
} // namespace OpenMS
#ifdef OPENMS_COMPILER_MSVC
#pragma warning( pop )
#endif
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/AnnotatedMSRun.h | .h | 13,164 | 414 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg$
// $Authors: David Voigt, Timo Sachsenberg $
// -------------------------------------------------------------------------------------------------------------------------------------
#pragma once
#include <OpenMS/OpenMSConfig.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <OpenMS/CONCEPT/HashUtils.h>
#include <boost/range/combine.hpp>
#include <functional>
#include <vector>
namespace OpenMS
{
class PeptideIdentification;
class MSSpectrum;
/**
* @brief Class for storing MS run data with peptide and protein identifications
*
* This class stores an MSExperiment (containing spectra) along with peptide and protein
* identifications. Each spectrum in the MSExperiment is associated with a single
* PeptideIdentification object.
*
* The class provides methods to access and modify these identifications, as well as
* iterators to traverse the spectra and their associated identifications together.
*/
class OPENMS_DLLAPI AnnotatedMSRun
{
public:
using SpectrumIdRef = std::pair<MSSpectrum&, PeptideIdentification&>;
using ConstSpectrumIdRef = std::pair<const MSSpectrum&, const PeptideIdentification&>;
using SpectrumType = MSExperiment::SpectrumType;
using ChromatogramType = MSExperiment::ChromatogramType;
/// Default constructor
AnnotatedMSRun() = default;
/**
* @brief Move constructor for efficiently loading a MSExperiment without a deep copy
* @param[in] experiment The MSExperiment to move into this object
*/
explicit AnnotatedMSRun(MSExperiment&& experiment) : data(std::move(experiment))
{};
/// Move constructor
AnnotatedMSRun(AnnotatedMSRun&&) = default;
/// Copy constructor
AnnotatedMSRun(const AnnotatedMSRun&) = default;
AnnotatedMSRun& operator=(const AnnotatedMSRun&) = default;
AnnotatedMSRun& operator=(AnnotatedMSRun&&) = default;
/// Destructor
~AnnotatedMSRun() = default;
/// Equality operator
bool operator==(const AnnotatedMSRun& rhs) const
{
return data == rhs.data &&
peptide_ids_ == rhs.peptide_ids_ &&
protein_ids_ == rhs.protein_ids_;
}
/// Inequality operator
bool operator!=(const AnnotatedMSRun& rhs) const
{
return !(*this == rhs);
}
/**
* @brief Get the protein identification
* @return A reference to the protein identification
*/
std::vector<ProteinIdentification>& getProteinIdentifications()
{
return protein_ids_;
}
/**
* @brief Get the protein identification (const version)
* @return A const reference to the protein identification
*/
const std::vector<ProteinIdentification>& getProteinIdentifications() const
{
return protein_ids_;
}
/**
* @brief set the protein identifications
* @param[in] ids Vector of protein identifications
*/
void setProteinIdentifications(const std::vector<ProteinIdentification>& ids)
{
protein_ids_ = ids;
}
/**
* @brief Set the protein identifications (move version)
* @param[in] ids Vector of protein identifications
*/
void setProteinIdentifications(std::vector<ProteinIdentification>&& ids)
{
protein_ids_ = std::move(ids);
}
/**
* @brief Get all peptide identifications for all spectra
* @return A reference to the vector of peptide identifications
*/
PeptideIdentificationList& getPeptideIdentifications();
/**
* @brief Get all peptide identifications for all spectra (const version)
* @return A const reference to the vector of peptide identifications
*/
const PeptideIdentificationList& getPeptideIdentifications() const;
/**
* @brief Set all peptide identifications for all spectra (move version)
* @param[in] ids Vector of peptide identifications
*/
void setPeptideIdentifications(PeptideIdentificationList&& ids);
/**
* @brief Set all peptide identifications for all spectra
* @param[in] ids Vector of peptide identifications
*/
void setPeptideIdentifications(const PeptideIdentificationList& ids);
/**
* @brief Get the MSExperiment
* @return A reference to the MSExperiment
*/
MSExperiment& getMSExperiment();
/**
* @brief Get the MSExperiment (const version)
* @return A const reference to the MSExperiment
*/
const MSExperiment& getMSExperiment() const;
/**
* @brief Set the MSExperiment
* @param[in] experiment The MSExperiment to set
*/
void setMSExperiment(MSExperiment&& experiment);
/**
* @brief Set the MSExperiment
* @param[in] experiment The MSExperiment to set
*/
void setMSExperiment(const MSExperiment& experiment);
/**
* @brief Get a const iterator to the beginning of the data
* @return A const iterator to the beginning
*/
inline auto cbegin() const
{
checkPeptideIdSize_(OPENMS_PRETTY_FUNCTION);
return PairIterator(data.getSpectra().cbegin(), peptide_ids_.cbegin());
}
/**
* @brief Get an iterator to the beginning of the data
* @return An iterator to the beginning
*/
inline auto begin()
{
checkPeptideIdSize_(OPENMS_PRETTY_FUNCTION);
return PairIterator(data.getSpectra().begin(), peptide_ids_.begin());
}
/**
* @brief Get a const iterator to the beginning of the data
* @return A const iterator to the beginning
*/
inline auto begin() const
{
checkPeptideIdSize_(OPENMS_PRETTY_FUNCTION);
return PairIterator(data.getSpectra().cbegin(), peptide_ids_.cbegin());
}
/**
* @brief Get an iterator to the end of the data
* @return An iterator to the end
*/
inline auto end()
{
return PairIterator(data.getSpectra().end(), peptide_ids_.end());
}
/**
* @brief Get a const iterator to the end of the data
* @return A const iterator to the end
*/
inline auto end() const
{
return PairIterator(data.getSpectra().end(), peptide_ids_.end());
}
/**
* @brief Get a const iterator to the end of the data
* @return A const iterator to the end
*/
inline auto cend() const
{
return PairIterator(data.getSpectra().cend(), peptide_ids_.cend());
}
/**
* @brief Access a spectrum and its associated peptide identification
* @param[in] idx The index of the spectrum
* @return A pair of references to the spectrum and its peptide identification
*/
inline SpectrumIdRef operator[](size_t idx)
{
if (idx >= peptide_ids_.size())
{
throw Exception::IndexOverflow(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION,
idx, peptide_ids_.size());
}
if (idx >= data.getSpectra().size())
{
throw Exception::IndexOverflow(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION,
idx, data.getSpectra().size());
}
return {data.getSpectra()[idx], peptide_ids_[idx]};
}
/**
* @brief Access a spectrum and its associated peptide identification (const version)
* @param[in] idx The index of the spectrum
* @return A pair of const references to the spectrum and its peptide identification
*/
inline ConstSpectrumIdRef operator[](size_t idx) const
{
if (idx >= peptide_ids_.size())
{
throw Exception::IndexOverflow(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION,
idx, peptide_ids_.size());
}
if (idx >= data.getSpectra().size())
{
throw Exception::IndexOverflow(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION,
idx, data.getSpectra().size());
}
return {data.getSpectra()[idx], peptide_ids_[idx]};
}
/**
* @brief Iterator for pairs of spectra and peptide identifications
*
* This iterator allows traversing the spectra and their associated peptide
* identifications together.
*/
template<typename T1, typename T2>
struct PairIterator
{
using iterator_category = std::forward_iterator_tag;
using difference_type = std::ptrdiff_t;
/**
* @brief Constructor
* @param[in] ptr1 Iterator to the spectra
* @param[in] ptr2 Iterator to the peptide identifications
*/
PairIterator(T1 ptr1, T2 ptr2) : m_ptr1(ptr1), m_ptr2(ptr2)
{}
/**
* @brief Pre-increment operator
* @return Reference to this iterator after incrementing
*/
PairIterator& operator++()
{
++m_ptr1;
++m_ptr2;
return *this;
}
/**
* @brief Post-increment operator
* @return Copy of this iterator before incrementing
*/
PairIterator operator++(int)
{
auto tmp(*this);
++(*this);
return tmp;
}
/**
* @brief Dereference operator
* @return A pair of references to the current spectrum and peptide identification
*/
auto operator*()
{
return std::make_pair(std::ref(*m_ptr1), std::ref(*m_ptr2));
}
/**
* @brief Equality operator
* @param[in] a First iterator
* @param[in] b Second iterator
* @return True if the iterators are equal
*/
inline friend bool operator==(const PairIterator& a, const PairIterator& b)
{
return a.m_ptr1 == b.m_ptr1 && a.m_ptr2 == b.m_ptr2;
}
/**
* @brief Inequality operator
* @param[in] a First iterator
* @param[in] b Second iterator
* @return True if the iterators are not equal
*/
inline friend bool operator!=(const PairIterator& a, const PairIterator& b)
{
return !(a == b);
}
private:
T1 m_ptr1;
T2 m_ptr2;
};
typedef AnnotatedMSRun::PairIterator<std::vector<MSSpectrum>::iterator, PeptideIdentificationList::iterator> Iterator;
typedef AnnotatedMSRun::PairIterator<std::vector<MSSpectrum>::const_iterator, PeptideIdentificationList::const_iterator> ConstIterator;
private:
// Helper to enforce invariant
void checkPeptideIdSize_(const char* function_name) const;
PeptideIdentificationList peptide_ids_;
std::vector<ProteinIdentification> protein_ids_;
MSExperiment data;
};
} // namespace OpenMS
// Hash function specialization for AnnotatedMSRun
namespace std
{
/**
* @brief Hash function for OpenMS::AnnotatedMSRun.
*
* Hashes all fields used in operator==: data (MSExperiment), peptide_ids_, and protein_ids_.
* Since the component types don't have std::hash specializations, this hash uses
* identifying properties (sizes and identifiers) to create a fast, consistent hash.
*/
template<>
struct hash<OpenMS::AnnotatedMSRun>
{
std::size_t operator()(const OpenMS::AnnotatedMSRun& run) const noexcept
{
// Start with hash of the MSExperiment size (number of spectra)
std::size_t seed = OpenMS::hash_int(run.getMSExperiment().size());
// Hash the number of chromatograms
OpenMS::hash_combine(seed, OpenMS::hash_int(run.getMSExperiment().getChromatograms().size()));
// Hash the number of peptide identifications
OpenMS::hash_combine(seed, OpenMS::hash_int(run.getPeptideIdentifications().size()));
// Hash the number of protein identifications
OpenMS::hash_combine(seed, OpenMS::hash_int(run.getProteinIdentifications().size()));
// Hash identifying properties from protein identifications
for (const auto& prot_id : run.getProteinIdentifications())
{
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(prot_id.getIdentifier()));
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(prot_id.getSearchEngine()));
OpenMS::hash_combine(seed, OpenMS::hash_int(prot_id.getHits().size()));
}
// Hash identifying properties from peptide identifications
for (const auto& pep_id : run.getPeptideIdentifications())
{
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(pep_id.getIdentifier()));
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(pep_id.getScoreType()));
OpenMS::hash_combine(seed, OpenMS::hash_int(pep_id.getHits().size()));
OpenMS::hash_combine(seed, OpenMS::hash_float(pep_id.getSignificanceThreshold()));
}
// Hash identifying properties from spectra
for (const auto& spectrum : run.getMSExperiment().getSpectra())
{
OpenMS::hash_combine(seed, OpenMS::hash_float(spectrum.getRT()));
OpenMS::hash_combine(seed, OpenMS::hash_int(spectrum.getMSLevel()));
OpenMS::hash_combine(seed, OpenMS::hash_int(spectrum.size()));
}
return seed;
}
};
} // namespace std
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/Software.h | .h | 2,506 | 88 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/METADATA/MetaInfoInterface.h>
#include <OpenMS/METADATA/CVTermList.h>
#include <OpenMS/CONCEPT/HashUtils.h>
#include <functional>
namespace OpenMS
{
/**
@brief Description of the software used for processing
@ingroup Metadata
*/
class OPENMS_DLLAPI Software :
public CVTermList
{
public:
/// Constructor
explicit Software(const String& name = "", const String& version = "");
/// Copy constructor
Software(const Software&) = default;
/// Move constructor
Software(Software&&) = default;
/// Destructor
~Software() override;
/// Assignment operator
Software& operator=(const Software&) = default;
/// Move assignment operator
Software& operator=(Software&&)& = default;
/// Equality operator
bool operator==(const Software& rhs) const;
/// Inequality operator
bool operator!=(const Software& rhs) const;
/// Less-than operator (for sorting)
bool operator<(const Software& rhs) const;
/// Returns the name of the software
const String& getName() const;
/// Sets the name of the software
void setName(const String& name);
/// Returns the software version
const String& getVersion() const;
/// Sets the software version
void setVersion(const String& version);
protected:
String name_;
String version_;
};
} // namespace OpenMS
// Hash function specialization for Software
namespace std
{
/**
* @brief Hash function for OpenMS::Software.
*
* Hashes name and version fields.
* Note: CVTermList base class fields are not included in the hash as CVTermList
* does not yet have a hash implementation. This hash is consistent with operator==
* for objects that differ only in the Software-specific fields.
*/
template<>
struct hash<OpenMS::Software>
{
std::size_t operator()(const OpenMS::Software& s) const noexcept
{
std::size_t seed = OpenMS::fnv1a_hash_string(s.getName());
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(s.getVersion()));
return seed;
}
};
} // namespace std
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/SpectrumSettings.h | .h | 12,279 | 296 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm, Timo Sachsenberg $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/METADATA/InstrumentSettings.h>
#include <OpenMS/METADATA/AcquisitionInfo.h>
#include <OpenMS/METADATA/SourceFile.h>
#include <OpenMS/METADATA/Precursor.h>
#include <OpenMS/METADATA/Product.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/DataProcessing.h>
#include <OpenMS/IONMOBILITY/IMTypes.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
#include <OpenMS/CONCEPT/HashUtils.h>
#include <OpenMS/ANALYSIS/TARGETED/TargetedExperimentHelper.h>
#include <functional>
#include <map>
#include <vector>
namespace OpenMS
{
/**
@brief Representation of 1D spectrum settings.
It contains the metadata about spectrum specific instrument settings,
acquisition settings, description of the meta values used in the peaks and precursor info.
Precursor info should only be used if this spectrum is a tandem-MS spectrum.
The precursor spectrum is the first spectrum before this spectrum, that has a lower MS-level than
the current spectrum.
@ingroup Metadata
*/
class OPENMS_DLLAPI SpectrumSettings :
public MetaInfoInterface
{
public:
///Spectrum peak type
enum class SpectrumType
{
UNKNOWN, ///< Unknown spectrum type
CENTROID, ///< centroid data or stick data
PROFILE, ///< profile data
SIZE_OF_SPECTRUMTYPE
};
/// Names of spectrum types
static const std::string NamesOfSpectrumType[static_cast<size_t>(SpectrumType::SIZE_OF_SPECTRUMTYPE)];
/// returns all spectrum type names known to OpenMS
static StringList getAllNamesOfSpectrumType();
/// Convert a SpectrumType enum to String
/// @throws Exception::InvalidValue if @p type is SIZE_OF_SPECTRUMTYPE
static const std::string& spectrumTypeToString(SpectrumType type);
/// Convert an entry in NamesOfSpectrumType[] to SpectrumType enum
/// @throws Exception::InvalidValue if @p name is not contained in NamesOfSpectrumType[]
static SpectrumType toSpectrumType(const std::string& name);
/// Constructor
SpectrumSettings() = default;
/// Copy constructor
SpectrumSettings(const SpectrumSettings &) = default;
/// Move constructor
SpectrumSettings(SpectrumSettings&&) noexcept = default;
/// Destructor
~SpectrumSettings() noexcept = default;
// Assignment operator
SpectrumSettings & operator=(const SpectrumSettings &) = default;
/// Move assignment operator
SpectrumSettings& operator=(SpectrumSettings&&) & = default;
/// Equality operator
bool operator==(const SpectrumSettings & rhs) const;
/// Equality operator
bool operator!=(const SpectrumSettings & rhs) const;
/// merge another spectrum setting into this one (data is usually appended, except for spectrum type which needs to be unambiguous to be kept)
void unify(const SpectrumSettings & rhs);
///returns the spectrum type (centroided (PEAKS) or profile data (RAW))
SpectrumType getType() const;
///sets the spectrum type
void setType(SpectrumType type);
/// @brief sets the IMFormat of the spectrum
/// @param[in] im_type
void setIMFormat(const IMFormat& im_type);
/// @brief returns the IMFormat of the spectrum if set. Otherwise UNKNOWN (default).
///
/// Note: If UNKNOWN, use IMFormat::determineIMFormat to determine the IMFormat based on the data.
/// @return IMFormat of the spectrum
IMFormat getIMFormat() const;
/// returns the native identifier for the spectrum, used by the acquisition software.
const String & getNativeID() const;
/// sets the native identifier for the spectrum, used by the acquisition software.
void setNativeID(const String & native_id);
/// returns the free-text comment
const String & getComment() const;
/// sets the free-text comment
void setComment(const String & comment);
/// returns a const reference to the instrument settings of the current spectrum
const InstrumentSettings & getInstrumentSettings() const;
/// returns a mutable reference to the instrument settings of the current spectrum
InstrumentSettings & getInstrumentSettings();
/// sets the instrument settings of the current spectrum
void setInstrumentSettings(const InstrumentSettings & instrument_settings);
/// returns a const reference to the acquisition info
const AcquisitionInfo & getAcquisitionInfo() const;
/// returns a mutable reference to the acquisition info
AcquisitionInfo & getAcquisitionInfo();
/// sets the acquisition info
void setAcquisitionInfo(const AcquisitionInfo & acquisition_info);
/// returns a const reference to the source file
const SourceFile & getSourceFile() const;
/// returns a mutable reference to the source file
SourceFile & getSourceFile();
/// sets the source file
void setSourceFile(const SourceFile & source_file);
/// returns a const reference to the precursors
const std::vector<Precursor> & getPrecursors() const;
/// returns a mutable reference to the precursors
std::vector<Precursor> & getPrecursors();
/// sets the precursors
void setPrecursors(const std::vector<Precursor> & precursors);
/// returns a const reference to the products
const std::vector<Product> & getProducts() const;
/// returns a mutable reference to the products
std::vector<Product> & getProducts();
/// sets the products
void setProducts(const std::vector<Product> & products);
/// sets the description of the applied processing
void setDataProcessing(const std::vector< DataProcessingPtr > & data_processing);
/// returns a mutable reference to the description of the applied processing
std::vector< DataProcessingPtr > & getDataProcessing();
/// returns a const reference to the description of the applied processing
const std::vector< std::shared_ptr<const DataProcessing > > getDataProcessing() const;
protected:
SpectrumType type_ = SpectrumType::UNKNOWN;
IMFormat im_type_ = IMFormat::UNKNOWN;
String native_id_;
String comment_;
InstrumentSettings instrument_settings_;
SourceFile source_file_;
AcquisitionInfo acquisition_info_;
std::vector<Precursor> precursors_;
std::vector<Product> products_;
std::vector< DataProcessingPtr > data_processing_;
};
///Print the contents to a stream.
OPENMS_DLLAPI std::ostream & operator<<(std::ostream & os, const SpectrumSettings & spec);
} // namespace OpenMS
namespace std
{
/**
* @brief Hash function for OpenMS::SpectrumSettings.
*
* Hashes all fields used in operator==:
* - MetaInfoInterface (via getKeys/getMetaValue)
* - type_ (SpectrumType enum)
* - native_id_ (String)
* - comment_ (String)
* - instrument_settings_ (InstrumentSettings - hashes scan_mode, zoom_scan, polarity, scan_windows)
* - acquisition_info_ (AcquisitionInfo - hashes method_of_combination and acquisitions)
* - source_file_ (SourceFile - hashes name, path, file_size, file_type, checksum, native_id_type)
* - precursors_ (vector<Precursor> - hashes each precursor's key fields)
* - products_ (vector<Product> - uses std::hash<Product>)
* - data_processing_ (vector<DataProcessingPtr> - hashes dereferenced contents)
*
* @note This hash is consistent with operator==. Since operator== compares
* all fields including MetaInfoInterface and complex nested types, this hash
* includes representative fields from each. For nested types without their own
* std::hash, we hash their primary identifying fields.
*/
template<>
struct hash<OpenMS::SpectrumSettings>
{
std::size_t operator()(const OpenMS::SpectrumSettings& s) const noexcept
{
std::size_t seed = 0;
// Hash type_ (enum)
OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(s.getType())));
// Hash native_id_ (String)
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(s.getNativeID()));
// Hash comment_ (String)
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(s.getComment()));
// Hash instrument_settings_ (all fields from operator==)
const auto& is = s.getInstrumentSettings();
OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(is.getScanMode())));
OpenMS::hash_combine(seed, OpenMS::hash_int(is.getZoomScan() ? 1 : 0));
OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(is.getPolarity())));
OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(is.getScanWindows().size())));
for (const auto& sw : is.getScanWindows())
{
OpenMS::hash_combine(seed, OpenMS::hash_float(sw.begin));
OpenMS::hash_combine(seed, OpenMS::hash_float(sw.end));
}
OpenMS::hash_combine(seed, std::hash<OpenMS::MetaInfoInterface>{}(is));
// Hash acquisition_info_ (all fields from operator==)
const auto& ai = s.getAcquisitionInfo();
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(ai.getMethodOfCombination()));
OpenMS::hash_combine(seed, std::hash<OpenMS::MetaInfoInterface>{}(ai));
OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(ai.size())));
for (const auto& acq : ai)
{
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(acq.getIdentifier()));
OpenMS::hash_combine(seed, std::hash<OpenMS::MetaInfoInterface>{}(acq));
}
// Hash source_file_ (all fields from operator==, including CVTermList base)
const auto& sf = s.getSourceFile();
OpenMS::hash_combine(seed, OpenMS::hashCVTermList(sf));
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(sf.getNameOfFile()));
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(sf.getPathToFile()));
OpenMS::hash_combine(seed, OpenMS::hash_float(sf.getFileSize()));
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(sf.getFileType()));
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(sf.getChecksum()));
OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(sf.getChecksumType())));
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(sf.getNativeIDType()));
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(sf.getNativeIDTypeAccession()));
// Hash precursors_ (using std::hash<Precursor>)
OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(s.getPrecursors().size())));
for (const auto& p : s.getPrecursors())
{
OpenMS::hash_combine(seed, std::hash<OpenMS::Precursor>{}(p));
}
// Hash products_ (using std::hash<Product>)
OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(s.getProducts().size())));
for (const auto& p : s.getProducts())
{
OpenMS::hash_combine(seed, std::hash<OpenMS::Product>{}(p));
}
// Hash data_processing_ (dereferenced contents)
const auto dp = s.getDataProcessing();
OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(dp.size())));
for (const auto& dp_ptr : dp)
{
if (dp_ptr)
{
// Hash Software name and version
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(dp_ptr->getSoftware().getName()));
OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(dp_ptr->getSoftware().getVersion()));
// Hash processing actions
for (const auto& action : dp_ptr->getProcessingActions())
{
OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(action)));
}
// Hash completion time
OpenMS::hash_combine(seed, std::hash<OpenMS::DateTime>{}(dp_ptr->getCompletionTime()));
}
}
// Hash MetaInfoInterface base class
OpenMS::hash_combine(seed, std::hash<OpenMS::MetaInfoInterface>{}(s));
return seed;
}
};
} // namespace std
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/PeptideEvidence.h | .h | 4,959 | 135 | // 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/CONCEPT/HashUtils.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <functional>
namespace OpenMS
{
/**
@brief Representation of a peptide evidence.
A peptide evidence object describes a single peptide to protein match.
@ingroup Metadata
*/
class OPENMS_DLLAPI PeptideEvidence
{
public:
static const int UNKNOWN_POSITION; // == -1
// Note: we use 0 as position of the N-terminus while e.g. mzTab or other formats start counting at 1.
static const int N_TERMINAL_POSITION;
static const char UNKNOWN_AA; // PeptideEvidence::UNKNOWN_AA = 'X';
// Note: we use '[' and ']' instead of e.g. '-' as in mzTab specification
static const char N_TERMINAL_AA;
static const char C_TERMINAL_AA;
/// Constructor
PeptideEvidence();
/// Constructor
explicit PeptideEvidence(const String& accession, Int start=UNKNOWN_POSITION, Int end=UNKNOWN_POSITION, char aa_before=UNKNOWN_AA, char aa_after=UNKNOWN_AA);
/// Copy constructor
PeptideEvidence(const PeptideEvidence&) = default;
/// Move constructor
PeptideEvidence(PeptideEvidence&&) noexcept = default;
/// Destructor
~PeptideEvidence() = default;
//@}
/// Assignment operator
PeptideEvidence& operator=(const PeptideEvidence&) = default;
/// Move assignment operator
PeptideEvidence& operator=(PeptideEvidence&&) = default; // TODO: add noexcept (gcc 4.8 bug)
/// Equality operator
bool operator==(const PeptideEvidence& rhs) const;
/// Less operator
bool operator<(const PeptideEvidence& rhs) const;
/// not equal
bool operator!=(const PeptideEvidence& rhs) const;
/// start and end numbers in evidence represent actual numeric indices
bool hasValidLimits() const;
/// get the protein accession the peptide matches to. If not available the empty string is returned.
const String& getProteinAccession() const;
/// set the protein accession the peptide matches to. If not available set to empty string.
void setProteinAccession(const String& s);
/// set the position of the last AA of the peptide in protein coordinates (starting at 0 for the N-terminus). If not available, set to UNKNOWN_POSITION. N-terminal positions must be marked with N_TERMINAL_AA
void setStart(const Int a);
/// get the position in the protein (starting at 0 for the N-terminus). If not available UNKNOWN_POSITION constant is returned.
Int getStart() const;
/// set the position of the last AA of the peptide in protein coordinates (starting at 0 for the N-terminus). If not available, set UNKNOWN_POSITION. C-terminal positions must be marked with C_TERMINAL_AA
void setEnd(const Int a);
/// get the position of the last AA of the peptide in protein coordinates (starting at 0 for the N-terminus). If not available UNKNOWN_POSITION constant is returned.
Int getEnd() const;
/// sets the amino acid single letter code before the sequence (preceding amino acid in the protein). If not available, set to UNKNOWN_AA. If N-terminal set to N_TERMINAL_AA
void setAABefore(const char acid);
/// returns the amino acid single letter code before the sequence (preceding amino acid in the protein). If not available, UNKNOWN_AA is returned. If N-terminal, N_TERMINAL_AA is returned.
char getAABefore() const;
/// sets the amino acid single letter code after the sequence (subsequent amino acid in the protein). If not available, set to UNKNOWN_AA. If C-terminal set to C_TERMINAL_AA
void setAAAfter(const char acid);
/// returns the amino acid single letter code after the sequence (subsequent amino acid in the protein). If not available, UNKNOWN_AA is returned. If C-terminal, C_TERMINAL_AA is returned.
char getAAAfter() const;
protected:
String accession_;
Int start_;
Int end_;
char aa_before_;
char aa_after_;
};
} // namespace OpenMS
// Hash function specialization for PeptideEvidence
namespace std
{
template<>
struct hash<OpenMS::PeptideEvidence>
{
std::size_t operator()(const OpenMS::PeptideEvidence& pe) const noexcept
{
std::size_t seed = OpenMS::fnv1a_hash_string(pe.getProteinAccession());
OpenMS::hash_combine(seed, OpenMS::hash_int(pe.getStart()));
OpenMS::hash_combine(seed, OpenMS::hash_int(pe.getEnd()));
OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(pe.getAABefore())));
OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(pe.getAAAfter())));
return seed;
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/MetaInfoInterfaceUtils.h | .h | 3,864 | 100 | // 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/OpenMSConfig.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/METADATA/MetaInfoInterface.h>
#include <algorithm>
#include <map>
#include <vector>
namespace OpenMS
{
namespace Detail
{
template<typename T>
struct MetaKeyGetter
{
static void getKeys(const T& object, std::vector<String>& keys)
{
object.getKeys(keys);
};
};
}
/**
@brief Utilities operating on containers inheriting from MetaInfoInterface
@ingroup Metadata
*/
class /*OPENMS_DLLAPI -- disabled since it's template code only */ MetaInfoInterfaceUtils
{
public:
/// hide c'tors to avoid instantiation of utils class
MetaInfoInterfaceUtils() = delete;
MetaInfoInterfaceUtils(const MetaInfoInterfaceUtils&) = delete;
MetaInfoInterfaceUtils& operator=(MetaInfoInterfaceUtils&) = delete;
// no Move semantics for utils class
///@name Methods to find key sets
//@{
/**
@brief Find keys in a collection of MetaInfoInterface objects which reach a certain frequency threshold.
Searches the given iterator range for the keys of each element's MetaInfoInterface keys and returns those keys, which
reach a certain frequency threshold. Common use cases
are @p min_frequency = 0 (i.e. take any key which occurs)
and @p min_frequency = 100 (i.e. take only keys which are common to all elements in the iterator range).
@tparam T_In Input container (e.g. std::vector or alike), containing objects which implement the MetaInfoInterface (i.e. support 'getKeys()')
@tparam T_Out Output container of type T<String> (e.g. std::set<String>)
@param[in] it_start Iterator pointing to the initial position to search. (note: this does not need to correspond to the beginning of the container)
@param[in] it_end Iterator pointing to the end final position to search.
@param[in] min_frequency Minimum required frequency (in percent). Must be between 0-100. Other values are corrected to the closest value allowed.
@param[in] getter Helper class, which has a getKeys() member, which can extract the keys for a given MetaInfoInterface-object; see MetaKeyGetter
@return Returns a vector/list/set of keys passing the frequency criterion.
*/
template<typename T_In, typename T_Out>
static T_Out findCommonMetaKeys(const typename T_In::const_iterator& it_start, const typename T_In::const_iterator& it_end, float min_frequency, typename Detail::MetaKeyGetter<typename T_In::value_type> getter = Detail::MetaKeyGetter<typename T_In::value_type>())
{
// make sure min_frequency is within [0,100]
min_frequency = std::min(100.0f, std::max(0.0f, min_frequency));
std::map<String, UInt> counter;
typedef std::vector<String> KeysType;
KeysType keys;
for (typename T_In::const_iterator it = it_start; it != it_end; ++it)
{
getter.getKeys(*it, keys);
for (KeysType::const_iterator itk = keys.begin(); itk != keys.end(); ++itk)
{
++counter[*itk];
}
}
// pick the keys which occur often enough
const UInt required_counts = UInt(min_frequency / 100.0 * std::distance(it_start, it_end));
T_Out common_keys;
for (const auto& [key, count] : counter)
{
if (count >= required_counts)
{
common_keys.insert(common_keys.end(), key);
}
}
return common_keys;
}
}; // class
} // namespace OPENMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/DataProcessing.h | .h | 5,322 | 127 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/METADATA/MetaInfoInterface.h>
#include <OpenMS/METADATA/Software.h>
#include <OpenMS/DATASTRUCTURES/DateTime.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
#include <set>
#include <memory>
namespace OpenMS
{
/**
@brief Description of the applied preprocessing steps
@ingroup Metadata
*/
class OPENMS_DLLAPI DataProcessing :
public MetaInfoInterface
{
public:
//The different processing types
enum ProcessingAction
{
DATA_PROCESSING, ///< General data processing (if no other term applies)
CHARGE_DECONVOLUTION, ///< Charge deconvolution
DEISOTOPING, ///< Deisotoping
SMOOTHING, ///< Smoothing of the signal to reduce noise
CHARGE_CALCULATION, ///< Determination of the peak charge
PRECURSOR_RECALCULATION, ///< Recalculation of precursor m/z
BASELINE_REDUCTION, ///< Baseline reduction
PEAK_PICKING, ///< Peak picking (conversion from raw to peak data)
ALIGNMENT, ///< Retention time alignment of different maps
CALIBRATION, ///< Calibration of m/z positions
NORMALIZATION, ///< Normalization of intensity values
FILTERING, ///< Data filtering or extraction
QUANTITATION, ///< Quantitation
FEATURE_GROUPING, ///< %Feature grouping
IDENTIFICATION_MAPPING, ///< %Identification mapping
FORMAT_CONVERSION, ///< General file format conversion (if no other term applies)
CONVERSION_MZDATA, ///< Conversion to mzData format
CONVERSION_MZML, ///< Conversion to mzML format
CONVERSION_MZXML, ///< Conversion to mzXML format
CONVERSION_DTA, ///< Conversion to DTA format
IDENTIFICATION, ///< Identification
ION_MOBILITY_BINNING, ///< Ion mobility binning (merging of spectra with similar IM values)
SIZE_OF_PROCESSINGACTION
};
/// Names of inlet types
static const std::string NamesOfProcessingAction[SIZE_OF_PROCESSINGACTION];
/// returns all processing action names known to OpenMS
static StringList getAllNamesOfProcessingAction();
/// Convert a ProcessingAction enum to String
/// @throws Exception::InvalidValue if @p action is SIZE_OF_PROCESSINGACTION
static const std::string& processingActionToString(ProcessingAction action);
/// Convert a string to ProcessingAction enum
/// @throws Exception::InvalidValue if @p name is not contained in NamesOfProcessingAction[]
static ProcessingAction toProcessingAction(const std::string& name);
/// Constructor
DataProcessing() = default;
/// Copy constructor
DataProcessing(const DataProcessing&) = default;
// note: we implement the move constructor ourselves due to a bug in MSVS
// 2015/2017 which cannot produce a default move constructor for classes
// that contain STL containers (other than vector).
/// Move constructor
DataProcessing(DataProcessing&&) noexcept;
/// Destructor
~DataProcessing();
/// Assignment operator
DataProcessing& operator=(const DataProcessing&) = default;
/// Move assignment operator
DataProcessing& operator=(DataProcessing&&)& = default;
/// Equality operator
bool operator==(const DataProcessing& rhs) const;
/// Equality operator
bool operator!=(const DataProcessing& rhs) const;
/// returns a const reference to the software used for processing
const Software& getSoftware() const;
/// returns a mutable reference to the software used for processing
Software& getSoftware();
/// sets the software used for processing
void setSoftware(const Software& software);
/// returns a const reference to the applied processing actions
const std::set<ProcessingAction>& getProcessingActions() const;
/// returns a mutable reference to the description of the applied processing
std::set<ProcessingAction>& getProcessingActions();
/// sets the description of the applied processing
void setProcessingActions(const std::set<ProcessingAction>& actions);
/// returns the time of completion of the processing
const DateTime& getCompletionTime() const;
/// sets the time of completion taking a DateTime object
void setCompletionTime(const DateTime& completion_time);
protected:
Software software_;
std::set<ProcessingAction> processing_actions_;
DateTime completion_time_;
};
typedef std::shared_ptr<DataProcessing> DataProcessingPtr;
typedef std::shared_ptr<const DataProcessing> ConstDataProcessingPtr;
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/IonDetector.h | .h | 7,517 | 209 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/METADATA/MetaInfoInterface.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
#include <OpenMS/CONCEPT/HashUtils.h>
#include <functional>
namespace OpenMS
{
/**
@brief Description of a ion detector (part of a MS Instrument)
@ingroup Metadata
*/
class OPENMS_DLLAPI IonDetector :
public MetaInfoInterface
{
public:
/// Detector type
enum class Type
{
TYPENULL, ///< Unknown
ELECTRONMULTIPLIER, ///< Electron multiplier
PHOTOMULTIPLIER, ///< Photo multiplier
FOCALPLANEARRAY, ///< Focal plane array
FARADAYCUP, ///< Faraday cup
CONVERSIONDYNODEELECTRONMULTIPLIER, ///< Conversion dynode electron multiplier
CONVERSIONDYNODEPHOTOMULTIPLIER, ///< Conversion dynode photo multiplier
MULTICOLLECTOR, ///< Multi-collector
CHANNELELECTRONMULTIPLIER, ///< Channel electron multiplier
CHANNELTRON, ///< channeltron
DALYDETECTOR, ///< daly detector
MICROCHANNELPLATEDETECTOR, ///< microchannel plate detector
ARRAYDETECTOR, ///< array detector
CONVERSIONDYNODE, ///< conversion dynode
DYNODE, ///< dynode
FOCALPLANECOLLECTOR, ///< focal plane collector
IONTOPHOTONDETECTOR, ///< ion-to-photon detector
POINTCOLLECTOR, ///< point collector
POSTACCELERATIONDETECTOR, ///< postacceleration detector
PHOTODIODEARRAYDETECTOR, ///< photodiode array detector
INDUCTIVEDETECTOR, ///< inductive detector
ELECTRONMULTIPLIERTUBE, ///< electron multiplier tube
SIZE_OF_TYPE
};
/// Names of detector types
static const std::string NamesOfType[static_cast<size_t>(Type::SIZE_OF_TYPE)];
/// Acquisition mode
enum class AcquisitionMode
{
ACQMODENULL, ///< Unknown
PULSECOUNTING, ///< Pulse counting
ADC, ///< Analog-digital converter
TDC, ///< Time-digital converter
TRANSIENTRECORDER, ///< Transient recorder
SIZE_OF_ACQUISITIONMODE
};
/// Names of acquisition modes
static const std::string NamesOfAcquisitionMode[static_cast<size_t>(AcquisitionMode::SIZE_OF_ACQUISITIONMODE)];
/**
@brief Returns all detector type names known to OpenMS
@return List of all detector type names
*/
static StringList getAllNamesOfType();
/**
@brief Returns all acquisition mode names known to OpenMS
@return List of all acquisition mode names
*/
static StringList getAllNamesOfAcquisitionMode();
/**
@brief Convert a Type enum to its string representation
@param type The detector type enum value to convert
@return Reference to the string representation
@throws Exception::InvalidValue if @p type is SIZE_OF_TYPE
*/
static const std::string& typeToString(Type type);
/**
@brief Convert a string to a Type enum
@param name The string name to convert
@return The corresponding Type enum value
@throws Exception::InvalidValue if @p name is not found in NamesOfType[]
*/
static Type toType(const std::string& name);
/**
@brief Convert an AcquisitionMode enum to its string representation
@param mode The acquisition mode enum value to convert
@return Reference to the string representation
@throws Exception::InvalidValue if @p mode is SIZE_OF_ACQUISITIONMODE
*/
static const std::string& acquisitionModeToString(AcquisitionMode mode);
/**
@brief Convert a string to an AcquisitionMode enum
@param name The string name to convert
@return The corresponding AcquisitionMode enum value
@throws Exception::InvalidValue if @p name is not found in NamesOfAcquisitionMode[]
*/
static AcquisitionMode toAcquisitionMode(const std::string& name);
/// Constructor
IonDetector();
/// Copy constructor
IonDetector(const IonDetector &) = default;
/// Move constructor
IonDetector(IonDetector&&) = default;
/// Destructor
~IonDetector();
/// Assignment operator
IonDetector & operator=(const IonDetector &) = default;
/// Move assignment operator
IonDetector& operator=(IonDetector&&) & = default;
/// Equality operator
bool operator==(const IonDetector & rhs) const;
/// Equality operator
bool operator!=(const IonDetector & rhs) const;
/// returns the detector type
Type getType() const;
/// sets the detector type
void setType(Type type);
/// returns the acquisition mode
AcquisitionMode getAcquisitionMode() const;
/// sets the acquisition mode
void setAcquisitionMode(AcquisitionMode acquisition_mode);
/// returns the resolution (in ns)
double getResolution() const;
/// sets the resolution (in ns)
void setResolution(double resolution);
/// returns the analog-to-digital converter sampling frequency (in Hz)
double getADCSamplingFrequency() const;
/// sets the analog-to-digital converter sampling frequency (in Hz)
void setADCSamplingFrequency(double ADC_sampling_frequency);
/**
@brief returns the position of this part in the whole Instrument.
Order can be ignored, as long the instrument has this default setup:
- one ion source
- one or many mass analyzers
- one ion detector
For more complex instruments, the order should be defined.
*/
Int getOrder() const;
/// sets the order
void setOrder(Int order);
protected:
Type type_;
AcquisitionMode acquisition_mode_;
double resolution_;
double ADC_sampling_frequency_;
Int order_;
};
} // namespace OpenMS
namespace std
{
/**
* @brief Hash function for OpenMS::IonDetector.
*
* Hashes type, acquisition mode, resolution, ADC sampling frequency, and order.
* Note: MetaInfoInterface base class fields are not included in the hash as
* MetaInfoInterface does not yet have a hash implementation. This hash is
* consistent with operator== for objects that differ only in the IonDetector-specific
* fields.
*/
template<>
struct hash<OpenMS::IonDetector>
{
std::size_t operator()(const OpenMS::IonDetector& d) const noexcept
{
std::size_t seed = OpenMS::hash_int(static_cast<int>(d.getType()));
OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(d.getAcquisitionMode())));
OpenMS::hash_combine(seed, OpenMS::hash_float(d.getResolution()));
OpenMS::hash_combine(seed, OpenMS::hash_float(d.getADCSamplingFrequency()));
OpenMS::hash_combine(seed, OpenMS::hash_int(d.getOrder()));
return seed;
}
};
} // namespace std
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/ID/Observation.h | .h | 2,349 | 73 | // 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/METADATA/ID/InputFile.h>
#include <OpenMS/METADATA/ID/MetaData.h>
#include <OpenMS/METADATA/MetaInfoInterface.h>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/composite_key.hpp>
#include <boost/multi_index/member.hpp>
namespace OpenMS
{
namespace IdentificationDataInternal
{
/*!
@brief Representation of an observation, e.g. a spectrum or feature, in an input data file.
*/
struct Observation: public MetaInfoInterface
{
/// Spectrum or feature ID (from the file referenced by @p input_file)
String data_id;
/// Reference to the input file
InputFileRef input_file;
double rt, mz; //< Position
/// Constructor
explicit Observation(
const String& data_id,
const InputFileRef& input_file,
double rt = std::numeric_limits<double>::quiet_NaN(),
double mz = std::numeric_limits<double>::quiet_NaN()):
data_id(data_id), input_file(input_file), rt(rt), mz(mz)
{
}
/// Merge in data from another object
Observation& merge(const Observation& other)
{
// merge meta info - existing entries may be overwritten:
addMetaValues(other);
rt = other.rt;
mz = other.mz;
return *this;
}
};
// combination of input file and data ID must be unique:
typedef boost::multi_index_container<
Observation,
boost::multi_index::indexed_by<
boost::multi_index::ordered_unique<
boost::multi_index::composite_key<
Observation,
boost::multi_index::member<Observation, InputFileRef,
&Observation::input_file>,
boost::multi_index::member<Observation, String,
&Observation::data_id>>>>
> Observations;
typedef IteratorWrapper<Observations::iterator> ObservationRef;
}
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/ID/ParentGroup.h | .h | 1,832 | 60 | // 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/METADATA/ID/ParentSequence.h>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/member.hpp>
namespace OpenMS
{
namespace IdentificationDataInternal
{
/** @brief: Group of ambiguously identified parent sequences (e.g. protein group)
*/
// @TODO: derive from MetaInfoInterface?
struct ParentGroup
{
std::map<ScoreTypeRef, double> scores;
// @TODO: does this need a "leader" or some such?
std::set<ParentSequenceRef> parent_refs;
};
typedef boost::multi_index_container<
ParentGroup,
boost::multi_index::indexed_by<
boost::multi_index::ordered_unique<
boost::multi_index::member<
ParentGroup, std::set<ParentSequenceRef>,
&ParentGroup::parent_refs>>>
> ParentGroups;
typedef IteratorWrapper<ParentGroups::iterator> ParentGroupRef;
/** @brief Set of groups of ambiguously identified parent sequences (e.g. results of running a protein inference algorithm)
*/
struct ParentGroupSet: public ScoredProcessingResult
{
String label; // @TODO: use "label" as a uniqueness constraint?
ParentGroups groups;
explicit ParentGroupSet(
const String& label = "",
const ParentGroups& groups = ParentGroups()):
label(label), groups(groups)
{
}
};
typedef std::vector<ParentGroupSet> ParentGroupSets;
}
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/ID/IdentifiedSequence.h | .h | 3,369 | 103 | // 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/AASequence.h>
#include <OpenMS/CHEMISTRY/NASequence.h>
#include <OpenMS/METADATA/ID/ParentMatch.h>
#include <OpenMS/METADATA/ID/ScoredProcessingResult.h>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/member.hpp>
namespace OpenMS
{
namespace IdentificationDataInternal
{
/// Representation of an identified sequence (peptide or oligonucleotide)
template <typename SeqType>
struct IdentifiedSequence: public ScoredProcessingResult
{
SeqType sequence;
ParentMatches parent_matches;
explicit IdentifiedSequence(
const SeqType& sequence,
const ParentMatches& parent_matches = ParentMatches(),
const AppliedProcessingSteps& steps_and_scores =
AppliedProcessingSteps()):
ScoredProcessingResult(steps_and_scores), sequence(sequence),
parent_matches(parent_matches)
{
}
IdentifiedSequence(const IdentifiedSequence& other) = default;
IdentifiedSequence& merge(const IdentifiedSequence& other)
{
ScoredProcessingResult::merge(other);
// merge parent matches:
for (const auto& pair : other.parent_matches)
{
auto pos = parent_matches.find(pair.first);
if (pos == parent_matches.end()) // new entry
{
parent_matches.insert(pair);
}
else // merge entries
{
pos->second.insert(pair.second.begin(), pair.second.end());
}
}
return *this;
}
bool allParentsAreDecoys() const
{
if (parent_matches.empty())
{
String msg = "no parent found for identified molecule";
throw Exception::MissingInformation(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION, msg);
}
for (const auto& pair : parent_matches)
{
if (!pair.first->is_decoy) return false;
}
return true;
}
};
typedef IdentifiedSequence<AASequence> IdentifiedPeptide;
typedef IdentifiedSequence<NASequence> IdentifiedOligo;
// identified peptides indexed by their sequences:
typedef boost::multi_index_container<
IdentifiedPeptide,
boost::multi_index::indexed_by<
boost::multi_index::ordered_unique<boost::multi_index::member<
IdentifiedPeptide, AASequence, &IdentifiedPeptide::sequence>>>
> IdentifiedPeptides;
typedef IteratorWrapper<IdentifiedPeptides::iterator> IdentifiedPeptideRef;
// identified oligos indexed by their sequences:
typedef boost::multi_index_container<
IdentifiedOligo,
boost::multi_index::indexed_by<
boost::multi_index::ordered_unique<boost::multi_index::member<
IdentifiedOligo, NASequence, &IdentifiedOligo::sequence>>>
> IdentifiedOligos;
typedef IteratorWrapper<IdentifiedOligos::iterator> IdentifiedOligoRef;
}
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/ID/MetaData.h | .h | 1,242 | 54 | // 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 <cstdint> // for "uintptr_t"
namespace OpenMS
{
namespace IdentificationDataInternal
{
/// Wrapper that adds @p operator< to iterators, so they can be used as (part of) keys in maps/sets or @p multi_index_containers
template <typename Iterator>
struct IteratorWrapper: public Iterator
{
IteratorWrapper(): Iterator() {}
IteratorWrapper(const Iterator& it): Iterator(it) {}
bool operator<(const IteratorWrapper& other) const
{
// compare by address of referenced element:
return &(**this) < &(*other);
}
/// Conversion to pointer type for hashing
operator uintptr_t() const
{
return uintptr_t(&(**this));
}
};
enum MoleculeType
{
PROTEIN,
COMPOUND,
RNA
};
enum MassType
{
MONOISOTOPIC,
AVERAGE
};
}
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/ID/ProcessingSoftware.h | .h | 1,593 | 46 | // 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/METADATA/Software.h>
#include <OpenMS/METADATA/ID/ScoreType.h>
namespace OpenMS
{
namespace IdentificationDataInternal
{
/** @brief Information about software used for data processing.
If the same processing is applied to multiple ID runs, e.g. if multiple files (fractions, replicates) are searched with the same search engine, store the software information only once.
*/
struct ProcessingSoftware: public Software
{
/*!
List of score types assigned by this software, ranked by importance.
The "primary" score should be the first in the list.
*/
// @TODO: make this a "list" for cheap "push_front"?
std::vector<ScoreTypeRef> assigned_scores;
explicit ProcessingSoftware(
const String& name = "", const String& version = "",
const std::vector<ScoreTypeRef>& assigned_scores = std::vector<ScoreTypeRef>()):
Software(name, version), assigned_scores(assigned_scores)
{
}
};
// ordering is done using "operator<" inherited from "Software":
typedef std::set<ProcessingSoftware> ProcessingSoftwares;
typedef IteratorWrapper<ProcessingSoftwares::iterator> ProcessingSoftwareRef;
}
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/ID/IdentificationData.h | .h | 28,997 | 719 | // 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/METADATA/ID/ProcessingStep.h>
#include <OpenMS/METADATA/ID/Observation.h>
#include <OpenMS/METADATA/ID/DBSearchParam.h>
#include <OpenMS/METADATA/ID/IdentifiedCompound.h>
#include <OpenMS/METADATA/ID/IdentifiedSequence.h>
#include <OpenMS/METADATA/ID/InputFile.h>
#include <OpenMS/METADATA/ID/MetaData.h>
#include <OpenMS/METADATA/ID/ParentMatch.h>
#include <OpenMS/METADATA/ID/ObservationMatch.h>
#include <OpenMS/METADATA/ID/ParentSequence.h>
#include <OpenMS/METADATA/ID/ParentGroup.h>
#include <OpenMS/METADATA/ID/ObservationMatchGroup.h>
#include <OpenMS/METADATA/ID/ScoreType.h>
#include <unordered_set>
namespace OpenMS
{
/*!
@brief Representation of spectrum identification results and associated data
This class provides capabilities for storing spectrum identification results from different
types of experiments/molecules (proteomics: peptides/proteins, metabolomics: small molecules, "nucleomics": RNA).
The class design has the following goals:
- Provide one structure for storing all relevant data for spectrum identification results.
- Store data non-redundantly.
- Ensure consistency (e.g. no conflicting information; no "dangling references").
- Allow convenient and efficient querying.
- Support different types of experiments, as mentioned above, in one common framework.
The following important subordinate classes are provided to represent different types of data:
<table>
<tr><th>Class <th>Represents <th>Key <th>Proteomics example <th>Corresponding legacy class
<tr><td>ProcessingStep <td>Information about a data processing step that was applied (e.g. input files, software used, parameters) <td>Combined information <td>Mascot search <td>ProteinIdentification
<tr><td>Observation <td>A search query (with identifier, RT, m/z) from an input file, i.e. an MS2 spectrum or feature (for accurate mass search) <td>File/Identifier <td>MS2 spectrum <td>PeptideIdentification
<tr><td>ParentSequence <td>An entry in a FASTA file with associated information (sequence, coverage, etc.) <td>Accession <td>Protein <td>ProteinHit
<tr><td>IdentifiedPeptide/-Oligo/-Compound <td>An identified molecule of the respective type <td>Sequence (or identifier for a compound) <td>Peptide <td>PeptideHit
<tr><td>ObservationMatch <td>A match between a query (Observation), identified molecule (Identified...), and optionally adduct <td>Combination of query/molecule/adduct references <td>Peptide-spectrum match (PSM) <td>PeptideIdentification/PeptideHit
</table>
To populate an IdentificationData instance with data, "register..." functions are used.
These functions return "references" (implemented as iterators) that can be used to refer to stored data items and thus form connections.
For example, a protein can be stored using registerParentSequence, which returns a corresponding reference.
This reference can be used to build an IdentifiedPeptide object that references the protein.
An identified peptide referencing a protein can only be registered if that protein has been registered already, to ensure data consistency.
Given the identified peptide, information about the associated protein can be retrieved efficiently by simply dereferencing the reference.
To ensure non-redundancy, many data types have a "key" (see table above) to which a uniqueness constraint applies.
This means only one item of such a type with a given key can be stored in an IdentificationData object.
If items with an existing key are registered subsequently, attempts are made to merge new information (e.g. additional scores) into the existing entry.
The details of this merging are handled in the @p merge function in each data class.
@warning This class is not thread-safe while being modified.
@ingroup Metadata
*/
/// Remove elements from a set (or ordered multi_index_container) if they fulfill a predicate (manual loop required for non-standard containers that don't support std::erase_if)
template <typename ContainerType, typename PredicateType>
static void removeFromSetIf_(ContainerType& container, PredicateType predicate)
{
for (auto it = container.begin(); it != container.end(); )
{
if (predicate(it))
{
it = container.erase(it);
}
else
{
++it;
}
}
}
class OPENMS_DLLAPI IdentificationData: public MetaInfoInterface
{
public:
// to be able to add overloads and still find the inherited ones
using MetaInfoInterface::setMetaValue;
// type definitions:
using MoleculeType = IdentificationDataInternal::MoleculeType;
using MassType = IdentificationDataInternal::MassType;
using InputFile = IdentificationDataInternal::InputFile;
using InputFiles = IdentificationDataInternal::InputFiles;
using InputFileRef = IdentificationDataInternal::InputFileRef;
using ProcessingSoftware =
IdentificationDataInternal::ProcessingSoftware;
using ProcessingSoftwares =
IdentificationDataInternal::ProcessingSoftwares;
using ProcessingSoftwareRef =
IdentificationDataInternal::ProcessingSoftwareRef;
using ProcessingStep = IdentificationDataInternal::ProcessingStep;
using ProcessingSteps = IdentificationDataInternal::ProcessingSteps;
using ProcessingStepRef = IdentificationDataInternal::ProcessingStepRef;
using DBSearchParam = IdentificationDataInternal::DBSearchParam;
using DBSearchParams = IdentificationDataInternal::DBSearchParams;
using SearchParamRef = IdentificationDataInternal::SearchParamRef;
using DBSearchSteps = IdentificationDataInternal::DBSearchSteps;
using ScoreType = IdentificationDataInternal::ScoreType;
using ScoreTypes = IdentificationDataInternal::ScoreTypes;
using ScoreTypeRef = IdentificationDataInternal::ScoreTypeRef;
using ScoredProcessingResult =
IdentificationDataInternal::ScoredProcessingResult;
using AppliedProcessingStep =
IdentificationDataInternal::AppliedProcessingStep;
using AppliedProcessingSteps =
IdentificationDataInternal::AppliedProcessingSteps;
using Observation = IdentificationDataInternal::Observation;
using Observations = IdentificationDataInternal::Observations;
using ObservationRef = IdentificationDataInternal::ObservationRef;
using ParentSequence = IdentificationDataInternal::ParentSequence;
using ParentSequences = IdentificationDataInternal::ParentSequences;
using ParentSequenceRef = IdentificationDataInternal::ParentSequenceRef;
using ParentMatch = IdentificationDataInternal::ParentMatch;
using ParentMatches = IdentificationDataInternal::ParentMatches;
using IdentifiedPeptide = IdentificationDataInternal::IdentifiedPeptide;
using IdentifiedPeptides = IdentificationDataInternal::IdentifiedPeptides;
using IdentifiedPeptideRef =
IdentificationDataInternal::IdentifiedPeptideRef;
using IdentifiedCompound = IdentificationDataInternal::IdentifiedCompound;
using IdentifiedCompounds = IdentificationDataInternal::IdentifiedCompounds;
using IdentifiedCompoundRef =
IdentificationDataInternal::IdentifiedCompoundRef;
using IdentifiedOligo = IdentificationDataInternal::IdentifiedOligo;
using IdentifiedOligos = IdentificationDataInternal::IdentifiedOligos;
using IdentifiedOligoRef = IdentificationDataInternal::IdentifiedOligoRef;
using IdentifiedMolecule = IdentificationDataInternal::IdentifiedMolecule;
using PeakAnnotations = IdentificationDataInternal::PeakAnnotations;
using Adducts = IdentificationDataInternal::Adducts;
using AdductRef = IdentificationDataInternal::AdductRef;
using AdductOpt = IdentificationDataInternal::AdductOpt;
using ObservationMatch = IdentificationDataInternal::ObservationMatch;
using ObservationMatches = IdentificationDataInternal::ObservationMatches;
using ObservationMatchRef = IdentificationDataInternal::ObservationMatchRef;
// @todo: allow multiple sets of groups, like with parent sequences
// ("ParentGroupSets")?
using ObservationMatchGroup = IdentificationDataInternal::ObservationMatchGroup;
using ObservationMatchGroups = IdentificationDataInternal::ObservationMatchGroups;
using MatchGroupRef = IdentificationDataInternal::MatchGroupRef;
using ParentGroup = IdentificationDataInternal::ParentGroup;
using ParentGroups =
IdentificationDataInternal::ParentGroups;
using ParentGroupRef = IdentificationDataInternal::ParentGroupRef;
using ParentGroupSet =
IdentificationDataInternal::ParentGroupSet;
using ParentGroupSets =
IdentificationDataInternal::ParentGroupSets;
using AddressLookup = std::unordered_set<uintptr_t>;
/// structure that maps references of corresponding objects after copying
struct RefTranslator {
std::map<InputFileRef, InputFileRef> input_file_refs;
std::map<ScoreTypeRef, ScoreTypeRef> score_type_refs;
std::map<ProcessingSoftwareRef, ProcessingSoftwareRef> processing_software_refs;
std::map<SearchParamRef, SearchParamRef> search_param_refs;
std::map<ProcessingStepRef, ProcessingStepRef> processing_step_refs;
std::map<ObservationRef, ObservationRef> observation_refs;
std::map<ParentSequenceRef, ParentSequenceRef> parent_sequence_refs;
std::map<IdentifiedPeptideRef, IdentifiedPeptideRef> identified_peptide_refs;
std::map<IdentifiedOligoRef, IdentifiedOligoRef> identified_oligo_refs;
std::map<IdentifiedCompoundRef, IdentifiedCompoundRef> identified_compound_refs;
std::map<AdductRef, AdductRef> adduct_refs;
std::map<ObservationMatchRef, ObservationMatchRef> observation_match_refs;
bool allow_missing = false;
IdentifiedMolecule translate(IdentifiedMolecule old) const;
ObservationMatchRef translate(ObservationMatchRef old) const;
};
/// Default constructor
IdentificationData():
current_step_ref_(processing_steps_.end()), no_checks_(false)
{
}
/*!
@brief Copy constructor
Copy-constructing is expensive due to the necessary "rewiring" of references.
Use the move constructor where possible.
*/
IdentificationData(const IdentificationData& other);
/*!
@brief Copy assignment operator
*/
IdentificationData& operator=(const IdentificationData& other);
/*!
@brief Move constructor
*/
IdentificationData(IdentificationData&& other) noexcept;
/*!
@brief Move assignment operator
*/
IdentificationData& operator=(IdentificationData&& other) noexcept;
/*!
@brief Register an input file
@return Reference to the registered file
*/
InputFileRef registerInputFile(const InputFile& file);
/*!
@brief Register data processing software
@return Reference to the registered software
*/
ProcessingSoftwareRef registerProcessingSoftware(
const ProcessingSoftware& software);
/*!
@brief Register database search parameters
@return Reference to the registered search parameters
*/
SearchParamRef registerDBSearchParam(const DBSearchParam& param);
/*!
@brief Register a data processing step
@return Reference to the registered processing step
*/
ProcessingStepRef registerProcessingStep(const ProcessingStep&
step);
/*!
@brief Register a database search step with associated parameters
@return Reference to the registered processing step
*/
ProcessingStepRef registerProcessingStep(
const ProcessingStep& step, SearchParamRef search_ref);
/*!
@brief Register a score type
@return Reference to the registered score type
*/
ScoreTypeRef registerScoreType(const ScoreType& score);
/*!
@brief Register an observation (e.g. MS2 spectrum or feature)
@return Reference to the registered observation
*/
ObservationRef registerObservation(const Observation& obs);
/*!
@brief Register a parent sequence (e.g. protein or intact RNA)
@return Reference to the registered parent sequence
*/
ParentSequenceRef registerParentSequence(const ParentSequence& parent);
/// Register a grouping of parent sequences (e.g. protein inference result)
void registerParentGroupSet(const ParentGroupSet& groups);
/*!
@brief Register an identified peptide
@return Reference to the registered peptide
*/
IdentifiedPeptideRef registerIdentifiedPeptide(const IdentifiedPeptide&
peptide);
/*!
@brief Register an identified compound (small molecule)
@return Reference to the registered compound
*/
IdentifiedCompoundRef registerIdentifiedCompound(const IdentifiedCompound&
compound);
/*!
@brief Register an identified RNA oligonucleotide
@return Reference to the registered oligonucleotide
*/
IdentifiedOligoRef registerIdentifiedOligo(const IdentifiedOligo& oligo);
/*!
@brief Register an adduct
@return Reference to the registered adduct
*/
AdductRef registerAdduct(const AdductInfo& adduct);
/*!
@brief Register an observation match (e.g. peptide-spectrum match)
@return Reference to the registered observation match
*/
ObservationMatchRef registerObservationMatch(const ObservationMatch& match);
/*!
@brief Register a group of observation matches that belong together
@return Reference to the registered group of observation matches
*/
MatchGroupRef registerObservationMatchGroup(const ObservationMatchGroup& group);
/// Return the registered input files (immutable)
const InputFiles& getInputFiles() const
{
return input_files_;
}
/// Return the registered data processing software (immutable)
const ProcessingSoftwares& getProcessingSoftwares() const
{
return processing_softwares_;
}
/// Return the registered data processing steps (immutable)
const ProcessingSteps& getProcessingSteps() const
{
return processing_steps_;
}
/// Return the registered database search parameters (immutable)
const DBSearchParams& getDBSearchParams() const
{
return db_search_params_;
}
/// Return the registered database search steps (immutable)
const DBSearchSteps& getDBSearchSteps() const
{
return db_search_steps_;
}
/// Return the registered score types (immutable)
const ScoreTypes& getScoreTypes() const
{
return score_types_;
}
/// Return the registered observations (immutable)
const Observations& getObservations() const
{
return observations_;
}
/// Return the registered parent sequences (immutable)
const ParentSequences& getParentSequences() const
{
return parents_;
}
/// Return the registered parent sequence groupings (immutable)
const ParentGroupSets& getParentGroupSets() const
{
return parent_groups_;
}
/// Return the registered identified peptides (immutable)
const IdentifiedPeptides& getIdentifiedPeptides() const
{
return identified_peptides_;
}
/// Return the registered compounds (immutable)
const IdentifiedCompounds& getIdentifiedCompounds() const
{
return identified_compounds_;
}
/// Return the registered identified oligonucleotides (immutable)
const IdentifiedOligos& getIdentifiedOligos() const
{
return identified_oligos_;
}
/// Return the registered adducts (immutable)
const Adducts& getAdducts() const
{
return adducts_;
}
/// Return the registered observation matches (immutable)
const ObservationMatches& getObservationMatches() const
{
return observation_matches_;
}
/// Return the registered groups of observation matches (immutable)
const ObservationMatchGroups& getObservationMatchGroups() const
{
return observation_match_groups_;
}
/// Add a score to an input match (e.g. PSM)
void addScore(ObservationMatchRef match_ref, ScoreTypeRef score_ref,
double value);
/*!
@brief Set a data processing step that will apply to all subsequent "register..." calls.
This step will be appended to the list of processing steps for all relevant elements that are registered subsequently (unless it is already the last entry in the list).
If a score type without a software reference is registered, the software reference of this processing step will be applied.
Effective until @ref clearCurrentProcessingStep() is called.
*/
void setCurrentProcessingStep(ProcessingStepRef step_ref);
/*!
@brief Return the current processing step (set via @ref setCurrentProcessingStep()).
If no current processing step has been set, @p processing_steps.end() is returned.
*/
ProcessingStepRef getCurrentProcessingStep();
/// Cancel the effect of @ref setCurrentProcessingStep().
void clearCurrentProcessingStep();
/*!
@brief Return the best match for each observation, according to a given score type
@param[in] score_ref Score type to use
@param[in] require_score Exclude matches without score of this type, even if they are the only matches for their observations?
*/
std::vector<ObservationMatchRef> getBestMatchPerObservation(ScoreTypeRef score_ref,
bool require_score = false) const;
// @todo: this currently doesn't take molecule type into account - should it?
/// Get range of matches (cf. @p equal_range) for a given observation
std::pair<ObservationMatchRef, ObservationMatchRef> getMatchesForObservation(ObservationRef obs_ref) const;
/*!
@brief Helper function for filtering observation matches (e.g. PSMs) in IdentificationData
If other parts are invalidated by filtering, the data structure is automatically cleaned up (IdentificationData::cleanup) to remove any invalidated references at the end of this operation.
@param[in] func Functor that returns true for container elements to be removed
*/
template <typename PredicateType>
void removeObservationMatchesIf(PredicateType&& func)
{
auto count = observation_matches_.size();
removeFromSetIf_(observation_matches_, func);
if (count != observation_matches_.size()) cleanup();
}
/*!
@brief Helper function for filtering parent sequences (e.g. protein sequences) in IdentificationData
If other parts are invalidated by filtering, the data structure is automatically cleaned up (IdentificationData::cleanup) to remove any invalidated references at the end of this operation.
@param[in] func Functor that returns true for container elements to be removed
*/
template <typename PredicateType>
void removeParentSequencesIf(PredicateType&& func)
{
auto count = parents_.size();
removeFromSetIf_(parents_, func);
if (count != parents_.size()) cleanup();
}
template <typename PredicateType>
void applyToObservations(PredicateType&& func)
{
for (auto it = observations_.begin(); it != observations_.end(); ++it)
observations_.modify(it, func);
}
/*!
@brief Look up a score type by name.
@return Reference to the score type, if found; otherwise @p getScoreTypes().end()
*/
ScoreTypeRef findScoreType(const String& score_name) const;
/// Calculate sequence coverages of parent sequences
void calculateCoverages(bool check_molecule_length = false);
/*!
@brief Clean up the data structure after filtering parts of it.
Make sure there are no invalid references or "orphan" data entries.
@param[in] require_observation_match Remove identified molecules, observations and adducts that aren't part of observation matches?
@param[in] require_identified_sequence Remove parent sequences (proteins/RNAs) that aren't referenced by identified peptides/oligonucleotides?
@param[in] require_parent_match Remove identified peptides/oligonucleotides that don't reference a parent sequence (protein/RNA)?
@param[in] require_parent_group Remove parent sequences that aren't part of parent sequence groups?
@param[in] require_match_group Remove input matches that aren't part of match groups?
*/
void cleanup(bool require_observation_match = true,
bool require_identified_sequence = true,
bool require_parent_match = true,
bool require_parent_group = false,
bool require_match_group = false);
/// Return whether the data structure is empty (no data)
bool empty() const;
/*!
@brief Merge in data from another instance.
Can be used to make a deep copy by calling merge() on an empty object.
The returned translation table allows updating of references that are held externally.
@param[in] other Instance to merge in.
@return Translation table for references (old -> new)
*/
RefTranslator merge(const IdentificationData& other);
/// Swap contents with a second instance
void swap(IdentificationData& other);
/// Clear all contents
void clear();
/*!
Pick a score type for operations (e.g. filtering) on a container of scored processing results (e.g. input matches, identified peptides, ...).
If @p all_elements is false, only the first element with a score will be considered (which is sufficient if all elements were processed in the same way).
If @p all_elements is true, the score type supported by the highest number of elements will be chosen.
If @p any_score is false, only the primary score from the most recent processing step (that assigned a score) is taken into account.
If @p any_score is true, all score types assigned across all elements are considered (this implies @p all_elements = true).
@param[in] container Container with elements derived from @p ScoredProcessingResult
@param[in] all_elements Consider all elements?
@param[in] any_score Consider any score (or just primary/most recent ones)?
@return Reference to the chosen score type (or @p getScoreTypes().end() if there were no scores)
*/
template <class ScoredProcessingResults>
ScoreTypeRef pickScoreType(const ScoredProcessingResults& container,
bool all_elements = false, bool any_score = false) const
{
std::map<ScoreTypeRef, Size> score_counts;
if (any_score)
{
for (const auto& element : container)
{
for (const auto& step : element.steps_and_scores)
{
for (const auto& pair : step.scores)
{
score_counts[pair.first]++;
}
}
}
}
else
{
for (const auto& element : container)
{
auto score_info = element.getMostRecentScore();
if (std::get<2>(score_info)) // check success indicator
{
ScoreTypeRef score_ref = *std::get<1>(score_info); // unpack the option
if (!all_elements) return score_ref;
score_counts[score_ref]++; // elements are zero-initialized
}
}
}
if (score_counts.empty()) return score_types_.end();
auto pos = max_element(score_counts.begin(), score_counts.end());
// @TODO: break ties according to some criterion
return pos->first;
}
/// Set a meta value on a stored observation match (e.g. PSM)
void setMetaValue(const ObservationMatchRef ref, const String& key, const DataValue& value);
/// Set a meta value on a stored observation
void setMetaValue(const ObservationRef ref, const String& key, const DataValue& value);
/// Set a meta value on a stored identified molecule (variant)
void setMetaValue(const IdentifiedMolecule& var, const String& key, const DataValue& value);
// @TODO: add overloads for other data types derived from MetaInfoInterface
/// Remove a meta value (if it exists) from a stored observation match (e.g. PSM)
/// @todo: return whether value existed? (requires changes in MetaInfo[Interface])
void removeMetaValue(const ObservationMatchRef ref, const String& key);
protected:
// containers:
InputFiles input_files_;
ProcessingSoftwares processing_softwares_;
ProcessingSteps processing_steps_;
DBSearchParams db_search_params_;
// @TODO: store SearchParamRef inside ProcessingStep? (may not be required
// for many processing steps)
DBSearchSteps db_search_steps_;
ScoreTypes score_types_;
Observations observations_;
ParentSequences parents_;
ParentGroupSets parent_groups_;
IdentifiedPeptides identified_peptides_;
IdentifiedCompounds identified_compounds_;
IdentifiedOligos identified_oligos_;
Adducts adducts_;
ObservationMatches observation_matches_;
ObservationMatchGroups observation_match_groups_;
/// Reference to the current data processing step (see @ref setCurrentProcessingStep())
ProcessingStepRef current_step_ref_;
/*!
@brief Suppress validity checks in @p register... calls?
This is useful in situations where validity is already guaranteed (e.g. copying).
*/
bool no_checks_;
// look-up tables for fast checking of reference validity:
AddressLookup observation_lookup_;
AddressLookup parent_lookup_;
// @TODO: just use one "identified_molecule_lookup_" for all molecule types?
AddressLookup identified_peptide_lookup_;
AddressLookup identified_compound_lookup_;
AddressLookup identified_oligo_lookup_;
AddressLookup observation_match_lookup_;
/// Helper function to check if all score types are valid
void checkScoreTypes_(const std::map<ScoreTypeRef, double>& scores) const;
/// Helper function to check if all applied processing steps are valid
void checkAppliedProcessingSteps_(const AppliedProcessingSteps&
steps_and_scores) const;
/// Helper function to check if all parent matches are valid
void checkParentMatches_(const ParentMatches& matches,
MoleculeType expected_type) const;
/*!
@brief Helper function to merge scored processing results while updating references (to processing steps and score types)
@param[in,out] result Instance that gets updated
@param[in] other Instance to merge into @p result
@param[in] trans Mapping of corresponding references between @p other and @p result
*/
void mergeScoredProcessingResults_(ScoredProcessingResult& result,
const ScoredProcessingResult& other,
const RefTranslator& trans);
/*!
@brief Helper functor for adding processing steps to elements in a @p boost::multi_index_container structure
The validity of the processing step reference cannot be checked here!
*/
template <typename ElementType>
struct ModifyMultiIndexAddProcessingStep;
/**
@brief Helper functor for adding scores to elements in a @em boost::multi_index_container structure
The validity of the score type reference cannot be checked here!
*/
template <typename ElementType>
struct ModifyMultiIndexAddScore;
/**
@brief Helper functor for removing invalid parent matches from elements in a @em boost::multi_index_container structure
Used during filtering, to update parent matches after parents have been removed.
*/
template <typename ElementType>
struct ModifyMultiIndexRemoveParentMatches;
/// Helper function for adding entries (derived from ScoredProcessingResult) to a @em boost::multi_index_container structure
template <typename ContainerType, typename ElementType>
typename ContainerType::iterator insertIntoMultiIndex_(ContainerType& container, const ElementType& element);
/// Variant of insertIntoMultiIndex_() that also updates a look-up table of valid references (addresses)
template <typename ContainerType, typename ElementType>
typename ContainerType::iterator insertIntoMultiIndex_(
ContainerType& container, const ElementType& element,
AddressLookup& lookup);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/ID/AppliedProcessingStep.h | .h | 3,612 | 111 | // 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/METADATA/ID/ProcessingStep.h>
#include <OpenMS/METADATA/ID/ScoreType.h>
#include <boost/range/adaptor/reversed.hpp>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/sequenced_index.hpp>
#include <optional>
namespace OpenMS
{
namespace IdentificationDataInternal
{
/*!
A processing step that was applied to a data item, possibly with associated scores.
*/
struct AppliedProcessingStep
{
/*!
@brief (Optional) reference to the processing step
If there are only scores, the processing step may be missing.
*/
std::optional<ProcessingStepRef> processing_step_opt;
/// Map of scores and their types
std::map<ScoreTypeRef, double> scores;
/// Constructor
explicit AppliedProcessingStep(
const std::optional<ProcessingStepRef>& processing_step_opt =
std::nullopt, const std::map<ScoreTypeRef, double>& scores =
std::map<ScoreTypeRef, double>()):
processing_step_opt(processing_step_opt), scores(scores)
{
}
/// Equality operator (needed for multi-index container)
bool operator==(const AppliedProcessingStep& other) const
{
return ((processing_step_opt == other.processing_step_opt) &&
(scores == other.scores));
}
/*!
@brief Return scores in order of priority (primary first).
The order is defined in the @p ProcessingSoftware referenced by the processing step (if available).
Scores not listed there are included at the end of the output.
@param[in] primary_only Only return the primary score (ignoring any others)?
*/
std::vector<std::pair<ScoreTypeRef, double>>
getScoresInOrder(bool primary_only = false) const
{
std::vector<std::pair<ScoreTypeRef, double>> result;
std::set<ScoreTypeRef> scores_done;
if (processing_step_opt)
{
ProcessingSoftwareRef sw_ref = (*processing_step_opt)->software_ref;
for (ScoreTypeRef score_ref : sw_ref->assigned_scores)
{
auto pos = scores.find(score_ref);
if (pos != scores.end())
{
result.push_back(*pos);
if (primary_only) return result;
scores_done.insert(score_ref);
}
}
}
for (const auto& pair: scores)
{
if (!scores_done.count(pair.first))
{
result.push_back(pair);
if (primary_only) return result;
}
}
return result;
}
};
// we want to keep track of the processing steps in sequence (order of
// application), but also ensure there are no duplicate steps:
typedef boost::multi_index_container<
AppliedProcessingStep,
boost::multi_index::indexed_by<
boost::multi_index::sequenced<>,
boost::multi_index::ordered_unique<
boost::multi_index::member<
AppliedProcessingStep, std::optional<ProcessingStepRef>,
&AppliedProcessingStep::processing_step_opt>>>
> AppliedProcessingSteps;
}
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/ID/ObservationMatchGroup.h | .h | 2,573 | 77 | // 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/METADATA/ID/ObservationMatch.h>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
namespace OpenMS
{
namespace IdentificationDataInternal
{
/** @brief: Group of related (co-identified) input matches
E.g. for cross-linking data or multiplexed spectra.
*/
struct ObservationMatchGroup: public ScoredProcessingResult
{
std::set<ObservationMatchRef> observation_match_refs;
bool allSameMolecule() const
{
// @TODO: return true or false for the empty set?
if (observation_match_refs.size() <= 1) return true;
const IdentifiedMolecule var =
(*observation_match_refs.begin())->identified_molecule_var;
for (auto it = ++observation_match_refs.begin();
it != observation_match_refs.end(); ++it)
{
if (!((*it)->identified_molecule_var == var)) return false;
}
return true;
}
bool allSameQuery() const
{
// @TODO: return true or false for the empty set?
if (observation_match_refs.size() <= 1) return true;
ObservationRef ref = (*observation_match_refs.begin())->observation_ref;
for (auto it = ++observation_match_refs.begin();
it != observation_match_refs.end(); ++it)
{
if ((*it)->observation_ref != ref) return false;
}
return true;
}
bool operator==(const ObservationMatchGroup& rhs) const
{
return ((rhs.observation_match_refs == observation_match_refs) &&
(rhs.steps_and_scores == steps_and_scores));
}
bool operator!=(const ObservationMatchGroup& rhs) const
{
return !operator==(rhs);
}
};
typedef boost::multi_index_container<
ObservationMatchGroup,
boost::multi_index::indexed_by<
boost::multi_index::ordered_unique<
boost::multi_index::member<ObservationMatchGroup, std::set<ObservationMatchRef>,
&ObservationMatchGroup::observation_match_refs>>>
> ObservationMatchGroups;
typedef IteratorWrapper<ObservationMatchGroups::iterator> MatchGroupRef;
}
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/ID/ObservationMatch.h | .h | 4,912 | 129 | // 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/METADATA/ID/Observation.h>
#include <OpenMS/METADATA/ID/MetaData.h>
#include <OpenMS/METADATA/ID/IdentifiedMolecule.h>
#include <OpenMS/METADATA/PeptideHit.h> // for "PeakAnnotation"
#include <OpenMS/CHEMISTRY/AdductInfo.h>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/composite_key.hpp>
namespace OpenMS
{
namespace IdentificationDataInternal
{
// @TODO: move "PeakAnnotation" out of "PeptideHit"
typedef std::vector<PeptideHit::PeakAnnotation> PeakAnnotations;
typedef std::map<std::optional<ProcessingStepRef>,
PeakAnnotations> PeakAnnotationSteps;
/// Comparator for adducts
// @TODO: this allows adducts with duplicate names, but requires different
// sum formulas/charges - is this what we want?
struct AdductCompare
{
bool operator()(const AdductInfo& left, const AdductInfo& right) const
{
return (std::make_pair(left.getCharge(), left.getEmpiricalFormula()) <
std::make_pair(right.getCharge(), right.getEmpiricalFormula()));
}
};
typedef std::set<AdductInfo, AdductCompare> Adducts;
typedef IteratorWrapper<Adducts::iterator> AdductRef;
typedef std::optional<AdductRef> AdductOpt;
/// Representation of a search hit (e.g. peptide-spectrum match).
struct ObservationMatch: public ScoredProcessingResult
{
IdentifiedMolecule identified_molecule_var;
ObservationRef observation_ref;
Int charge;
AdductOpt adduct_opt; ///< optional reference to adduct
// peak annotations (fragment ion matches), potentially from different
// data processing steps:
PeakAnnotationSteps peak_annotations;
explicit ObservationMatch(
IdentifiedMolecule identified_molecule_var,
ObservationRef observation_ref, Int charge = 0,
const std::optional<AdductRef>& adduct_opt = std::nullopt,
const AppliedProcessingSteps& steps_and_scores = AppliedProcessingSteps(),
const PeakAnnotationSteps& peak_annotations = PeakAnnotationSteps()):
ScoredProcessingResult(steps_and_scores),
identified_molecule_var(identified_molecule_var),
observation_ref(observation_ref), charge(charge), adduct_opt(adduct_opt),
peak_annotations(peak_annotations)
{
}
ObservationMatch(const ObservationMatch&) = default;
ObservationMatch& merge(const ObservationMatch& other)
{
ScoredProcessingResult::merge(other);
if (charge == 0)
{
charge = other.charge;
}
else if (charge != other.charge)
{
throw Exception::InvalidValue(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION,
"Trying to overwrite ObservationMatch charge with conflicting value.",
String(charge));
}
if (!adduct_opt)
{
adduct_opt = other.adduct_opt;
}
else if (adduct_opt != other.adduct_opt)
{
throw Exception::InvalidValue(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION,
"Trying to overwrite ObservationMatch adduct_opt with conflicting value.",
(*adduct_opt)->getName());
}
peak_annotations.insert(other.peak_annotations.begin(),
other.peak_annotations.end());
return *this;
}
};
// all matches for the same observation should be consecutive, so make sure
// the observation is used as the first member in the composite key:
typedef boost::multi_index_container<
ObservationMatch,
boost::multi_index::indexed_by<
boost::multi_index::ordered_unique<
boost::multi_index::composite_key<
ObservationMatch,
boost::multi_index::member<ObservationMatch, ObservationRef,
&ObservationMatch::observation_ref>,
boost::multi_index::member<
ObservationMatch, IdentifiedMolecule,
&ObservationMatch::identified_molecule_var>,
boost::multi_index::member<ObservationMatch, AdductOpt,
&ObservationMatch::adduct_opt>>>>
> ObservationMatches;
typedef IteratorWrapper<ObservationMatches::iterator> ObservationMatchRef;
}
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/ID/ParentMatch.h | .h | 2,857 | 79 | // 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/METADATA/ID/ParentSequence.h>
namespace OpenMS
{
namespace IdentificationDataInternal
{
/** @brief Meta data for the association between an identified molecule (e.g. peptide) and a parent sequence (e.g. protein).
*/
struct ParentMatch: public MetaInfoInterface
{
// in extraordinary cases (e.g. database searches that allow insertions/
// deletions), the length of the identified molecule may differ from the
// length of the subsequence in the parent; therefore, store "end_pos":
Size start_pos, end_pos;
// String instead of char so modified residues can be represented:
String left_neighbor, right_neighbor; // neighboring sequence elements
static constexpr Size UNKNOWN_POSITION = Size(-1);
static constexpr char UNKNOWN_NEIGHBOR = 'X';
static constexpr char LEFT_TERMINUS = '[';
static constexpr char RIGHT_TERMINUS = ']';
explicit ParentMatch(Size start_pos = UNKNOWN_POSITION,
Size end_pos = UNKNOWN_POSITION,
String left_neighbor = UNKNOWN_NEIGHBOR,
String right_neighbor = UNKNOWN_NEIGHBOR):
start_pos(start_pos), end_pos(end_pos), left_neighbor(left_neighbor),
right_neighbor(right_neighbor)
{
}
bool operator<(const ParentMatch& other) const
{
// positions determine neighbors - no need to compare those:
return (std::tie(start_pos, end_pos) <
std::tie(other.start_pos, other.end_pos));
}
bool operator==(const ParentMatch& other) const
{
// positions determine neighbors - no need to compare those:
return (std::tie(start_pos, end_pos) ==
std::tie(other.start_pos, other.end_pos));
}
bool hasValidPositions(Size molecule_length = 0, Size parent_length = 0) const
{
if ((start_pos == UNKNOWN_POSITION) || (end_pos == UNKNOWN_POSITION))
{
return false;
}
if (end_pos < start_pos) return false;
if (molecule_length && (end_pos - start_pos + 1 != molecule_length))
{
return false;
}
if (parent_length && (end_pos >= parent_length)) return false;
return true;
}
};
/// mapping: parent sequence -> match information
typedef std::map<ParentSequenceRef,
std::set<ParentMatch>> ParentMatches;
}
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/ID/ScoredProcessingResult.h | .h | 6,882 | 204 | // 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/METADATA/ID/AppliedProcessingStep.h>
namespace OpenMS
{
namespace IdentificationDataInternal
{
/// Base class for ID data with scores and processing steps (and meta info)
struct ScoredProcessingResult: public MetaInfoInterface
{
AppliedProcessingSteps steps_and_scores;
/// Return the applied processing steps (incl. scores) as a set ordered by processing step reference (option)
AppliedProcessingSteps::nth_index<1>::type& getStepsAndScoresByStep()
{
return steps_and_scores.get<1>();
}
/// Return the applied processing steps (incl. scores) as a set ordered by processing step reference (option) - const variant
const AppliedProcessingSteps::nth_index<1>::type&
getStepsAndScoresByStep() const
{
return steps_and_scores.get<1>();
}
/*!
@brief Add an applied processing step
If the step already exists, scores are merged (existing ones updated).
*/
void addProcessingStep(const AppliedProcessingStep& step)
{
auto step_pos =
steps_and_scores.get<1>().find(step.processing_step_opt);
if (step_pos == steps_and_scores.get<1>().end()) // new step
{
steps_and_scores.push_back(step);
}
else // existing step - add or update scores
{
steps_and_scores.get<1>().modify(
step_pos, [&](AppliedProcessingStep& old_step)
{
for (const auto& pair : step.scores)
{
old_step.scores[pair.first] = pair.second;
}
});
}
}
/// Add a processing step (and associated scores, if any)
void addProcessingStep(ProcessingStepRef step_ref,
const std::map<ScoreTypeRef, double>& scores =
std::map<ScoreTypeRef, double>())
{
AppliedProcessingStep applied(step_ref, scores);
addProcessingStep(applied);
}
/// Add a score (possibly connected to a processing step)
void addScore(ScoreTypeRef score_type, double score,
const std::optional<ProcessingStepRef>&
processing_step_opt = std::nullopt)
{
AppliedProcessingStep applied(processing_step_opt);
applied.scores[score_type] = score;
addProcessingStep(applied);
}
/// Merge in data from another object
ScoredProcessingResult& merge(const ScoredProcessingResult& other)
{
// merge applied processing steps and scores:
for (const auto& step : other.steps_and_scores)
{
addProcessingStep(step);
}
// merge meta info - existing entries may be overwritten:
addMetaValues(other);
return *this;
}
/*!
@brief Look up a score by score type
All processing steps are considered, in "most recent first" order.
@return A pair: score (or NaN), success indicator
*/
std::pair<double, bool> getScore(ScoreTypeRef score_ref) const
{
std::tuple<double, std::optional<ProcessingStepRef>, bool> result =
getScoreAndStep(score_ref);
return std::make_pair(std::get<0>(result), std::get<2>(result));
}
/*!
@brief Look up a score by score type and processing step
@return A pair: score (or NaN), success indicator
*/
std::pair<double, bool> getScore(ScoreTypeRef score_ref,
std::optional<ProcessingStepRef>
processing_step_opt) const
{
auto step_pos = steps_and_scores.get<1>().find(processing_step_opt);
if (step_pos != steps_and_scores.get<1>().end())
{
auto score_pos = step_pos->scores.find(score_ref);
if (score_pos != step_pos->scores.end())
{
return std::make_pair(score_pos->second, true);
}
}
// not found:
return std::make_pair(std::numeric_limits<double>::quiet_NaN(), false);
}
/*!
@brief Look up a score and associated processing step by score type
All processing steps are considered, in "most recent first" order.
@return A tuple: score (or NaN), processing step reference (option), success indicator
*/
std::tuple<double, std::optional<ProcessingStepRef>, bool>
getScoreAndStep(ScoreTypeRef score_ref) const
{
// give priority to scores from later processing steps:
for (const auto& step : boost::adaptors::reverse(steps_and_scores))
{
auto pos = step.scores.find(score_ref);
if (pos != step.scores.end())
{
return std::make_tuple(pos->second, step.processing_step_opt, true);
}
}
// not found:
return std::make_tuple(std::numeric_limits<double>::quiet_NaN(),
std::nullopt, false);
}
/*!
@brief Get the (primary) score from the most recent processing step
This will fail if no scores have been assigned.
@return A tuple: score (or NaN), score type reference (option), success indicator
*/
std::tuple<double, std::optional<ScoreTypeRef>, bool>
getMostRecentScore() const
{
// check steps starting with most recent:
for (const auto& step : boost::adaptors::reverse(steps_and_scores))
{
auto top_score = step.getScoresInOrder(true);
if (!top_score.empty())
{
return std::make_tuple(top_score[0].second, top_score[0].first,
true);
}
}
return std::make_tuple(std::numeric_limits<double>::quiet_NaN(),
std::nullopt, false); // no score available
}
/// Return the number of scores associated with this result
Size getNumberOfScores() const
{
Size counter = 0;
for (const auto& step : steps_and_scores)
{
counter += step.scores.size();
}
return counter;
}
protected:
/// Constructor
explicit ScoredProcessingResult(
const AppliedProcessingSteps& steps_and_scores =
AppliedProcessingSteps()):
steps_and_scores(steps_and_scores)
{
}
/// Copy c'tor
ScoredProcessingResult(const ScoredProcessingResult&) = default;
};
}
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/ID/ParentSequence.h | .h | 3,571 | 99 | // 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/METADATA/ID/ScoredProcessingResult.h>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/member.hpp>
namespace OpenMS
{
namespace IdentificationDataInternal
{
/** @brief Representation of a parent sequence that is identified only indirectly (e.g. a protein).
*/
struct ParentSequence: public ScoredProcessingResult
{
String accession;
enum MoleculeType molecule_type;
// @TODO: if there are modifications in the sequence, "sequence.size()"
// etc. will be misleading!
String sequence;
String description;
double coverage; ///< sequence coverage as a fraction between 0 and 1
bool is_decoy;
explicit ParentSequence(
const String& accession,
MoleculeType molecule_type = MoleculeType::PROTEIN,
const String& sequence = "", const String& description = "",
double coverage = 0.0, bool is_decoy = false,
const AppliedProcessingSteps& steps_and_scores = AppliedProcessingSteps()):
ScoredProcessingResult(steps_and_scores), accession(accession),
molecule_type(molecule_type), sequence(sequence),
description(description), coverage(coverage), is_decoy(is_decoy)
{
}
ParentSequence(const ParentSequence&) = default;
ParentSequence& merge(const ParentSequence& other)
{
ScoredProcessingResult::merge(other);
if (sequence.empty())
{
sequence = other.sequence;
}
else if (!other.sequence.empty() && sequence != other.sequence) // differ and none is empty
{
throw Exception::InvalidValue(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION,
"Trying to overwrite ParentSequence sequence '" + sequence + "' with conflicting value.",
other.sequence);
}
if (description.empty())
{
description = other.description;
}
else if (!other.description.empty() && description != other.description) // differ and none is empty
{
throw Exception::InvalidValue(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION,
"Trying to overwrite ParentSequence description '" + description + "' with conflicting value.",
other.description);
}
if (!is_decoy) is_decoy = other.is_decoy; // believe it when it's set
// @TODO: what about coverage? (not reliable if we're merging data)
return *this;
}
};
// parent sequences indexed by their accessions:
// @TODO: allow querying/iterating over proteins and RNAs separately
typedef boost::multi_index_container<
ParentSequence,
boost::multi_index::indexed_by<
boost::multi_index::ordered_unique<boost::multi_index::member<
ParentSequence, String, &ParentSequence::accession>>>
> ParentSequences;
typedef IteratorWrapper<ParentSequences::iterator> ParentSequenceRef;
}
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/ID/ProcessingStep.h | .h | 2,347 | 67 | // 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/METADATA/DataProcessing.h>
#include <OpenMS/METADATA/ID/ProcessingSoftware.h>
#include <OpenMS/METADATA/ID/InputFile.h>
namespace OpenMS
{
namespace IdentificationDataInternal
{
/** @brief Data processing step that is applied to the data (e.g. database search, PEP calculation, filtering, ConsensusID).
*/
struct ProcessingStep: public MetaInfoInterface
{
ProcessingSoftwareRef software_ref;
std::vector<InputFileRef> input_file_refs;
DateTime date_time;
// @TODO: add processing actions that are relevant for ID data
std::set<DataProcessing::ProcessingAction> actions;
explicit ProcessingStep(
ProcessingSoftwareRef software_ref,
const std::vector<InputFileRef>& input_file_refs = std::vector<InputFileRef>(),
const DateTime& date_time = DateTime::now(),
const std::set<DataProcessing::ProcessingAction>& actions = std::set<DataProcessing::ProcessingAction>())
:
software_ref(software_ref), input_file_refs(input_file_refs),
date_time(date_time), actions(actions)
{
}
ProcessingStep(const ProcessingStep& other) = default;
// order by date/time first, don't compare meta data (?):
bool operator<(const ProcessingStep& other) const
{
return (std::tie(date_time, software_ref, input_file_refs, actions) <
std::tie(other.date_time, other.software_ref,
other.input_file_refs, other.actions));
}
// don't compare meta data (?):
bool operator==(const ProcessingStep& other) const
{
return (std::tie(software_ref, input_file_refs, date_time, actions) ==
std::tie(other.software_ref, other.input_file_refs,
other.date_time, other.actions));
}
};
typedef std::set<ProcessingStep> ProcessingSteps;
typedef IteratorWrapper<ProcessingSteps::iterator> ProcessingStepRef;
}
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/ID/ScoreType.h | .h | 1,888 | 69 | // 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/METADATA/ID/MetaData.h>
namespace OpenMS
{
namespace IdentificationDataInternal
{
/** @brief Information about a score type.
*/
struct ScoreType: public MetaInfoInterface
{
CVTerm cv_term; // @TODO: derive from CVTerm instead?
bool higher_better;
ScoreType():
higher_better(true)
{
}
explicit ScoreType(const CVTerm& cv_term, bool higher_better):
cv_term(cv_term), higher_better(higher_better)
{
}
explicit ScoreType(const String& name, bool higher_better):
cv_term(), higher_better(higher_better)
{
cv_term.setName(name);
}
ScoreType(const ScoreType& other) = default;
// don't include "higher_better" in the comparison:
bool operator<(const ScoreType& other) const
{
// @TODO: implement/use "CVTerm::operator<"?
return (std::tie(cv_term.getAccession(), cv_term.getName()) <
std::tie(other.cv_term.getAccession(),
other.cv_term.getName()));
}
// don't include "higher_better" in the comparison:
bool operator==(const ScoreType& other) const
{
return cv_term == other.cv_term;
}
bool isBetterScore(double first, double second) const
{
if (higher_better) return first > second;
return first < second;
}
};
typedef std::set<ScoreType> ScoreTypes;
typedef IteratorWrapper<ScoreTypes::iterator> ScoreTypeRef;
}
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/ID/DBSearchParam.h | .h | 4,304 | 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/DigestionEnzyme.h>
#include <OpenMS/CHEMISTRY/EnzymaticDigestion.h>
#include <OpenMS/METADATA/ID/MetaData.h>
namespace OpenMS
{
namespace IdentificationDataInternal
{
/** @brief Parameters specific to a database search step.
*/
struct DBSearchParam: public MetaInfoInterface
{
enum MoleculeType molecule_type;
enum MassType mass_type;
String database;
String database_version;
String taxonomy;
std::set<Int> charges;
std::set<String> fixed_mods;
std::set<String> variable_mods;
double precursor_mass_tolerance;
double fragment_mass_tolerance;
bool precursor_tolerance_ppm;
bool fragment_tolerance_ppm;
// allow for either "DigestionEnzymeProtein" or "DigestionEnzymeRNA":
const DigestionEnzyme* digestion_enzyme;
EnzymaticDigestion::Specificity enzyme_term_specificity;
Size missed_cleavages;
Size min_length;
Size max_length;
DBSearchParam():
molecule_type(MoleculeType::PROTEIN),
mass_type(MassType::MONOISOTOPIC),
precursor_mass_tolerance(0.0), fragment_mass_tolerance(0.0),
precursor_tolerance_ppm(false), fragment_tolerance_ppm(false),
digestion_enzyme(nullptr), enzyme_term_specificity(EnzymaticDigestion::SPEC_UNKNOWN),
missed_cleavages(0), min_length(0), max_length(0)
{
}
DBSearchParam(const DBSearchParam& other) = default;
bool operator<(const DBSearchParam& other) const
{
return (std::tie(molecule_type, mass_type,
database, database_version, taxonomy,
charges, fixed_mods, variable_mods,
precursor_mass_tolerance, fragment_mass_tolerance,
precursor_tolerance_ppm, fragment_tolerance_ppm,
digestion_enzyme, enzyme_term_specificity, missed_cleavages,
min_length, max_length) <
std::tie(other.molecule_type, other.mass_type,
other.database, other.database_version, other.taxonomy,
other.charges, other.fixed_mods, other.variable_mods,
other.precursor_mass_tolerance, other.fragment_mass_tolerance,
other.precursor_tolerance_ppm, other.fragment_tolerance_ppm,
other.digestion_enzyme, other.enzyme_term_specificity, other.missed_cleavages,
other.min_length, other.max_length));
}
bool operator==(const DBSearchParam& other) const
{
return (std::tie(molecule_type, mass_type, database,
database_version, taxonomy, charges, fixed_mods,
variable_mods, fragment_mass_tolerance,
precursor_mass_tolerance, fragment_tolerance_ppm,
precursor_tolerance_ppm, digestion_enzyme, enzyme_term_specificity,
missed_cleavages, min_length, max_length) ==
std::tie(other.molecule_type, other.mass_type,
other.database, other.database_version, other.taxonomy,
other.charges, other.fixed_mods, other.variable_mods,
other.fragment_mass_tolerance,
other.precursor_mass_tolerance,
other.fragment_tolerance_ppm,
other.precursor_tolerance_ppm,
other.digestion_enzyme, other.enzyme_term_specificity,
other.missed_cleavages,
other.min_length, other.max_length));
}
};
typedef std::set<DBSearchParam> DBSearchParams;
typedef IteratorWrapper<DBSearchParams::iterator> SearchParamRef;
typedef std::map<ProcessingStepRef, SearchParamRef> DBSearchSteps;
}
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/ID/IdentifiedMolecule.h | .h | 1,903 | 59 | // 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/METADATA/ID/MetaData.h>
#include <OpenMS/METADATA/ID/IdentifiedCompound.h>
#include <OpenMS/METADATA/ID/IdentifiedSequence.h>
#include <OpenMS/CHEMISTRY/EmpiricalFormula.h>
#include <variant>
namespace OpenMS
{
namespace IdentificationDataInternal
{
typedef std::variant<IdentifiedPeptideRef, IdentifiedCompoundRef,
IdentifiedOligoRef> RefVariant;
/**
@brief Variant type holding Peptide/Compound/Oligo references and convenience functions.
**/
struct OPENMS_DLLAPI IdentifiedMolecule: public RefVariant
{
IdentifiedMolecule() = default;
IdentifiedMolecule(IdentifiedPeptideRef ref): RefVariant(ref) {};
IdentifiedMolecule(IdentifiedCompoundRef ref): RefVariant(ref) {};
IdentifiedMolecule(IdentifiedOligoRef ref): RefVariant(ref) {};
IdentifiedMolecule(const IdentifiedMolecule&) = default;
MoleculeType getMoleculeType() const;
IdentifiedPeptideRef getIdentifiedPeptideRef() const;
IdentifiedCompoundRef getIdentifiedCompoundRef() const;
IdentifiedOligoRef getIdentifiedOligoRef() const;
String toString() const;
EmpiricalFormula getFormula(Size fragment_type = 0, Int charge = 0) const;
};
OPENMS_DLLAPI bool operator==(const IdentifiedMolecule& a, const IdentifiedMolecule& b);
OPENMS_DLLAPI bool operator!=(const IdentifiedMolecule& a, const IdentifiedMolecule& b);
OPENMS_DLLAPI bool operator<(const IdentifiedMolecule& a, const IdentifiedMolecule& b);
}
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/ID/InputFile.h | .h | 2,333 | 73 | // 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 <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/member.hpp>
#include <set>
namespace OpenMS
{
namespace IdentificationDataInternal
{
/// Information about input files that were processed
struct InputFile
{
String name;
String experimental_design_id;
std::set<String> primary_files;
explicit InputFile(const String& name,
const String& experimental_design_id = "",
const std::set<String>& primary_files =
std::set<String>()):
name(name), experimental_design_id(experimental_design_id),
primary_files(primary_files)
{
}
InputFile(const InputFile& other) = default;
/// Merge in data from another object
InputFile& merge(const InputFile& other)
{
if (experimental_design_id.empty())
{
experimental_design_id = other.experimental_design_id;
}
else if (!other.experimental_design_id.empty() && experimental_design_id != other.experimental_design_id)
{
throw Exception::InvalidValue(__FILE__, __LINE__,
OPENMS_PRETTY_FUNCTION,
"Trying to overwrite InputFile experimental design id with conflicting value.",
experimental_design_id);
}
primary_files.insert(other.primary_files.begin(),
other.primary_files.end());
return *this;
}
};
typedef boost::multi_index_container<
InputFile,
boost::multi_index::indexed_by<
boost::multi_index::ordered_unique<boost::multi_index::member<
InputFile, String, &InputFile::name>>>
> InputFiles;
typedef IteratorWrapper<InputFiles::iterator> InputFileRef;
}
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/ID/IdentifiedCompound.h | .h | 1,817 | 58 | // 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/METADATA/ID/ScoredProcessingResult.h>
#include <OpenMS/CHEMISTRY/EmpiricalFormula.h>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/member.hpp>
namespace OpenMS
{
namespace IdentificationDataInternal
{
struct IdentifiedCompound: public ScoredProcessingResult
{
String identifier;
EmpiricalFormula formula;
String name;
String smile;
String inchi;
explicit IdentifiedCompound(
const String& identifier,
const EmpiricalFormula& formula = EmpiricalFormula(),
const String& name = "", const String& smile = "",
const String& inchi = "", const AppliedProcessingSteps&
steps_and_scores = AppliedProcessingSteps()):
ScoredProcessingResult(steps_and_scores), identifier(identifier),
formula(formula), name(name), smile(smile), inchi(inchi)
{
}
IdentifiedCompound(const IdentifiedCompound& other) = default;
};
// identified compounds indexed by their identifiers:
typedef boost::multi_index_container<
IdentifiedCompound,
boost::multi_index::indexed_by<
boost::multi_index::ordered_unique<boost::multi_index::member<
IdentifiedCompound, String, &IdentifiedCompound::identifier>>>
> IdentifiedCompounds;
typedef IteratorWrapper<IdentifiedCompounds::iterator> IdentifiedCompoundRef;
}
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/METADATA/ID/IdentificationDataConverter.h | .h | 11,588 | 292 | // 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/METADATA/ID/IdentificationData.h>
#include <OpenMS/FORMAT/FASTAFile.h>
#include <OpenMS/FORMAT/MzTab.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <OpenMS/METADATA/ProteinIdentification.h>
namespace OpenMS
{
class FeatureMap;
class OPENMS_DLLAPI IdentificationDataConverter
{
public:
/// Import from legacy peptide/protein identifications
static void importIDs(IdentificationData& id_data,
const std::vector<ProteinIdentification>& proteins,
const PeptideIdentificationList& peptides);
/*!
@brief Export to legacy peptide/protein identifications
Results are added to existing data (if any) in @p proteins and @p peptides.
*/
static void exportIDs(const IdentificationData& id_data,
std::vector<ProteinIdentification>& proteins,
PeptideIdentificationList& peptides,
bool export_ids_wo_scores = false);
/// Export to mzTab format
static MzTab exportMzTab(const IdentificationData& id_data);
/// Import FASTA sequences as parent sequences
static void importSequences(IdentificationData& id_data,
const std::vector<FASTAFile::FASTAEntry>& fasta,
IdentificationData::MoleculeType type =
IdentificationData::MoleculeType::PROTEIN,
const String& decoy_pattern = "");
/// Convert parent matches to peptide evidences
static void exportParentMatches(
const IdentificationData::ParentMatches& parent_matches, PeptideHit& hit);
/*!
@brief Convert IDs from legacy peptide/protein identifications in a feature map
@param[in,out] features Feature map containing IDs in legacy format
@param[in] clear_original Clear original IDs after conversion?
*/
static void importFeatureIDs(FeatureMap& features, bool clear_original = true);
/*!
@brief Convert IDs in a feature map to legacy peptide/protein identifications
@param[in,out] features Feature map containing IDs in new format
@param[in] clear_original Clear original IDs after conversion?
*/
static void exportFeatureIDs(FeatureMap& features, bool clear_original = true);
/*!
@brief Convert IDs from legacy peptide/protein identifications in a consensus map
@param[in,out] consensus Consensus map containing IDs in legacy format
@param[in] clear_original Clear original IDs after conversion?
*/
static void importConsensusIDs(ConsensusMap& consensus, bool clear_original = true);
/*!
@brief Convert IDs in a consensus map to legacy peptide/protein identifications
@param[in,out] consensus Consensus map containing IDs in new format
@param[in] clear_original Clear original IDs after conversion?
*/
static void exportConsensusIDs(ConsensusMap& consensus, bool clear_original = true);
protected:
using StepOpt = std::optional<IdentificationData::ProcessingStepRef>;
/// Functor for ordering @p StepOpt (by date of the steps, if available):
struct StepOptCompare
{
bool operator()(const StepOpt& left, const StepOpt& right) const
{
// @TODO: should runs without associated step go first or last?
if (!left) return bool(right);
if (!right) return false;
return **left < **right;
}
};
/// Functor for ordering peptide IDs by RT and m/z (if available)
struct PepIDCompare
{
bool operator()(const PeptideIdentification& left,
const PeptideIdentification& right) const
{
// @TODO: should IDs without RT go first or last?
if (left.hasRT())
{
if (right.hasRT())
{
if (right.getRT() != left.getRT())
{
return left.getRT() < right.getRT();
} // else: compare by m/z (below)
}
else
{
return false;
}
}
else if (right.hasRT())
{
return true;
}
// no RTs or same RTs -> try to compare by m/z:
if (left.hasMZ())
{
if (right.hasMZ())
{
return left.getMZ() < right.getMZ();
}
else
{
return false;
}
}
// if both PI's have nothing, return false (to ensure 'x < x' is false for strict weak ordering)
return right.hasMZ();
}
};
/// Export a parent sequence (protein or nucleic acid) to mzTab
template <typename MzTabSectionRow>
static void exportParentSequenceToMzTab_(
const IdentificationData::ParentSequence& parent,
std::vector<MzTabSectionRow>& output,
std::map<IdentificationData::ScoreTypeRef, Size>& score_map)
{
MzTabSectionRow row;
row.accession.set(parent.accession);
exportStepsAndScoresToMzTab_(parent.steps_and_scores, row.search_engine,
row.best_search_engine_score, score_map);
row.description.set(parent.description);
row.coverage.set(parent.coverage);
if (!parent.sequence.empty())
{
MzTabOptionalColumnEntry opt_seq;
opt_seq.first = "opt_sequence";
opt_seq.second.set(parent.sequence);
row.opt_.push_back(opt_seq);
}
output.push_back(row);
}
/// Export an identified sequence (peptide or oligonucleotide, but not small molecule/compound) to mzTab
template <typename MzTabSectionRow, typename IdentSeq>
static void exportPeptideOrOligoToMzTab_(
const IdentSeq& identified, std::vector<MzTabSectionRow>& output,
std::map<IdentificationData::ScoreTypeRef, Size>& score_map)
{
MzTabSectionRow row;
// @TODO: handle modifications properly
row.sequence.set(identified.sequence.toString());
exportStepsAndScoresToMzTab_(identified.steps_and_scores,
row.search_engine,
row.best_search_engine_score, score_map);
if (identified.parent_matches.empty()) // no parent information given
{
// row.unique.set(false); // leave this unset?
output.push_back(row);
}
else // generate entries (with duplicated data) for every accession
{
// in mzTab, "unique" means "peptide is unique for this protein"
row.unique.set(identified.parent_matches.size() == 1);
for (const auto& match_pair : identified.parent_matches)
{
row.accession.set(match_pair.first->accession);
for (const IdentificationData::ParentMatch& match :
match_pair.second)
{
MzTabSectionRow copy = row;
addMzTabMoleculeParentContext_(match, copy);
output.push_back(copy);
}
}
}
}
/// Export an input match (peptide- or oligonucleotide-spectrum match) to mzTab
template <typename MzTabSectionRow>
static void exportObservationMatchToMzTab_(
const String& sequence,
const IdentificationData::ObservationMatch& match, double calc_mass,
std::vector<MzTabSectionRow>& output,
std::map<IdentificationData::ScoreTypeRef, Size>& score_map,
std::map<IdentificationData::InputFileRef, Size>& file_map)
{
MzTabSectionRow xsm; // PSM or OSM
// @TODO: handle modifications properly
xsm.sequence.set(sequence);
exportStepsAndScoresToMzTab_(match.steps_and_scores, xsm.search_engine,
xsm.search_engine_score, score_map);
const IdentificationData::Observation& query = *match.observation_ref;
std::vector<MzTabDouble> rts(1);
rts[0].set(query.rt);
xsm.retention_time.set(rts);
xsm.charge.set(match.charge);
xsm.exp_mass_to_charge.set(query.mz);
xsm.calc_mass_to_charge.set(calc_mass / abs(match.charge));
xsm.spectra_ref.setMSFile(file_map[query.input_file]);
xsm.spectra_ref.setSpecRef(query.data_id);
// optional column for adduct:
if (match.adduct_opt)
{
MzTabOptionalColumnEntry opt_adduct;
opt_adduct.first = "opt_adduct";
opt_adduct.second.set((*match.adduct_opt)->getName());
xsm.opt_.push_back(opt_adduct);
}
// optional columns for isotope offset:
// @TODO: find a way of passing in the names of relevant meta values
// (e.g. from NucleicAcidSearchEngine), instead of hard-coding them here
if (match.metaValueExists("isotope_offset"))
{
MzTabOptionalColumnEntry opt_meta;
opt_meta.first = "opt_isotope_offset";
opt_meta.second.set(match.getMetaValue("isotope_offset"));
xsm.opt_.push_back(opt_meta);
}
// don't repeat data from the peptide section (e.g. accessions)
// why are "pre"/"post"/"start"/"end" not in the peptide section?!
output.push_back(xsm);
}
/// Helper function to add processing steps (search engines) and their scores to MzTab
static void exportStepsAndScoresToMzTab_(
const IdentificationData::AppliedProcessingSteps& steps_and_scores,
MzTabParameterList& steps_out, std::map<Size, MzTabDouble>& scores_out,
std::map<IdentificationData::ScoreTypeRef, Size>& score_map);
/// Helper function to add search engine score entries to MzTab's meta data section
static void addMzTabSEScores_(
const std::map<IdentificationData::ScoreTypeRef, Size>& scores,
std::map<Size, MzTabParameter>& output);
/// Helper function for @ref exportPeptideOrOligoToMzTab_() - oligonucleotide variant
static void addMzTabMoleculeParentContext_(
const IdentificationData::ParentMatch& match,
MzTabOligonucleotideSectionRow& row);
/// Helper function for @ref exportPeptideOrOligoToMzTab_() - peptide variant
static void addMzTabMoleculeParentContext_(
const IdentificationData::ParentMatch& match,
MzTabPeptideSectionRow& row);
/// Helper function to import DB search parameters from legacy format
static IdentificationData::SearchParamRef importDBSearchParameters_(
const ProteinIdentification::SearchParameters& pisp,
IdentificationData& id_data);
/// Helper function to export DB search parameters to legacy format
static ProteinIdentification::SearchParameters exportDBSearchParameters_(
IdentificationData::SearchParamRef ref);
/// Helper function to export (primary) MS run information to legacy format
static void exportMSRunInformation_(
IdentificationData::ProcessingStepRef step_ref,
ProteinIdentification& protein);
static void handleFeatureImport_(Feature& feature, const IntList& indexes,
PeptideIdentificationList& peptides,
Size& id_counter, bool clear_original);
static void handleFeatureExport_(Feature& feature, const IntList& indexes,
IdentificationData& id_data, Size& id_counter);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/SYSTEM/ExternalProcess.h | .h | 4,260 | 102 | // 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
// OpenMS_GUI config
#include <OpenMS/DATASTRUCTURES/String.h>
#include <QtCore/QObject>
#include <functional> // for std::function
#include <map> // for std::map
class QProcess; // forward declare to avoid header include
class QString;
#include <QtCore/qcontainerfwd.h> // for QStringList
namespace OpenMS
{
/**
@brief A wrapper around QProcess to conveniently start an external program and forward its outputs
Use the custom Ctor to provide callback functions for stdout/stderr output or set them via setCallbacks().
Running an external program blocks the caller, so do not use this in a main GUI thread
(unless you have some other means to tell the user that no interaction is possible at the moment).
If you want QMessageBoxes to be shown if something went wrong, use ExternalProcessMBox as a convenient wrapper instead.
*/
class OPENMS_DLLAPI ExternalProcess
: public QObject
{
Q_OBJECT
public:
/// result of calling an external executable
enum class RETURNSTATE
{
SUCCESS, ///< everything went smoothly (exit-code = 0)
NONZERO_EXIT, /// finished, but returned with an exit-code other than 0
CRASH, ///< ran, but crashed (segfault etc)
FAILED_TO_START ///< executable not found or not enough access rights for user
};
/// Open mode for the process.
enum class IO_MODE
{
NO_IO, ///< No read nor write access
READ_ONLY,
WRITE_ONLY,
READ_WRITE
};
/// default Ctor; callbacks for stdout/stderr are empty
ExternalProcess();
/// set the callback functions to process stdout and stderr output when the external process generates it
ExternalProcess(std::function<void(const String&)> callbackStdOut, std::function<void(const String&)> callbackStdErr);
/// D'tor
~ExternalProcess() override ;
/// re-wire the callbacks used during run()
void setCallbacks(std::function<void(const String&)> callbackStdOut, std::function<void(const String&)> callbackStdErr);
/**
@brief Runs a program and calls the callback functions from time to time if output from the external program is available.
@param[in] exe The program to call (can contain spaces in path, no problem)
@param[in] args A list of extra arguments (can be empty)
@param[in] working_dir Execute the external process in the given directory (relevant when relative input/output paths are given). Leave empty to use the current working directory.
@param[in] verbose Report the call command and errors via the callbacks (default: false)
@param[out] error_msg Message to display to the user if something went wrong (if return != SUCCESS)
@param[in] io_mode Open mode for the process (read access, write access, ...)
@param[in] env Additional environment variables to pass to the process (key-value pairs). These will be added to the system environment.
@return Did the external program succeed (SUCCESS) or did something go wrong?
*/
RETURNSTATE run(const QString& exe, const QStringList& args, const QString& working_dir, const bool verbose, String& error_msg, IO_MODE io_mode = IO_MODE::READ_WRITE, const std::map<QString, QString>& env = std::map<QString, QString>());
/**
@brief Same as other overload, just without a returned error message
*/
ExternalProcess::RETURNSTATE run(const QString& exe, const QStringList& args, const QString& working_dir, const bool verbose, IO_MODE io_mode = IO_MODE::READ_WRITE, const std::map<QString, QString>& env = std::map<QString, QString>());
private slots:
void processStdOut_();
void processStdErr_();
private:
QProcess* qp_; ///< pointer to avoid including the QProcess header here (it's huge)
std::function<void(const String&)> callbackStdOut_;
std::function<void(const String&)> callbackStdErr_;
};
} // ns OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/SYSTEM/PythonInfo.h | .h | 2,396 | 66 | // 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/config.h>
namespace OpenMS
{
class String;
/**
@brief Detect Python and retrieve information.
Similar classes exist for other external tools, e.g. JavaInfo .
@ingroup System
*/
class OPENMS_DLLAPI PythonInfo
{
public:
/**
@brief Determine if Python is installed and executable
The call fails if either Python is not installed or if a relative location is given and Python is not on the search PATH.
If Python is found, the executable name will be modified to the absolute path.
If Python is not found, an error message will be put into @p error_msg
@param[in,out] python_executable Path to Python executable. Can be absolute, relative or just a filename
@param[out] error_msg On error, contains detailed error description (e.g.
@return Returns false if Python executable can not be called; true if Python executable can be executed
**/
static bool canRun(String& python_executable, String& error_msg);
/**
@brief Determine if the Python given in @p python_executable has the package @p package_name already installed
If Python cannot be found, the function will just return false.
Thus, make sure that PythonInfo::canRun() succeeds before calling this function.
@param[in] python_executable As determined by canRun()...
@param[in] package_name The package you want to test (mind lower/upper case!)
@return true if package is installed
*/
static bool isPackageInstalled(const String& python_executable, const String& package_name);
/**
@brief Determine the version of Python given in @p python_executable by calling '--version'
If Python cannot be found, the function will return the empty string.
Thus, make sure that PythonInfo::canRun() succeeds before calling this function.
@param[in] python_executable As determined by canRun()...
@return the output of 'python --version'
*/
static String getVersion(const String& python_executable);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/SYSTEM/NetworkGetRequest.h | .h | 1,947 | 84 | // 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/config.h>
#include <QtCore/QObject>
#include <QtCore/QString>
#include <QtCore/QUrl>
#include <QtNetwork/QNetworkReply>
namespace OpenMS
{
class NetworkGetRequest :
public QObject
{
Q_OBJECT
public:
/** @name Constructors and destructors
*/
//@{
/// default constructor
OPENMS_DLLAPI NetworkGetRequest(QObject* parent = nullptr);
/// destructor
OPENMS_DLLAPI ~NetworkGetRequest() override;
//@}
// set request parameters
OPENMS_DLLAPI void setUrl(const QUrl& url);
/// returns the response
OPENMS_DLLAPI QString getResponse() const;
/// returns the response
OPENMS_DLLAPI const QByteArray& getResponseBinary() const;
/// returns true if an error occurred during the query
OPENMS_DLLAPI bool hasError() const;
/// returns the error message, if hasError can be used to check whether an error has occurred
OPENMS_DLLAPI QString getErrorString() const;
protected:
public slots:
OPENMS_DLLAPI void run();
OPENMS_DLLAPI void timeOut();
private slots:
OPENMS_DLLAPI void replyFinished(QNetworkReply*);
signals:
OPENMS_DLLAPI void done();
private:
/// assignment operator
OPENMS_DLLAPI NetworkGetRequest& operator=(const NetworkGetRequest& rhs);
/// copy constructor
OPENMS_DLLAPI NetworkGetRequest(const NetworkGetRequest& rhs);
QByteArray response_bytes_;
QUrl url_;
QNetworkAccessManager* manager_;
QNetworkReply* reply_;
QNetworkReply::NetworkError error_;
QString error_string_;
};
}
| Unknown |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.