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/CHEMISTRY/ISOTOPEDISTRIBUTION/IsotopeDistribution.h | .h | 7,895 | 236 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Clemens Groepl, Andreas Bertsch, Chris Bielow $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/Peak1D.h>
#include <OpenMS/CONCEPT/HashUtils.h>
#include <functional>
#include <vector>
namespace OpenMS
{
/**
@ingroup Chemistry
@brief Isotope distribution class
A container that holds an isotope distribution. It consists of mass values
and their correspondent probabilities (stored in the intensity slot).
Isotope distributions can be calculated using either the
CoarseIsotopePatternGenerator for quantized atomic masses which group
isotopes with the same atomic number. Alternatively, the
FineIsotopePatternGenerator can be used that calculates hyperfine isotopic
distributions.
@note: This class only describes the container that holds the isotopic
distribution, calculations are done using classes derived from
IsotopePatternGenerator.
*/
class Element;
class OPENMS_DLLAPI IsotopeDistribution
{
public:
/// @name typedefs
//@{
/// container type, first holds the weight of the isotope, second the probability
typedef Peak1D MassAbundance;
typedef std::vector<MassAbundance> ContainerType;
typedef ContainerType::iterator iterator;
typedef ContainerType::iterator Iterator;
typedef ContainerType::const_iterator const_iterator;
typedef ContainerType::const_iterator ConstIterator;
typedef ContainerType::reverse_iterator reverse_iterator;
typedef ContainerType::reverse_iterator ReverseIterator;
typedef ContainerType::const_reverse_iterator const_reverse_iterator;
typedef ContainerType::const_reverse_iterator ConstReverseIterator;
//@}
enum Sorted {INTENSITY, MASS, UNDEFINED};
/// @name Constructors and Destructors
//@{
/** Default constructor
*/
IsotopeDistribution();
/// Copy constructor
IsotopeDistribution(const IsotopeDistribution&) = default;
/// Move constructor
IsotopeDistribution(IsotopeDistribution&&) noexcept = default;
/// Destructor
virtual ~IsotopeDistribution() = default;
//@}
/// @name Accessors
//@{
/// overwrites the container which holds the distribution using @p distribution
void set(const ContainerType & distribution);
/// overwrites the container which holds the distribution using @p distribution
void set(ContainerType && distribution);
/// returns the container which holds the distribution
const ContainerType & getContainer() const;
/// returns the isotope with the largest m/z
Peak1D::CoordinateType getMax() const;
/// returns the isotope with the smallest m/z
Peak1D::CoordinateType getMin() const;
/// returns the most abundant isotope which is stored in the distribution
Peak1D getMostAbundant() const;
/// returns the size of the distribution which is the number of isotopes in the distribution
Size size() const;
/// clears the distribution
void clear();
// resizes distribution container
void resize(UInt size);
/// remove intensities below the cutoff
void trimIntensities(double cutoff);
/// sort isotope distribution by intensity
void sortByIntensity();
/// sort isotope distribution by mass
void sortByMass();
/** @brief Re-normalizes the sum of the probabilities of all the isotopes to 1
The re-normalisation may be needed as in some distributions with a lot
of isotopes the calculations tend to be inexact.
*/
void renormalize();
/** @brief Merges distributions of arbitrary data points with constant defined resolution.
It creates a new IsotopeDistribution Container and assigns each isotope to the nearest bin.
This function should be used to downsample the existing distribution.
If the size of the new Container is larger this function throws an IllegalArgument Exception.
*/
void merge(double resolution, double min_prob);
/** @brief Trims the right side of the isotope distribution to isotopes with a significant contribution.
If the isotope distribution is calculated for large masses, it might
happen that many entries contain only small numbers. This function can
be used to remove these entries.
@note Consider normalising the distribution afterwards.
*/
void trimRight(double cutoff);
/** @brief Trims the left side of the isotope distribution to isotopes with a significant contribution.
If the isotope distribution is calculated for large masses, it might
happen that many entries contain only small numbers. This function can
be used to remove these entries.
@note Consider normalising the distribution afterwards.
*/
void trimLeft(double cutoff);
/// Compute average mass of isotope distribution (weighted average of all isotopes)
double averageMass() const;
//@}
/// @name Operators
//@{
/// Assignment operator
IsotopeDistribution & operator=(const IsotopeDistribution & isotope_distribution);
/// equality operator, returns true if the @p isotope_distribution is identical to this, false else
bool operator==(const IsotopeDistribution & isotope_distribution) const;
/// inequality operator, returns true if the @p isotope_distribution differs from this, false else
bool operator!=(const IsotopeDistribution & isotope_distribution) const;
/// less operator
bool operator<(const IsotopeDistribution & isotope_distribution) const;
//@}
/// @name Iterators
//@{
inline Iterator begin() { return distribution_.begin(); }
inline Iterator end() { return distribution_.end(); }
inline ConstIterator begin() const { return distribution_.begin(); }
inline ConstIterator end() const { return distribution_.end(); }
inline ReverseIterator rbegin() { return distribution_.rbegin(); }
inline ReverseIterator rend() { return distribution_.rend(); }
inline ConstReverseIterator rbegin() const { return distribution_.rbegin(); }
inline ConstReverseIterator rend() const { return distribution_.rend(); }
inline void insert(const Peak1D::CoordinateType& mass, const Peak1D::IntensityType& intensity)
{
distribution_.push_back(Peak1D(mass, intensity));
}
//@}
/// @name Data Access Operators
//@{
/// operator to access a cell of the distribution and wraps it in SpectrumFragment struct
Peak1D& operator[](const Size& index){ return distribution_[index];}
/// const operator to access a cell of the distribution and wraps it in SpectrumFragment struct
const Peak1D& operator[](const Size& index) const { return distribution_[index]; }
//@}
protected:
/// sort wrapper of the distribution
void sort_(std::function<bool(const MassAbundance& p1, const MassAbundance& p2)> sorter);
/// takes a function as a parameter to transform the distribution
void transform_(std::function<void(MassAbundance&)> lambda);
/// stores the isotope distribution
ContainerType distribution_;
};
} // namespace OpenMS
// Hash function specialization for IsotopeDistribution
namespace std
{
template<>
struct hash<OpenMS::IsotopeDistribution>
{
std::size_t operator()(const OpenMS::IsotopeDistribution& id) const noexcept
{
std::size_t seed = OpenMS::hash_int(id.size());
for (const auto& peak : id)
{
OpenMS::hash_combine(seed, std::hash<OpenMS::Peak1D>{}(peak));
}
return seed;
}
};
} // namespace std
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FEATUREFINDER/MultiplexFilteringCentroided.h | .h | 3,249 | 73 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Lars Nilse $
// $Authors: Lars Nilse $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/BaseFeature.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/PROCESSING/CENTROIDING/PeakPickerHiRes.h>
#include <OpenMS/FEATUREFINDER/MultiplexIsotopicPeakPattern.h>
#include <OpenMS/FEATUREFINDER/MultiplexFiltering.h>
#include <OpenMS/FEATUREFINDER/MultiplexFilteredPeak.h>
#include <OpenMS/FEATUREFINDER/MultiplexFilteredMSExperiment.h>
#include <OpenMS/MATH/MISC/CubicSpline2d.h>
#include <vector>
#include <algorithm>
#include <iostream>
namespace OpenMS
{
/**
* @brief filters centroided data for peak patterns
*
* The algorithm searches for patterns of multiple peptides in the data.
* The peptides appear as characteristic patterns of isotopic peaks in
* MS1 spectra. We search the centroided data for such patterns.
* For each peak pattern the algorithm generates a filter result.
*
* @see MultiplexIsotopicPeakPattern
* @see MultiplexFilterResult
* @see MultiplexFiltering
*/
class OPENMS_DLLAPI MultiplexFilteringCentroided :
public MultiplexFiltering
{
public:
/**
* @brief constructor
*
* @param[in] exp_centroided experimental data in centroid mode
* @param[in] patterns patterns of isotopic peaks to be searched for
* @param[in] isotopes_per_peptide_min minimum number of isotopic peaks in peptides
* @param[in] isotopes_per_peptide_max maximum number of isotopic peaks in peptides
* @param[in] intensity_cutoff intensity cutoff
* @param[in] rt_band RT range for filtering
* @param[in] mz_tolerance error margin in m/z for matching expected patterns to experimental data
* @param[in] mz_tolerance_unit unit for mz_tolerance, ppm (true), Da (false)
* @param[in] peptide_similarity similarity score for two peptides in the same multiplet
* @param[in] averagine_similarity similarity score for peptide isotope pattern and averagine model
* @param[in] averagine_similarity_scaling scaling factor x for the averagine similarity parameter p when detecting peptide singlets. With p' = p + x(1-p).
* @param[in] averagine_type The averagine model to use, current options are RNA DNA or peptide.
*/
MultiplexFilteringCentroided(const MSExperiment& exp_centroided, const std::vector<MultiplexIsotopicPeakPattern>& patterns, int isotopes_per_peptide_min, int isotopes_per_peptide_max, double intensity_cutoff, double rt_band, double mz_tolerance, bool mz_tolerance_unit, double peptide_similarity, double averagine_similarity, double averagine_similarity_scaling, String averagine_type="peptide");
/**
* @brief filter for patterns
* (generates a filter result for each of the patterns)
*
* @see MultiplexIsotopicPeakPattern, MultiplexFilterResult
*/
std::vector<MultiplexFilteredMSExperiment> filter();
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FEATUREFINDER/EmgScoring.h | .h | 6,546 | 186 | // 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/FEATUREFINDER/EmgFitter1D.h>
#include <OpenMS/FEATUREFINDER/EmgModel.h>
#include <OpenMS/PROCESSING/SMOOTHING/GaussFilter.h>
#include <OpenMS/KERNEL/MRMFeature.h>
#include <OpenMS/KERNEL/MRMTransitionGroup.h>
#include <OpenMS/KERNEL/MSSpectrum.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <vector>
#include <cmath> // for isnan
namespace OpenMS
{
/**
@brief Scoring of an elution peak using an exponentially modified gaussian distribution model.
This class uses the original ideas from FeatureFinderAlgorithmMRM to
construct an interface that allows scoring of chromatographic peaks.
*/
class EmgScoring
{
public :
EmgScoring() = default;
~EmgScoring() = default;
/// overwrites params for the Emg1DFitter. Unspecified params will stay default.
/// use getDefaults to see what you can set.
void setFitterParam(const Param& param)
{
fitter_emg1D_params_ = param;
}
/// Get default params for the Emg1D fitting
Param getDefaults()
{
return EmgFitter1D().getDefaults();
}
/// calculate the elution profile fit score
template<typename SpectrumType, class TransitionT>
double calcElutionFitScore(MRMFeature & mrmfeature, MRMTransitionGroup<SpectrumType, TransitionT> & transition_group) const
{
double avg_score = 0;
bool smooth_data = false;
for (Size k = 0; k < transition_group.size(); k++)
{
// get the id, then find the corresponding transition and features within this peakgroup
String native_id = transition_group.getChromatograms()[k].getNativeID();
Feature f = mrmfeature.getFeature(native_id);
OPENMS_PRECONDITION(f.getConvexHulls().size() == 1, "Convex hulls need to have exactly one hull point structure");
//TODO think about penalizing aborted fits even more. Currently -1 is just the "lowest" pearson correlation to
// a fit that you can have.
double fscore = elutionModelFit(f.getConvexHulls()[0].getHullPoints(), smooth_data);
avg_score += fscore;
}
avg_score /= transition_group.size();
return avg_score;
}
// Fxn from FeatureFinderAlgorithmMRM
// TODO: check whether we can leave out some of the steps here, e.g. gaussian smoothing
double elutionModelFit(const ConvexHull2D::PointArrayType& current_section, bool smooth_data) const
{
// We need at least 2 datapoints in order to create a fit
if (current_section.size() < 2)
{
return -1;
}
// local PeakType is a small hack since here we *need* data of type
// Peak1D, otherwise our fitter will not accept it.
typedef Peak1D LocalPeakType;
// -- cut line 301 of FeatureFinderAlgorithmMRM
std::vector<LocalPeakType> data_to_fit;
prepareFit_(current_section, data_to_fit, smooth_data);
std::unique_ptr<InterpolationModel> model_rt;
double quality = fitRT_(data_to_fit, model_rt);
// cut line 354 of FeatureFinderAlgorithmMRM
return quality;
}
protected:
template<class LocalPeakType>
double fitRT_(std::vector<LocalPeakType>& rt_input_data, std::unique_ptr<InterpolationModel>& model) const
{
EmgFitter1D fitter_emg1D;
fitter_emg1D.setParameters(fitter_emg1D_params_);
// Construct model for rt
// NaN is checked in fit1d: if (std::isnan(quality)) quality = -1.0;
return fitter_emg1D.fit1d(rt_input_data, model);
}
// Fxn from FeatureFinderAlgorithmMRM
// TODO: check whether we can leave out some of the steps here, e.g. gaussian smoothing
template<class LocalPeakType>
void prepareFit_(const ConvexHull2D::PointArrayType & current_section, std::vector<LocalPeakType> & data_to_fit, bool smooth_data) const
{
// typedef Peak1D LocalPeakType;
PeakSpectrum filter_spec;
// first smooth the data to prevent outliers from destroying the fit
for (const auto& pa : current_section)
{
LocalPeakType p;
using IntensityType = typename LocalPeakType::IntensityType;
p.setMZ(pa.getX());
p.setIntensity(IntensityType(pa.getY()));
filter_spec.push_back(p);
}
// add two peaks at the beginning and at the end for better fit
// therefore calculate average distance first
std::vector<double> distances;
for (Size j = 1; j < filter_spec.size(); ++j)
{
distances.push_back(filter_spec[j].getMZ() - filter_spec[j - 1].getMZ());
}
double dist_average = std::accumulate(distances.begin(), distances.end(), 0.0) / (double) distances.size();
// append peaks
Peak1D new_peak;
new_peak.setIntensity(0);
new_peak.setMZ(filter_spec.back().getMZ() + dist_average);
filter_spec.push_back(new_peak);
new_peak.setMZ(filter_spec.back().getMZ() + dist_average);
filter_spec.push_back(new_peak);
new_peak.setMZ(filter_spec.back().getMZ() + dist_average);
filter_spec.push_back(new_peak);
// prepend peaks
new_peak.setMZ(filter_spec.front().getMZ() - dist_average);
filter_spec.insert(filter_spec.begin(), new_peak);
new_peak.setMZ(filter_spec.front().getMZ() - dist_average);
filter_spec.insert(filter_spec.begin(), new_peak);
new_peak.setMZ(filter_spec.front().getMZ() - dist_average);
filter_spec.insert(filter_spec.begin(), new_peak);
// To get an estimate of the peak quality, we probably should not smooth
// and/or transform the data.
if (smooth_data)
{
GaussFilter filter;
Param filter_param(filter.getParameters());
filter.setParameters(filter_param);
filter_param.setValue("gaussian_width", 4 * dist_average);
filter.setParameters(filter_param);
filter.filter(filter_spec);
}
// transform the data for fitting and fit RT profile
for (Size j = 0; j != filter_spec.size(); ++j)
{
LocalPeakType p;
p.setPosition(filter_spec[j].getMZ());
p.setIntensity(filter_spec[j].getIntensity());
data_to_fit.push_back(p);
}
}
Param fitter_emg1D_params_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FEATUREFINDER/GaussTraceFitter.h | .h | 2,528 | 96 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg$
// $Authors: Stephan Aiche, Marc Sturm$
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/FEATUREFINDER/TraceFitter.h>
namespace OpenMS
{
/**
* @brief Fitter for RT profiles using a Gaussian background model
*
* @htmlinclude OpenMS_GaussTraceFitter.parameters
*
* @todo More docu
*/
class OPENMS_DLLAPI GaussTraceFitter :
public TraceFitter
{
public:
GaussTraceFitter();
GaussTraceFitter(const GaussTraceFitter& other);
GaussTraceFitter& operator=(const GaussTraceFitter& source);
~GaussTraceFitter() override;
// override important methods
void fit(FeatureFinderAlgorithmPickedHelperStructs::MassTraces& traces) override;
double getLowerRTBound() const override;
double getUpperRTBound() const override;
double getHeight() const override;
double getCenter() const override;
double getFWHM() const override;
/**
* @brief Returns the sigma of the fitted gaussian model
*/
double getSigma() const;
bool checkMaximalRTSpan(const double max_rt_span) override;
bool checkMinimalRTSpan(const std::pair<double, double>& rt_bounds, const double min_rt_span) override;
double getValue(double rt) const override;
double getArea() override;
String getGnuplotFormula(const FeatureFinderAlgorithmPickedHelperStructs::MassTrace& trace, const char function_name, const double baseline, const double rt_shift) override;
protected:
double sigma_;
double x0_;
double height_;
double region_rt_span_;
static const Size NUM_PARAMS_;
void getOptimizedParameters_(const std::vector<double>& s) override;
class GaussTraceFunctor :
public TraceFitter::GenericFunctor
{
public:
GaussTraceFunctor(int dimensions,
const TraceFitter::ModelData* data);
int operator()(const double* x, double* fvec) override;
// compute Jacobian matrix for the different parameters
int df(const double* x, double* J) override;
protected:
const TraceFitter::ModelData* m_data;
};
void setInitialParameters_(FeatureFinderAlgorithmPickedHelperStructs::MassTraces& traces);
void updateMembers_() override;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FEATUREFINDER/FeatureFinderAlgorithmPicked.h | .h | 16,461 | 365 | // 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/MSExperiment.h>
#include <OpenMS/FEATUREFINDER/FeatureFinderAlgorithmPickedHelperStructs.h>
#include <OpenMS/FEATUREFINDER/TraceFitter.h>
#include <OpenMS/DATASTRUCTURES/IsotopeCluster.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/CONCEPT/GlobalExceptionHandler.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <fstream>
namespace OpenMS
{
/**@brief The purpose of this struct is to provide definitions of classes and typedefs which are used throughout all FeatureFinder classes. */
struct OPENMS_DLLAPI FeatureFinderDefs
{
/// Index to peak consisting of two UInts (scan index / peak index)
typedef IsotopeCluster::IndexPair IndexPair;
/// Index to peak consisting of two UInts (scan index / peak index) with charge information
typedef IsotopeCluster::ChargedIndexSet ChargedIndexSet;
/// A set of peak indices
typedef IsotopeCluster::IndexSet IndexSet;
/// Flags that indicate if a peak is already used in a feature
enum Flag {UNUSED, USED};
/// Exception that is thrown if a method an invalid IndexPair is given
class OPENMS_DLLAPI NoSuccessor :
public Exception::BaseException
{
public:
NoSuccessor(const char * file, int line, const char * function, const IndexPair & index) :
BaseException(file, line, function, "NoSuccessor", String("there is no successor/predecessor for the given Index: ") + String(index.first) + "/" + String(index.second)),
index_(index)
{
Exception::GlobalExceptionHandler::setMessage(what());
}
~NoSuccessor() noexcept override = default;
protected:
IndexPair index_; // index without successor/predecessor
};
};
/**
@brief FeatureFinderAlgorithm for picked peaks.
This module identifies "features" in a LC/MS map. By feature, we understand a peptide in an MS sample that
reveals a characteristic isotope distribution over time. The algorithm
computes positions in RT and m/z dimension and a charge estimate
of each peptide.
The algorithm identifies pronounced regions of the data around so-called <tt>seeds</tt>.
The user can provide a list of seeds (e.g. from an identification run of MS/MS spectra) or the algorithm can compute seeds itself.
In the next step, we iteratively fit a model of the isotope profile and the retention time to
the initial seed data points. Data points with a low probability under this model are removed from the
feature region. The intensity of the feature is then given by the sum of the data points included
in its regions.
How to find suitable parameters and details of the different algorithms implemented are described
in the "TOPP tutorial" (on https://openms.readthedocs.io/).
@htmlinclude OpenMS_FeatureFinderAlgorithmPicked.parameters
@improvement RT model with tailing/fronting (Marc)
@improvement More general MZ model - e.g. based on co-elution or with sulfur-averagines (Marc)
@todo Fix output in parallel mode, change assignment of charges to threads, add parallel TOPP test (Marc)
@todo Implement user-specified seed lists support (Marc)
@ingroup FeatureFinder
*/
class OPENMS_DLLAPI FeatureFinderAlgorithmPicked :
public DefaultParamHandler, public ProgressLogger
{
public:
/// @name Type definitions
//@{
typedef MSExperiment MapType;
typedef MapType::SpectrumType SpectrumType;
typedef SpectrumType::FloatDataArrays FloatDataArrays;
//@}
protected:
typedef Peak1D PeakType;
typedef FeatureFinderAlgorithmPickedHelperStructs::Seed Seed;
typedef FeatureFinderAlgorithmPickedHelperStructs::MassTrace MassTrace;
typedef FeatureFinderAlgorithmPickedHelperStructs::MassTraces MassTraces;
typedef FeatureFinderAlgorithmPickedHelperStructs::TheoreticalIsotopePattern TheoreticalIsotopePattern;
typedef FeatureFinderAlgorithmPickedHelperStructs::IsotopePattern IsotopePattern;
public:
/// default constructor
FeatureFinderAlgorithmPicked();
void setSeeds(const FeatureMap& seeds);
void setData(const MSExperiment& map, FeatureMap& features);
/**
@brief Main method of the FeatureFinderAlgorithmPicked.
@note The input map has to be sorted by RT and m/z. If this is not the case, the algorithm will sort the input data internally.
@note The algorithm will not work on profile data and throw an exception.
@note: The algorithm will not work on data with negative m/z values and throw an exception.
@note: the input data will be copied internally (leading to a memory overhead).
@param[in] input_map The input map of centroided spectra with MS level 1.
@param[out] features The output feature map.
@param[in] param The parameters for the algorithm.
@param[in] seeds The seeds that should be used for the feature finding. Provide an empty feature map if you want the algorithm to find seeds.
*/
void run(PeakMap& input_map,
FeatureMap& features,
const Param& param,
const FeatureMap& seeds);
virtual Param getDefaultParameters() const
{
return defaults_;
}
protected:
void run();
/// editable copy of the map
MapType map_;
FeatureMap* features_;
/// Output stream for log/debug info
mutable std::ofstream log_;
/// debug flag
bool debug_;
/// Array of abort reasons
std::map<String, UInt> aborts_;
/// Array of abort reasons
std::map<Seed, String> abort_reasons_;
/// User-specified seed list
FeatureMap seeds_;
/// @name Members for parameters often needed in methods
//@{
double pattern_tolerance_; ///< Stores mass_trace:mz_tolerance
double trace_tolerance_; ///< Stores isotopic_pattern:mz_tolerance
UInt min_spectra_; ///< Number of spectra that have to show the same mass (for finding a mass trace)
UInt max_missing_trace_peaks_; ///< Stores mass_trace:max_missing
double slope_bound_; ///< Max slope of mass trace intensities
double intensity_percentage_; ///< Isotope pattern intensity contribution of required peaks
double intensity_percentage_optional_; ///< Isotope pattern intensity contribution of optional peaks
double optional_fit_improvement_; ///< Minimal improvement for leaving out optional isotope
double mass_window_width_; ///< Width of the isotope pattern mass bins
UInt intensity_bins_; ///< Number of bins (in RT and MZ) for intensity significance estimation
double min_isotope_fit_; ///< Minimum isotope pattern fit for a feature
double min_trace_score_; ///< Minimum quality of a traces
double min_rt_span_; ///< Minimum RT range that has to be left after the fit
double max_rt_span_; ///< Maximum RT range the model is allowed to span
double max_feature_intersection_; ///< Maximum allowed feature intersection (if larger, that one of the feature is removed)
String reported_mz_; ///< The mass type that is reported for features. 'maximum' returns the m/z value of the highest mass trace. 'average' returns the intensity-weighted average m/z value of all contained peaks. 'monoisotopic' returns the monoisotopic m/z value derived from the fitted isotope model.
//@}
/// @name Members for intensity significance estimation
//@{
/// RT bin width
double intensity_rt_step_;
/// m/z bin width
double intensity_mz_step_;
/// Precalculated intensity 20-quantiles (binned)
std::vector<std::vector<std::vector<double> > > intensity_thresholds_;
//@}
///Vector of precalculated isotope distributions for several mass windows
std::vector<TheoreticalIsotopePattern> isotope_distributions_;
// Docu in base class
void updateMembers_() override;
/// Writes the abort reason to the log file and counts occurrences for each reason
void abort_(const Seed& seed, const String& reason);
/**
* Calculates the intersection between features.
* The value is normalized by the size of the smaller feature, so it ranges from 0 to 1.
*/
double intersection_(const Feature& f1, const Feature& f2) const;
/// Returns the isotope distribution for a certain mass window
const TheoreticalIsotopePattern& getIsotopeDistribution_(double mass) const;
/**
@brief Finds the best fitting position of the isotopic pattern estimate defined by @p center
@param[in] center the maximum peak of the isotope distribution (contains charge as well)
@param[in] charge The charge of the pattern
@param[out] best_pattern Returns the indices of the isotopic peaks. If a isotopic peak is missing -1 is returned.
*/
double findBestIsotopeFit_(const Seed& center, UInt charge, IsotopePattern& best_pattern) const;
/**
Extends all mass traces of an isotope pattern in one step
@param[out] pattern The IsotopePattern that should be extended.
@param[in] traces The MassTraces datastructure where the extended mass traces will be stored in.
@param[in] meta_index_overall The index of the data array where the quality scores for the given charge are stored.
*/
void extendMassTraces_(const IsotopePattern& pattern, MassTraces& traces, Size meta_index_overall) const;
/**
@brief Extends a single mass trace in one RT direction
How to use this method:
- Add the starting peak to the @p trace
- Indicate using @c increase_rt whether to extend in downstream or upstream direction
@param[in] trace The trace that should be extended
@param[in] spectrum_index The index of the spectrum from which on the mass trace should be extended
@param[in] mz The mz location (center) of the trace
@param[in] increase_rt Indicator whether the extension is done in forward or backward direction (with respect to the current spectrum)
@param[out] meta_index_overall The index of the overall score
@param[in] min_rt The rt minimum up to which the trace will be extended.
@param[in] max_rt The rt maximum up to which the trace will be extended.
@note This method assumes that it extends from a local maximum.
@note If @c min_rt or @c max_rt are set to 0.0 no boundary is assumed in the respective direction.
*/
void extendMassTrace_(MassTrace& trace, SignedSize spectrum_index, double mz, bool increase_rt, Size meta_index_overall, double min_rt = 0.0, double max_rt = 0.0) const;
/// Returns the index of the peak nearest to m/z @p pos in spectrum @p spec (linear search starting from index @p start)
Size nearest_(double pos, const MSSpectrum& spec, Size start) const;
/**
@brief Searches for an isotopic peak in the current spectrum and the adjacent spectra
@param[in] pos m/z position of the searched for peak
@param[in] spectrum_index index of the central spectrum
@param[in] pattern IsotopePattern to store found peaks
@param[in] pattern_index index of the isotope in the pattern
@param[in] peak_index starting index of the search (to avoid multiple binary searches)
*/
void findIsotope_(double pos, Size spectrum_index, IsotopePattern& pattern, Size pattern_index, Size& peak_index) const;
/// Calculates a score between 0 and 1 for the m/z deviation of two peaks.
double positionScore_(double pos1, double pos2, double allowed_deviation) const;
/// Calculates a score between 0 and 1 for the correlation between theoretical and found isotope pattern
double isotopeScore_(const TheoreticalIsotopePattern& isotopes, IsotopePattern& pattern, bool consider_mz_distances) const;
/**
@brief Compute the intensity score for the peak @p peak in spectrum @p spectrum.
The intensity score is computed by interpolating the score between the 4 nearest intensity
bins. The scores from the different bins are weighted by the distance of the bin center to
the peak.
@param[in] spectrum Index of the spectrum we are currently looking at
@param[in] peak Index of the peak that should be scored inside the spectrum @p spectrum
*/
double intensityScore_(Size spectrum, Size peak) const;
/**
@brief Choose a the best trace fitter for the current mass traces based on the user parameter
(symmetric, asymmetric) or based on an inspection of the mass trace (auto)
@return A pointer to the trace fitter that should be used.
*/
std::unique_ptr<TraceFitter> chooseTraceFitter_(double& tau);
double intensityScore_(Size rt_bin, Size mz_bin, double intensity) const;
/**
@name Handling of fitted mass traces
Methods to handle the results of the mass trace fitting process.
*/
//@{
/**
@brief Creates new mass traces @p new_traces based on the fitting result and the
original traces @p traces.
@param[out] fitter The TraceFitter containing the results from the rt profile fitting step.
@param[in] traces Original mass traces found in the experiment.
@param[in] new_traces Mass traces created by cropping the original mass traces.
*/
void cropFeature_(const std::shared_ptr<TraceFitter>& fitter,
const MassTraces& traces,
MassTraces& new_traces);
/**
@brief Checks the feature based on different score thresholds and model constraints
Feature can get invalid for following reasons:
<ul>
<li>Invalid fit: Fitted model is bigger than 'max_rt_span'</li>
<li>Invalid feature after fit - too few traces or peaks left</li>
<li>Invalid fit: Center outside of feature bounds</li>
<li>Invalid fit: Less than 'min_rt_span' left after fit</li>
<li>Feature quality too low after fit</li>
</ul>
@param[out] fitter The TraceFitter containing the results from the rt profile fitting step.
@param[in] feature_traces Cropped feature mass traces.
@param[in] seed_mz Mz of the seed
@param[in] min_feature_score Minimal required feature score
@param[in] error_msg Will be filled with the error message, if the feature is invalid
@param[out] fit_score Will be filled with the fit score
@param[out] correlation Will be filled with correlation between feature and model
@param[in] final_score Will be filled with the final score
@return true if the feature is valid
*/
bool checkFeatureQuality_(const std::shared_ptr<TraceFitter>& fitter,
MassTraces& feature_traces,
const double& seed_mz, const double& min_feature_score,
String& error_msg, double& fit_score, double& correlation, double& final_score);
/**
@brief Creates several files containing plots and viewable data of the fitted mass trace
@param[out] fitter The TraceFitter containing the results from the rt profile fitting step.
@param[out] traces Original mass traces found in the spectra
@param[in] new_traces Cropped feature mass traces
@param[in] feature_ok Status of the feature
@param[out] error_msg If the feature is invalid, @p error_msg contains the reason
@param[out] final_score Final score of the feature
@param[in] plot_nr Index of the feature
@param[in] peak The Seed Peak
@param[in] path The path where to put the debug files (default is debug/features)
*/
void writeFeatureDebugInfo_(const std::shared_ptr<TraceFitter>& fitter,
const MassTraces& traces,
const MassTraces& new_traces,
bool feature_ok, const String& error_msg, const double final_score, const Int plot_nr, const PeakType& peak,
const String& path = "debug/features/");
//@}
private:
/// Not implemented
FeatureFinderAlgorithmPicked& operator=(const FeatureFinderAlgorithmPicked&);
/// Not implemented
FeatureFinderAlgorithmPicked(const FeatureFinderAlgorithmPicked&);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FEATUREFINDER/TraceFitter.h | .h | 5,547 | 172 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg$
// $Authors: Stephan Aiche, Marc Sturm $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/FEATUREFINDER/FeatureFinderAlgorithmPickedHelperStructs.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/KERNEL/Peak1D.h>
#include <vector>
namespace OpenMS
{
/**
* @brief Abstract fitter for RT profile fitting
*
* This class provides the basic interface and some functionality to fit multiple mass traces to
* a given RT shape model using the Levenberg-Marquardt algorithm.
*
* @todo docu needs update
*
*/
class OPENMS_DLLAPI TraceFitter :
public DefaultParamHandler
{
public:
/** Generic functor for LM-Optimization
* Uses raw pointer interface to avoid Eigen in public headers.
* Implementations should use Eigen::Map to wrap these pointers.
*/
//TODO: This is copy and paste from LevMarqFitter1d.h. Make a generic wrapper for LM optimization
class GenericFunctor
{
public:
int inputs() const;
int values() const;
GenericFunctor(int dimensions, int num_data_points);
virtual ~GenericFunctor();
/// Compute residuals. x has size inputs(), fvec has size values()
virtual int operator()(const double* x, double* fvec) = 0;
/// Compute Jacobian matrix. x has size inputs(), J is values() x inputs() (column-major)
virtual int df(const double* x, double* J) = 0;
protected:
const int m_inputs, m_values;
};
/// default constructor
TraceFitter();
/// copy constructor
TraceFitter(const TraceFitter& source);
/// assignment operator
TraceFitter& operator=(const TraceFitter& source);
/// destructor
~TraceFitter() override;
/**
* Main method of the TraceFitter which triggers the actual fitting.
*/
virtual void fit(FeatureFinderAlgorithmPickedHelperStructs::MassTraces& traces) = 0;
/**
* Returns the lower bound of the fitted RT model
*/
virtual double getLowerRTBound() const = 0;
/**
* Returns the upper bound of the fitted RT model
*/
virtual double getUpperRTBound() const = 0;
/**
* Returns the height of the fitted model
*/
virtual double getHeight() const = 0;
/**
* Returns the center position of the fitted model
*/
virtual double getCenter() const = 0;
/**
* Returns the mass trace width at half max (FWHM)
*/
virtual double getFWHM() const = 0;
/**
* Evaluate the fitted model at a time point
*/
virtual double getValue(double rt) const = 0;
/**
* Returns the theoretical value of the fitted model at position k in the passed mass trace
*
* @param[in] trace the mass trace for which the value should be computed
* @param[in] k use the position of the k-th peak to compute the value
*/
double computeTheoretical(const FeatureFinderAlgorithmPickedHelperStructs::MassTrace& trace, Size k) const;
/**
* Checks if the fitted model fills out at least 'min_rt_span' of the RT span
*
* @param[in] rt_bounds RT boundaries of the fitted model
* @param[in] min_rt_span Minimum RT span in relation to extended area that has to remain after model fitting
*/
virtual bool checkMinimalRTSpan(const std::pair<double, double>& rt_bounds, const double min_rt_span) = 0;
/**
* Checks if the fitted model is not to big
*
* @param[in] max_rt_span Maximum RT span in relation to extended area that the model is allowed to have
*/
virtual bool checkMaximalRTSpan(const double max_rt_span) = 0;
/**
* Returns the peak area of the fitted model
*/
virtual double getArea() = 0;
/**
* Returns a textual representation of the fitted model function, that can be plotted using Gnuplot
*
* @param[in] trace The mass trace that should be plotted
* @param[in] function_name The name of the function (e.g. f(x) -> function_name = f)
* @param[in] baseline The intensity of the baseline
* @param[in] rt_shift A shift value, that allows to plot all RT profiles side by side, even if they would overlap in reality.
* This should be 0 for the first mass trace and increase by a fixed value for each mass trace.
*/
virtual String getGnuplotFormula(const FeatureFinderAlgorithmPickedHelperStructs::MassTrace& trace, const char function_name, const double baseline, const double rt_shift) = 0;
protected:
struct ModelData
{
FeatureFinderAlgorithmPickedHelperStructs::MassTraces* traces_ptr;
bool weighted;
};
void updateMembers_() override;
/**
* Updates all member variables to the fitted values stored in the solver.
*
* @param[in] s The solver containing the fitted parameter values.
*/
virtual void getOptimizedParameters_(const std::vector<double>& s) = 0;
/**
* Optimize the given parameters using the Levenberg-Marquardt algorithm.
*/
void optimize_(std::vector<double>& x_init, GenericFunctor& functor);
/// Maximum number of iterations
SignedSize max_iterations_;
/// Whether to weight mass traces by theoretical intensity during the optimization
bool weighted_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FEATUREFINDER/FFIDAlgoExternalIDHandler.h | .h | 6,181 | 174 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Hendrik Weisser $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/ANALYSIS/MAPMATCHING/TransformationDescription.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
#include <OpenMS/KERNEL/Feature.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/CHEMISTRY/AASequence.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <OpenMS/METADATA/ProteinIdentification.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/CONCEPT/Types.h>
#include <map>
#include <set>
#include <vector>
namespace OpenMS
{
namespace Internal
{
/**
* @brief Class for handling external peptide identifications in feature finding
*
* This class encapsulates all functionality related to external peptide IDs in the
* feature finding process, including storage, RT transformation, and feature annotation.
*/
class OPENMS_DLLAPI FFIDAlgoExternalIDHandler
{
public:
/// RTMap for external data structure storage
typedef std::multimap<double, PeptideIdentification*> ExternalRTMap;
/// Charge to External RTMap mapping
typedef std::map<Int, ExternalRTMap> ExternalChargeMap;
/// Sequence to External Charge Map mapping
typedef std::map<AASequence, ExternalChargeMap> ExternalPeptideMap;
/// Default constructor
FFIDAlgoExternalIDHandler();
/// Reset the handler's state
void reset();
/// Add an external peptide to the handler's map
void addExternalPeptide(PeptideIdentification& peptide);
/// Process external peptide IDs
void processExternalPeptides(PeptideIdentificationList& peptides_ext);
/// Align internal and external IDs to estimate RT shifts and return RT uncertainty
double alignInternalAndExternalIDs(
const PeptideIdentificationList& peptides_internal,
const PeptideIdentificationList& peptides_external,
double rt_quantile);
/// Transform RT from internal to external scale
double transformRT(double rt) const;
/// Check if we have RT transformation data
bool hasRTTransformation() const;
/// Get the RT transformation
const TransformationDescription& getRTTransformation() const;
/// Classify features using SVM
void classifyFeaturesWithSVM(FeatureMap& features, const Param& param);
/// Filter classified features
void filterClassifiedFeatures(FeatureMap& features, double quality_cutoff);
/// Calculate FDR for classified features
void calculateFDR(FeatureMap& features);
/// Get SVM probabilities for internal features
const std::map<double, std::pair<Size, Size> >& getSVMProbsInternal() const;
private:
/// Add external peptide to charge map (merged version for compatibility)
void addExternalPeptideToMap_(PeptideIdentification& peptide,
std::map<AASequence,
std::map<Int, std::pair<std::multimap<double, PeptideIdentification*>,
std::multimap<double, PeptideIdentification*>>>>& peptide_map);
/// Fill an external RTMap from our data for a specific peptide and charge
bool fillExternalRTMap_(const AASequence& sequence, Int charge,
std::multimap<double, PeptideIdentification*>& rt_map);
/// Check and set feature class based on external data
void annotateFeatureWithExternalIDs_(Feature& feature);
/// Initialize SVM parameters
void initSVMParameters_(const Param& param);
/// Finalize assay features
void finalizeAssayFeatures_(Feature& best_feature, double best_quality, double quality_cutoff);
/// Get random sample for SVM training
void getRandomSample_(std::map<Size, double>& training_labels);
/// Check observation counts for SVM
void checkNumObservations_(Size n_pos, Size n_neg, const String& note = "") const;
/// Get unbiased sample for SVM training
void getUnbiasedSample_(const std::multimap<double, std::pair<Size, bool> >& valid_obs,
std::map<Size, double>& training_labels);
/// Add dummy peptide identification from external data
void addDummyPeptideID_(Feature& feature, const PeptideIdentification* ext_id);
/// Handle external feature probability
void handleExternalFeature_(Feature& feature, double prob_positive, double quality_cutoff);
/// Adjust FDR calculation for external features
void adjustFDRForExternalFeatures_(std::vector<double>& fdr_probs,
std::vector<double>& fdr_qvalues,
Size n_internal_features);
/// External peptide storage
ExternalPeptideMap external_peptide_map_;
/// RT transformation description
TransformationDescription rt_transformation_;
/// Number of external peptides
Size n_external_peptides_;
/// Number of external features
Size n_external_features_;
/// SVM probabilities for external features
std::multiset<double> svm_probs_external_;
/// SVM probabilities for internal features
std::map<double, std::pair<Size, Size> > svm_probs_internal_;
/// SVM number of parts for cross-validation
Size svm_n_parts_;
/// SVM number of samples for training
Size svm_n_samples_;
/// SVM minimum probability threshold
double svm_min_prob_;
/// SVM quality cutoff
double svm_quality_cutoff;
/// SVM predictor names
std::vector<String> svm_predictor_names_;
/// SVM cross-validation output file
String svm_xval_out_;
/// Debug level
Int debug_level_;
/// Number of internal features
Size n_internal_features_;
};
} // namespace Internal
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FEATUREFINDER/MultiplexFilteringProfile.h | .h | 5,629 | 118 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Lars Nilse $
// $Authors: Lars Nilse $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/BaseFeature.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/PROCESSING/CENTROIDING/PeakPickerHiRes.h>
#include <OpenMS/FEATUREFINDER/MultiplexIsotopicPeakPattern.h>
#include <OpenMS/FEATUREFINDER/MultiplexFiltering.h>
#include <OpenMS/FEATUREFINDER/MultiplexFilteredPeak.h>
#include <OpenMS/FEATUREFINDER/MultiplexFilteredMSExperiment.h>
#include <OpenMS/MATH/MISC/CubicSpline2d.h>
#include <OpenMS/PROCESSING/MISC/SplineInterpolatedPeaks.h>
#include <vector>
#include <algorithm>
#include <iostream>
namespace OpenMS
{
/**
* @brief filters centroided and profile data for peak patterns
*
* The algorithm searches for patterns of multiple peptides in the data.
* The peptides appear as characteristic patterns of isotopic peaks in
* MS1 spectra. We first search the centroided data, and optionally in
* a second step the spline interpolated profile data. For each
* peak pattern the algorithm generates a filter result.
*
* @see MultiplexIsotopicPeakPattern
* @see MultiplexFilterResult
* @see MultiplexFiltering
*/
class OPENMS_DLLAPI MultiplexFilteringProfile :
public MultiplexFiltering
{
public:
/**
* @brief constructor
*
* @param[in,out] exp_profile experimental data in profile mode
* @param[in] exp_centroided experimental data in centroid mode
* @param[in] boundaries peak boundaries for exp_centroided
* @param[in] patterns patterns of isotopic peaks to be searched for
* @param[in] isotopes_per_peptide_min minimum number of isotopic peaks in peptides
* @param[in] isotopes_per_peptide_max maximum number of isotopic peaks in peptides
* @param[in] intensity_cutoff intensity cutoff
* @param[in] rt_band RT range used for filtering
* @param[in] mz_tolerance error margin in m/z for matching expected patterns to experimental data
* @param[in] mz_tolerance_unit unit for mz_tolerance, ppm (true), Da (false)
* @param[in] peptide_similarity similarity score for two peptides in the same multiplet
* @param[in] averagine_similarity similarity score for peptide isotope pattern and averagine model
* @param[in] averagine_similarity_scaling scaling factor x for the averagine similarity parameter p when detecting peptide singlets. With p' = p + x(1-p).
* @param[in] averagine_type The averagine model to use, current options are RNA DNA or peptide.
*
* @throw Exception::IllegalArgument if profile and centroided data do not contain same number of spectra
* @throw Exception::IllegalArgument if centroided data and the corresponding list of peak boundaries do not contain same number of spectra
*/
MultiplexFilteringProfile(MSExperiment& exp_profile, const MSExperiment& exp_centroided, const std::vector<std::vector<PeakPickerHiRes::PeakBoundary> >& boundaries,
const std::vector<MultiplexIsotopicPeakPattern>& patterns, int isotopes_per_peptide_min, int isotopes_per_peptide_max, double intensity_cutoff, double rt_band,
double mz_tolerance, bool mz_tolerance_unit, double peptide_similarity, double averagine_similarity, double averagine_similarity_scaling, String averagine_type="peptide");
/**
* @brief filter for patterns
* (generates a filter result for each of the patterns)
*
* @throw Exception::IllegalArgument if number of peaks and number of peak boundaries differ
*
* @see MultiplexIsotopicPeakPattern
* @see MultiplexFilteredMSExperiment
*/
std::vector<MultiplexFilteredMSExperiment> filter();
/**
* @brief returns the intensity-filtered peak boundaries
*/
std::vector<std::vector<PeakPickerHiRes::PeakBoundary> >& getPeakBoundaries();
private:
/**
* @brief averagine filter for profile mode
*
* @param[in] pattern m/z pattern to search for
* @param[in] peak peak to be filtered
* @param[in] satellites_profile spline-interpolated satellites of the peak. If they pass, they will be added to the peak.
*
* @return if this filter was passed i.e. the correlation coefficient is greater than averagine_similarity_
*/
bool filterAveragineModel_(const MultiplexIsotopicPeakPattern& pattern, const MultiplexFilteredPeak& peak, const std::multimap<size_t, MultiplexSatelliteProfile >& satellites_profile) const;
/**
* @brief peptide correlation filter for profile mode
*
* @param[in] pattern m/z pattern to search for
* @param[in] satellites_profile spline-interpolated satellites of the peak. If they pass, they will be added to the peak.
*
* @return if this filter was passed i.e. the correlation coefficient is greater than averagine_similarity_
*/
bool filterPeptideCorrelation_(const MultiplexIsotopicPeakPattern& pattern, const std::multimap<size_t, MultiplexSatelliteProfile >& satellites_profile) const;
/**
* @brief spline interpolated profile data and peak boundaries
*/
std::vector<SplineInterpolatedPeaks> exp_spline_profile_;
std::vector<std::vector<PeakPickerHiRes::PeakBoundary> > boundaries_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FEATUREFINDER/IsotopeFitter1D.h | .h | 1,340 | 53 | // 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/FEATUREFINDER/MaxLikeliFitter1D.h>
namespace OpenMS
{
/**
@brief Isotope distribution fitter (1-dim.) approximated using linear interpolation.
@htmlinclude OpenMS_IsotopeFitter1D.parameters
*/
class OPENMS_DLLAPI IsotopeFitter1D :
public MaxLikeliFitter1D
{
public:
/// Default constructor
IsotopeFitter1D();
/// copy constructor
IsotopeFitter1D(const IsotopeFitter1D & source);
/// destructor
~IsotopeFitter1D() override;
/// assignment operator
virtual IsotopeFitter1D & operator=(const IsotopeFitter1D & source);
/// return interpolation model
QualityType fit1d(const RawDataArrayType & range, std::unique_ptr<InterpolationModel>& model) override;
protected:
/// isotope charge
CoordinateType charge_;
/// standard derivation in isotope
CoordinateType isotope_stdev_;
/// maximum isotopic rank to be considered
Int max_isotope_;
void updateMembers_() override;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FEATUREFINDER/MultiplexFilteredPeak.h | .h | 5,867 | 172 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Lars Nilse $
// $Authors: Lars Nilse $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/FEATUREFINDER/MultiplexSatelliteCentroided.h>
#include <OpenMS/FEATUREFINDER/MultiplexSatelliteProfile.h>
#include <map>
#include <vector>
#include <algorithm>
#include <iostream>
namespace OpenMS
{
/**
* @brief data structure storing a single peak that passed all filters
*
* Each filter result corresponds to a successful search for a particular
* peak pattern in the centroided data. The actual m/z shifts seen in the filter
* result might differ from the theoretical shifts listed in the peak pattern.
*
* Each MultiplexFilteredPeak consists of a primary peak and a set of satellite peaks.
* The primary peak is a peak in the mono-isotopic masstrace of the lightest peptide
* in the multiplet. The satellite peaks are peaks that form the m/z shift pattern
* relative to the primary peak within a retention time range rt_band_. They are the
* evidence on which grounds a peak may pass the filters.
*
* Note that in both centroid and profile mode, centroided data are filtered. (One of
* the first steps in the profile mode algorithm is the peak picking of the profile
* data.) Consequently in both modes, centroided peaks make up a final filtered peak.
* @see size(). In profile mode, we additional store the profile data points that make
* up these peak. @see sizeProfile().
*
* @see MultiplexPeakPattern
*/
class OPENMS_DLLAPI MultiplexFilteredPeak
{
public:
/**
* @brief constructor
*/
MultiplexFilteredPeak(double mz, float rt, size_t mz_idx, size_t rt_idx);
/**
* @brief returns m/z of the peak
*/
double getMZ() const;
/**
* @brief returns RT of the peak
*/
float getRT() const;
/**
* @brief returns the index of the peak in the spectrum
*/
size_t getMZidx() const;
/**
* @brief returns the index of the corresponding spectrum in the MS experiment
*/
size_t getRTidx() const;
/**
* @brief add a satellite peak
*/
void addSatellite(size_t rt_idx, size_t mz_idx, size_t pattern_idx);
void addSatellite(const MultiplexSatelliteCentroided& satellite, size_t pattern_idx);
/**
* @brief add a satellite data point
*/
void addSatelliteProfile(float rt, double mz, float intensity, size_t pattern_idx);
void addSatelliteProfile(const MultiplexSatelliteProfile& satellite, size_t pattern_idx);
/**
* @brief check if the peak (rt_idx, mz_idx) is already in the set of satellite peaks
*/
bool checkSatellite(size_t rt_idx, size_t mz_idx) const;
/**
* @brief return all satellite peaks
*
* @see also satellites_
*/
const std::multimap<size_t, MultiplexSatelliteCentroided >& getSatellites() const;
/**
* @brief return all satellite data points
*
* @see also satellites_profile_
*/
const std::multimap<size_t, MultiplexSatelliteProfile >& getSatellitesProfile() const;
/**
* @brief return number of satellite peaks
*/
size_t size() const;
/**
* @brief return number of satellite data points
*/
size_t sizeProfile() const;
private:
/**
* @brief position of the primary peak
*
* Position of the primary peak in the m/z-RT plane in [Th, sec].
* It is the input for the subsequent clustering step.
*/
double mz_;
float rt_;
/**
* @brief indices of the primary peak position in the centroided experiment
*
* Spectral index and peak index within the spectrum of the primary peak.
* The indices are used to check the blacklist.
*/
size_t mz_idx_;
size_t rt_idx_;
/**
* @brief set of satellites
*
* Mapping from a pattern index i.e. a specific mass trace to all peaks forming
* the pattern. The primary peak is part of the satellite peak set.
*
* pattern_idx -> (rt_idx, mz_idx)
*
* Typically peaks of the same mass trace show up in neighbouring spectra. The algorithm
* considers spectra in the RT range @p rt_band. Consequently, the same @p pattern_idx key
* will have multiple associated satellites, and a multimap is required.
*
* Note that we store only indices, not iterators or pointers. We filter
* 'white' experiments, but all indices refer to the original experiment.
* White experiments are temporary (for each pattern), but the original
* @p exp_picked_ experiment is permanent.
*/
std::multimap<size_t, MultiplexSatelliteCentroided > satellites_;
/**
* @brief set of profile satellites (used on profile data only)
*
* Mapping from a pattern index i.e. a specific mass trace to all spline-interpolated
* data points forming the pattern. Basically, when profile data are available as input,
* we scan over the profile of each satellite peak (see MultiplexSatelliteCentroided above)
* and decide if it passes the filters or not.
*
* pattern_idx -> (rt, mz, intensity)
*
* Typically peaks of the same mass trace show up in neighbouring spectra. The algorithm
* considers spectra in the RT range @p rt_band. Consequently, the same @p pattern_idx key
* will have multiple associated satellites, and a multimap is required.
*/
std::multimap<size_t, MultiplexSatelliteProfile > satellites_profile_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FEATUREFINDER/BiGaussModel.h | .h | 1,794 | 66 | // 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/FEATUREFINDER/InterpolationModel.h>
#include <OpenMS/MATH/STATISTICS/BasicStatistics.h>
namespace OpenMS
{
/**
@brief BiGaussian distribution approximated using linear interpolation.
Asymmetric distribution realized via two normal distributions with
different variances combined at the mean.
@htmlinclude OpenMS_BiGaussModel.parameters
*/
class OPENMS_DLLAPI BiGaussModel :
public InterpolationModel
{
public:
typedef InterpolationModel::CoordinateType CoordinateType;
/// Default constructor
BiGaussModel();
/// copy constructor
BiGaussModel(const BiGaussModel & source);
/// destructor
~BiGaussModel() override;
/// assignment operator
virtual BiGaussModel & operator=(const BiGaussModel & source);
/** @brief set the offset of the model
The whole model will be shifted to the new offset without being computing all over
and without any discrepancy.
*/
void setOffset(CoordinateType offset) override;
/// set sample/supporting points of interpolation
void setSamples() override;
/// get the center of the BiGaussian model i.e. the position of the maximum
CoordinateType getCenter() const override;
protected:
CoordinateType min_;
CoordinateType max_;
Math::BasicStatistics<> statistics1_;
Math::BasicStatistics<> statistics2_;
void updateMembers_() override;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FEATUREFINDER/Biosaur2Algorithm.h | .h | 35,739 | 719 | // 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/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <map>
#include <vector>
namespace OpenMS
{
/**
@brief Implementation of the Biosaur2 feature detection workflow for LC-MS1 data.
This algorithm is a C++ reimplementation of the Biosaur2 feature detection method, originally developed in Python.
It processes centroided LC-MS1 data (with optional profile mode support) to detect peptide features by:
1. Building retention time-contiguous signal traces called "hills" by linking peaks across consecutive scans
2. Splitting hills at valley points to separate co-eluting species
3. Detecting and annotating isotopic patterns based on expected mass differences and intensity correlations
4. Calculating comprehensive feature properties including m/z, RT, intensity, and charge state
The algorithm supports several advanced features:
- FAIMS compensation voltage grouping for FAIMS-enabled instruments
- Ion mobility-aware processing for PASEF/TIMS data
- TOF-specific intensity filtering
- Automatic mass calibration for improved accuracy
- Profile mode centroiding via PeakPickerHiRes
The implementation closely mirrors the reference Python implementation to ensure reproducible results.
All core parameters are exposed through the parameter system and can be configured via INI files
or programmatically. For detailed parameter descriptions and usage examples, see @ref TOPP_FeatureFinderLFQ.
Reference:
Abdrakhimov, et al. Biosaur: An open-source Python software for liquid chromatography-mass
spectrometry peptide feature detection with ion mobility support.
Rapid Communications in Mass Spectrometry, 2022. https://doi.org/10.1002/rcm.9045
@ingroup FeatureFinder
*/
class OPENMS_DLLAPI Biosaur2Algorithm :
public DefaultParamHandler
{
public:
/**
@brief Representation of a single hill (continuous m/z trace across adjacent scans).
A hill represents a contiguous series of peaks at similar m/z values across multiple consecutive scans.
Hills are the fundamental building blocks for feature detection. Each hill stores the raw peak data
(indices, m/z, intensity, RT) along with optional ion mobility information for PASEF/TIMS data.
Summary statistics (intensity-weighted mean m/z, apex RT/intensity, etc.) are precomputed for efficient downstream processing.
*/
struct Hill
{
std::vector<Size> scan_indices; ///< Indices of spectra containing peaks of this hill
std::vector<Size> peak_indices; ///< Indices of peaks within each spectrum
std::vector<double> mz_values; ///< m/z values of peaks in this hill
std::vector<double> intensities; ///< Intensity values of peaks in this hill
std::vector<double> rt_values; ///< Retention time values corresponding to each peak
std::vector<double> drift_times; ///< Drift time values (TIMS data), empty if not available
std::vector<double> ion_mobilities; ///< Ion mobility values, empty if not available
double mz_weighted_mean = 0.0; ///< Intensity-weighted mean m/z (hill center)
double rt_start = 0.0; ///< Retention time of first peak
double rt_end = 0.0; ///< Retention time of last peak
double rt_apex = 0.0; ///< Retention time at maximum intensity
double intensity_apex = 0.0; ///< Maximum intensity value in the hill
double intensity_sum = 0.0; ///< Sum of all intensities in the hill
double drift_time_median = -1.0; ///< Median drift time (-1 if not available)
double ion_mobility_median = -1.0; ///< Intensity-weighted mean ion mobility (median fallback; -1 if not available)
Size length = 0; ///< Number of points/peaks in this hill
Size hill_idx = 0; ///< Unique identifier for this hill
};
/**
@brief Candidate isotope peak that can be associated with a monoisotopic hill.
During isotope pattern detection, candidate hills are evaluated for their suitability as isotope peaks
of a monoisotopic hill. This structure stores the association along with quality metrics that quantify
how well the candidate matches the expected isotope pattern in terms of mass accuracy and intensity correlation.
*/
struct IsotopeCandidate
{
Size hill_idx = 0; ///< Index of the hill that represents this isotope peak
Size isotope_number = 0; ///< Ordinal isotope number (0=monoisotopic, 1=first isotope, etc.)
double mass_diff_ppm = 0.0; ///< Mass difference to expected isotope position in ppm
double cos_corr = 0.0; ///< Cosine correlation between monoisotopic and isotope intensity traces
};
/**
@brief Aggregated properties of a detected peptide feature.
A peptide feature represents a complete isotope pattern detected across multiple scans. It aggregates
information from the monoisotopic hill and its associated isotope hills, providing comprehensive
characterization including m/z, retention time, charge state, and intensity metrics. For ion mobility
data, drift time and ion mobility values are also included.
*/
struct PeptideFeature
{
double mz = 0.0; ///< Monoisotopic m/z value
double rt_start = 0.0; ///< Retention time of first detection
double rt_end = 0.0; ///< Retention time of last detection
double rt_apex = 0.0; ///< Retention time at maximum intensity
double intensity_apex = 0.0; ///< Maximum intensity across the feature
double intensity_sum = 0.0; ///< Sum of intensities (based on iuse parameter)
int charge = 0; ///< Detected charge state
Size n_isotopes = 0; ///< Number of detected isotope peaks
Size n_scans = 0; ///< Number of scans contributing to the monoisotopic hill
double mass_calib = 0.0; ///< Calibrated neutral mass of the feature in Da (neutral_mass = mz * charge ± charge * proton_mass; + for negative mode, − for positive mode)
double drift_time = -1.0; ///< Median drift time (-1 if not available)
double ion_mobility = -1.0; ///< Intensity-weighted mean ion mobility (median fallback; -1 if not available)
std::vector<IsotopeCandidate> isotopes; ///< List of associated isotope peaks
Size mono_hill_idx = 0; ///< Index of the monoisotopic hill
};
/**
@brief Default constructor
Initializes all algorithm parameters with their default values according to the Biosaur2 specification.
*/
Biosaur2Algorithm();
/**
@brief Set the MS data used for feature detection (copy version)
@param[in] ms_data Input MS experiment containing centroided or profile MS1 spectra
*/
void setMSData(const MSExperiment& ms_data);
/**
@brief Set the MS data used for feature detection (move version)
@param[in] ms_data Input MS experiment containing centroided or profile MS1 spectra (will be moved)
*/
void setMSData(MSExperiment&& ms_data);
/**
@brief Get non-const reference to MS data
@return Reference to the internal MS experiment data
*/
MSExperiment& getMSData();
/**
@brief Get const reference to MS data
@return Const reference to the internal MS experiment data
*/
const MSExperiment& getMSData() const;
/**
@brief Execute the Biosaur2 workflow on the stored MS1 experiment (simplified interface)
This is a convenience overload that discards the intermediate hills and peptide feature vectors.
Use this when you only need the final FeatureMap output.
@param[out] feature_map Output FeatureMap that will receive the detected features and meta information
@note The input MS data must be set via setMSData() before calling this method
*/
void run(FeatureMap& feature_map);
/**
@brief Execute the Biosaur2 workflow on the stored MS1 experiment.
This is the main processing method that performs the complete feature detection pipeline:
1. Filters input data to MS1 spectra only
2. Optionally centroids profile data
3. Applies TOF-specific intensity filtering if enabled
4. Groups spectra by FAIMS compensation voltage if applicable
5. Detects hills (continuous m/z traces across scans)
6. Splits hills at valley points
7. Detects isotope patterns and assembles peptide features
8. Converts features to OpenMS FeatureMap format
@param[out] feature_map Output FeatureMap that receives the detected features and meta information
@param[out] hills Output container for all detected hills that survived filtering steps. Useful for diagnostics and quality control.
@param[out] peptide_features Output container storing intermediate peptide feature representations before conversion to FeatureMap entries
@note The input MS data must be set via setMSData() before calling this method
@note All spectra with MS level != 1 will be removed from the internal MS data
@note If profile_mode is enabled, spectra will be centroided using PeakPickerHiRes
*/
void run(FeatureMap& feature_map,
std::vector<Hill>& hills,
std::vector<PeptideFeature>& peptide_features);
/**
@brief Export detected peptide features to a Biosaur2-compatible TSV file.
The TSV file format matches the output of the reference Python implementation, allowing
for easy comparison and downstream processing with Biosaur2-compatible tools.
@param[in] features Peptide features to export (typically obtained from run())
@param[in] filename Destination file path for the TSV output
*/
void writeTSV(const std::vector<PeptideFeature>& features, const String& filename) const;
/**
@brief Export the detected hills as TSV for diagnostic purposes.
This method writes detailed information about each detected hill to a TSV file,
which is useful for debugging, quality control, and understanding the feature detection process.
@param[in] hills Hills to export (typically obtained from run())
@param[in] filename Destination file path for the TSV output
*/
void writeHills(const std::vector<Hill>& hills, const String& filename) const;
protected:
/// @brief Update internal member variables from parameters (called automatically when parameters change)
void updateMembers_() override;
private:
/// @name Internal helper structs
//@{
/**
@brief Lightweight index entry for fast m/z-based hill lookup.
Stores the hill index in the main @ref Hill vector together with the first
and last scan index for quick RT overlap checks when assembling isotope patterns.
*/
struct FastHillEntry
{
Size hill_index = 0;
Size first_scan = 0;
Size last_scan = 0;
};
/**
@brief Internal representation of a candidate isotope pattern.
Encapsulates a monoisotopic hill together with a set of isotope candidates,
the associated charge state and quality metrics used during pattern refinement.
*/
struct PatternCandidate
{
Size mono_index = 0; ///< Index of the monoisotopic hill in the hills vector
double mono_mz = 0.0; ///< Monoisotopic m/z
int charge = 0; ///< Charge state of the pattern
double cos_cor_isotopes = 0.0; ///< Cosine correlation in isotope-intensity space
std::vector<IsotopeCandidate> isotopes; ///< Associated isotope candidates
Size n_scans = 0; ///< Number of scans contributing to the monoisotopic hill
};
//@}
/// @name Internal helper methods
//@{
/**
@brief Calculate the mass accuracy (ppm) between two m/z values
@param[in] mz1 First m/z value
@param[in] mz2 Second m/z value (reference)
@return Mass difference in parts per million (ppm)
*/
double calculatePPM_(double mz1, double mz2) const;
/**
@brief Calculate the median of a vector of values
@param[in] values Input values
@return Median value, or 0.0 if input is empty
*/
double calculateMedian_(const std::vector<double>& values) const;
/**
@brief Compute a cosine correlation between two 1D intensity vectors.
Used internally for comparing theoretical and experimental isotope intensities.
*/
double cosineCorrelation1D_(const std::vector<double>& v1,
const std::vector<double>& v2) const;
/**
@brief Check cosine correlation for averagine-based isotope intensities.
Returns the best correlation and the optimal truncation position in the
experimental vector given a minimum explained averagine fraction and
correlation threshold.
*/
std::pair<double, Size> checkingCosCorrelationForCarbon_(const std::vector<double>& theor_full,
const std::vector<double>& exp_full,
double thresh) const;
/**
@brief Compute averagine-based theoretical isotope intensities.
Uses a C-only binomial model on a 100 Da neutral-mass grid and rescales
the resulting probabilities to the provided monoisotopic apex intensity.
Returns the theoretical intensities and the index of the expected
maximum-intensity isotope.
*/
std::pair<std::vector<double>, Size> computeAveragine_(double neutral_mass,
double apex_intensity) const;
/**
@brief Apply a mean filter (moving average) to smooth data
Uses zero-padding at boundaries to match NumPy's 'same' convolution mode.
@param[in] data Input data to be smoothed
@param[in] window Half-width of the filter kernel (total kernel size = 2*window + 1)
@return Filtered data of the same length as input
*/
std::vector<double> meanFilter_(const std::vector<double>& data, Size window) const;
/**
@brief Estimate mass calibration parameters from a distribution of mass errors
Creates a histogram of mass errors and identifies the peak to determine systematic shift and spread.
@param[in] mass_errors Collection of mass errors (in ppm)
@param[in] bin_width Width of histogram bins (default: 0.05 ppm)
@return Pair of (shift, sigma) where shift is the systematic error and sigma is the spread
*/
std::pair<double, double> calibrateMass_(const std::vector<double>& mass_errors, double bin_width = 0.05) const;
/**
@brief Determine m/z binning step for hill detection.
Performs a pre-scan over the experiment to find the maximum m/z value
after basic filtering and derives the m/z bin width used for fast
hill linking.
*/
double computeHillMzStep_(const MSExperiment& exp,
double htol_ppm,
double min_intensity,
double min_mz,
double max_mz) const;
/**
@brief Apply TOF-specific intensity filtering
For TOF instruments, applies a specialized filtering step to reduce noise by considering
local intensity distributions.
@param[in] exp MS experiment to be filtered (modified in place)
*/
void processTOF_(MSExperiment& exp) const;
/**
@brief Centroid profile spectra using PeakPickerHiRes
@param[in,out] exp MS experiment to be centroided (modified in place)
*/
void centroidProfileSpectra_(MSExperiment& exp) const;
/**
@brief Centroid PASEF/TIMS spectra in joint m/z-ion mobility space
Performs 2D clustering of peaks in the m/z and ion mobility dimensions to reduce data complexity
for ion mobility-enabled instruments.
@param[in,out] exp MS experiment to be centroided (modified in place)
@param[out] mz_step m/z binning width for clustering
@param[in] pasef_tolerance Ion mobility accuracy (in IM units) used to cluster peaks in the IM dimension
*/
void centroidPASEFData_(MSExperiment& exp, double mz_step, double pasef_tolerance) const;
/**
@brief Detect hills (continuous m/z traces) in the MS experiment
Scans through the experiment and groups peaks with similar m/z values across consecutive scans
into hills. Optionally collects mass differences for subsequent calibration.
@param[in,out] exp Input MS experiment
@param[in] htol_ppm Mass tolerance in ppm for linking peaks into hills
@param[in] min_intensity Minimum intensity threshold for peaks
@param[in] min_mz Minimum m/z value to consider
@param[in] max_mz Maximum m/z value to consider
@param[in] use_im Whether to use ion-mobility information during hill linking (2D m/z–IM hills)
@param[out] hill_mass_diffs Optional output container for mass differences (for calibration)
@return Vector of detected hills
*/
std::vector<Hill> detectHills_(const MSExperiment& exp, double htol_ppm, double min_intensity, double min_mz, double max_mz, bool use_im, std::vector<double>* hill_mass_diffs = nullptr) const;
/**
@brief Link peaks in a single scan to existing hills or start new hills.
This method implements the core hill-linking logic for one spectrum,
updating the running hill list and the state that is carried across
scans (previous fast m/z dictionary, ion-mobility bins, and peak-to-hill
assignments).
*/
void linkScanToHills_(const MSSpectrum& spectrum,
Size scan_idx,
double htol_ppm,
double min_intensity,
double min_mz,
double max_mz,
double mz_step,
bool use_im_global,
std::vector<Hill>& hills,
Size& hill_idx_counter,
std::vector<Size>& prev_peak_to_hill,
const MSSpectrum*& prev_spectrum_ptr,
std::map<int, std::vector<int>>& prev_fast_dict,
std::vector<int>& prev_im_bins,
std::vector<double>* hill_mass_diffs) const;
/**
@brief Filter and process hills by applying length constraints and computing summary statistics
@param[in] hills Input hills
@param[in] min_length Minimum number of scans required for a hill to be retained
@return Filtered hills with computed statistics (median m/z, apex RT/intensity, etc.)
*/
std::vector<Hill> processHills_(const std::vector<Hill>& hills, Size min_length) const;
/**
@brief Split hills at valley positions to separate co-eluting species
Identifies local minima in the intensity profile and splits hills where the valley factor
criterion is satisfied, effectively separating features that were initially grouped together.
@param[in,out] hills Input hills to be split
@param[in] hvf Hill valley factor threshold (ratio of valley to neighboring peaks)
@param[in] min_length Minimum length required for split segments to be retained
@return Hills after splitting, with valley-separated segments as independent hills
*/
std::vector<Hill> splitHills_(const std::vector<Hill>& hills, double hvf, Size min_length) const;
/**
@brief Evaluate whether isotope pattern should be truncated at valley positions
Checks if there are significant valleys within the isotope traces that suggest the pattern
should be cut short.
@param[in] isotopes Isotope candidates to evaluate
@param[in] hills All available hills
@param[in] ivf Isotope valley factor threshold
@return Recommended number of isotopes to retain (may be shorter than input)
*/
Size checkIsotopeValleySplit_(const std::vector<IsotopeCandidate>& isotopes, const std::vector<Hill>& hills, double ivf) const;
/**
@brief Perform an initial mass calibration for isotope spacings based on raw hills.
Scans all hills for regularly spaced C13 isotope peaks across a range of charge
states and derives per-isotope shift/sigma estimates (in ppm). The results are
primarily diagnostic and mirror the behaviour of the reference Biosaur2 code.
@param[in] hills Input hills sorted by m/z
@param[in] itol_ppm Isotope mass tolerance in ppm
@param[in] min_charge Minimum charge state to consider
@param[in] max_charge Maximum charge state to consider
@param[in] enable_isotope_calib Whether isotope calibration is enabled
@return Map from isotope index (1..9) to (shift, sigma) in ppm
*/
std::map<int, std::pair<double, double>> performInitialIsotopeCalibration_(const std::vector<Hill>& hills,
double itol_ppm,
int min_charge,
int max_charge,
bool enable_isotope_calib) const;
/**
@brief Build fast m/z and optional ion-mobility lookup structures for hills.
Populates a binned m/z lookup and per-hill ion-mobility bins that accelerate
subsequent isotope candidate searches.
@param[in] hills Input hills
@param[in] use_im Whether ion mobility is used for gating
@param[in] hills_mz_fast Output map from m/z bin to hills overlapping that bin
@param[in] hill_im_bins Output ion-mobility bin per hill (0 if IM is not used or not available)
@return m/z step size used for binning (0 if no binning is possible)
*/
double buildFastMzLookup_(const std::vector<Hill>& hills,
bool use_im,
std::map<int, std::vector<FastHillEntry>>& hills_mz_fast,
std::vector<int>& hill_im_bins) const;
/**
@brief Generate initial isotope pattern candidates for all monoisotopic hills.
For each potential monoisotopic hill and charge state, searches the fast m/z lookup
for matching isotope hills, evaluates RT profile correlation and averagine agreement,
and returns all viable pattern candidates.
@param[in] hills Input hills
@param[in] itol_ppm Isotope mass tolerance in ppm
@param[in] min_charge Minimum charge state to consider
@param[in] max_charge Maximum charge state to consider
@param[in] ivf Isotope valley factor controlling truncation at valleys
@param[in] mz_step m/z step size returned by @ref buildFastMzLookup_
@param[out] hills_mz_fast Fast m/z lookup map
@param[in] hill_idx_to_index Lookup from hill index to position in @p hills
@param[out] hill_im_bins Ion-mobility bins per hill
@param[in] use_im Whether to use ion-mobility gating
@return Vector of initial isotope pattern candidates
*/
std::vector<PatternCandidate> generateIsotopeCandidates_(const std::vector<Hill>& hills,
double itol_ppm,
int min_charge,
int max_charge,
double ivf,
double mz_step,
const std::map<int, std::vector<FastHillEntry>>& hills_mz_fast,
const std::map<Size, Size>& hill_idx_to_index,
const std::vector<int>& hill_im_bins,
bool use_im) const;
/**
@brief Apply RT-apex based filtering to isotope pattern candidates.
Discards isotope hills whose apex RT deviates by more than @ref hrttol_ seconds
from the monoisotopic hill apex.
@param[in] candidates Input candidates (unchanged)
@param[in] hills All hills
@param[in] hill_idx_to_index Lookup from hill index to position in @p hills
@return RT-filtered candidates (identical to input if RT gating is disabled)
*/
std::vector<PatternCandidate> applyRtFiltering_(const std::vector<PatternCandidate>& candidates,
const std::vector<Hill>& hills,
const std::map<Size, Size>& hill_idx_to_index) const;
/**
@brief Refine isotope mass calibration based on initial pattern candidates.
Aggregates mass errors from all candidates and derives per-isotope shift/sigma
estimates to be used for subsequent filtering.
@param[in] candidates Initial (optionally RT-filtered) pattern candidates
@param[in] itol_ppm Isotope mass tolerance in ppm
@param[in] enable_isotope_calib Whether isotope calibration is enabled
@return Map from isotope index (1..9) to (shift, sigma) in ppm
*/
std::map<int, std::pair<double, double>> refineIsotopeCalibration_(const std::vector<PatternCandidate>& candidates,
double itol_ppm,
bool enable_isotope_calib) const;
/**
@brief Filter isotope pattern candidates using refined calibration and cosine checks.
Applies mass error windows based on the refined calibration and recomputes the
isotope-intensity cosine correlation, truncating patterns as necessary.
@param[in,out] candidates Input pattern candidates
@param[in] hills All hills
@param[in] hill_idx_to_index Lookup from hill index to position in @p hills
@param[in] isotope_calib_map_ready Per-isotope calibration parameters
@param[in] enable_isotope_calib Whether isotope calibration is enabled
@return Filtered pattern candidates suitable for final greedy selection
*/
std::vector<PatternCandidate> filterByCalibration_(const std::vector<PatternCandidate>& candidates,
const std::vector<Hill>& hills,
const std::map<Size, Size>& hill_idx_to_index,
const std::map<int, std::pair<double, double>>& isotope_calib_map_ready,
bool enable_isotope_calib) const;
/**
@brief Greedily select non-overlapping isotope patterns and assemble peptide features.
Sorts candidates by pattern length and quality, resolves conflicts between overlapping
hills, performs final averagine/cosine checks and converts surviving patterns into
@ref PeptideFeature entries.
@param[in] filtered_ready Pattern candidates after calibration-based filtering
@param[in] hills All hills
@param[in] negative_mode Whether negative ion mode is enabled
@param[in] iuse Number of isotopes to use for intensity calculation
@param[in] itol_ppm Isotope mass tolerance in ppm (for debug sanity checks)
@return Final list of peptide features with non-overlapping isotope patterns
*/
std::vector<PeptideFeature> selectNonOverlappingPatterns_(const std::vector<PatternCandidate>& filtered_ready,
const std::vector<Hill>& hills,
bool negative_mode,
int iuse,
double itol_ppm) const;
/**
@brief Detect isotope patterns and assemble peptide features
For each candidate monoisotopic hill, searches for matching isotope peaks based on expected
mass differences and charge states. Evaluates isotope candidates using cosine correlation
and mass accuracy, then assembles complete peptide features.
@param[in] hills Input hills (will be modified to mark used hills)
@param[in] itol_ppm Mass tolerance in ppm for isotope matching
@param[in] min_charge Minimum charge state to consider
@param[in] max_charge Maximum charge state to consider
@param[in] negative_mode Whether to use negative ion mode (affects mass calculations)
@param[in] ivf Isotope valley factor for splitting patterns
@param[in] iuse Number of isotopes to use for intensity calculation (0=mono only, -1=all, etc.)
@param[in] enable_isotope_calib Whether to apply automatic mass calibration for isotopes
@param[in] use_im Whether to use ion-mobility information when scoring and grouping isotope patterns
@return Vector of detected peptide features
*/
std::vector<PeptideFeature> detectIsotopePatterns_(std::vector<Hill>& hills, double itol_ppm, int min_charge, int max_charge, bool negative_mode, double ivf, int iuse, bool enable_isotope_calib, bool use_im) const;
/**
@brief Convert peptide features to OpenMS FeatureMap format
Transfers all feature properties (m/z, RT, intensity, charge, etc.) to OpenMS Feature objects
and constructs convex hulls from the contributing hills.
The representation of convex hulls (full mass-trace hulls vs. a single RT–m/z bounding box)
is controlled via the @em convex_hulls parameter.
@param[in] features Input peptide features
@param[in] hills All hills (needed to construct convex hulls)
@return FeatureMap containing the converted features
*/
FeatureMap convertToFeatureMap_(const std::vector<PeptideFeature>& features,
const std::vector<Hill>& hills) const;
/**
@brief Debug helper to log obviously inconsistent isotope assignments
Emits warnings when an isotope hill is far away in RT or m/z from the
corresponding monoisotopic hill. Intended for diagnosing pathological
isotope linking behaviour in complex data (e.g. FAIMS).
@param[in] stage_label Text label indicating the call site (e.g. \"detectIsotopePatterns_\" or \"convertToFeatureMap_\")
@param[in] mono_mz_center Intensity-weighted mean m/z of the monoisotopic hill
@param[in] mono_rt_apex RT apex of the monoisotopic hill
@param[in] mono_hill_idx Hill index of the monoisotopic hill
@param[in] charge Charge state of the feature
@param[in] itol_ppm Isotope mass tolerance used at the call site (ppm)
@param[in] iso_hill Isotope hill to check
@param[in] isotope_number Ordinal isotope index (1=first isotope, ...)
*/
void debugCheckIsotopeConsistency_(const char* stage_label,
double mono_mz_center,
double mono_rt_apex,
Size mono_hill_idx,
int charge,
double itol_ppm,
const Hill& iso_hill,
Size isotope_number) const;
/**
@brief Compute cosine correlation between two intensity traces
Evaluates similarity of intensity profiles between two hills by computing the cosine of the
angle between their intensity vectors (considering only overlapping scan indices).
@param[in] intensities1 First intensity trace
@param[in] scans1 Scan indices for first trace
@param[in] intensities2 Second intensity trace
@param[in] scans2 Scan indices for second trace
@return Cosine correlation coefficient [0, 1], where 1 indicates perfect correlation
*/
double cosineCorrelation_(const std::vector<double>& intensities1, const std::vector<Size>& scans1,
const std::vector<double>& intensities2, const std::vector<Size>& scans2) const;
/**
@brief Check if missing ion mobility data should be treated as an error
The Python reference implementation gracefully degrades when ion mobility arrays are missing.
This method implements the same behavior by returning false to allow processing without IM data.
@param[in] spectrum Spectrum to check
@return Currently always returns false (missing IM is not an error)
*/
bool shouldThrowForMissingIM_(const MSSpectrum& spectrum) const;
/**
@brief Process a single FAIMS compensation voltage group
Performs the complete feature detection pipeline (optional PASEF centroiding, hill detection,
isotope pattern detection) for a single FAIMS CV group or non-FAIMS data.
@param[in] faims_cv FAIMS compensation voltage for this group (NaN for non-FAIMS)
@param[in,out] group_exp MS experiment for this group (modified in place)
@param[in] original_paseftol Original PASEF tolerance setting
@param[out] hills_out Output container for hills detected in this group
@param[out] features_out Output container for peptide features detected in this group
*/
void processFAIMSGroup_(double faims_cv,
MSExperiment& group_exp,
double original_paseftol,
std::vector<Hill>& hills_out,
std::vector<PeptideFeature>& features_out);
//@}
/// @name Member variables
//@{
MSExperiment ms_data_; ///< Input LC-MS data
// Algorithm parameters (cached from Param for performance)
double mini_; ///< Minimum intensity threshold
double minmz_; ///< Minimum m/z value
double maxmz_; ///< Maximum m/z value
double htol_; ///< Mass tolerance in ppm for hill detection
double itol_; ///< Mass tolerance in ppm for isotope pattern detection
double hvf_; ///< Hill valley factor for splitting hills at valleys
double ivf_; ///< Isotope valley factor for splitting isotope patterns
Size minlh_; ///< Minimum number of scans required for a hill
int cmin_; ///< Minimum charge state to consider
int cmax_; ///< Maximum charge state to consider
double pasefmini_; ///< Minimum intensity for PASEF/TIMS clusters after centroiding
Size pasefminlh_; ///< Minimum number of points per PASEF/TIMS cluster
int iuse_; ///< Number of isotopes for intensity calculation (0=mono, -1=all, N=mono+N)
bool negative_mode_; ///< Whether to use negative ion mode
bool tof_mode_; ///< Whether to enable TOF-specific intensity filtering
bool profile_mode_; ///< Whether to centroid profile data using PeakPickerHiRes
bool use_hill_calib_; ///< Whether to use automatic hill mass tolerance calibration
bool ignore_iso_calib_; ///< Whether to disable automatic isotope mass calibration
double paseftol_; ///< Ion mobility tolerance for PASEF/TIMS data (0=disable)
double hrttol_; ///< Maximum RT difference between monoisotopic and isotope apex (0=disable)
String convex_hull_mode_; ///< Representation of feature convex hulls ("mass_traces" vs. "bounding_box")
bool faims_merge_features_; ///< Whether to merge features at different FAIMS CV values representing the same analyte
//@}
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FEATUREFINDER/MultiplexDeltaMassesGenerator.h | .h | 6,640 | 208 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Lars Nilse $
// $Authors: Lars Nilse $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/CHEMISTRY/AASequence.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/FEATUREFINDER/MultiplexDeltaMasses.h>
#include <vector>
#include <algorithm>
#include <iosfwd>
namespace OpenMS
{
/**
* @brief generates complete list of all possible mass shifts due to isotopic labelling
*
* Isotopic labelling results in the shift of peptide masses.
*
* For example in a Lys8/Arg10 SILAC labelled sample, some peptides (the ones with one
* Arg in their sequence) will show a relative mass shift between light and heavy
* partners of 10 Da. This class constructs the complete list of all possible mass
* shifts that arise from isotopic labelling.
*/
class OPENMS_DLLAPI MultiplexDeltaMassesGenerator :
public DefaultParamHandler
{
public:
/**
* @brief complete label information
*/
struct OPENMS_DLLAPI Label
{
String short_name;
String long_name;
String description;
double delta_mass;
Label(String sn, String ln, String d, double dm);
};
/**
* @brief constructor
*/
MultiplexDeltaMassesGenerator();
/**
* @brief constructor
*
* @param[in] labels string describing the labels used in each sample. [...] specifies the labels for a single sample. For example
* For example, [][Lys8,Arg10] describes a standard SILAC experiment. In the "light" sample, none of the amino acids are labelled [].
* In the "heavy" sample, lysines and arginines are isotopically labelled [Lys8,Arg10].
* @param[in] missed_cleavages maximum number of missed cleavages due to incomplete digestion
* @param[in] label_mass_shift name of labels (e.g. Lys8) and their corresponding mass shifts (e.g. 8.0141988132)
*/
MultiplexDeltaMassesGenerator(String labels, int missed_cleavages, std::map<String,double> label_mass_shift);
/**
* @brief generate all mass shifts that can occur due to the absence of one or multiple peptides
* (e.g. for a triplet experiment generate the doublets and singlets that might be present)
*/
void generateKnockoutDeltaMasses();
/**
* @brief write the list of labels for each of the sample
*
* For example in a standard SILAC experiment, sample 1 (light) is unlabelled and sample 2 (heavy) contains Lys8 and Arg 10 labels.
* sample 1: no_label
* sample 2: Lys8 Arg10
* @param[out] stream output stream
*/
void printSamplesLabelsList(std::ostream &stream) const;
/**
* @brief write the list of all mass patterns
*
* For example in a standard SILAC experiment allowing for one missed cleavage, five mass shift patterns are possible.
* mass shift 1: 0 (no_label) 8.0142 (Lys8)
* mass shift 2: 0 (no_label) 10.0083 (Arg10)
* mass shift 3: 0 (no_label) 16.0284 (Lys8,Lys8)
* mass shift 4: 0 (no_label) 18.0225 (Arg10,Lys8)
* mass shift 5: 0 (no_label) 20.0165 (Arg10,Arg10)
*
* @param[out] stream output stream
*/
void printDeltaMassesList(std::ostream &stream) const;
/**
* @brief returns the list of mass shift patterns
*/
std::vector<MultiplexDeltaMasses> getDeltaMassesList();
/**
* @brief returns the list of mass shift patterns
*/
const std::vector<MultiplexDeltaMasses>& getDeltaMassesList() const;
/**
* @brief returns the list of samples with their corresponding labels
*
* For example in a standard SILAC experiment:
* sample 1: no_label
* sample 2: Lys8 Arg10
*/
std::vector<std::vector<String> > getSamplesLabelsList();
/**
* @brief returns the list of samples with their corresponding labels
*
* For example in a standard SILAC experiment:
* sample 1: no_label
* sample 2: Lys8 Arg10
*/
const std::vector<std::vector<String> >& getSamplesLabelsList() const;
/**
* @brief returns the short label string
*
* @param[in] label long label, UniMod name as it appears in peptide sequences, e.g. "Label:13C(6)15N(4)"
*/
String getLabelShort(const String& label);
/**
* @brief returns the long label string
*
* @param[in] label short label, as it appears in the "labels" parameter, e.g. "Arg10"
*/
String getLabelLong(const String& label);
/**
* @brief extract the label set from the sequence
*
* @param[in] sequence amino acid sequence
*
* For example, the sequence VLSEEEIDDNFK(Label:13C(6)15N(2))AQR(Label:13C(6)15N(4))
* contains a set of two labels, Lys8 and Arg10.
*/
MultiplexDeltaMasses::LabelSet extractLabelSet(const AASequence& sequence);
private:
/**
* @brief isotopic labels
*/
String labels_;
/**
* @brief flat list of all occurring isotopic labels
*/
std::vector<String> labels_list_;
/**
* @brief list of samples with their corresponding labels
*/
std::vector<std::vector<String> > samples_labels_;
/**
* @brief maximum number of missed cleavages
*/
int missed_cleavages_;
/**
* @brief list of all possible mass shift patterns
*/
std::vector<MultiplexDeltaMasses> delta_masses_list_;
/**
* @brief master list of all labels
*/
std::vector<Label> label_master_list_;
/**
* @brief mapping from single label to delta mass
* e.g. "Arg10" -> 10.0082686
*/
std::map<String, double> label_delta_mass_;
/**
* @brief mapping from a short label (as in the user params) to a long label (as in PSI-MS name)
* e.g. "Arg10" -> "Label:13C(6)15N(4)"
*/
std::map<String, String> label_short_long_;
/**
* @brief mapping from a long label (as in PSI-MS name) to a short label (as in the user params)
* e.g. "Label:13C(6)15N(4)" -> "Arg10"
*/
std::map<String, String> label_long_short_;
/**
* @brief fill label master list
*/
void fillLabelMasterList_();
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FEATUREFINDER/FeatureFinderIdentificationAlgorithm.h | .h | 15,891 | 405 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Hendrik Weisser $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/ANALYSIS/TARGETED/TargetedExperiment.h>
#include <OpenMS/ANALYSIS/MAPMATCHING/TransformationDescription.h>
#include <OpenMS/ANALYSIS/OPENSWATH/MRMFeatureFinderScoring.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/FEATUREFINDER/FeatureFinderAlgorithmPickedHelperStructs.h>
#include <OpenMS/FEATUREFINDER/FFIDAlgoExternalIDHandler.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <vector>
#include <fstream>
#include <map>
namespace OpenMS {
class OPENMS_DLLAPI FeatureFinderIdentificationAlgorithm :
public DefaultParamHandler
{
public:
/// default constructor
FeatureFinderIdentificationAlgorithm();
/// Main method for actual FeatureFinder
/// External IDs (@p peptides_ext, @p proteins_ext) may be empty,
/// in which case no machine learning or FDR estimation will be performed.
/// Optional seeds from e.g. untargeted FeatureFinders can be added with
/// @p seeds.
/// Results will be written to @p features.
/// Note: The primaryMSRunPath of features will be updated to the primaryMSRunPath
/// stored in the MSExperiment.
/// If that path is not a valid and readable mzML @p spectra_file
/// will be annotated as a fall-back.
/// Caution: peptide IDs will be shrunk to best hit, FFid metavalues added
/// and potential seed IDs added.
///
/// FAIMS data is handled automatically: if the MS data contains multiple FAIMS
/// compensation voltages, each CV group is processed independently (with peptide IDs
/// filtered by FAIMS_CV) and results are combined with FAIMS_CV annotation on features.
/// IDs without FAIMS_CV annotation are included in all groups for backward compatibility.
/// For multi-FAIMS data, getLibrary() returns an empty library since each FAIMS group
/// has its own assay library.
void run(
PeptideIdentificationList peptides,
const std::vector<ProteinIdentification>& proteins,
PeptideIdentificationList peptides_ext,
std::vector<ProteinIdentification> proteins_ext,
FeatureMap& features,
const FeatureMap& seeds = FeatureMap(),
const String& spectra_file = ""
);
void runOnCandidates(FeatureMap& features);
PeakMap& getMSData();
const PeakMap& getMSData() const;
/// @brief set the MS data used for feature detection
void setMSData(const PeakMap& ms_data); // for pyOpenMS
void setMSData(PeakMap&& ms_data); // moves peak data and saves the copy. Note that getMSData() will give back a processed/modified version.
PeakMap& getChromatograms();
const PeakMap& getChromatograms() const;
ProgressLogger& getProgressLogger();
const ProgressLogger& getProgressLogger() const;
TargetedExperiment& getLibrary();
const TargetedExperiment& getLibrary() const;
protected:
typedef FeatureFinderAlgorithmPickedHelperStructs::MassTrace MassTrace;
typedef FeatureFinderAlgorithmPickedHelperStructs::MassTraces MassTraces;
/// mapping: RT (not necessarily unique) -> pointer to peptide
typedef std::multimap<double, PeptideIdentification*> RTMap;
/// mapping: charge -> internal/external: (RT -> pointer to peptide)
typedef std::map<Int, std::pair<RTMap, RTMap> > ChargeMap;
/// mapping: sequence -> charge -> internal/external ID information
typedef std::map<AASequence, ChargeMap> PeptideMap;
/// mapping: peptide ref. -> int./ext.: (RT -> pointer to peptide)
typedef std::map<String, std::pair<RTMap, RTMap> > PeptideRefRTMap;
PeptideMap peptide_map_;
Size n_internal_peps_; ///< number of internal peptide
Size n_external_peps_; ///< number of external peptides
Size batch_size_; ///< nr of peptides to use at the same time during chromatogram extraction
double rt_window_; ///< RT window width
double mz_window_; ///< m/z window width
bool mz_window_ppm_; ///< m/z window width is given in PPM (not Da)?
double mapping_tolerance_; ///< RT tolerance for mapping IDs to features
double isotope_pmin_; ///< min. isotope probability for peptide assay
Size n_isotopes_; ///< number of isotopes for peptide assay
double rt_quantile_;
double peak_width_;
double min_peak_width_;
double signal_to_noise_;
String elution_model_;
// SVM related parameters
double svm_min_prob_;
StringList svm_predictor_names_;
String svm_xval_out_;
double svm_quality_cutoff;
Size svm_n_parts_; ///< number of partitions for SVM cross-validation
Size svm_n_samples_; ///< number of samples for SVM training
// output file (before filtering)
String candidates_out_;
Size debug_level_;
void updateMembers_() override;
/// region in RT in which a peptide elutes:
struct RTRegion
{
double start, end;
ChargeMap ids; ///< internal/external peptide IDs (per charge) in this region
};
/**
* @brief Ion mobility statistics for a peptide in a specific RT region and charge state
*
* This structure stores statistical measures of ion mobility values collected from
* peptide identifications within a single RT region. These statistics are used for:
* - Chromatogram extraction with appropriate IM windows (using median)
* - Feature annotation for quality control (all three values)
* - Detecting potential mis-identifications (large min-max spread may indicate issues)
*
* All values default to -1.0 to indicate missing/unavailable IM data.
*/
struct IMStats
{
double median = -1.0; ///< Median IM value (robust central tendency, used for extraction)
double min = -1.0; ///< Minimum IM value (lower bound of IM distribution)
double max = -1.0; ///< Maximum IM value (upper bound of IM distribution)
};
/// predicate for filtering features by overall quality:
struct FeatureFilterQuality
{
bool operator()(const Feature& feature)
{
return feature.getOverallQuality() == 0.0;
}
} feature_filter_quality_;
/// predicate for filtering features by assigned peptides:
struct FeatureFilterPeptides
{
bool operator()(const Feature& feature)
{
return feature.getPeptideIdentifications().empty();
}
} feature_filter_peptides_;
/// comparison functor for (unassigned) peptide IDs
struct PeptideCompare
{
bool operator()(const PeptideIdentification& p1,
const PeptideIdentification& p2)
{
const String& seq1 = p1.getHits()[0].getSequence().toString();
const String& seq2 = p2.getHits()[0].getSequence().toString();
if (seq1 == seq2)
{
Int charge1 = p1.getHits()[0].getCharge();
Int charge2 = p2.getHits()[0].getCharge();
if (charge1 == charge2)
{
return p1.getRT() < p2.getRT();
}
return charge1 < charge2;
}
return seq1 < seq2;
}
} peptide_compare_;
/// comparison functor for features
struct FeatureCompare
{
bool operator()(const Feature& f1, const Feature& f2)
{
const String& ref1 = f1.getMetaValue("PeptideRef");
const String& ref2 = f2.getMetaValue("PeptideRef");
if (ref1 == ref2)
{
return f1.getRT() < f2.getRT();
}
return ref1 < ref2;
}
} feature_compare_;
PeakMap ms_data_; ///< input LC-MS data
PeakMap chrom_data_; ///< accumulated chromatograms (XICs)
TargetedExperiment library_; ///< assays for peptides (cleared per chunk during processing)
TargetedExperiment output_library_; ///< accumulated assays for output (populated from library_ before clearing)
bool quantify_decoys_;
double add_mass_offset_peptides_{0.0}; ///< non-zero if for every feature an additional offset features should be extracted
bool use_psm_cutoff_;
double psm_score_cutoff_;
PeptideIdentificationList unassignedIDs_;
const double seed_rt_window_ = 60.0; ///< extraction window used for seeds (smaller than rt_window_ as we know the exact apex positions)
/// SVM probability -> number of pos./neg. features (for FDR calculation):
std::map<double, std::pair<Size, Size> > svm_probs_internal_;
/// SVM probabilities for "external" features (for FDR calculation):
std::multiset<double> svm_probs_external_;
Size n_internal_features_; ///< internal feature counter (for FDR calculation)
Size n_external_features_; ///< external feature counter (for FDR calculation)
/// TransformationDescription trafo_; // RT transformation (to range 0-1)
std::map<String, double> isotope_probs_; ///< isotope probabilities of transitions
/**
* @brief Ion mobility statistics per peptide reference (peptide sequence/charge:region)
*
* Maps from full peptide reference (e.g., "PEPTIDE/2:1") to IM statistics.
* Populated during createAssayLibrary_() and used during annotateFeatures_()
* to add IM_median, IM_min, and IM_max meta-values to features.
*/
std::map<String, IMStats> im_stats_;
/**
* @brief Global ion mobility statistics from all peptide identifications
*
* Calculated from peptide identifications BEFORE seeds are added (ensuring we only
* learn from real IDs with IM annotation). Provides context for the typical IM range
* in the dataset.
*/
IMStats global_im_stats_;
MRMFeatureFinderScoring feat_finder_; ///< OpenSWATH feature finder
Internal::FFIDAlgoExternalIDHandler external_id_handler_; ///< Handler for external peptide IDs
ProgressLogger prog_log_;
/// generate transitions (isotopic traces) for a peptide ion and add them to the library:
void generateTransitions_(const String& peptide_id, double mz, Int charge,
const IsotopeDistribution& iso_dist);
void addPeptideRT_(TargetedExperiment::Peptide& peptide, double rt) const;
/// get regions in which peptide eludes (ideally only one) by clustering RT elution times
void getRTRegions_(ChargeMap& peptide_data, std::vector<RTRegion>& rt_regions, bool clear_IDs = true) const;
/**
* @brief Calculate ion mobility statistics for peptide identifications in an RT region
*
* Computes median, min, and max IM values from peptide identifications within
* the given RT region (across all charge states). Individual IDs lacking IM
* annotation are skipped (with warning), and statistics are calculated from the
* remaining IDs with valid IM data. The median is used for robust central tendency
* estimation and is more resistant to outliers than the mean.
*
* Seeds from untargeted feature finders may or may not have an IM meta value set,
* depending on the feature finder. If IM is annotated on the seed, it is used for
* targeted extraction. If not, the seed is extracted across the full IM range
* (ChromatogramExtractor disables IM filtering when ion_mobility < 0).
*
* Note: RT region boundaries are determined from ALL IDs (including those without IM),
* so this only affects IM statistics calculation, not RT extraction.
*
* @param[in] r RT region containing peptide identifications grouped by charge state
* @return IMStats structure with median/min/max, or {-1, -1, -1} if no valid IM data
*
* @see IMStats for details on the returned structure
*/
IMStats getRTRegionIMStats_(const RTRegion& r);
/**
* @brief Calculate global IM statistics from MS data and peptide identifications
*
* Uses MSExperiment::getMinMobility()/getMaxMobility() to get the full IM range
* from raw data (min/max), and calculates median from peptide identifications
* for robust central tendency. Must be called BEFORE addSeeds_() to ensure
* global statistics are based only on identified peptides.
*
* Seeds may or may not have IM annotation depending on the feature finder.
* Seeds with IM annotation use their own IM value; seeds without IM are
* extracted across the full IM range of the dataset.
*/
void calculateGlobalIMStats_();
void annotateFeaturesFinalizeAssay_(
FeatureMap& features,
std::map<Size, std::vector<PeptideIdentification*> >& feat_ids,
RTMap& rt_internal);
/// annotate identified features with m/z, isotope probabilities, etc.
void annotateFeatures_(FeatureMap& features, PeptideRefRTMap& ref_rt_map);
void ensureConvexHulls_(Feature& feature) const;
void postProcess_(FeatureMap& features, bool with_external_ids);
/// Helper functions for run()
void validateSVMParameters_() const;
void initializeFeatureFinder_();
double calculateRTWindow_(double rt_uncertainty) const;
void removeSeedPseudoIDs_(FeatureMap& features);
/// Helper function to check if a peptide hit is a seed pseudo-ID
static bool isSeedPseudoHit_(const PeptideHit& hit);
/// Calculate RT bounds with optional tolerance expansion
std::pair<double, double> calculateRTBounds_(double rt_min, double rt_max) const;
/// some statistics on detected features
void statistics_(const FeatureMap& features) const;
/// creates an assay library out of the peptide sequences and their RT elution windows
/// the PeptideMap is mutable since we clear it on-the-go
/// @p clear_IDs set to false to keep IDs in internal charge maps (only needed for debugging purposes)
void createAssayLibrary_(const PeptideMap::iterator& begin, const PeptideMap::iterator& end, PeptideRefRTMap& ref_rt_map, bool clear_IDs = true);
/// CAUTION: This method stores a pointer to the given @p peptide reference in internals
/// Make sure it stays valid until destruction of the class.
/// @todo find better solution
void addPeptideToMap_(PeptideIdentification& peptide,
PeptideMap& peptide_map,
bool external = false);
void filterFeatures_(FeatureMap& features, bool classified);
/// Core processing logic for a single (non-FAIMS or single FAIMS group) dataset
/// Called by run() either directly or for each FAIMS CV group
void runSingleGroup_(
PeptideIdentificationList peptides,
const std::vector<ProteinIdentification>& proteins,
PeptideIdentificationList peptides_ext,
std::vector<ProteinIdentification> proteins_ext,
FeatureMap& features,
const FeatureMap& seeds,
const String& spectra_file);
// seeds for untargeted extraction
Size addSeeds_(PeptideIdentificationList& peptides, const FeatureMap& seeds);
// quant. decoys
Size addOffsetPeptides_(PeptideIdentificationList& peptides, double offset);
/// Chunks an iterator range (allowing advance and distance) into batches of size batch_size.
/// Last batch might be smaller.
template <typename It>
std::vector<std::pair<It,It>>
chunk_(It range_from, It range_to, const std::ptrdiff_t batch_size)
{
/* Aliases, to make the rest of the code more readable. */
using std::vector;
using std::pair;
using std::make_pair;
using std::distance;
using diff_t = std::ptrdiff_t;
/* Total item number and batch_size size. */
const diff_t total {distance(range_from, range_to)};
const diff_t num {total / batch_size};
vector<pair<It,It>> chunks(num);
It batch_end {range_from};
/* Use the 'generate' algorithm to create batches. */
std::generate(begin(chunks), end(chunks), [&batch_end, batch_size]()
{
It batch_start {batch_end };
std::advance(batch_end, batch_size);
return make_pair(batch_start, batch_end);
});
/* The last batch_size's end must always be 'range_to'. */
if (chunks.empty())
{
chunks.emplace_back(range_from, range_to);
}
else
{
chunks.back().second = range_to;
}
return chunks;
}
}; // namespace OpenMS
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FEATUREFINDER/EmgModel.h | .h | 1,727 | 65 | // 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/FEATUREFINDER/InterpolationModel.h>
#include <OpenMS/MATH/STATISTICS/BasicStatistics.h>
namespace OpenMS
{
/**
@brief Exponentially modified gaussian distribution model for elution profiles.
@htmlinclude OpenMS_EmgModel.parameters
*/
class OPENMS_DLLAPI EmgModel :
public InterpolationModel
{
public:
typedef InterpolationModel::CoordinateType CoordinateType;
typedef Math::BasicStatistics<CoordinateType> BasicStatistics;
typedef LinearInterpolation::container_type ContainerType;
/// Default constructor
EmgModel();
/// copy constructor
EmgModel(const EmgModel & source);
/// destructor
~EmgModel() override;
/// assignment operator
EmgModel & operator=(const EmgModel & source);
/// set offset without being computing all over and without any discrepancy
void setOffset(CoordinateType offset) override;
/// set sample/supporting points of interpolation
void setSamples() override;
/// get the center of the Gaussian model i.e. the position of the maximum
CoordinateType getCenter() const override;
protected:
CoordinateType min_;
CoordinateType max_;
BasicStatistics statistics_;
CoordinateType height_;
CoordinateType width_;
CoordinateType symmetry_;
CoordinateType retention_;
void updateMembers_() override;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FEATUREFINDER/MultiplexSatelliteCentroided.h | .h | 1,440 | 61 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Lars Nilse $
// $Authors: Lars Nilse $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/StandardTypes.h>
#include <map>
#include <vector>
#include <algorithm>
#include <iostream>
namespace OpenMS
{
/**
* @brief data structure storing a single satellite peak
*
* The satellite peak is part of a centroided MSExperiment.
* Hence indices rt_idx_ and mz_idx_ are sufficient to specify RT, m/z and intensity.
*
* @see MultiplexFilteredPeak, MultiplexSatelliteProfile
*/
class OPENMS_DLLAPI MultiplexSatelliteCentroided
{
public:
/**
* @brief constructor
*/
MultiplexSatelliteCentroided(size_t rt_idx, size_t mz_idx);
/**
* @brief returns the m/z index of the satellite peak
*/
size_t getMZidx() const;
/**
* @brief returns the RT index of the satellite peak
*/
size_t getRTidx() const;
private:
/**
* @brief indices of the satellite peak position in the centroided experiment
*
* Spectral index and peak index within the spectrum of the satellite peak.
*/
size_t rt_idx_;
size_t mz_idx_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FEATUREFINDER/ModelDescription.h | .h | 2,473 | 125 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/Param.h>
#include <OpenMS/FEATUREFINDER/BaseModel.h>
#include <sstream>
namespace OpenMS
{
/**
@brief Stores the name and parameters of a model.
This class also allows reconstruction of the model.
@see BaseModel
*/
template <UInt D>
class ModelDescription
{
public:
/// Default constructor
ModelDescription() :
name_(),
parameters_()
{
}
/// copy constructor
ModelDescription(const ModelDescription & source) :
name_(source.name_),
parameters_(source.parameters_)
{
}
/// constructor provided for convenience
ModelDescription(const BaseModel * model) :
name_(model->getName()),
parameters_(model->getParameters())
{
}
/// destructor
virtual ~ModelDescription()
{
}
/// assignment operator
virtual ModelDescription & operator=(const ModelDescription & source)
{
if (&source == this) return *this;
name_ = source.name_;
parameters_ = source.parameters_;
return *this;
}
/** Accessors */
//@{
/// Non-mutable access to model name
const String & getName() const
{
return name_;
}
/// Mutable access to the model name
String & getName()
{
return name_;
}
/// Set the model name
void setName(const String & name)
{
name_ = name;
}
/// Non-mutable access to model parameters
const Param & getParam() const
{
return parameters_;
}
/// Mutable access to the model parameters
Param & getParam()
{
return parameters_;
}
/// Set the model parameters
void setParam(const Param & param)
{
parameters_ = param;
}
/** @name Predicates */
//@{
virtual bool operator==(const ModelDescription & rhs) const
{
return (name_ == rhs.name_) && (parameters_ == rhs.parameters_);
}
virtual bool operator!=(const ModelDescription & rhs) const
{
return !(operator==(rhs));
}
//@}
protected:
String name_;
Param parameters_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FEATUREFINDER/ExtendedIsotopeFitter1D.h | .h | 1,471 | 55 | // 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/FEATUREFINDER/MaxLikeliFitter1D.h>
namespace OpenMS
{
/**
@brief Extended isotope distribution fitter (1-dim.) approximated using linear interpolation.
@htmlinclude OpenMS_ExtendedIsotopeFitter1D.parameters
*/
class OPENMS_DLLAPI ExtendedIsotopeFitter1D :
public MaxLikeliFitter1D
{
public:
/// Default constructor
ExtendedIsotopeFitter1D();
/// copy constructor
ExtendedIsotopeFitter1D(const ExtendedIsotopeFitter1D & source);
/// destructor
~ExtendedIsotopeFitter1D() override;
/// assignment operator
virtual ExtendedIsotopeFitter1D & operator=(const ExtendedIsotopeFitter1D & source);
/// return interpolation model
QualityType fit1d(const RawDataArrayType & range, std::unique_ptr<InterpolationModel>& model) override;
protected:
/// isotope charge
CoordinateType charge_;
/// standard derivation in isotope
CoordinateType isotope_stdev_;
/// monoisotopic mass
CoordinateType monoisotopic_mz_;
/// maximum isotopic rank to be considered
Int max_isotope_;
void updateMembers_() override;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FEATUREFINDER/BaseModel_impl.h | .h | 713 | 26 | // 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/FEATUREFINDER/BaseModel.h>
// include derived classes here
#include <OpenMS/FEATUREFINDER/GaussModel.h>
#include <OpenMS/FEATUREFINDER/BiGaussModel.h>
#include <OpenMS/FEATUREFINDER/IsotopeModel.h>
#include <OpenMS/FEATUREFINDER/ExtendedIsotopeModel.h>
#include <OpenMS/FEATUREFINDER/EmgModel.h>
namespace OpenMS
{
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FEATUREFINDER/FeatureFinderDefs.h | .h | 1,881 | 52 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/IsotopeCluster.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/CONCEPT/GlobalExceptionHandler.h>
namespace OpenMS
{
/**@brief The purpose of this struct is to provide definitions of classes and typedefs which are used throughout all FeatureFinder classes. */
struct OPENMS_DLLAPI FeatureFinderDefs
{
/// Index to peak consisting of two UInts (scan index / peak index)
typedef IsotopeCluster::IndexPair IndexPair;
/// Index to peak consisting of two UInts (scan index / peak index) with charge information
typedef IsotopeCluster::ChargedIndexSet ChargedIndexSet;
/// A set of peak indices
typedef IsotopeCluster::IndexSet IndexSet;
/// Flags that indicate if a peak is already used in a feature
enum Flag {UNUSED, USED};
/// Exception that is thrown if a method an invalid IndexPair is given
class OPENMS_DLLAPI NoSuccessor :
public Exception::BaseException
{
public:
NoSuccessor(const char * file, int line, const char * function, const IndexPair & index) :
BaseException(file, line, function, "NoSuccessor", String("there is no successor/predecessor for the given Index: ") + String(index.first) + "/" + String(index.second)),
index_(index)
{
Exception::GlobalExceptionHandler::setMessage(what());
}
~NoSuccessor() noexcept override = default;
protected:
IndexPair index_; // index without successor/predecessor
};
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FEATUREFINDER/FeatureFinderAlgorithmPickedHelperStructs.h | .h | 6,054 | 195 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm, Stephan Aiche $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CONCEPT/Types.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/DATASTRUCTURES/ConvexHull2D.h>
#include <OpenMS/KERNEL/Peak1D.h>
#include <vector>
#include <list>
#include <cmath>
namespace OpenMS
{
/**
* @brief Wrapper struct for all the classes needed by the FeatureFinderAlgorithmPicked and the associated classes
*
* @see FeatureFinderAlgorithmPicked
* @see TraceFitter
*/
struct OPENMS_DLLAPI FeatureFinderAlgorithmPickedHelperStructs
{
/**
* @brief Helper structure for seeds used in FeatureFinderAlgorithmPicked
*/
struct OPENMS_DLLAPI Seed
{
///Spectrum index
Size spectrum;
///Peak index
Size peak;
///Intensity
float intensity;
/// Comparison operator
bool operator<(const Seed& rhs) const;
};
/**
* @brief Helper struct for mass traces used in FeatureFinderAlgorithmPicked
*/
struct OPENMS_DLLAPI MassTrace
{
///Maximum peak pointer
const Peak1D* max_peak = nullptr;
///RT of maximum peak
double max_rt;
///Theoretical intensity value (scaled to [0,1])
double theoretical_int;
///Contained peaks (pair of RT and pointer to peak)
std::vector<std::pair<double, const Peak1D*> > peaks;
///determines the convex hull of the trace
ConvexHull2D getConvexhull() const;
///Sets the maximum to the highest contained peak of the trace
void updateMaximum();
///Returns the average m/z of all peaks in this trace (weighted by intensity)
double getAvgMZ() const;
///Checks if this Trace is valid (has more than 2 points)
bool isValid() const;
};
/**
* @brief Helper struct for a collection of mass traces used in FeatureFinderAlgorithmPicked
*/
struct OPENMS_DLLAPI MassTraces :
private std::vector<MassTrace>
{
typedef std::vector<MassTrace> privvec;
// public exports of used methods
using privvec::size;
using privvec::at;
using privvec::reserve;
using privvec::push_back;
using privvec::operator[];
using privvec::back;
using privvec::clear;
using privvec::begin;
using privvec::end;
typedef privvec::iterator iterator;
typedef privvec::const_iterator const_iterator;
/// Constructor
MassTraces();
/// Returns the peak count of all traces
Size getPeakCount() const;
/**
@brief Checks if still valid (seed still contained and enough traces)
@param[in] seed_mz The seed m/z value
@param[in] trace_tolerance Tolerance for traces
*/
bool isValid(double seed_mz, double trace_tolerance);
/**
@brief Returns the theoretical maximum trace index
@exception Exception::Precondition is thrown if there are no mass traces (not only in debug mode)
*/
Size getTheoreticalmaxPosition() const;
///Sets the baseline to the lowest contained peak of the trace
void updateBaseline();
/**
@brief Returns the RT boundaries of the mass traces
@exception Exception::Precondition is thrown if there are no mass traces (not only in debug mode)
*/
std::pair<double, double> getRTBounds() const;
/**
@brief Computes a flat representation of MassTraces, i.e., a single
intensity value for each point in RT. The flattened representation
is comparable to the TIC of the MassTraces.
@param[out] intensity_profile An empty std::list of pair<double, double> that will be filled.
The first element of the pair holds the RT value, the second value the sum of intensities
of all peaks in the different mass traces with this specific RT.
*/
void computeIntensityProfile(std::list<std::pair<double, double> >& intensity_profile) const;
/// Maximum intensity trace
Size max_trace;
/// Estimated baseline in the region of the feature (used for the fit)
double baseline;
};
/**
* @brief Helper structure for a theoretical isotope pattern used in FeatureFinderAlgorithmPicked
*/
struct OPENMS_DLLAPI TheoreticalIsotopePattern
{
///Vector of intensity contributions
std::vector<double> intensity;
///Number of optional peaks at the beginning of the pattern
Size optional_begin;
///Number of optional peaks at the end of the pattern
Size optional_end;
///The maximum intensity contribution before scaling the pattern to 1
double max;
///The number of isotopes trimmed on the left side. This is needed to reconstruct the monoisotopic peak.
Size trimmed_left;
/// Returns the size
Size size() const;
};
/**
* @brief Helper structure for a found isotope pattern used in FeatureFinderAlgorithmPicked
*/
struct OPENMS_DLLAPI IsotopePattern
{
///Peak index (-1 if peak was not found, -2 if it was removed to improve the isotope fit)
std::vector<SignedSize> peak;
///Spectrum index (undefined if peak index is -1 or -2)
std::vector<Size> spectrum;
///Peak intensity (0 if peak index is -1 or -2)
std::vector<double> intensity;
///m/z score of peak (0 if peak index is -1 or -2)
std::vector<double> mz_score;
///Theoretical m/z value of the isotope peak
std::vector<double> theoretical_mz;
///Theoretical isotope pattern
TheoreticalIsotopePattern theoretical_pattern;
/// Constructor that resizes the internal vectors
explicit IsotopePattern(Size size);
};
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FEATUREFINDER/FeatureFinderMultiplexAlgorithm.h | .h | 7,681 | 170 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Lars Nilse $
// $Authors: Lars Nilse $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/KERNEL/ConsensusMap.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/FEATUREFINDER/MultiplexDeltaMasses.h>
#include <OpenMS/FEATUREFINDER/MultiplexIsotopicPeakPattern.h>
#include <OpenMS/FEATUREFINDER/MultiplexFilteredMSExperiment.h>
#include <OpenMS/PROCESSING/MISC/SplinePackage.h>
#include <OpenMS/ML/CLUSTERING/GridBasedCluster.h>
#include <vector>
#include <fstream>
#include <map>
namespace OpenMS
{
/**
FeatureFinderMultiplexAlgorithm is a tool for the fully automated analysis of quantitative proteomics data. It detects pairs of isotopic envelopes with fixed m/z separation.
It requires no prior sequence identification of the peptides and works on both profile or centroided spectra. In what follows we outline the algorithm.
<b>Algorithm</b>
The algorithm is divided into three parts: filtering, clustering and linear fitting, see Fig. (d), (e) and (f).
In the following discussion let us consider a particular mass spectrum at retention time 1350 s, see Fig. (a).
It contains a peptide of mass 1492 Da and its 6 Da heavier labelled counterpart. Both are doubly charged in this instance.
Their isotopic envelopes therefore appear at 746 and 749 in the spectrum. The isotopic peaks within each envelope are separated by 0.5.
The spectrum was recorded at finite intervals. In order to read accurate intensities at arbitrary m/z we spline-fit over the data, see Fig. (b).
We would like to search for such peptide pairs in our LC-MS data set. As a warm-up let us consider a standard intensity cut-off filter, see Fig. (c).
Scanning through the entire m/z range (red dot) only data points with intensities above a certain threshold pass the filter.
Unlike such a local filter, the filter used in our algorithm takes intensities at a range of m/z positions into account, see Fig. (d). A data point (red dot) passes if
- all six intensities at m/z, m/z+0.5, m/z+1, m/z+3, m/z+3.5 and m/z+4 lie above a certain threshold,
- the intensity profiles in neighbourhoods around all six m/z positions show a good correlation and
- the relative intensity ratios within a peptide agree up to a factor with the ratios of a theoretic averagine model.
Let us now filter not only a single spectrum but all spectra in our data set. Data points that pass the filter form clusters in the t-m/z plane, see Fig. (e).
Each cluster corresponds to the mono-isotopic mass trace of the lightest peptide of a SILAC pattern. We now use hierarchical clustering methods to assign each data point to a specific cluster.
The optimum number of clusters is determined by maximizing the silhouette width of the partitioning.
Each data point in a cluster corresponds to three pairs of intensities (at [m/z, m/z+3], [m/z+0.5, m/z+3.5] and [m/z+1, m/z+4]).
A plot of all intensity pairs in a cluster shows a clear linear correlation, see Fig. (f).
Using linear regression we can determine the relative amounts of labelled and unlabelled peptides in the sample.
@image html SILACAnalyzer_algorithm.png
*/
class OPENMS_DLLAPI FeatureFinderMultiplexAlgorithm :
public DefaultParamHandler, public ProgressLogger
{
public:
/// default constructor
FeatureFinderMultiplexAlgorithm();
/// main method for feature detection
void run(MSExperiment& exp, bool progress);
/// get methods
FeatureMap& getFeatureMap();
ConsensusMap& getConsensusMap();
MSExperiment& getBlacklist();
protected:
// experimental data
MSExperiment exp_profile_;
MSExperiment exp_centroid_;
bool centroided_;
ProgressLogger prog_log_;
bool progress_;
unsigned charge_min_;
unsigned charge_max_;
unsigned isotopes_per_peptide_min_;
unsigned isotopes_per_peptide_max_;
// mass shift names and their values
std::map<String, double> label_mass_shift_;
// final results, maps of detected features
FeatureMap feature_map_;
ConsensusMap consensus_map_;
// blacklist
MSExperiment exp_blacklist_;
/**
* @brief generate list of m/z shifts
*
* @param[in] charge_min minimum charge
* @param[in] charge_max maximum charge
* @param[in] peaks_per_peptide_max maximum number of isotopes in peptide
* @param[in] mass_pattern_list mass shifts due to labelling
*
* @return list of m/z shifts
*/
std::vector<MultiplexIsotopicPeakPattern> generatePeakPatterns_(int charge_min, int charge_max, int peaks_per_peptide_max, const std::vector<MultiplexDeltaMasses>& mass_pattern_list);
/**
* @brief determine ratios through linear regression and correct peptide intensities
*
* In most labelled mass spectrometry experiments, the fold change i.e. ratio and not the individual peptide intensities
* are of primary interest. For that reason, we determine the ratios from interpolated chromatogram data points directly,
* and then correct the current ones.
*
* @param[in] pattern Isotopic peak pattern
* @param[in,out] spline_chromatograms Spline chromatograms to be used/modified
* @param[in] rt_peptide Retention times of peptides
* @param[out] intensity_peptide Corrected peptide intensities
*/
void correctPeptideIntensities_(const MultiplexIsotopicPeakPattern& pattern, std::map<size_t, SplinePackage>& spline_chromatograms, const std::vector<double>& rt_peptide, std::vector<double>& intensity_peptide) const;
/**
* @brief calculate peptide intensities
*
* @param[in] pattern Isotopic peak pattern
* @param[in] satellites Satellite peaks
*
* @return vector with intensities for each of the peptides
*/
std::vector<double> determinePeptideIntensitiesCentroided_(const MultiplexIsotopicPeakPattern& pattern, const std::multimap<size_t, MultiplexSatelliteCentroided >& satellites);
/**
* @brief calculate peptide intensities
*
* @param[in] pattern Isotopic peak pattern
* @param[in] satellites Satellite peaks
*
* @return vector with intensities for each of the peptides
*/
std::vector<double> determinePeptideIntensitiesProfile_(const MultiplexIsotopicPeakPattern& pattern, const std::multimap<size_t, MultiplexSatelliteProfile >& satellites);
/**
* @brief generates consensus and feature maps containing all peptide multiplets
*
* @param[in] patterns patterns of isotopic peaks we have been searching for
* @param[in] filter_results filter results for each of the patterns
* @param[in,out] cluster_results clusters of filter results
*/
void generateMapsCentroided_(const std::vector<MultiplexIsotopicPeakPattern>& patterns, const std::vector<MultiplexFilteredMSExperiment>& filter_results, std::vector<std::map<int, GridBasedCluster> >& cluster_results);
/**
* @brief generates consensus and feature maps containing all peptide multiplets
*
* @param[in] patterns patterns of isotopic peaks we have been searching for
* @param[in] filter_results filter results for each of the patterns
* @param[in] cluster_results clusters of filter results
*/
void generateMapsProfile_(const std::vector<MultiplexIsotopicPeakPattern>& patterns, const std::vector<MultiplexFilteredMSExperiment>& filter_results, const std::vector<std::map<int, GridBasedCluster> >& cluster_results);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FEATUREFINDER/MassTraceDetection.h | .h | 8,362 | 208 | // 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, Mohammed Alhigaylan $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/KERNEL/MassTrace.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <boost/dynamic_bitset.hpp>
namespace OpenMS
{
/**
@brief A mass trace extraction method that gathers peaks similar in m/z and moving along retention time.
Peaks of a @ref MSExperiment are sorted by their intensity and stored in a
list of potential chromatographic apex positions. Only peaks that are above
the noise threshold (user-defined) are analyzed and only peaks that are n
times above this minimal threshold are considered as apices. This saves
computational resources and decreases the noise in the resulting output.
Starting with these, mass traces are extended in- and decreasingly in
retention time. During this extension phase, the centroid m/z is computed
on-line as an intensity-weighted mean of peaks.
The extension phase ends when either the frequency of gathered peaks drops
below a threshold (min_sample_rate, see @ref MassTraceDetection parameters)
or when the number of missed scans exceeds a threshold
(trace_termination_outliers, see @ref MassTraceDetection parameters).
Finally, only mass traces that pass a filter (a certain minimal and maximal
length as well as having the minimal sample rate criterion fulfilled) get
added to the result.
@htmlinclude OpenMS_MassTraceDetection.parameters
@ingroup Quantitation
*/
class OPENMS_DLLAPI MassTraceDetection :
public DefaultParamHandler,
public ProgressLogger
{
public:
/// Trace termination criteria enum for performance optimization
enum TraceTerminationCriterion
{
OUTLIER, ///< Terminate when consecutive outliers exceed threshold
SAMPLE_RATE ///< Terminate when sample rate falls below threshold
};
/// Default constructor
MassTraceDetection();
/// Default destructor
~MassTraceDetection() override;
/** @name Helper methods
*/
/** @name Main computation methods
*/
/// Main method of MassTraceDetection. Extracts mass traces of a @ref MSExperiment and gathers them into a vector container.
void run(const PeakMap &, std::vector<MassTrace> &, const Size max_traces = 0);
/// Invokes the run method (see above) on merely a subregion of a @ref MSExperiment map.
void run(PeakMap::ConstAreaIterator & begin, PeakMap::ConstAreaIterator & end, std::vector<MassTrace> & found_masstraces);
/// determine if meta array is available
bool hasFwhmMz() const { return has_fwhm_mz_; }
bool hasFwhmIm() const { return has_fwhm_im_; }
bool hasCentroidIm() const { return has_centroid_im_; }
/** @name Private methods and members
*/
protected:
void updateMembers_() override;
/// allows for the iterative computation of intensity weighted of a mass trace's centroid m/z or ion mobility
static void updateIterativeWeightedMean_(const double& added_value,
const double& added_intensity,
double& centroid_value,
double& prev_counter,
double& prev_denom);
private:
struct Apex
{
Apex(double intensity, Size scan_idx, Size peak_idx);
double intensity;
Size scan_idx;
Size peak_idx;
};
/// Encapsulates peak finding logic for both up and down directions
struct PeakCandidate
{
Size idx;
double mz;
double intensity;
double im;
bool found;
PeakCandidate() : idx(0), mz(-1.0), intensity(-1.0), im(-1.0), found(false) {}
};
/// Encapsulates trace extension state
struct TraceExtensionState
{
Size scan_counter;
Size hitting_peak_count;
Size consecutive_missed;
bool active;
TraceExtensionState() : scan_counter(0), hitting_peak_count(0), consecutive_missed(0), active(true) {}
};
/// The internal run method
void run_(const std::vector<Apex>& chrom_apices,
const Size peak_count,
const PeakMap & work_exp,
const std::vector<Size>& spec_offsets,
std::vector<MassTrace> & found_masstraces,
const Size max_traces = 0);
/// Internal helper to extract and validate metadata float array indices
void getIMIndices_(const PeakMap& spectra,
int& fwhm_meta_idx, bool& has_fwhm_mz,
int& im_idx, bool& has_centroid_im,
int& im_fwhm_idx, bool& has_fwhm_im) const;
/// Find the best matching peak in a spectrum considering m/z and optionally ion mobility
PeakCandidate findBestPeak_(const MSSpectrum& spectrum,
double centroid_mz,
double ftl_sd,
double centroid_im = -1.0) const;
/// Check if peak candidate meets acceptance criteria
bool isPeakAcceptable_(const PeakCandidate& candidate,
double centroid_mz,
double ftl_sd,
double centroid_im,
Size spectrum_idx,
const std::vector<Size>& spec_offsets,
const boost::dynamic_bitset<>& peak_visited) const;
/// Process a single peak during trace extension
void processPeak_(const PeakCandidate& candidate,
const MSSpectrum& spectrum,
std::list<PeakType>& current_trace,
std::vector<std::pair<Size, Size>>& gathered_idx,
std::vector<double>& fwhms_mz,
std::vector<double>& fwhms_im,
double& centroid_mz,
double& centroid_im,
double& prev_counter,
double& prev_denom,
double& prev_counter_im,
double& prev_denom_im,
double& ftl_sd,
double& intensity_so_far,
Size spectrum_idx,
bool is_upward_extension);
/// Check if a mass trace meets quality criteria
bool isTraceValid_(const std::list<PeakType>& trace,
Size total_scans_visited,
Size consecutive_missed_down,
Size consecutive_missed_up) const;
// Metadata availability flags – set by getIMIndices_ and valid after run_()
bool has_fwhm_mz_ = false;
bool has_fwhm_im_ = false;
bool has_centroid_im_ = false;
// parameter stuff
double mass_error_ppm_;
double mass_error_da_;
double noise_threshold_int_;
double chrom_peak_snr_;
double ion_mobility_tolerance_;
MassTrace::MT_QUANTMETHOD quant_method_;
TraceTerminationCriterion trace_termination_criterion_;
Size trace_termination_outliers_;
double min_sample_rate_;
double min_trace_length_;
double max_trace_length_;
bool reestimate_mt_sd_;
// Metadata array indices - set during run_()
mutable int fwhm_meta_idx_ = -1;
mutable int ion_mobility_idx_ = -1;
mutable int im_fwhm_idx_ = -1;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FEATUREFINDER/Fitter1D.h | .h | 2,164 | 76 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/DATASTRUCTURES/IsotopeCluster.h>
#include <OpenMS/KERNEL/Feature.h>
#include <OpenMS/KERNEL/Peak1D.h>
#include <OpenMS/MATH/STATISTICS/BasicStatistics.h>
#include <memory>
namespace OpenMS
{
class InterpolationModel;
/**
@brief Abstract base class for all 1D-dimensional model fitter.
@htmlinclude OpenMS_Fitter1D.parameters
@ingroup FeatureFinder
*/
class OPENMS_DLLAPI Fitter1D : public DefaultParamHandler
{
public:
/// IndexSet
typedef IsotopeCluster::IndexSet IndexSet;
/// IndexSet with charge information
typedef IsotopeCluster::ChargedIndexSet ChargedIndexSet;
/// Single coordinate
typedef Feature::CoordinateType CoordinateType;
/// Quality of a feature
typedef Feature::QualityType QualityType;
/// Peak type data point type
typedef Peak1D PeakType;
/// Peak type data container type using for the temporary storage of the input data
typedef std::vector<PeakType> RawDataArrayType;
/// Peak type data iterator
typedef RawDataArrayType::iterator PeakIterator;
/// Default constructor.
Fitter1D();
/// copy constructor
Fitter1D(const Fitter1D& source);
/// destructor
~Fitter1D() override;
/// assignment operator
Fitter1D& operator=(const Fitter1D& source);
/// return interpolation model
virtual QualityType fit1d(const RawDataArrayType& /* range */, std::unique_ptr<InterpolationModel>& /* model */);
protected:
/// standard derivation in bounding box
CoordinateType tolerance_stdev_box_;
/// basic statistics
Math::BasicStatistics<> statistics_;
/// interpolation step size
CoordinateType interpolation_step_;
void updateMembers_() override;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FEATUREFINDER/FeatureFinderAlgorithmMetaboIdent.h | .h | 8,630 | 247 | // 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, Hendrik Weisser $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/ANALYSIS/TARGETED/TargetedExperiment.h>
#include <OpenMS/ANALYSIS/MAPMATCHING/TransformationDescription.h>
#include <OpenMS/ANALYSIS/OPENSWATH/MRMFeatureFinderScoring.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/FEATUREFINDER/FeatureFinderAlgorithmPickedHelperStructs.h>
#include <OpenMS/CHEMISTRY/ISOTOPEDISTRIBUTION/CoarseIsotopePatternGenerator.h>
#include <map>
#include <vector>
namespace OpenMS
{
class IsotopeDistribution;
class OPENMS_DLLAPI FeatureFinderAlgorithmMetaboIdent :
public DefaultParamHandler
{
public:
/// @brief represents a compound in the assay library
struct OPENMS_DLLAPI FeatureFinderMetaboIdentCompound
{
FeatureFinderMetaboIdentCompound(const String& _name,
const String& _formula,
double _mass,
const std::vector<int>& _charges,
const std::vector<double>& _rts,
const std::vector<double>& _rt_ranges,
const std::vector<double>& _iso_distrib,
const std::vector<double>& _ion_mobilities = {}):
name_(_name),
formula_(_formula),
mass_(_mass),
charges_(_charges),
rts_(_rts),
rt_ranges_(_rt_ranges),
iso_distrib_(_iso_distrib),
ion_mobilities_(_ion_mobilities)
{
}
private:
String name_;
String formula_;
double mass_;
std::vector<int> charges_;
std::vector<double> rts_;
std::vector<double> rt_ranges_;
std::vector<double> iso_distrib_;
std::vector<double> ion_mobilities_; ///< Expected ion mobility values (optional)
public:
const String& getName() const {
return name_;
}
const String& getFormula() const {
return formula_;
}
double getMass() const {
return mass_;
}
const std::vector<int>& getCharges() const {
return charges_;
}
const std::vector<double>& getRTs() const {
return rts_;
}
const std::vector<double> getRTRanges() const {
return rt_ranges_;
}
const std::vector<double>& getIsotopeDistribution() const {
return iso_distrib_;
}
const std::vector<double>& getIonMobilities() const {
return ion_mobilities_;
}
};
/// default constructor
FeatureFinderAlgorithmMetaboIdent();
/// @brief perform targeted feature extraction of compounds from @p metaboIdentTable and stores them in @p features.
/// If @p spectra_file is provided it will be used as a fall-back to setPrimaryMSRunPath
/// in the feature map in case a proper primaryMSRunPath is not annotated in the MSExperiment.
/// If there are no MS1 scans in the MSData return @p features unchanged.
///
/// FAIMS data is handled automatically: if the MS data contains multiple FAIMS compensation
/// voltages, each CV group is processed independently and results are combined with
/// FAIMS_CV annotation on features. For multi-FAIMS data, getLibrary() returns an empty
/// library since each FAIMS group has its own assay library.
void run(const std::vector<FeatureFinderMetaboIdentCompound>& metaboIdentTable, FeatureMap& features, const String& spectra_file = "");
/// @brief Retrieve chromatograms (empty if run was not executed)
PeakMap& getMSData() { return ms_data_; }
const PeakMap& getMSData() const { return ms_data_; }
/// @brief Set spectra
void setMSData(const PeakMap& m); // needed because pyOpenMS can't wrap the non-const reference version
void setMSData(PeakMap&& m); // moves peak data and saves the copy. Note that getMSData() will give back a processed/modified version.
/// @brief Retrieve chromatograms (empty if run was not executed)
const PeakMap& getChromatograms() const { return chrom_data_; }
PeakMap& getChromatograms() { return chrom_data_; }
/// @brief Retrieve the assay library (e.g., to store as TraML, empty if run was not executed)
const TargetedExperiment& getLibrary() const { return library_; }
/// @brief Retrieve deviations between provided coordinates and extracted ones (e.g., to store as TrafoXML or for plotting)
const TransformationDescription& getTransformations() const { return trafo_; }
/// @brief Retrieve number of features with shared identifications
size_t getNShared() const { return n_shared_; }
static String prettyPrintCompound(const TargetedExperiment::Compound& compound);
protected:
/// Boundaries for a mass trace in a feature
struct MassTraceBounds
{
Size sub_index;
double rt_min, rt_max, mz_min, mz_max;
};
/// Boundaries for all mass traces per feature
typedef std::map<UInt64, std::vector<MassTraceBounds> > FeatureBoundsMap;
typedef FeatureFinderAlgorithmPickedHelperStructs::MassTrace MassTrace;
typedef FeatureFinderAlgorithmPickedHelperStructs::MassTraces MassTraces;
typedef std::vector<Feature*> FeatureGroup; ///< group of (overlapping) features
/// Predicate for filtering features by overall quality
struct FeatureFilterQuality
{
bool operator()(const Feature& feature)
{
return feature.metaValueExists("FFMetId_remove");
}
} feature_filter_;
/// Comparison functor for features
struct FeatureCompare
{
bool operator()(const Feature& f1, const Feature& f2)
{
const String& ref1 = f1.getMetaValue("PeptideRef");
const String& ref2 = f2.getMetaValue("PeptideRef");
if (ref1 == ref2)
{
return f1.getRT() < f2.getRT();
}
return ref1 < ref2;
}
} feature_compare_;
void extractTransformations_(const FeatureMap& features);
/// Add a target (from the input file) to the assay library
void addTargetToLibrary_(const String& name, const String& formula,
double mass, const std::vector<Int>& charges,
const std::vector<double>& rts,
std::vector<double> rt_ranges,
const std::vector<double>& iso_distrib,
const std::vector<double>& ion_mobilities = {});
/// Add "peptide" identifications with information about targets to features
Size addTargetAnnotations_(FeatureMap& features);
void addTargetRT_(TargetedExperiment::Compound& target, double rt);
/// Calculate mass-to-charge ratio from mass and charge
double calculateMZ_(double mass, Int charge) const;
void generateTransitions_(const String& target_id, double mz, Int charge,
const IsotopeDistribution& iso_dist);
void annotateFeatures_(FeatureMap& features);
void ensureConvexHulls_(Feature& feature) const;
void selectFeaturesFromCandidates_(FeatureMap& features);
/// Core processing logic for a single (non-FAIMS or single FAIMS group) dataset
/// Called by run() either directly or for each FAIMS CV group
void runSingleGroup_(const std::vector<FeatureFinderMetaboIdentCompound>& metaboIdentTable,
FeatureMap& features,
const String& spectra_file);
double rt_window_; ///< RT window width
double mz_window_; ///< m/z window width
bool mz_window_ppm_; ///< m/z window width is given in PPM (not Da)?
double im_window_; ///< Ion mobility window width (0 = disabled)
double isotope_pmin_; ///< min. isotope probability for peptide assay
Size n_isotopes_; ///< number of isotopes for peptide assay
double peak_width_;
double min_peak_width_;
double signal_to_noise_;
String elution_model_;
// output file (before filtering)
String candidates_out_;
Size debug_level_;
void updateMembers_() override;
PeakMap ms_data_; ///< input LC-MS data
PeakMap chrom_data_; ///< accumulated chromatograms (XICs)
MRMFeatureFinderScoring feat_finder_; ///< OpenSWATH feature finder
TargetedExperiment library_; ///< accumulated assays for targets
TransformationDescription trafo_;
CoarseIsotopePatternGenerator iso_gen_; ///< isotope pattern generator
std::map<String, double> isotope_probs_; ///< isotope probabilities of transitions
std::map<String, double> target_rts_; ///< RTs of targets (assays)
size_t n_shared_ = 0;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FEATUREFINDER/GaussModel.h | .h | 1,714 | 65 | // 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/FEATUREFINDER/InterpolationModel.h>
#include <OpenMS/MATH/STATISTICS/BasicStatistics.h>
namespace OpenMS
{
/**
@brief Normal distribution approximated using linear interpolation
@htmlinclude OpenMS_GaussModel.parameters
*/
class OPENMS_DLLAPI GaussModel :
public InterpolationModel
{
public:
typedef InterpolationModel::CoordinateType CoordinateType;
typedef Math::BasicStatistics<CoordinateType> BasicStatistics;
typedef InterpolationModel InterpolationModel;
/// Default constructor
GaussModel();
/// copy constructor
GaussModel(const GaussModel & source);
/// destructor
~GaussModel() override;
/// assignment operator
virtual GaussModel & operator=(const GaussModel & source);
/** @brief set the offset of the model
The whole model will be shifted to the new offset without being computing all over.
and without any discrepancy.
*/
void setOffset(CoordinateType offset) override;
/// set sample/supporting points of interpolation
void setSamples() override;
/// get the center of the Gaussian model i.e. the position of the maximum
CoordinateType getCenter() const override;
protected:
CoordinateType min_;
CoordinateType max_;
BasicStatistics statistics_;
void updateMembers_() override;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FEATUREFINDER/MultiplexFilteredMSExperiment.h | .h | 2,335 | 87 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Lars Nilse $
// $Authors: Lars Nilse $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/FEATUREFINDER/MultiplexFilteredPeak.h>
#include <vector>
#include <algorithm>
#include <iostream>
namespace OpenMS
{
/**
* @brief data structure storing all peaks (and optionally their raw data points)
* of an experiment corresponding to one specific peak pattern
*
* @see MultiplexPeakPattern
*/
class OPENMS_DLLAPI MultiplexFilteredMSExperiment
{
public:
/**
* @brief constructor
*/
MultiplexFilteredMSExperiment();
/**
* @brief adds a single peak to the results
*/
void addPeak(const MultiplexFilteredPeak& peak);
/**
* @brief returns a single peak from the results
*/
MultiplexFilteredPeak getPeak(size_t i) const;
/**
* @brief returns m/z of a single peak
*/
double getMZ(size_t i) const;
/**
* @brief returns m/z positions of all peaks
*/
std::vector<double> getMZ() const;
/**
* @brief returns RT of a single peak
*/
double getRT(size_t i) const;
/**
* @brief returns RT of all peaks
*/
std::vector<double> getRT() const;
/**
* @brief returns number of peaks in the result
*/
size_t size() const;
/**
* @brief write all peaks to a consensusXML file
*
* @param[in] exp_picked original (i.e. not white) centroided experimental data
* @param[in] debug_out file name of the debug output
*/
void writeDebugOutput(const MSExperiment& exp_picked, const String& debug_out) const;
private:
/**
* @brief peaks which passed the peak pattern filter
*/
std::vector<MultiplexFilteredPeak> result_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FEATUREFINDER/BaseModel.h | .h | 3,074 | 115 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/KERNEL/DPeak.h>
namespace OpenMS
{
/**
@brief Abstract base class for 1-dimensional models.
*/
class BaseModel : public DefaultParamHandler
{
public:
typedef double IntensityType;
typedef double CoordinateType;
typedef DPosition<1> PositionType;
typedef typename DPeak<1>::Type PeakType;
typedef std::vector<PeakType> SamplesType;
/// Default constructor.
BaseModel() : DefaultParamHandler("BaseModel")
{
defaults_.setValue("cutoff", 0.0, "Low intensity cutoff of the model. Peaks below this intensity are not considered part of the model.");
}
/// copy constructor
BaseModel(const BaseModel& source) = default;
/// Destructor
~BaseModel() override
{
}
/// assignment operator
BaseModel& operator=(const BaseModel& source) = default;
/// access model predicted intensity at position @p pos
virtual IntensityType getIntensity(const PositionType& pos) const = 0;
/// check if position @p pos is part of the model regarding the models cut-off.
virtual bool isContained(const PositionType& pos) const
{
return getIntensity(pos) >= cut_off_;
}
/**@brief Convenience function to set the intensity of a peak to the
predicted intensity at its current position, calling virtual void
getIntensity().
*/
template<typename PeakType>
void fillIntensity(PeakType& peak) const
{
peak.setIntensity(getIntensity(peak.getPosition()));
}
/**@brief Convenience function that applies fillIntensity() to an iterator
range.
*/
template<class PeakIterator>
void fillIntensities(PeakIterator begin, PeakIterator end) const
{
for (PeakIterator it = begin; it != end; ++it)
{
fillIntensity(*it);
}
}
/// get cutoff value
virtual IntensityType getCutOff() const
{
return cut_off_;
}
/// set cutoff value
virtual void setCutOff(IntensityType cut_off)
{
cut_off_ = cut_off;
param_.setValue("cutoff", cut_off_);
}
/// get reasonable set of samples from the model (i.e. for printing)
virtual void getSamples(SamplesType& cont) const = 0;
/// fill stream with reasonable set of samples from the model (i.e. for printing)
virtual void getSamples(std::ostream& os)
{
SamplesType samples;
getSamples(samples);
for (const auto& sample : samples)
{
os << sample << std::endl;
}
}
protected:
IntensityType cut_off_;
void updateMembers_() override
{
cut_off_ = (double)param_.getValue("cutoff");
}
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FEATUREFINDER/FeatureFindingMetabo.h | .h | 12,149 | 339 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/MassTrace.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/KERNEL/MSChromatogram.h>
#include <OpenMS/CHEMISTRY/Element.h>
#include <vector>
struct svm_model;
namespace OpenMS
{
/**
@brief Internal structure used in @ref FeatureFindingMetabo that keeps
track of a feature hypothesis (isotope group hypothesis).
@htmlinclude OpenMS_FeatureFindingMetabo.parameters
@ingroup Quantitation
*/
class OPENMS_DLLAPI FeatureHypothesis
{
public:
/// default constructor
FeatureHypothesis() = default;
/// default destructor
~FeatureHypothesis() = default;
/// copy constructor
FeatureHypothesis(const FeatureHypothesis&) = default;
/// assignment operator
FeatureHypothesis& operator=(const FeatureHypothesis& rhs) = default;
// getter & setter
Size getSize() const;
String getLabel() const;
std::vector<String> getLabels() const;
double getScore() const;
void setScore(const double& score);
SignedSize getCharge() const;
void setCharge(const SignedSize& ch);
std::vector<double> getAllIntensities(bool smoothed = false) const;
std::vector<double> getAllCentroidMZ() const;
std::vector<double> getAllCentroidRT() const;
std::vector<double> getIsotopeDistances() const;
double getCentroidMZ() const;
double getCentroidRT() const;
double getFWHM() const;
/// addMassTrace
void addMassTrace(const MassTrace&);
double getMonoisotopicFeatureIntensity(bool) const;
double getSummedFeatureIntensity(bool) const;
/// return highest apex of all isotope traces
double getMaxIntensity(bool smoothed = false) const;
Size getNumFeatPoints() const;
std::vector<ConvexHull2D> getConvexHulls() const;
std::vector< OpenMS::MSChromatogram > getChromatograms(UInt64 feature_id) const;
private:
// pointers of MassTraces contained in isotopic pattern
std::vector<const MassTrace*> iso_pattern_;
double feat_score_{};
SignedSize charge_{};
};
class OPENMS_DLLAPI CmpMassTraceByMZ
{
public:
bool operator()(const MassTrace& x, const MassTrace& y) const
{
return x.getCentroidMZ() < y.getCentroidMZ();
}
};
class OPENMS_DLLAPI CmpHypothesesByScore
{
public:
bool operator()(const FeatureHypothesis& x, const FeatureHypothesis& y) const
{
return x.getScore() > y.getScore();
}
};
/**
* @brief Internal structure to store a lower and upper bound of an m/z range
*/
struct OPENMS_DLLAPI Range
{
double left_boundary;
double right_boundary;
};
/**
@brief Method for the assembly of mass traces belonging to the same isotope
pattern, i.e., that are compatible in retention times, mass-to-charge ratios,
and isotope abundances.
In @ref FeatureFindingMetabo, mass traces detected by the @ref
MassTraceDetection method and afterwards split into individual
chromatographic peaks by the @ref ElutionPeakDetection method are assembled
to composite features if they are compatible with respect to RTs, m/z ratios,
and isotopic intensities. To this end, feature hypotheses are formulated
exhaustively based on the set of mass traces detected within a local RT and
m/z region. These feature hypotheses are scored by their similarity to real
metabolite isotope patterns. The score is derived from independent models for
retention time shifts and m/z differences between isotopic mass traces.
Hypotheses with correct or false isotopic abundances are distinguished by a
SVM model. Mass traces that could not be assembled or low-intensity
metabolites with only a monoisotopic mass trace to observe are left in the
resulting @ref FeatureMap as singletons with the undefined charge state of 0.
Reference: Kenar et al., doi: 10.1074/mcp.M113.031278
@htmlinclude OpenMS_FeatureFindingMetabo.parameters
@ingroup Quantitation
*/
class OPENMS_DLLAPI FeatureFindingMetabo :
public DefaultParamHandler,
public ProgressLogger
{
public:
/// Default constructor
FeatureFindingMetabo();
/// Default destructor
~FeatureFindingMetabo() override;
/// main method of FeatureFindingMetabo
void run(std::vector<MassTrace>& input_mtraces, FeatureMap& output_featmap, std::vector<std::vector< OpenMS::MSChromatogram > >& output_chromatograms);
protected:
void updateMembers_() override;
private:
/**
* @brief parses a string of element symbols into a vector of Elements
* @param[in] elements_string string of element symbols without whitespaces or commas. e.g. CHNOPSCl
* @return vector of Elements
*/
std::vector<const Element*> elementsFromString_(const std::string& elements_string) const;
/**
* Calculate the maximal and minimal mass defects of isotopes for a given set of elements.
*
* @param[in] alphabet chemical alphabet (elements which are expected to be present)
* @param[in] peakOffset integer distance between isotope peak and monoisotopic peak (minimum: 1)
* @return an interval which should contain the isotopic peak. This interval is relative to the monoisotopic peak.
*/
Range getTheoreticIsotopicMassWindow_(const std::vector<Element const *>& alphabet, int peakOffset) const;
/** @brief Computes the cosine similarity between two vectors
*
* The cosine similarity (or cosine distance) is the cosine of the angle
* between two vectors or the normalized dot product of two vectors.
*
* See also https://en.wikipedia.org/wiki/Cosine_similarity
*
* @param[in] vec1 First vector
* @param[in] vec2 Second vector
*/
double computeCosineSim_(const std::vector<double>& vec1, const std::vector<double>& vec2) const;
/** @brief Compare intensities of feature hypothesis with model
*
* Use a pre-trained SVM model to evaluate the intensity distribution of a
* given feature hypothesis. The model is trained on the monoisotopic and
* the first tree isotopic traces of each feature and uses the scaled
* ratios between the traces as input.
*
* Reference: Kenar et al., doi: 10.1074/mcp.M113.031278
*
* @param[in] feat_hypo A feature hypotheses containing mass traces
* @return 0 for 'no'; 1 for 'yes'; -1 if only a single mass trace exists
*/
int isLegalIsotopePattern_(const FeatureHypothesis& feat_hypo) const;
void loadIsotopeModel_(const String&);
/** @brief Perform mass to charge scoring of two multiple mass traces
*
* Scores two mass traces based on the m/z and the hypothesis that one
* trace is an isotopic trace of the other one. The isotopic position
* (which trace it is) and the charge for the hypothesis are given as
* additional parameters.
* The scoring is described in Kenar et al., and is based on a random
* sample of 115 000 compounds drawn from a comprehensive set of 24 million
* putative sum formulas, of which the isotopic distribution was accurately
* calculated. Thus, a theoretical mu and sigma are calculated as:
*
* mu = 1.000857 * j + 0.001091 u
* sigma = 0.0016633 j * 0.0004751
*
* where j is the isotopic peak considered. A similarity score based on
* agreement with the model is then computed.
*
* Reference: Kenar et al., doi: 10.1074/mcp.M113.031278
*
* An alternative scoring was added which test if isotope m/z distances lie in an expected m/z window.
* This window is computed from a given set of elements.
*
* @param[in] mt1 First mass trace
* @param[in] mt2 Second mass trace
* @param[in] isotopic_position Isotopic position
* @param[in] charge Charge
* @param[in] isotope_window Isotope window
*/
double scoreMZ_(const MassTrace& mt1, const MassTrace& mt2, Size isotopic_position, Size charge, Range isotope_window) const;
/**
* @brief score isotope m/z distance based on the expected m/z distances using C13-C12 or Kenar method
* @param[in] iso_pos Isotopic position
* @param[in] charge Charge
* @param[in] diff_mz Mass-to-charge difference
* @param[in] mt_variances Mass trace variances
* @return Score value
*/
double scoreMZByExpectedMean_(Size iso_pos, Size charge, const double diff_mz, double mt_variances) const;
/**
* @brief score isotope m/z distance based on an expected isotope window which was calculated from a set of expected elements
* @param[in] charge Charge
* @param[in] diff_mz Mass-to-charge difference
* @param[in] mt_variances m/z variance between the two mass traces which are compared
* @param[in] isotope_window Isotope window
* @return Score value
*/
double scoreMZByExpectedRange_(Size charge, const double diff_mz, double mt_variances, Range isotope_window) const;
/** @brief Perform retention time scoring of two multiple mass traces
*
* Computes the similarity of the two peak shapes using cosine similarity
* (see computeCosineSim_) if some conditions are fulfilled. Mainly the
* overlap between the two peaks at FHWM needs to exceed a certain
* threshold. The threshold is set at 0.7 (i.e. 70 % overlap) as also
* described in Kenar et al.
*
* @note this only works for equally sampled mass traces, e.g. they need to
* come from the same map (not for SRM measurements for example).
*
* @param[in] mt1 First mass trace
* @param[in] mt2 Second mass trace
*/
double scoreRT_(const MassTrace& mt1, const MassTrace& mt2) const;
/** @brief Perform intensity scoring using the averagine model (for peptides only)
*
* Compare the isotopic intensity distribution with the theoretical one
* expected for peptides, using the averagine model. Compute the cosine
* similarity between the two values.
*
* @param[in] intensities Intensity values
* @param[in] molecular_weight Molecular weight
*/
double computeAveragineSimScore_(const std::vector<double>& intensities, const double& molecular_weight) const;
/** @brief Identify groupings of mass traces based on a set of reasonable candidates
*
* Takes a set of reasonable candidates for mass trace grouping and checks
* all combinations of charge and isotopic positions on the candidates. It
* is assumed that candidates[0] is the monoisotopic trace.
*
* The resulting possible groupings are appended to output_hypotheses.
*
* @param[in] candidates Candidate mass traces
* @param[in] total_intensity Total intensity
* @param[out] output_hypotheses Output feature hypotheses
*/
void findLocalFeatures_(const std::vector<const MassTrace*>& candidates, double total_intensity, std::vector<FeatureHypothesis>& output_hypotheses) const;
/// SVM parameters
svm_model* isotope_filt_svm_ = nullptr;
std::vector<double> svm_feat_centers_;
std::vector<double> svm_feat_scales_;
//unused
//double total_intensity_;
/// parameter stuff
double local_rt_range_;
double local_mz_range_;
Size charge_lower_bound_;
Size charge_upper_bound_;
double chrom_fwhm_;
bool report_summed_ints_;
bool enable_RT_filtering_;
String isotope_filtering_model_;
bool use_smoothed_intensities_;
bool report_smoothed_intensities_;
bool use_mz_scoring_C13_;
bool use_mz_scoring_by_element_range_;
bool report_convex_hulls_;
bool report_chromatograms_;
bool remove_single_traces_;
std::vector<const Element*> elements_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FEATUREFINDER/GaussFitter1D.h | .h | 1,130 | 47 | // 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/FEATUREFINDER/MaxLikeliFitter1D.h>
namespace OpenMS
{
/**
@brief Gaussian distribution fitter (1-dim.) approximated using linear interpolation.
@htmlinclude OpenMS_GaussFitter1D.parameters
*/
class OPENMS_DLLAPI GaussFitter1D :
public MaxLikeliFitter1D
{
public:
/// Default constructor
GaussFitter1D();
/// copy constructor
GaussFitter1D(const GaussFitter1D & source);
/// destructor
~GaussFitter1D() override;
/// assignment operator
virtual GaussFitter1D & operator=(const GaussFitter1D & source);
/// return interpolation model
QualityType fit1d(const RawDataArrayType & range, std::unique_ptr<InterpolationModel>& model) override;
protected:
void updateMembers_() override;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FEATUREFINDER/BiGaussFitter1D.h | .h | 1,365 | 54 | // 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/FEATUREFINDER/MaxLikeliFitter1D.h>
#include <OpenMS/MATH/STATISTICS/BasicStatistics.h>
namespace OpenMS
{
/**
@brief BiGaussian distribution fitter (1-dim.) approximated using linear interpolation.
@htmlinclude OpenMS_BiGaussFitter1D.parameters
*/
class OPENMS_DLLAPI BiGaussFitter1D :
public MaxLikeliFitter1D
{
public:
/// Default constructor
BiGaussFitter1D();
/// copy constructor
BiGaussFitter1D(const BiGaussFitter1D & source);
/// destructor
~BiGaussFitter1D() override;
/// assignment operator
virtual BiGaussFitter1D & operator=(const BiGaussFitter1D & source);
/// return interpolation model
QualityType fit1d(const RawDataArrayType & range, std::unique_ptr<InterpolationModel>& model) override;
protected:
/// statistics for first peak site
Math::BasicStatistics<> statistics1_;
/// statistics for second peak site
Math::BasicStatistics<> statistics2_;
void updateMembers_() override;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FEATUREFINDER/MultiplexClustering.h | .h | 5,087 | 139 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Lars Nilse $
// $Authors: Lars Nilse $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/MATH/MISC/BSpline2d.h>
#include <OpenMS/PROCESSING/CENTROIDING/PeakPickerHiRes.h>
#include <OpenMS/FEATUREFINDER/MultiplexFilteredMSExperiment.h>
#include <OpenMS/FEATUREFINDER/MultiplexFiltering.h>
#include <OpenMS/ML/CLUSTERING/GridBasedCluster.h>
#include <vector>
#include <algorithm>
#include <iostream>
namespace OpenMS
{
/**
* @brief clusters results from multiplex filtering
*
* The multiplex filtering algorithm identified regions in the picked and
* profile data that correspond to peptide features. This clustering algorithm
* takes these filter results as input and groups data points that belong to
* the same peptide features. It makes use of the general purpose hierarchical
* clustering implementation LocalClustering.
*
* @see MultiplexFiltering
* @see LocalClustering
*/
class OPENMS_DLLAPI MultiplexClustering :
public ProgressLogger
{
public:
/**
* @brief cluster centre, cluster bounding box, grid index
*/
typedef GridBasedCluster::Point Point; ///< DPosition<2>
/**
* @brief constructor
*
* @param[in] exp_profile experimental data in profile mode
* @param[in] exp_picked experimental data in centroid mode
* @param[in] boundaries peak boundaries for exp_picked
* @param[in] rt_typical elution time of a characteristic peptide in the sample
*
* @throw Exception::IllegalArgument if centroided data and the corresponding list of peak boundaries do not contain same number of spectra
*/
MultiplexClustering(const MSExperiment& exp_profile, const MSExperiment& exp_picked, const std::vector<std::vector<PeakPickerHiRes::PeakBoundary> >& boundaries, double rt_typical);
/**
* @brief constructor
*
* @param[in] exp experimental data in centroid mode
* @param[in] mz_tolerance margin in m/z with which the centres of the same peak in different spectra my shift (or 'jitter')
* @param[in] mz_tolerance_unit unit for mz_tolerance, ppm (true), Da (false)
* @param[in] rt_typical elution time of a characteristic peptide in the sample
*
* @throw Exception::IllegalArgument if centroided data and the corresponding list of peak boundaries do not contain same number of spectra
*/
MultiplexClustering(const MSExperiment& exp, double mz_tolerance, bool mz_tolerance_unit, double rt_typical);
/**
* @brief cluster filter results
* Data points are grouped into clusters. Each cluster contains data about one peptide multiplet.
*
* @param[in] filter_results data points relevant for peptide multiplets i.e. output from multiplex filtering
*
* @return cluster results (cluster ID, details about cluster including list of filter result IDs belonging to the cluster)
*/
std::vector<std::map<int,GridBasedCluster> > cluster(const std::vector<MultiplexFilteredMSExperiment>& filter_results);
/**
* @brief scaled Euclidean distance for clustering
*/
class OPENMS_DLLAPI MultiplexDistance
{
public:
/**
* @brief constructor
*
* @param[in] rt_scaling scaling of RT coordinates before calculating Euclidean distance
*/
MultiplexDistance(double rt_scaling);
/**
* @brief constructor
*/
MultiplexDistance();
/**
* @brief returns Euclidean distance
*
* @param[in] p1 first point in the (m/z,RT) plane
* @param[in] p2 second point in the (m/z,RT) plane
* @return distance
*/
double operator()(const Point& p1, const Point& p2) const;
private:
double rt_scaling_;
};
private:
/**
* @brief grid spacing for clustering
*/
std::vector<double> grid_spacing_mz_;
std::vector<double> grid_spacing_rt_;
/**
* @brief scaling in y-direction for clustering
*/
double rt_scaling_;
/**
* @brief typical retention time
*/
double rt_typical_;
/**
* @brief minimum retention time
*/
//unused
//double rt_minimum_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FEATUREFINDER/MultiplexFiltering.h | .h | 10,289 | 262 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Lars Nilse $
// $Authors: Lars Nilse $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/BaseFeature.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/PROCESSING/CENTROIDING/PeakPickerHiRes.h>
#include <OpenMS/FEATUREFINDER/MultiplexIsotopicPeakPattern.h>
#include <OpenMS/FEATUREFINDER/MultiplexFilteredPeak.h>
#include <OpenMS/MATH/MISC/CubicSpline2d.h>
#include <vector>
#include <algorithm>
#include <iostream>
#include <boost/serialization/strong_typedef.hpp>
namespace OpenMS
{
/**
* @brief base class for filtering centroided and profile data for peak patterns
*
* The algorithm searches for patterns of multiple peptides in the data.
* The peptides appear as characteristic patterns of isotopic peaks in
* MS1 spectra. We first search the centroided data, and optionally in
* a second step the spline interpolated profile data. For each
* peak pattern the algorithm generates a filter result.
*
* The algorithm differs slightly for centroided and profile input data.
* This base class comprises code common to both. The two child classes
* MultiplexFilteringCentroided and MultiplexFilteringProfile contain
* specific functions and the primary filter() method.
*
* @see MultiplexIsotopicPeakPattern
* @see MultiplexFilteredMSExperiment
* @see MultiplexFilteringCentroided
* @see MultiplexFilteringProfile
*/
class OPENMS_DLLAPI MultiplexFiltering :
public ProgressLogger
{
public:
/**
* @brief index mapping from a 'white' experiment to its original experiment
*
* An MSExperiment contains a set of spectra each containing a number of peaks.
* In the course of the filtering, some peaks are blacklisted since they are
* identified to belong to a certain pattern i.e. peptide. An experiment in
* which blacklisted peaks are removed is called 'white'. White spectra
* contain fewer peaks than their corresponding primary spectra. Consequently,
* their indices are shifted. The type maps a peak index in a 'white'
* spectrum back to its original spectrum.
*/
typedef std::vector<std::map<int, int> > White2Original;
/**
* @brief constructor
*
* @param[in] exp_centroided experimental data in centroid mode
* @param[in] patterns patterns of isotopic peaks to be searched for
* @param[in] isotopes_per_peptide_min minimum number of isotopic peaks in peptides
* @param[in] isotopes_per_peptide_max maximum number of isotopic peaks in peptides
* @param[in] intensity_cutoff intensity cutoff
* @param[in] rt_band RT range used for filtering
* @param[in] mz_tolerance error margin in m/z for matching expected patterns to experimental data
* @param[in] mz_tolerance_unit unit for mz_tolerance, ppm (true), Da (false)
* @param[in] peptide_similarity similarity score for two peptides in the same multiplet
* @param[in] averagine_similarity similarity score for peptide isotope pattern and averagine model
* @param[in] averagine_similarity_scaling scaling factor x for the averagine similarity parameter p when detecting peptide singlets. With p' = p + x(1-p).
* @param[in] averagine_type Averagine model to use: 'peptide', 'RNA', 'DNA'
*/
MultiplexFiltering(const MSExperiment& exp_centroided, const std::vector<MultiplexIsotopicPeakPattern>& patterns, int isotopes_per_peptide_min,
int isotopes_per_peptide_max, double intensity_cutoff, double rt_band, double mz_tolerance, bool mz_tolerance_unit,
double peptide_similarity, double averagine_similarity, double averagine_similarity_scaling, String averagine_type="peptide");
/**
* @brief returns the intensity-filtered, centroided spectral data
*/
MSExperiment& getCentroidedExperiment();
/**
* @brief returns the blacklisted, centroided peaks
*/
MSExperiment getBlacklist();
protected:
/**
* @brief construct an MS experiment from exp_centroided_ containing
* peaks which have not been previously blacklisted in blacklist_
*
* In addition, construct an index mapping of 'white' peak positions
* to their position in the corresponding, original spectrum.
*/
void updateWhiteMSExperiment_();
/**
* @brief check for significant peak
*
* @param[in] mz position where the peak is expected
* @param[in] mz_tolerance m/z tolerance within the peak may lie
* @param[in] it_rt pointer to the spectrum
* @param[in] intensity_first_peak intensity to compare to
*
* @return -1 (if there is no significant peak), or peak index mz_idx (if there is a significant peak)
*/
int checkForSignificantPeak_(double mz, double mz_tolerance, MSExperiment::ConstIterator& it_rt, double intensity_first_peak) const;
/**
* @brief check if there are enough peaks in the RT band to form the pattern
*
* Checks if there are peaks at m/z positions corresponding to the pattern
* and that the primary peak position is not blacklisted.
*
* @param[in] mz m/z of the primary peak
* @param[in] it_rt_begin RT iterator of the very first spectrum of the experiment (needed to determine indices)
* @param[in] it_rt_band_begin RT iterator of the first spectrum in the RT band
* @param[in] it_rt_band_end RT iterator of the spectrum after the last spectrum in the RT band
* @param[in] pattern m/z pattern to search for
* @param[out] peak filter result output
*
* @return boolean if this filter was passed i.e. there are @em isotopes_per_peptide_min_ or more mass traces which form the pattern.
*/
bool filterPeakPositions_(double mz, const MSExperiment::ConstIterator& it_rt_begin, const MSExperiment::ConstIterator& it_rt_band_begin, const MSExperiment::ConstIterator& it_rt_band_end, const MultiplexIsotopicPeakPattern& pattern, MultiplexFilteredPeak& peak) const;
/**
* @brief blacklist this peak
*
* Blacklist all satellites associated with this peak.
*
* @param[in] peak peak to be blacklisted
*/
void blacklistPeak_(const MultiplexFilteredPeak& peak);
/**
* @brief blacklist this peak
*
* Each of the satellites is associated with a specific mass trace. We blacklist
* all peaks in these mass traces (even if they are not a satellite) extending them
* by a margin @em rt_band_.
*
* @param[in] peak peak to be blacklisted
* @param[in] pattern_idx index of the pattern in @em patterns_
*/
void blacklistPeak_(const MultiplexFilteredPeak& peak, unsigned pattern_idx);
/**
* @brief check if the satellite peaks conform with the averagine model
*
* Check if the intensities of the satellite peaks correlate with the peak intensities
* of the averagine model. We check both Pearson and Spearman rank correlation.
*
* @param[in] pattern m/z pattern to search for
* @param[in] peak peak with set of satellite peaks
*
* @return boolean if this filter was passed i.e. the correlation coefficient is greater than @em averagine_similarity_
*/
bool filterAveragineModel_(const MultiplexIsotopicPeakPattern& pattern, const MultiplexFilteredPeak& peak) const;
/**
* @brief check if corresponding satellite peaks of different peptides show a good correlation
*
* Different peptides in the same multiplet have the same amino acid sequence and should therefore exhibit very similar
* isotope distributions. The filter checks if satellite peaks corresponding to different isotopes in different peptide
* features show a strong correlation. The filter is of course ignored for singlet feature detection.
*
* @param[in] pattern m/z pattern to search for
* @param[in] peak peak with set of satellite peaks
*
* @return boolean if this filter was passed i.e. the correlation coefficient is greater than @em peptide_similarity_
*/
bool filterPeptideCorrelation_(const MultiplexIsotopicPeakPattern& pattern, const MultiplexFilteredPeak& peak) const;
/**
* @brief centroided experimental data
*/
MSExperiment exp_centroided_;
/**
* @brief auxiliary structs for blacklisting
*/
std::vector<std::vector<int> > blacklist_;
/**
* @brief "white" centroided experimental data
*
* subset of all peaks of @em exp_centroided_ which are not blacklisted in @em blacklist_
*/
MSExperiment exp_centroided_white_;
/**
* @brief mapping of peak indices from a 'white' experiment @em exp_centroided_white_ to its original experiment @em exp_centroided_
*/
White2Original exp_centroided_mapping_;
/**
* @brief list of peak patterns
*/
std::vector<MultiplexIsotopicPeakPattern> patterns_;
/**
* @brief minimum number of isotopic peaks per peptide
*/
size_t isotopes_per_peptide_min_;
/**
* @brief maximum number of isotopic peaks per peptide
*/
size_t isotopes_per_peptide_max_;
/**
* @brief intensity cutoff
*/
double intensity_cutoff_;
/**
* @brief RT range used for filtering
*/
double rt_band_;
/**
* @brief m/z shift tolerance
*/
double mz_tolerance_;
/**
* @brief unit for m/z shift tolerance (ppm - true, Da - false)
*/
bool mz_tolerance_unit_in_ppm_;
/**
* @brief peptide similarity
*/
double peptide_similarity_;
/**
* @brief averagine similarity
*/
double averagine_similarity_;
/**
* @brief averagine similarity scaling
*/
double averagine_similarity_scaling_;
/**
* @brief type of averagine to use
*/
String averagine_type_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FEATUREFINDER/IsotopeModel.h | .h | 3,396 | 108 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Clemens Groepl, Chris Bielow $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/FEATUREFINDER/InterpolationModel.h>
#include <OpenMS/CHEMISTRY/ISOTOPEDISTRIBUTION/IsotopeDistribution.h>
namespace OpenMS
{
class EmpiricalFormula;
/**
@brief Isotope distribution approximated using linear interpolation.
This models a smoothed (widened) distribution, i.e. can be used to sample actual raw peaks (depending on the points you query).
If you only want the distribution (no widening), use either
EmpiricalFormula::getIsotopeDistribution() // for a certain sum formula
or
CoarseIsotopePatternGenerator::estimateFromPeptideWeight (double average_weight) // for averagine
Peak widening is achieved by either a Gaussian or Lorentzian shape.
@htmlinclude OpenMS_IsotopeModel.parameters
*/
class OPENMS_DLLAPI IsotopeModel :
public InterpolationModel
{
public:
typedef InterpolationModel::CoordinateType CoordinateType;
typedef InterpolationModel::CoordinateType IntensityType;
enum Averagines {C = 0, H, N, O, S, AVERAGINE_NUM};
/// Default constructor
IsotopeModel();
/// copy constructor
IsotopeModel(const IsotopeModel & source);
/// destructor
~IsotopeModel() override;
/// assignment operator
virtual IsotopeModel & operator=(const IsotopeModel & source);
UInt getCharge() const;
/** @brief set the offset of the model
The whole model will be shifted to the new offset without being computing all over.
This leaves a discrepancy which is minor in small shifts (i.e. shifting by one or two
standard deviations) but can get significant otherwise. In that case use setParameters()
which enforces a recomputation of the model.
*/
void setOffset(CoordinateType offset) override;
CoordinateType getOffset();
/// return the Averagine peptide formula (mass calculated from mean mass and charge -- use .setParameters() to set them)
EmpiricalFormula getFormula();
/// set sample/supporting points of interpolation
virtual void setSamples(const EmpiricalFormula & formula);
/// set sample/supporting points of interpolation (from base class)
using InterpolationModel::setSamples;
/** @brief get the center of the Isotope model
This is a m/z-value not necessarily the monoisotopic mass.
*/
CoordinateType getCenter() const override;
/** @brief the Isotope distribution (without widening) from the last setSamples() call
Useful to determine the number of isotopes that the model contains and their position
*/
const IsotopeDistribution & getIsotopeDistribution() const;
protected:
CoordinateType isotope_stdev_;
CoordinateType isotope_lorentz_fwhm_;
UInt charge_;
CoordinateType mean_;
CoordinateType monoisotopic_mz_;
double averagine_[AVERAGINE_NUM];
Int max_isotope_;
double trim_right_cutoff_;
double isotope_distance_;
IsotopeDistribution isotope_distribution_;
void updateMembers_() override;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FEATUREFINDER/InterpolationModel.h | .h | 4,999 | 173 | // 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/FEATUREFINDER/BaseModel.h>
#include <OpenMS/ML/INTERPOLATION/LinearInterpolation.h>
namespace OpenMS
{
/**
@brief Abstract class for 1D-models that are approximated using linear interpolation
Model wrapping LinearInterpolation for speed-up in calculation of predicted intensities
Derived classes have to implement setSamples()
@htmlinclude OpenMS_InterpolationModel.parameters
@ingroup FeatureFinder
*/
class OPENMS_DLLAPI InterpolationModel :
public BaseModel
{
public:
typedef double IntensityType;
typedef DPosition<1> PositionType;
typedef double CoordinateType;
using KeyType = double;
typedef Math::LinearInterpolation<KeyType> LinearInterpolation;
/// Default constructor
InterpolationModel() :
BaseModel(),
interpolation_()
{
this->defaults_.setValue("interpolation_step", 0.1, "Sampling rate for the interpolation of the model function ");
this->defaults_.setValue("intensity_scaling", 1.0, "Scaling factor used to adjust the model distribution to the intensities of the data");
defaultsToParam_();
}
/// copy constructor
InterpolationModel(const InterpolationModel & source) :
BaseModel(source),
interpolation_(source.interpolation_),
interpolation_step_(source.interpolation_step_),
scaling_(source.scaling_)
{
updateMembers_();
}
/// destructor
~InterpolationModel() override = default;
/// assignment operator
InterpolationModel & operator=(const InterpolationModel & source)
{
if (&source == this) return *this;
BaseModel::operator=(source);
interpolation_step_ = source.interpolation_step_;
interpolation_ = source.interpolation_;
scaling_ = source.scaling_;
updateMembers_();
return *this;
}
/// access model predicted intensity at position @p pos
IntensityType getIntensity(const PositionType & pos) const override
{
return interpolation_.value(pos[0]);
}
/// access model predicted intensity at position @p pos
IntensityType getIntensity(CoordinateType coord) const
{
return interpolation_.value(coord);
}
/// Returns the interpolation class
const LinearInterpolation & getInterpolation() const
{
return interpolation_;
}
/** @brief get the scaling for the model
A scaling factor of @p scaling means that the area under the model equals
@p scaling. Default is 1.
*/
CoordinateType getScalingFactor() const
{
return scaling_;
}
/** @brief set the offset of the model
The whole model will be shifted to the new offset without being recomputed all over.
Setting takes affect immediately.
*/
virtual void setOffset(CoordinateType offset)
{
interpolation_.setOffset(offset);
}
/// get reasonable set of samples from the model (i.e. for printing)
void getSamples(SamplesType & cont) const override
{
cont.clear();
using PeakT = BaseModel::PeakType;
PeakT peak;
for (Size i = 0; i < interpolation_.getData().size(); ++i)
{
peak.getPosition()[0] = interpolation_.index2key((KeyType)i);
peak.setIntensity((PeakT::IntensityType)interpolation_.getData()[i]);
cont.push_back(peak);
}
}
/// "center" of the model, particular definition (depends on the derived model)
virtual CoordinateType getCenter() const
{
throw Exception::NotImplemented(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
/// set sample/supporting points of interpolation wrt params.
virtual void setSamples()
{
throw Exception::NotImplemented(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
/**
@brief Set the interpolation step for the linear interpolation of the model
For setting to take affect, call setSamples().
*/
void setInterpolationStep(CoordinateType interpolation_step)
{
interpolation_step_ = interpolation_step;
this->param_.setValue("interpolation_step", interpolation_step_);
}
void setScalingFactor(CoordinateType scaling)
{
scaling_ = scaling;
this->param_.setValue("intensity_scaling", scaling_);
}
protected:
LinearInterpolation interpolation_;
CoordinateType interpolation_step_;
CoordinateType scaling_;
void updateMembers_() override
{
BaseModel::updateMembers_();
interpolation_step_ = this->param_.getValue("interpolation_step");
scaling_ = this->param_.getValue("intensity_scaling");
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FEATUREFINDER/EmgFitter1D.h | .h | 2,813 | 94 | // 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/FEATUREFINDER/LevMarqFitter1D.h>
#include <OpenMS/CONCEPT/Constants.h>
namespace OpenMS
{
/**
@brief Exponentially modified gaussian distribution fitter (1-dim.) using Levenberg-Marquardt algorithm (Eigen implementation) for parameter optimization.
@htmlinclude OpenMS_EmgFitter1D.parameters
*/
class OPENMS_DLLAPI EmgFitter1D :
public LevMarqFitter1D
{
public:
/// Default constructor
EmgFitter1D();
/// copy constructor
EmgFitter1D(const EmgFitter1D& source);
/// destructor
~EmgFitter1D() override;
/// assignment operator
virtual EmgFitter1D& operator=(const EmgFitter1D& source);
/// return interpolation model
QualityType fit1d(const RawDataArrayType& range, std::unique_ptr<InterpolationModel>& model) override;
protected:
/// Helper struct (contains the size of an area and a raw data container)
struct Data
{
typedef Peak1D PeakType;
typedef std::vector<PeakType> RawDataArrayType;
Size n;
RawDataArrayType set;
};
class EgmFitterFunctor :
public LevMarqFitter1D::GenericFunctor
{
public:
EgmFitterFunctor(int dimensions, const EmgFitter1D::Data* data) :
LevMarqFitter1D::GenericFunctor(dimensions,
static_cast<int>(data->n)),
m_data(data)
{}
int operator()(const double* x, double* fvec) const override;
// compute Jacobian matrix for the different parameters
int df(const double* x, double* J) const override;
protected:
const EmgFitter1D::Data* m_data;
static const EmgFitter1D::CoordinateType c;
static const EmgFitter1D::CoordinateType sqrt2pi;
static const EmgFitter1D::CoordinateType emg_const;
static const EmgFitter1D::CoordinateType sqrt_2;
};
/// Compute start parameter
virtual void setInitialParameters_(const RawDataArrayType& set);
/// Compute start parameters using method of moments (usually reduces nr. of iterations needed at some
/// additional one-time costs
void setInitialParametersMOM_(const RawDataArrayType& set);
/// Parameter of emg - peak height
CoordinateType height_;
/// Parameter of emg - peak width
CoordinateType width_;
/// Parameter of emg - peak symmetry
CoordinateType symmetry_;
/// Parameter of emg - peak retention time
CoordinateType retention_;
void updateMembers_() override;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FEATUREFINDER/MaxLikeliFitter1D.h | .h | 1,312 | 46 | // 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/FEATUREFINDER/Fitter1D.h>
namespace OpenMS
{
class InterpolationModel;
/**
@brief Abstract base class for all 1D-model fitters using maximum likelihood optimization.
*/
class OPENMS_DLLAPI MaxLikeliFitter1D : public Fitter1D
{
public:
/// default constructor
MaxLikeliFitter1D() : Fitter1D()
{
}
/// copy constructor
MaxLikeliFitter1D(const MaxLikeliFitter1D& source) = default;
/// destructor
~MaxLikeliFitter1D() override
{
}
/// assignment operator
MaxLikeliFitter1D& operator=(const MaxLikeliFitter1D& source) = default;
protected:
/// fit an offset on the basis of the Pearson correlation coefficient
QualityType fitOffset_(std::unique_ptr<InterpolationModel>& model, const RawDataArrayType& set, const CoordinateType stdev1, const CoordinateType stdev2, const CoordinateType offset_step) const;
void updateMembers_() override;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FEATUREFINDER/ExtendedIsotopeModel.h | .h | 2,582 | 84 | // 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/FEATUREFINDER/InterpolationModel.h>
namespace OpenMS
{
/**
@brief Extended isotope distribution approximated using linear interpolation.
This models a smoothed (widened) distribution, i.e. can be used to sample actual raw peaks (depending on the points you query).
If you only want the distribution (no widening), use either
EmpiricalFormula::getIsotopeDistribution() // for a certain sum formula
or
CoarseIsotopePatternGenerator::estimateFromPeptideWeight (double average_weight) // for averagine
Peak widening is achieved by a Gaussian shape.
@htmlinclude OpenMS_ExtendedIsotopeModel.parameters
*/
class OPENMS_DLLAPI ExtendedIsotopeModel :
public InterpolationModel
{
public:
typedef InterpolationModel::CoordinateType CoordinateType;
typedef InterpolationModel::CoordinateType IntensityType;
enum Averagines {C = 0, H, N, O, S, AVERAGINE_NUM};
/// Default constructor
ExtendedIsotopeModel();
/// copy constructor
ExtendedIsotopeModel(const ExtendedIsotopeModel & source);
/// destructor
~ExtendedIsotopeModel() override;
/// assignment operator
virtual ExtendedIsotopeModel & operator=(const ExtendedIsotopeModel & source);
UInt getCharge() const;
/** @brief set the offset of the model
The whole model will be shifted to the new offset without being computing all over.
This leaves a discrepancy which is minor in small shifts (i.e. shifting by one or two
standard deviations) but can get significant otherwise. In that case use setParameters()
which enforces a recomputation of the model.
*/
void setOffset(CoordinateType offset) override;
CoordinateType getOffset();
/// set sample/supporting points of interpolation
void setSamples() override;
/** @brief get the monoisotopic mass of the Isotope model
*/
CoordinateType getCenter() const override;
protected:
CoordinateType isotope_stdev_;
UInt charge_;
CoordinateType monoisotopic_mz_;
double averagine_[AVERAGINE_NUM];
Int max_isotope_;
double trim_right_cutoff_;
double isotope_distance_;
void updateMembers_() override;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FEATUREFINDER/PeakWidthEstimator.h | .h | 1,994 | 75 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Lars Nilse $
// $Authors: Lars Nilse $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/MATH/MISC/BSpline2d.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/PROCESSING/CENTROIDING/PeakPickerHiRes.h>
namespace OpenMS
{
/**
@brief Rough estimation of the peak width at m/z
Based on the peaks of the dataset (peak position & width) and the peak
boundaries as reported by the PeakPickerHiRes, the typical peak width is
estimated for arbitrary m/z using a spline interpolation.
*/
class OPENMS_DLLAPI PeakWidthEstimator
{
public:
/**
* @brief constructor
*
* @param[in] exp_picked m/z positions of picked peaks
* @param[in] boundaries corresponding peak widths
*
* @throw Exception::UnableToFit if the B-spline initialisation fails.
*/
PeakWidthEstimator(const PeakMap & exp_picked, const std::vector<std::vector<PeakPickerHiRes::PeakBoundary> > & boundaries);
/**
* @brief returns the estimated peak width at m/z
*
* @note If the mz value is outside the interpolation range, the peak width
* value of the maximal/minimal value is used.
*
* @throw Exception::InvalidValue if the peak width estimation returns a negative value.
*/
double getPeakWidth(double mz);
/**
* @brief destructor
*/
virtual ~PeakWidthEstimator();
private:
/// hide default constructor
PeakWidthEstimator();
/**
* @brief B-spline for peak width interpolation
*/
BSpline2d* bspline_;
/**
* @brief m/z range of peak width interpolation
*/
double mz_min_;
double mz_max_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FEATUREFINDER/ElutionPeakDetection.h | .h | 5,709 | 146 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/KERNEL/MassTrace.h>
namespace OpenMS
{
/**
@brief Extracts chromatographic peaks from a mass trace.
Mass traces may consist of several consecutively (partly overlapping)
eluting peaks, e.g., stemming from (almost) isobaric compounds that are
separated by retention time. Especially in metabolomics, isomeric compounds
with exactly the same mass but different retentional behaviour may still be
contained in the same mass trace.
This method first applies smoothing on the mass trace's intensities, then
detects local minima/maxima in order to separate the chromatographic peaks
from each other. Detection of maxima is performed on the smoothed
intensities and uses a fixed peak width (given as parameter chrom_fwhm)
within which only a single maximum is expected. Currently smoothing is
done using SavitzkyGolay smoothing with a second order polynomial and a
frame length of the fixed peak width.
Depending on the "width_filtering" parameters, mass traces are filtered by
length in seconds ("fixed" filter) or by quantile.
The output of the algorithm is a set of chromatographic
peaks for each mass trace, i.e. a vector of split mass traces (see @ref
ElutionPeakDetection parameters).
In general, a user would want to call the "detectPeaks" functions,
potentially followed by the "filterByPeakWidth" function.
@htmlinclude OpenMS_ElutionPeakDetection.parameters
@ingroup Quantitation
*/
class OPENMS_DLLAPI ElutionPeakDetection :
public DefaultParamHandler, public ProgressLogger
{
public:
/// Default Constructor
ElutionPeakDetection();
/// Destructor
~ElutionPeakDetection() override;
/** @brief Extracts chromatographic peaks from a single MassTrace and
* stores the resulting split traces in a vector of new mass traces.
*
* @note Smoothed intensities are added to @p mt_vec
*
* @param[in,out] mt Input mass trace
* @param[out] single_mtraces Output single mass traces (detected peaks)
*
*/
void detectPeaks(MassTrace& mt, std::vector<MassTrace>& single_mtraces);
/** @brief Extracts chromatographic peaks from multiple MassTraces and
* stores the resulting split traces in a vector of new mass traces.
*
* @note Smoothed intensities are added to @p mt_vec
*
* @param[in,out] mt_vec Input mass traces
* @param[out] single_mtraces Output single mass traces (detected peaks)
*
*/
void detectPeaks(std::vector<MassTrace>& mt_vec, std::vector<MassTrace>& single_mtraces);
/// Filter out mass traces below lower 5 % quartile and above upper 95 % quartile
void filterByPeakWidth(std::vector<MassTrace>&, std::vector<MassTrace>&);
/// Compute noise level (as RMSE of the actual signal and the smoothed signal)
double computeMassTraceNoise(const MassTrace&);
/// Compute the signal to noise ratio (estimated by computeMassTraceNoise)
double computeMassTraceSNR(const MassTrace&);
/// Compute the signal to noise ratio at the apex (estimated by computeMassTraceNoise)
double computeApexSNR(const MassTrace&);
/** @brief Computes local extrema on a mass trace
*
* This function computes local extrema on a given input mass trace. It
* works on the smoothed intensities which must be available at this step.
* Initially it identifies potential maxima as peaks that have maximum
* intensity within a range of peak +/- num_neighboring_peaks.
* All such maxima in the smoothed data get added to the list of maxima.
* Minima are found through bisection between the maxima.
*
* @param[in] tr Input mass trace
* @param[in] num_neighboring_peaks How many data points are expected to belong
* to a peak, i.e. the expected peak width
* (this is used to split traces and find
* maxima)
* @param[out] chrom_maxes Output of maxima (gets cleared)
* @param[out] chrom_mins Output of minima (gets cleared)
*
* Returns a vector of indices where a maxima may occur (chrom_maxes) and a
* vector of indices where a minima may occur (chrom_mins).
*
* @note this expects that the input mass trace has been smoothed before
* and the smoothed intensities are available through tr.getSmoothedIntensities().
*
*/
void findLocalExtrema(const MassTrace& tr, const Size& num_neighboring_peaks,
std::vector<Size>& chrom_maxes, std::vector<Size>& chrom_mins) const;
/// adds smoothed_intensities to internal data of @p mt
void smoothData(MassTrace& mt, int win_size) const;
protected:
void updateMembers_() override;
private:
double chrom_fwhm_;
double chrom_peak_snr_;
double min_fwhm_;
double max_fwhm_;
/// Type of width filtering
String pw_filtering_;
/// Whether to apply S/N filtering
bool mt_snr_filtering_;
/// Main function to do the work
void detectElutionPeaks_(MassTrace&, std::vector<MassTrace>&);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FEATUREFINDER/SeedListGenerator.h | .h | 3,361 | 84 | // 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/KERNEL/StandardTypes.h>
#include <OpenMS/DATASTRUCTURES/DPosition.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/KERNEL/ConsensusMap.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <vector>
namespace OpenMS
{
/**
@brief Generate seed lists for feature detection
Seed lists specify locations in an MS experiment where features are expected. Currently, only the "centroided" FeatureFinder algorithm (class @p FeatureFinderAlgorithmPicked) supports custom seed lists (in featureXML format).
@experimental This is a new class that still needs to be tested.
*/
class OPENMS_DLLAPI SeedListGenerator
{
public:
/// List of seed positions
typedef std::vector<DPosition<2> > SeedList;
/// Default constructor
SeedListGenerator();
/**
@brief Generate a seed list based on an MS experiment
This uses the locations of MS2 precursors as seed positions.
*/
void generateSeedList(const PeakMap & experiment, SeedList & seeds);
/**
@brief Generate a seed list based on a list of peptide identifications
This uses the retention time of the MS2 precursor ("RT" MetaInfo entry) together with either the precursor m/z value ("MZ" MetaInfo entry) or - if @p use_peptide_mass is true - the monoisotopic mass and charge of the best peptide hit to define the seed position for a peptide identification.
The peptide hits in @p peptides will be sorted if @p use_peptide_mass is true.
*/
void generateSeedList(PeptideIdentificationList & peptides,
SeedList & seeds, bool use_peptide_mass = false);
/**
@brief Generate seed lists based on a consensus map
This creates one seed list per constituent map of the consensus map. For each constituent map, a seed is generated at the position of each consensus feature that does not contain a sub-feature from this map. (The idea is to fill "holes" in the consensus map by looking for features explicitly at the positions of the "holes".)
The seed lists are indexed by the IDs of the constituent maps in the consensus map.
Note that the resulting seed lists use the retention time scale of the consensus map, which might be different from the original time scales of the experiments if e.g. the MapAligner tool was used to perform retention time correction as part of the alignment process.
*/
void generateSeedLists(const ConsensusMap & consensus,
std::map<UInt64, SeedList> & seed_lists);
/// Convert a list of seed positions to a feature map (expected format for FeatureFinder)
void convertSeedList(const SeedList & seeds, FeatureMap & features);
/// Convert a feature map with seed positions back to a simple list
void convertSeedList(const FeatureMap & features, SeedList & seeds);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FEATUREFINDER/ElutionModelFitter.h | .h | 2,261 | 63 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hendrik Weisser $
// $Authors: Hendrik Weisser $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/FEATUREFINDER/FeatureFinderAlgorithmPickedHelperStructs.h>
#include <OpenMS/FEATUREFINDER/TraceFitter.h>
namespace OpenMS
{
/**
@brief Helper class for fitting elution models to features
@htmlinclude OpenMS_ElutionModelFitter.parameters
*/
class OPENMS_DLLAPI ElutionModelFitter :
public DefaultParamHandler
{
public:
/// Default constructor
ElutionModelFitter();
/// Destructor
~ElutionModelFitter() override;
/**
@brief Fit models of elution profiles to all features (and validate them)
Assumptions (not checked!):
- all features have meta values "left-"/"rightWidth" giving RT start/end
- all features have subordinates (for the mass traces/transitions)
- each subordinate has an appropriate meta value "isotope_probability"
- each subordinate has one convex hull
- all convex hulls in one feature contain the same number (> 0) of points
- the y coordinates of the hull points store the intensities
*/
void fitElutionModels(FeatureMap& features);
protected:
typedef FeatureFinderAlgorithmPickedHelperStructs::MassTrace MassTrace;
typedef FeatureFinderAlgorithmPickedHelperStructs::MassTraces MassTraces;
/// Calculate quality of model fit (mean relative error)
double calculateFitQuality_(const TraceFitter* fitter,
const MassTraces& traces);
/// Helper function to fit (and validate) a model for one set of mass traces
void fitAndValidateModel_(TraceFitter* fitter, MassTraces& traces,
Feature& feature, double region_start,
double region_end, bool asymmetric,
double area_limit, double check_boundaries);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FEATUREFINDER/EGHTraceFitter.h | .h | 3,450 | 119 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Stephan Aiche $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/FEATUREFINDER/TraceFitter.h>
namespace OpenMS
{
/**
* @brief A RT Profile fitter using an Exponential Gaussian Hybrid background model
*
* Lan K, Jorgenson JW.
* <b>A hybrid of exponential and gaussian functions as a simple model of asymmetric chromatographic peaks.</b>
* <em>Journal of Chromatography A.</em> 915 (1-2)p. 1-13.
* Available at: http://linkinghub.elsevier.com/retrieve/pii/S0021967301005945
*
* @htmlinclude OpenMS_EGHTraceFitter.parameters
*
* @experimental Needs further testing on real data. Note that the tests are currently also focused on testing the EGH as replacement for the gaussian.
*/
class OPENMS_DLLAPI EGHTraceFitter :
public TraceFitter
{
public:
/** Functor for LM Optimization */
class EGHTraceFunctor :
public TraceFitter::GenericFunctor
{
public:
EGHTraceFunctor(int dimensions,
const TraceFitter::ModelData* data);
~EGHTraceFunctor() override;
int operator()(const double* x, double* fvec) override;
// compute Jacobian matrix for the different parameters
int df(const double* x, double* J) override;
protected:
const TraceFitter::ModelData* m_data;
};
EGHTraceFitter();
EGHTraceFitter(const EGHTraceFitter& other);
EGHTraceFitter& operator=(const EGHTraceFitter& source);
~EGHTraceFitter() override;
// override important methods
void fit(FeatureFinderAlgorithmPickedHelperStructs::MassTraces& traces) override;
double getLowerRTBound() const override;
double getTau() const;
double getUpperRTBound() const override;
double getHeight() const override;
double getSigma() const;
double getCenter() const override;
bool checkMaximalRTSpan(const double max_rt_span) override;
bool checkMinimalRTSpan(const std::pair<double, double>& rt_bounds, const double min_rt_span) override;
double getValue(double rt) const override;
double getArea() override;
double getFWHM() const override;
String getGnuplotFormula(const FeatureFinderAlgorithmPickedHelperStructs::MassTrace& trace, const char function_name, const double baseline, const double rt_shift) override;
protected:
double apex_rt_;
double height_;
double sigma_;
double tau_;
std::pair<double, double> sigma_5_bound_;
double region_rt_span_;
/// Coefficients to calculate the proportionality factor for the peak area
static const double EPSILON_COEFS_[];
static const Size NUM_PARAMS_;
/**
* @brief Return an ordered pair of the positions where the EGH reaches a height of alpha * height of the EGH
*
* @param[in] alpha The alpha at which the boundaries should be computed
*/
std::pair<double, double> getAlphaBoundaries_(const double alpha) const;
void getOptimizedParameters_(const std::vector<double>& x_init) override;
void setInitialParameters_(FeatureFinderAlgorithmPickedHelperStructs::MassTraces& traces);
void updateMembers_() override;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FEATUREFINDER/LevMarqFitter1D.h | .h | 2,849 | 106 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
#include <OpenMS/FEATUREFINDER/Fitter1D.h>
#include <algorithm>
#include <vector>
namespace OpenMS
{
/**
@brief Abstract class for 1D-model fitter using Levenberg-Marquardt algorithm for parameter optimization.
*/
class OPENMS_DLLAPI LevMarqFitter1D : public Fitter1D
{
public:
typedef std::vector<double> ContainerType;
/** Generic functor for LM-Optimization
* Uses raw pointer interface to avoid Eigen in public headers.
* Implementations should use Eigen::Map to wrap these pointers.
*/
// TODO: This is copy and paste from TraceFitter.h. Make a generic wrapper for LM optimization
class GenericFunctor
{
public:
int inputs() const
{
return m_inputs;
}
int values() const
{
return m_values;
}
GenericFunctor(int dimensions, int num_data_points) : m_inputs(dimensions), m_values(num_data_points)
{
}
virtual ~GenericFunctor()
{
}
/// Compute residuals. x has size inputs(), fvec has size values()
virtual int operator()(const double* x, double* fvec) const = 0;
/// Compute Jacobian matrix. x has size inputs(), J is values() x inputs() (column-major)
virtual int df(const double* x, double* J) const = 0;
protected:
const int m_inputs, m_values;
};
/// Default constructor
LevMarqFitter1D() : Fitter1D()
{
this->defaults_.setValue("max_iteration", 500, "Maximum number of iterations using by Levenberg-Marquardt algorithm.", {"advanced"});
}
/// copy constructor
LevMarqFitter1D(const LevMarqFitter1D& source) : Fitter1D(source), max_iteration_(source.max_iteration_)
{
}
/// destructor
~LevMarqFitter1D() override
{
}
/// assignment operator
LevMarqFitter1D& operator=(const LevMarqFitter1D& source)
{
if (&source == this)
return *this;
Fitter1D::operator=(source);
max_iteration_ = source.max_iteration_;
return *this;
}
protected:
/// Parameter indicates symmetric peaks
bool symmetric_;
/// Maximum number of iterations
Int max_iteration_;
/**
@brief Optimize start parameter
@exception Exception::UnableToFit is thrown if fitting cannot be performed
*/
void optimize_(std::vector<double>& x_init, GenericFunctor& functor) const;
void updateMembers_() override;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FEATUREFINDER/MultiplexIsotopicPeakPattern.h | .h | 2,518 | 110 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Lars Nilse $
// $Authors: Lars Nilse $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/FEATUREFINDER/MultiplexDeltaMasses.h>
#include <vector>
#include <algorithm>
#include <iostream>
namespace OpenMS
{
/**
* @brief data structure for pattern of isotopic peaks
*
* Groups of peptides appear as characteristic patterns of isotopic peaks
* in MS1 spectra. For example, for an Arg6 labeled SILAC peptide pair
* of charge 2+ with three isotopic peaks we expect peaks
* at relative m/z shifts of 0, 0.5, 1, 3, 3.5 and 4 Th.
*/
class OPENMS_DLLAPI MultiplexIsotopicPeakPattern
{
public:
/**
* @brief constructor
*/
MultiplexIsotopicPeakPattern(int c, int ppp, MultiplexDeltaMasses ms, int msi);
/**
* @brief returns charge
*/
int getCharge() const;
/**
* @brief returns peaks per peptide
*/
int getPeaksPerPeptide() const;
/**
* @brief returns mass shifts
*/
MultiplexDeltaMasses getMassShifts() const;
/**
* @brief returns mass shift index
*/
int getMassShiftIndex() const;
/**
* @brief returns number of mass shifts i.e. the number of peptides in the multiplet
*/
unsigned getMassShiftCount() const;
/**
* @brief returns mass shift at position i
*/
double getMassShiftAt(size_t i) const;
/**
* @brief returns m/z shift at position i
*/
double getMZShiftAt(size_t i) const;
/**
* @brief returns number of m/z shifts
*/
unsigned getMZShiftCount() const;
private:
/**
* @brief m/z shifts between isotopic peaks
* (number of mz_shifts_ = peaks_per_peptide_ * number of mass_shifts_)
*/
std::vector<double> mz_shifts_;
/**
* @brief charge
*/
int charge_;
/**
* @brief number of isotopic peaks in each peptide
*/
int peaks_per_peptide_;
/**
* @brief mass shifts between peptides
* (including zero mass shift for first peptide)
*/
MultiplexDeltaMasses mass_shifts_;
/**
* @brief index in mass shift list
*/
int mass_shift_index_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FEATUREFINDER/MultiplexSatelliteProfile.h | .h | 1,393 | 58 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Lars Nilse $
// $Authors: Lars Nilse $
// --------------------------------------------------------------------------
#pragma once
namespace OpenMS
{
/**
* @brief data structure storing a single satellite data point
*
* The satellite data point is a spline-interpolated point of profile MSExperiment.
* The triplet of RT, m/z and intensity is therefore stored explicitly.
*
* @see MultiplexFilteredPeak, MultiplexSatelliteCentroided
*/
class OPENMS_DLLAPI MultiplexSatelliteProfile
{
public:
/**
* @brief constructor
*/
MultiplexSatelliteProfile(float rt, double mz, float intensity);
/**
* @brief returns the RT of the satellite data point
*/
float getRT() const;
/**
* @brief returns the m/z of the satellite data point
*/
double getMZ() const;
/**
* @brief returns the intensity of the satellite data point
*/
float getIntensity() const;
private:
/**
* @brief position and intensity of the data point within the spline-interpolated experiment
*/
float rt_;
double mz_;
float intensity_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FEATUREFINDER/FeatureFinderAlgorithm.h | .h | 3,220 | 128 | // 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/KERNEL/StandardTypes.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
namespace OpenMS
{
// forward declaration
class FeatureMap;
/// Summary of fitting results
struct OPENMS_DLLAPI Summary
{
std::map<String, UInt> exception; ///<count exceptions
UInt no_exceptions;
std::map<String, UInt> mz_model; ///<count used mz models
std::map<float, UInt> mz_stdev; ///<count used mz standard deviations
std::vector<UInt> charge; ///<count used charges
double corr_mean, corr_max, corr_min; //boxplot for correlation
/// Initial values
Summary() :
no_exceptions(0),
corr_mean(0),
corr_max(0),
corr_min(1)
{}
};
/**
@brief Abstract base class for FeatureFinder algorithms
*/
class FeatureFinderAlgorithm :
public DefaultParamHandler,
public ProgressLogger
{
public:
/// Input map type
typedef PeakMap MapType;
/// Coordinate/Position type of peaks
typedef MapType::CoordinateType CoordinateType;
/// Intensity type of peaks
typedef MapType::IntensityType IntensityType;
/// default constructor
FeatureFinderAlgorithm() :
DefaultParamHandler("FeatureFinderAlgorithm"),
map_(nullptr),
features_(nullptr)
{
}
/// destructor
~FeatureFinderAlgorithm() override
{
}
/// register all derived classes here (see FeatureFinderAlgorithm_impl.h)
/// Main method that implements the actual algorithm
virtual void run() = 0;
/**
@brief Returns the default parameters. Reimplement
Reimplement if you derive a class and have to incorporate sub-algorithm default parameters.
*/
virtual Param getDefaultParameters() const
{
return this->defaults_;
}
/// Sets a reference to the calling FeatureFinder
void setData(const MapType& map, FeatureMap& features)
{
map_ = ↦
features_ = &features;
}
/**
@brief Sets a reference to the calling FeatureFinder
@exception Exception::IllegalArgument is thrown if the algorithm does not support user-specified seed lists
*/
virtual void setSeeds(const FeatureMap& seeds)
{
if (!seeds.empty())
{
throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "The used feature detection algorithm does not support user-specified seed lists!");
}
}
protected:
/// Input data pointer
const MapType* map_;
/// Output data pointer
FeatureMap* features_;
private:
/// Not implemented
FeatureFinderAlgorithm& operator=(const FeatureFinderAlgorithm&);
/// Not implemented
FeatureFinderAlgorithm(const FeatureFinderAlgorithm&);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/FEATUREFINDER/MultiplexDeltaMasses.h | .h | 2,599 | 102 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Lars Nilse $
// $Authors: Lars Nilse $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <vector>
#include <set>
#include <algorithm>
#include <iostream>
namespace OpenMS
{
/**
* @brief data structure for mass shift pattern
*
* Groups of labelled peptides appear with characteristic mass shifts.
*
* For example, for an Arg6 labeled SILAC peptide pair we expect to see
* mass shifts of 0 and 6 Da. Or as second example, for a
* peptide pair of a dimethyl labelled sample with a single lysine
* we will see mass shifts of 56 Da and 64 Da.
* 28 Da (N-term) + 28 Da (K) and 34 Da (N-term) + 34 Da (K)
* for light and heavy partners respectively.
*
* The data structure stores the mass shifts and corresponding labels
* for a group of matching peptide features.
*/
class OPENMS_DLLAPI MultiplexDeltaMasses
{
public:
/**
* @brief set of labels associated with a mass shift
*
* For example, a set of SILAC labels [Lys8, Lys8, Arg10] would
* result in a +26 Da mass shift.
*/
typedef std::multiset<String> LabelSet;
/**
* @brief mass shift with corresponding label set
*/
struct OPENMS_DLLAPI DeltaMass
{
double delta_mass;
LabelSet label_set;
DeltaMass(double dm, LabelSet ls);
// delta mass with a label set containing a single label
DeltaMass(double dm, const String& l);
};
/**
* @brief constructor
*/
MultiplexDeltaMasses();
/**
* @brief constructor
*/
MultiplexDeltaMasses(const std::vector<DeltaMass>& dm);
/**
* @brief returns delta masses
*/
std::vector<DeltaMass>& getDeltaMasses();
/**
* @brief returns delta masses
*/
const std::vector<DeltaMass>& getDeltaMasses() const;
/**
* @brief converts a label set to a string
*/
static String labelSetToString(const LabelSet& ls);
private:
/**
* @brief mass shifts between peptides
* (including zero mass shift for first peptide)
*/
std::vector<DeltaMass> delta_masses_;
};
bool operator<(const MultiplexDeltaMasses &dm1, const MultiplexDeltaMasses &dm2);
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/APPLICATIONS/INIUpdater.h | .h | 1,276 | 54 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/DATASTRUCTURES/Param.h>
#include <OpenMS/DATASTRUCTURES/ToolDescription.h>
#include <map>
namespace OpenMS
{
/**
@brief Updates an INI
*/
/// map each old TOPP tool to its new Name
typedef std::map<Internal::ToolDescriptionInternal, Internal::ToolDescriptionInternal> ToolMapping;
class OPENMS_DLLAPI INIUpdater
{
public:
INIUpdater();
StringList getToolNamesFromINI(const Param & ini) const;
const ToolMapping & getNameMapping();
/*
Finds the name of the new tool.
The tools_type is optional and should be "" if there is none.
The tools_type is ignored if there is a mapping without a type.
@return true on success
*/
bool getNewToolName(const String & old_name, const String & tools_type, String & new_name);
private:
static ToolMapping map_;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/APPLICATIONS/TOPPBase.h | .h | 47,671 | 1,022 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm, Clemens Groepl $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/CONCEPT/GlobalExceptionHandler.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/DATASTRUCTURES/Param.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/METADATA/DataProcessing.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <fstream>
#include <QtCore/QString>
#include <QtCore/qcontainerfwd.h> // for QStringList
namespace OpenMS
{
class FeatureMap;
class ConsensusMap;
struct ParameterInformation;
/**
@brief Stores Citations for individual TOPP tools.
An example would be
\code{.cpp}
Citation c = {"Pfeuffer J, Bielow C, Wein S, Jeong K, Netz E, Walter A, Alka O et al.",
"OpenMS 3 enables reproducible analysis of large-scale mass spectrometry data",
"Nat Methods 21, 365–367 (2024)",
"10.1038/s41592-024-02197-7"};
\endcode
Suggested format is AMA, e.g. https://www.lib.jmu.edu/citation/amaguide.pdf
*/
struct Citation
{
std::string authors; ///< list of authors in AMA style, i.e. "surname initials", ...
std::string title; ///< title of article
std::string when_where; ///< suggested format: journal. year; volume, issue: pages
std::string doi; ///< plain DOI (no urls), e.g. 10.1021/pr100177k
/// mangle members to string
std::string toString() const
{
return authors + ". " + title + ". " + when_where + ". doi:" + doi + ".";
}
};
namespace Exception
{
/// An unregistered parameter was accessed
class OPENMS_DLLAPI UnregisteredParameter :
public Exception::BaseException
{
public:
UnregisteredParameter(const char* file, int line, const char* function, const String& parameter) :
BaseException(file, line, function, "UnregisteredParameter", parameter)
{
GlobalExceptionHandler::getInstance().setMessage(what());
}
};
/// A parameter was accessed with the wrong type
class OPENMS_DLLAPI WrongParameterType :
public Exception::BaseException
{
public:
WrongParameterType(const char* file, int line, const char* function, const String& parameter) :
BaseException(file, line, function, "WrongParameterType", parameter)
{
GlobalExceptionHandler::getInstance().setMessage(what());
}
};
/// A required parameter was not given
class OPENMS_DLLAPI RequiredParameterNotGiven :
public Exception::BaseException
{
public:
RequiredParameterNotGiven(const char* file, int line, const char* function, const String& parameter) :
BaseException(file, line, function, "RequiredParameterNotGiven", parameter)
{
GlobalExceptionHandler::getInstance().setMessage(what());
}
};
}
/**
@brief Base class for TOPP applications.
This base class implements functionality used in most TOPP tools:
- parameter handling
- file handling
- progress logging
If you want to create a new TOPP tool, please take care of the following:
- derive a new class from this class
- implement the registerOptionsAndFlags_ and main_ methods
- add a Doxygen page for the tool and add the page to TOPP.doxygen
- hide the derived class in the OpenMS documentation by using Doxygen condition macros.
@todo: replace writeLog_, writeDebug_ with a logger concept
we'd need something like -VLevels [LOGGERS] to specify which loggers shall print something
the '-log' flag should clone all output to the log-file (maybe with custom [LOGGERS]), which can either be specified directly or is
equal to '-out' (if present) with a ".log" suffix
maybe a new LOGGER type (TOPP), which is only usable on TOPP level?
*/
class OPENMS_DLLAPI TOPPBase
{
public:
inline static const char* TAG_OUTPUT_FILE = "output file";
inline static const char* TAG_INPUT_FILE = "input file";
inline static const char* TAG_OUTPUT_DIR = "output dir";
inline static const char* TAG_OUTPUT_PREFIX = "output prefix";
inline static const char* TAG_ADVANCED = "advanced";
inline static const char* TAG_REQUIRED = "required";
/// Exit codes
enum ExitCodes
{
EXECUTION_OK,
INPUT_FILE_NOT_FOUND,
INPUT_FILE_NOT_READABLE,
INPUT_FILE_CORRUPT,
INPUT_FILE_EMPTY,
CANNOT_WRITE_OUTPUT_FILE,
ILLEGAL_PARAMETERS,
MISSING_PARAMETERS,
UNKNOWN_ERROR,
EXTERNAL_PROGRAM_ERROR,
PARSE_ERROR,
INCOMPATIBLE_INPUT_DATA,
INTERNAL_ERROR,
UNEXPECTED_RESULT,
EXTERNAL_PROGRAM_NOTFOUND ///< external program, e.g. comet.exe not found
};
/// No default constructor
TOPPBase() = delete;
/// No default copy constructor.
TOPPBase(const TOPPBase&) = delete;
/**
@brief Constructor
@param[in] name Tool name.
@param[in] description Short description of the tool (one line).
@param[in] official If this is an official TOPP tool contained in the OpenMS/TOPP release.
If @em true the tool name is checked against the list of TOPP tools and a warning printed if missing.
@param[in] citations Add one or more citations if they are associated specifically to this TOPP tool; they will be printed during `--help`
@param[in] toolhandler_test Check if this tool is registered with the ToolHandler (disable for unit tests only)
*/
TOPPBase(const String& name, const String& description, bool official = true, const std::vector<Citation>& citations = {}, bool toolhandler_test = true);
/// Destructor
virtual ~TOPPBase();
/// Main routine of all TOPP applications
ExitCodes main(int argc, const char** argv);
/**
@brief Sets the maximal number of usable threads
@param[in] num_threads The number of threads that should be usable.
@note This method only works if %OpenMS is compiled with %OpenMP support.
*/
static void setMaxNumberOfThreads(int num_threads);
/**
@brief Returns the prefix used to identify the tool
This prefix is later found in the INI file for a TOPP tool.
f.e.: "FileConverter:1:"
*/
String getToolPrefix() const;
/// Returns a link to the documentation of the tool (accessible on our servers and only after inclusion in the nightly branch or a release).
String getDocumentationURL() const;
/// The latest and greatest OpenMS citation
static const Citation cite_openms;
private:
/// Tool name. This is assigned once and for all in the constructor.
String const tool_name_;
/// Tool description. This is assigned once and for all in the constructor.
String const tool_description_;
/// Instance number
Int const instance_number_;
/// Location in the ini file where to look for parameters.
String const ini_location_;
/// All parameters relevant to this invocation of the program.
Param param_;
/// All parameters specified in the ini file
Param param_inifile_;
/// Parameters from command line
Param param_cmdline_;
/// Parameters from instance section
Param param_instance_;
/// Parameters from common section with tool name.
Param param_common_tool_;
/// Parameters from common section without tool name.
Param param_common_;
/// Log file stream. Use the writeLog_() and writeDebug_() methods to access it.
mutable std::ofstream log_;
/**
@brief Ensures that at least some default logging destination is
opened for writing in append mode.
@note This might be invoked at various places early in the startup
process of the TOPP tool. Thus we cannot consider the ini file here.
The final logging destination is determined in main().
*/
void enableLogging_() const;
/// Storage location for parameter information
std::vector<ParameterInformation> parameters_;
/**
@brief This method should return the default parameters for subsections.
It is called once for each registered subsection, when writing the example ini file.
Reimplement this method to set the defaults written in the 'write_ini' method.
@note Make sure to set the 'advanced' flag of the parameters right in order to hide certain parameters from inexperienced users.
*/
virtual Param getSubsectionDefaults_(const String& section) const;
/**
@brief Returns a single Param object containing all subsection parameters.
@return A single Param object containing all parameters for all registered subsections.
@see getSubsectionDefaults_(String)
*/
Param getSubsectionDefaults_() const;
/// Storage location and description for allowed subsections
std::map<String, String> subsections_;
/// Storage location and description for allowed subsections from TOPP tool's command-line parameters
std::map<String, String> subsections_TOPP_;
/**
@brief Parses command line arguments using parameter definitions from TOPPBase
Parses command line arguments according to the current parameter definitions and returns the result as a Param object.
@param[in] argc @p argc variable from command line
@param[in] argv @p argv variable from command line
@param[in] misc Key to store a StringList of all non-option arguments
@param[in] unknown Key to store a StringList of all unknown options
@return A Param object representing the parameters set on the command line.
*/
Param parseCommandLine_(const int argc, const char** argv, const String& misc = "misc", const String& unknown = "unknown");
/**
@name Internal parameter handling
*/
//@{
/**
@brief Return the value of parameter @p key as a string or @p default_value if this value is not set.
@note See getParam_(const String&) const for the order in which parameters are searched.
*/
String getParamAsString_(const String& key, const String& default_value = "") const;
/**
@brief Return the value of parameter @p key as an integer or @p default_value if this value is not set.
@note See getParam_(const String&) const for the order in which parameters are searched.
*/
Int getParamAsInt_(const String& key, Int default_value = 0) const;
/**
@brief Return the value of parameter @p key as a double or @p default_value if this value is not set.
@note See getParam_(const String&) const for the order in which parameters are searched.
*/
double getParamAsDouble_(const String& key, double default_value = 0) const;
/**
@brief Return the value of parameter @p key as a StringList or @p default_value if this value is not set
@note See getParam_(const String&) const for the order in which parameters are searched.
*/
StringList getParamAsStringList_(const String& key, const StringList& default_value) const;
/**
@brief Return the value of parameter @p key as a IntList or @p default_value if this value is not set
@note See getParam_(const String&) const for the order in which parameters are searched.
*/
IntList getParamAsIntList_(const String& key, const IntList& default_value) const;
/**
@brief Return the value of parameter @p key as a DoubleList or @p default_value if this value is not set
@note See getParam_(const String&) const for the order in which parameters are searched.
*/
DoubleList getParamAsDoubleList_(const String& key, const DoubleList& default_value) const;
/**
@brief Return the value of flag parameter @p key as bool.
Only the string values 'true' and 'false' are interpreted.
@exception Exception::InvalidParameter is thrown for non-string parameters and string parameters with values other than 'true' and 'false'.
@note See getParam_(const String&) const for the order in which parameters are searched.
*/
bool getParamAsBool_(const String& key) const;
/**
@brief Return the value @p key of parameters as DataValue. ParamValue::EMPTY indicates that a parameter was not found.
Parameters are searched in this order:
-# command line
-# instance section, e.g. "TOPPTool:1:some_key", see getIniLocation_().
-# common section with tool name, e.g. "common:ToolName:some_key"
-# common section without tool name, e.g. "common:some_key"
where "some_key" == key in the examples.
*/
const ParamValue& getParam_(const String& key) const;
/**
@brief Get the part of a parameter name that makes up the subsection
The subsection extends until the last colon (":"). If there is no subsection, the empty string is returned.
*/
String getSubsection_(const String& name) const;
/// Returns the default parameters
Param getDefaultParameters_() const;
/// Returns the user defaults for the given tool, if any default parameters are stored in the users home
Param getToolUserDefaults_(const String& tool_name) const;
//@}
protected:
/// Version string (if empty, the OpenMS/TOPP version is printed)
String version_;
/// Version string including additional revision/date time information. Note: This differs from version_ only if not provided by the user.
String verboseVersion_;
/// Flag indicating if this an official TOPP tool
bool official_;
/// Papers, specific for this tool (will be shown in '--help')
std::vector<Citation> citations_;
/// Enable the ToolHandler tests
bool toolhandler_test_;
/**
@brief Returns the location of the ini file where parameters are taken
from. E.g. if the command line was <code>TOPPTool -instance 17</code>, then
this will be <code>"TOPPTool:17:"</code>. Note the ':' at the end.
This is assigned during tool startup, depending on the command line but (of course) not depending on ini files.
*/
const String& getIniLocation_() const
{
return ini_location_;
}
///Returns the tool name
const String& toolName_() const;
/**
@name Parameter handling
Use the methods registerStringOption_, registerInputFile_, registerOutputFile_, registerOutputPrefix_, registerDoubleOption_,
registerIntOption_ and registerFlag_ in order to register parameters in registerOptionsAndFlags_.
To access the values of registered parameters in the main_ method use methods
getStringOption_ (also for input and output files), getDoubleOption_, getIntOption_,getStringList_(also for input and output file lists),getIntList_,getDoubleList_, and getFlag_.
The values of certain options can be restricted using: setMinInt_, setMaxInt_, setMinFloat_,
setMaxFloat_, setValidStrings_ and setValidFormats_.
In order to format the help output, the method addEmptyLine_ can be used.
*/
//@{
/**
@brief Sets the valid command line options (with argument) and flags (without argument).
The options '-ini' '-log' '-instance' '-debug' and the flag '--help' are automatically registered.
*/
virtual void registerOptionsAndFlags_() = 0;
/// Utility function that determines a suitable argument value for the given Param::ParamEntry
String getParamArgument_(const Param::ParamEntry& entry) const;
/// Translates the given parameter object into a vector of ParameterInformation, that can be utilized for cl parsing
std::vector<ParameterInformation> paramToParameterInformation_(const Param& param) const;
/**
@brief Transforms a ParamEntry object to command line parameter (ParameterInformation).
A ParamEntry of type String is turned into a flag if its default value is "false" and its valid strings are "true" and "false".
@param[in] entry The ParamEntry that defines name, default value, description, restrictions, and required-/advancedness (via tags) of the parameter.
@param[in] argument Argument description text for the help output.
@param[in] full_name Full name of the parameter, if different from the name in the ParamEntry (ParamEntry names cannot contain sections)
*/
ParameterInformation paramEntryToParameterInformation_(const Param::ParamEntry& entry, const String& argument = "", const String& full_name = "") const;
void registerParamSubsectionsAsTOPPSubsections_(const Param& param);
/// Register command line parameters for all entries in a Param object
void registerFullParam_(const Param& param);
/**
@brief Registers a string option.
@param[in] name Name of the option in the command line and the INI file
@param[in] argument Argument description text for the help output
@param[in] default_value Default argument
@param[in] description Description of the parameter. Indentation of newline is done automatically.
@param[in] required If the user has to provide a value i.e. if the value has to differ from the default (checked in get-method)
@param[in] advanced If @em true, this parameter is advanced and by default hidden in the GUI and during --help.
*/
void registerStringOption_(const String& name, const String& argument, const String& default_value, const String& description, bool required = true, bool advanced = false);
/**
@brief Sets the valid strings for a string option or a whole string list
@exception Exception::ElementNotFound is thrown if the parameter is unset or not a string parameter
@exception Exception::InvalidParameter is thrown if the valid strings contain comma characters
*/
void setValidStrings_(const String& name, const std::vector<String>& strings);
/**
@brief Sets the valid strings for a string option or a whole string list
This overload should be used for options which are 1:1 with Enums + their static string representations.
E.g. MSNumpressCoder::NamesOfNumpressCompression[]
@exception Exception::ElementNotFound is thrown if the parameter is unset or not a string parameter
@exception Exception::InvalidParameter is thrown if the valid strings contain comma characters
*/
void setValidStrings_(const String& name, const std::string vstrings[], int count);
/**
@brief Registers an input file option.
Input files behave like string options, but are automatically checked with inputFileReadable_()
when the option is accessed in the TOPP tool.
This may also enable lookup on the PATH or skipping of the existence-check (see @p tags).
@param[in] name Name of the option in the command line and the INI file
@param[in] argument Argument description text for the help output
@param[in] default_value Default argument
@param[in] description Description of the parameter. Indentation of newline is done automatically.
@param[in] required If the user has to provide a value i.e. if the value has to differ from the default (verified in getStringOption())
@param[in] advanced If @em true, this parameter is advanced and by default hidden in the GUI and during --help.
@param[in] tags A list of tags, extending/omitting automated checks on the input file (e.g. when its an executable)
Valid tags: @em 'skipexists' - will prevent checking if the given file really exists (useful for partial paths, e.g. in OpenMS/share/... which will be resolved by the TOPP tool internally)
@em 'is_executable' - checks existence of the file first using its actual value, and upon failure also using the PATH environment (and common exe file endings on Windows, e.g. .exe and .bat).
*/
void registerInputFile_(const String& name, const String& argument, const String& default_value, const String& description, bool required = true, bool advanced = false, const StringList& tags = StringList());
/**
@brief Registers an output file option.
Output files behave like string options, but are automatically checked with outputFileWritable_()
when the option is accessed in the TOPP tool.
@param[in] name Name of the option in the command line and the INI file
@param[in] argument Argument description text for the help output
@param[in] default_value Default argument
@param[in] description Description of the parameter. Indentation of newline is done automatically.
@param[in] required If the user has to provide a value i.e. if the value has to differ from the default (checked in get-method)
@param[in] advanced If @em true, this parameter is advanced and by default hidden in the GUI and during --help.
*/
void registerOutputFile_(const String& name, const String& argument, const String& default_value, const String& description, bool required = true, bool advanced = false);
/**
@brief Registers an output file prefix used for tools with multiple file output.
Tools should follow the convention to name output files PREFIX_[0..N-1].EXTENSION.
For example, a tool that splits mzML files into multiple mgf files should create files:
splitted_0.mgf, splitted_1.mgf, ... if splitted got passed as prefix.
Note: setting format(s) via setValidFormat_ for an output prefix can be used to export
e.g. valid CTD files that contain information on the expected output file types. In theory, it is possible
to output different types and list them here but this should be avoided for cleanlyness (prefer multiple
separate outputs). This could be left empty in case of an unknown amount of different extensions that
are produced but is highly recommended.
@param[in] name Name of the option in the command line and the INI file
@param[in] argument Argument description text for the help output
@param[in] default_value Default value (remember, no extension is specified here)
@param[in] description Description of the parameter. Indentation of newline is done automatically.
@param[in] required If the user has to provide a value i.e. if the value has to differ from the default (checked in get-method)
@param[in] advanced If @em true, this parameter is advanced and by default hidden in the GUI and during --help.
*/
void registerOutputPrefix_(const String& name, const String& argument, const String& default_value, const String& description, bool required = true, bool advanced = false);
/**
@brief Registers an output directory used for tools with multiple output files which are not an output file list, i.e. do not correspond to the number of input files.
@note Setting format(s) via setValidFormat_ for an output directory is not possible as directories do not have a file extension.
@param[in] name Name of the option in the command line and the INI file
@param[in] argument Argument description text for the help output
@param[in] default_value Default value
@param[in] description Description of the parameter. Indentation of newline is done automatically.
@param[in] required If the user has to provide a value i.e. if the value has to differ from the default (checked in get-method)
@param[in] advanced If @em true, this parameter is advanced and by default hidden in the GUI and during --help.
*/
void registerOutputDir_(const String& name, const String& argument, const String& default_value, const String& description, bool required = true, bool advanced = false);
/**
@brief Sets the formats for a input/output file option or for all members of an input/output file lists
Setting the formats causes a check for the right file format (input file) or the right file extension (output file).
This check is performed only, when the option is accessed in the TOPP tool.
When @p force_OpenMS_format is set, only formats known to OpenMS internally are allowed (default).
Note: Formats for output file prefixes are exported to e.g. CTD but no checks are performed (as they don't contain a file extension)
@exception Exception::ElementNotFound is thrown if the parameter is unset or not a file parameter
@exception Exception::InvalidParameter is thrown if an unknown format name is used (@see FileHandler::Type)
*/
void setValidFormats_(const String& name, const std::vector<String>& formats, const bool force_OpenMS_format = true);
/**
@brief Registers a double option.
@param[in] name Name of the option in the command line and the INI file
@param[in] argument Argument description text for the help output
@param[in] default_value Default argument
@param[in] description Description of the parameter. Indentation of newline is done automatically.
@param[in] required If the user has to provide a value i.e. if the value has to differ from the default (checked in get-method)
@param[in] advanced If @em true, this parameter is advanced and by default hidden in the GUI and during --help.
*/
void registerDoubleOption_(const String& name, const String& argument, double default_value, const String& description, bool required = true, bool advanced = false);
/**
@brief Sets the minimum value for the integer parameter(can be a list of integers,too) @p name.
@exception Exception::ElementNotFound is thrown if @p name is not found or if the parameter type is wrong
*/
void setMinInt_(const String& name, Int min);
/**
@brief Sets the maximum value for the integer parameter(can be a list of integers,too) @p name.
@exception Exception::ElementNotFound is thrown if @p name is not found or if the parameter type is wrong
*/
void setMaxInt_(const String& name, Int max);
/**
@brief Sets the minimum value for the floating point parameter(can be a list of floating points,too) @p name.
@exception Exception::ElementNotFound is thrown if @p name is not found or if the parameter type is wrong
*/
void setMinFloat_(const String& name, double min);
/**
@brief Sets the maximum value for the floating point parameter(can be a list of floating points,too) @p name.
@exception Exception::ElementNotFound is thrown if @p name is not found or if the parameter type is wrong
*/
void setMaxFloat_(const String& name, double max);
/**
@brief Registers an integer option.
@param[in] name Name of the option in the command line and the INI file
@param[in] argument Argument description text for the help output
@param[in] default_value Default argument
@param[in] description Description of the parameter. Indentation of newline is done automatically.
@param[in] required If the user has to provide a value i.e. if the value has to differ from the default (checked in get-method)
@param[in] advanced If @em true, this parameter is advanced and by default hidden in the GUI and during --help.
*/
void registerIntOption_(const String& name, const String& argument,
Int default_value, const String& description,
bool required = true, bool advanced = false);
/**
@brief Registers a list of integers option.
@param[in] name Name of the option in the command line and the INI file
@param[in] argument Argument description text for the help output
@param[in] default_value Default argument
@param[in] description Description of the parameter. Indentation of newline is done automatically.
@param[in] required If the user has to provide a value i.e. if the value has to differ from the default (checked in get-method)
@param[in] advanced If @em true, this parameter is advanced and by default hidden in the GUI and during --help.
*/
void registerIntList_(const String& name, const String& argument, const IntList& default_value, const String& description, bool required = true, bool advanced = false);
/**
@brief Registers a list of doubles option.
@param[in] name Name of the option in the command line and the INI file
@param[in] argument Argument description text for the help output
@param[in] default_value Default argument
@param[in] description Description of the parameter. Indentation of newline is done automatically.
@param[in] required If the user has to provide a value i.e. if the value has to differ from the default (checked in get-method)
@param[in] advanced If @em true, this parameter is advanced and by default hidden in the GUI and during --help.
*/
void registerDoubleList_(const String& name, const String& argument, const DoubleList& default_value, const String& description, bool required = true, bool advanced = false);
/**
@brief Registers a list of strings option.
@param[in] name Name of the option in the command line and the INI file
@param[in] argument Argument description text for the help output
@param[in] default_value Default argument
@param[in] description Description of the parameter. Indentation of newline is done automatically.
@param[in] required If the user has to provide a value i.e. if the value has to differ from the default (checked in get-method)
@param[in] advanced If @em true, this parameter is advanced and by default hidden in the GUI and during --help.
*/
void registerStringList_(const String& name, const String& argument, const StringList& default_value, const String& description, bool required = true, bool advanced = false);
/**
@brief Registers a list of input files option.
A list of input files behaves like a StringList, but are automatically checked with inputFileWritable_()
when the option is accessed in the TOPP tool.
@param[in] name Name of the option in the command line and the INI file
@param[in] argument Argument description text for the help output
@param[in] default_value Default argument
@param[in] description Description of the parameter. Indentation of newline is done automatically.
@param[in] required If the user has to provide a value i.e. if the value has to differ from the default (checked in get-method)
@param[in] advanced If @em true, this parameter is advanced and by default hidden in the GUI and during --help.
@param[in] tags A list of tags, extending/omitting automated checks on the input file (e.g. when its an executable)
Valid tags: 'skipexists' - will prevent checking if the given file really exists (useful for partial paths, e.g. in OpenMS/share/... which will be resolved by the TOPP tool internally)
'is_executable' - checks existence of the file using the PATH environment (and common exe file endings on Windows, e.g. .exe and .bat).
*/
void registerInputFileList_(const String& name, const String& argument, const StringList& default_value, const String& description, bool required = true, bool advanced = false, const StringList& tags = StringList());
/**
@brief Registers a list of output files option.
A list of output files behaves like a StringList, but are automatically checked with outputFileWritable_()
when the option is accessed in the TOPP tool.
@param[in] name Name of the option in the command line and the INI file
@param[in] argument Argument description text for the help output
@param[in] default_value Default argument
@param[in] description Description of the parameter. Indentation of newline is done automatically.
@param[in] required If the user has to provide a value i.e. if the value has to differ from the default (checked in get-method)
@param[in] advanced If @em true, this parameter is advanced and by default hidden in the GUI and during --help.
*/
void registerOutputFileList_(const String& name, const String& argument, const StringList& default_value, const String& description, bool required = true, bool advanced = false);
/// Registers a flag
void registerFlag_(const String& name, const String& description, bool advanced = false);
/**
@brief Registers an allowed subsection in the INI file (usually from OpenMS algorithms).
Use this method to register subsections that are passed to algorithms.
@see checkParam_
*/
void registerSubsection_(const String& name, const String& description);
/**
@brief Registers an allowed subsection in the INI file originating from the TOPP tool itself.
Use this method to register subsections which is created by a commandline param (registered by e.g. registerDoubleOption_() )
and contains a ':' in its name. This is done to distinguish these parameters from normal subsections,
which are filled by calling 'getSubsectionDefaults_()'. This is not necessary for here.
@see checkParam_
*/
void registerTOPPSubsection_(const String& name, const String& description);
/// Adds an empty line between registered variables in the documentation.
void addEmptyLine_();
/**
@brief Returns the value of a previously registered string option (use `getOutputDirOption()` for output directories)
@exception Exception::UnregisteredParameter is thrown if the parameter was not registered
@exception Exception::RequiredParameterNotGiven is if a required parameter is not present
@exception Exception::WrongParameterType is thrown if the parameter has the wrong type
@exception Exception::InvalidParameter is thrown if the parameter restrictions are not met
*/
String getStringOption_(const String& name) const;
/**
@brief Returns the value of a previously registered output_dir option
@exception Exception::UnregisteredParameter is thrown if the parameter was not registered
@exception Exception::RequiredParameterNotGiven is if a required parameter is not present
@exception Exception::WrongParameterType is thrown if the parameter has the wrong type
@exception Exception::InvalidParameter is thrown if the parameter restrictions are not met
*/
String getOutputDirOption(const String& name) const;
/**
@brief Returns the value of a previously registered double option
@exception Exception::UnregisteredParameter is thrown if the parameter was not registered
@exception Exception::RequiredParameterNotGiven is if a required parameter is not present
@exception Exception::WrongParameterType is thrown if the parameter has the wrong type
@exception Exception::InvalidParameter is thrown if the parameter restrictions are not met
*/
double getDoubleOption_(const String& name) const;
/**
@brief Returns the value of a previously registered integer option
@exception Exception::UnregisteredParameter is thrown if the parameter was not registered
@exception Exception::RequiredParameterNotGiven is if a required parameter is not present
@exception Exception::WrongParameterType is thrown if the parameter has the wrong type
@exception Exception::InvalidParameter is thrown if the parameter restrictions are not met
*/
Int getIntOption_(const String& name) const;
/**
@brief Returns the value of a previously registered StringList
@exception Exception::UnregisteredParameter is thrown if the parameter was not registered
@exception Exception::RequiredParameterNotGiven is if a required parameter is not present
@exception Exception::WrongParameterType is thrown if the parameter has the wrong type
@exception Exception::InvalidParameter is thrown if the parameter restrictions are not met
*/
StringList getStringList_(const String& name) const;
/**
@brief Returns the value of a previously registered IntList
@exception Exception::UnregisteredParameter is thrown if the parameter was not registered
@exception Exception::RequiredParameterNotGiven is if a required parameter is not present
@exception Exception::WrongParameterType is thrown if the parameter has the wrong type
@exception Exception::InvalidParameter is thrown if the parameter restrictions are not met
*/
IntList getIntList_(const String& name) const;
/**
@brief Returns the value of a previously registered DoubleList
@exception Exception::UnregisteredParameter is thrown if the parameter was not registered
@exception Exception::RequiredParameterNotGiven is if a required parameter is not present
@exception Exception::WrongParameterType is thrown if the parameter has the wrong type
@exception Exception::InvalidParameter is thrown if the parameter restrictions are not met
*/
DoubleList getDoubleList_(const String& name) const;
///Returns the value of a previously registered flag
bool getFlag_(const String& name) const;
/**
@brief Finds the entry in the parameters_ array that has the name @p name
@exception Exception::UnregisteredParameter is thrown if the parameter was not registered
*/
const ParameterInformation& findEntry_(const String& name) const;
/**
@brief Return <em>all</em> parameters relevant to this TOPP tool.
Returns a Param that contains everything you can get by the getParamAs...() methods.
*/
Param const& getParam_() const;
/**
@brief Checks top-level entries of @p param according to the information during registration
Only top-level entries and allowed subsections are checked.
Checking the content of the subsection is the duty of the algorithm it is passed to.
This method does not abort execution of the tool, but will warn the user through stderr!
It is called automatically in the main method.
@param[in] param Parameters to check
@param[in] filename The source file name
@param[in] location Exact location inside the source file
*/
void checkParam_(const Param& param, const String& filename, const String& location) const;
/**
@brief checks if files of an input file list exist
Checks if String/Format restrictions are met (or throws InvalidParameter() otherwise).
@param[in] param_value As given via commandline/ini/default
@param[in] param_name Name of the parameter (key)
@param[in] p All meta information for this param
*/
void fileParamValidityCheck_(const StringList& param_value, const String& param_name, const ParameterInformation& p) const;
/**
@brief checks if an input file exists (respecting the flags)
Checks if String/Format restrictions are met (or throws InvalidParameter() otherwise).
For InputFile(s), it checks if the file is readable/findable.
If 'is_executable' is specified as a tag, the filename is searched on PATH and upon success, the full absolute path is returned.
For OutputFile(s), it checks if the file is writeable.
@param[in,out] param_value As given via commandline/ini/default
@param[in] param_name Name of the parameter (key)
@param[in] p All meta information for this param
*/
void fileParamValidityCheck_(String& param_value, const String& param_name, const ParameterInformation& p) const;
/**
@brief Checks if the parameters of the provided ini file are applicable to this tool
This method does not abort execution of the tool, but will warn the user through stderr!
It is called automatically whenever a ini file is loaded.
*/
void checkIfIniParametersAreApplicable_(const Param& ini_params);
//@}
/// Prints the tool-specific command line options and appends the common options.
void printUsage_();
/// The actual "main" method. main_() is invoked by main().
virtual ExitCodes main_(int argc, const char** argv) = 0;
///@name Debug and Log output
//@{
/// Writes a string to the log file and to OPENMS_LOG_INFO
void writeLogInfo_(const String& text) const;
/// Writes a string to the log file and to OPENMS_LOG_WARN
void writeLogWarn_(const String& text) const;
/// Writes a string to the log file and to OPENMS_LOG_ERROR
void writeLogError_(const String& text) const;
/// Writes a string to the log file and to OPENMS_LOG_DEBUG if the debug level is at least @p min_level
void writeDebug_(const String& text, UInt min_level) const;
/// Writes a String followed by a Param to the log file and to OPENMS_LOG_DEBUG if the debug level is at least @p min_level
void writeDebug_(const String& text, const Param& param, UInt min_level) const;
//@}
///@name External processes (TODO consider creating another AdapterBase class)
//@{
/// Runs an external process via ExternalProcess and prints its stderr output on failure or if debug_level > 4
ExitCodes runExternalProcess_(const QString& executable, const QStringList& arguments, const QString& workdir = "", const std::map<QString, QString>& env = std::map<QString, QString>()) const;
/// Runs an external process via ExternalProcess and prints its stderr output on failure or if debug_level > 4
/// Additionally returns the process' stdout and stderr
ExitCodes runExternalProcess_(const QString& executable, const QStringList& arguments, String& proc_stdout, String& proc_stderr, const QString& workdir = "", const std::map<QString, QString>& env = std::map<QString, QString>()) const;
//@}
/**
@name File IO checking methods
Methods used to check the validity of input and output files in main_.
Checking input and output files is only necessary, if you did register the file as string option,
e.g. when only a file prefix is given which is completed in the program.
The exceptions thrown in these methods are caught in the main method of this class.
They do not have to be handled in the tool itself!
*/
//@{
/**
@brief Checks if an input file exists, is readable and is not empty
The @em filename is a URI to the file to be read and @em param_name gives the name of the parameter
, e.g. "in" which specified the filename (this is useful for error messages when the file cannot be read, so the
user can immediately see which parameter to change). If no parameter is responsible for the
name of the input file, then leave @em param_name empty.
@param[in] filename An absolute or relative path+filename
@param[in] param_name Name of the parameter the filename value was provided by
@exception Exception::FileNotFound is thrown if the file is not found
@exception Exception::FileNotReadable is thrown if the file is not readable
@exception Exception::FileEmpty is thrown if the file is empty
*/
void inputFileReadable_(const String& filename, const String& param_name) const;
/**
@brief Checks if an output file is writable
The @em filename is a URI to the file to be written and @em param_name gives the name of the parameter
, e.g. "out" which specified the filename (this is useful for error messages when the file cannot be written, so the
user can immediately see which parameter to change). If no parameter is responsible for the
name of the output file, then leave @em param_name empty.
@exception Exception::UnableToCreateFile is thrown if the file cannot be created
*/
void outputFileWritable_(const String& filename, const String& param_name) const;
//@}
/**
@brief Parses a range string ([a]:[b]) into two variables (doubles)
The variables are only overwritten if a value is set for the respective boundary.
@return True if a value was set for either of the two boundaries
*/
bool parseRange_(const String& text, double& low, double& high) const;
/**
@brief Parses a range string ([a]:[b]) into two variables (integers)
The variables are only overwritten if a value is set for the respective boundary.
@return True if a value was set for either of the two boundaries
*/
bool parseRange_(const String& text, Int& low, Int& high) const;
///Type of progress logging
ProgressLogger::LogType log_type_;
///@name Data processing auxiliary functions
//@{
///Data processing setter for consensus maps
void addDataProcessing_(ConsensusMap& map, const DataProcessing& dp) const;
///Data processing setter for feature maps
void addDataProcessing_(FeatureMap& map, const DataProcessing& dp) const;
///Data processing setter for peak maps
void addDataProcessing_(PeakMap& map, const DataProcessing& dp) const;
///Returns the data processing information
DataProcessing getProcessingInfo_(DataProcessing::ProcessingAction action) const;
///Returns the data processing information
DataProcessing getProcessingInfo_(const std::set<DataProcessing::ProcessingAction>& actions) const;
//@}
/**
@brief Helper function avoiding repeated code between CTD, JSON and CWL.
@param[in,out] writer a parameter writer, designed to be of type ParamCTDFile,
ParamJSONFile or ParamCWLFile
@param[in] write_type The type of file that is being written, typically
write_ctd, write_json or write_cwl.
@param[in] fileExtension The extension of the requested tool description file.
*/
template <typename Writer>
void writeToolDescription_(Writer& writer, std::string write_type, std::string fileExtension);
/**
@brief Test mode
Test mode is enabled using the command line parameter @em -test .
It disables writing of data, which would corrupt tests:
- absolute paths (e.g. in consensus maps)
- processing parameters (input/output files contain absolute paths as well)
- current date
- current OpenMS version
*/
bool test_mode_;
/// .TOPP.ini file for storing system default parameters
static String topp_ini_file_;
/// Debug level set by -debug
Int debug_level_;
private:
/// Adds a left aligned text between registered variables in the documentation e.g. for subdividing the documentation.
/// This should not be usable for derived classes, since this formatting is not carried over to INI files
/// and thus INI files might lack important information.
/// Instead, subdivision of parameters should be achieved using TOPPSubsections with appropriate description
/// Currently only used for "Common TOPP options" within TOPPBase.cpp
void addText_(const String& text);
/**
@brief Returns the parameter identified by the given name.
@param[in] name The name of the parameter to search.
@exception Exception::UnregisteredParameter is thrown if the parameter was not registered
@return A reference to the parameter with the given name.
*/
ParameterInformation& getParameterByName_(const String& name);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/APPLICATIONS/ToolHandler.h | .h | 3,014 | 88 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/ToolDescription.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <map>
#include <QtCore/qcontainerfwd.h> // for QStringList
namespace OpenMS
{
/**
@brief Handles lists of TOPP tools and their categories (for TOPPAS)
Path's were *.ttd files are searched for:
Default:
The OpenMS share directory ([OpenMS]/share/TOOLS/EXTERNAL)
OS specific directories
- [OpenMS]/share/TOOLS/EXTERNAL/LINUX (for Mac and Linux)
- [OpenMS]/share/TOOLS/EXTERNAL/WINDOWS (for Windows)
Environment:
OPENMS_TTD_PATH (use only one path here!)
*/
/*
internal details & discussion:
We could create the list of TOPP tools from a set of files in /share
instead of hard coding them here.
Advantage: - no recompile if new tool is added (but the new tool will necessitate that anyway)
- quickly changing a tool's category (e.g. from PreProcessing to Quantitation) and thus its place in TOPPAS
even users could rearrange tools themselves...
Disadvantage:
- when to library loads, we'd need to parse all the files. Making our start-up time even longer...
- when files are broken/missing, we will have a hard time initializing the lib
*/
/// map each tool to its ToolDescription
typedef std::map<String, Internal::ToolDescription> ToolListType;
class OPENMS_DLLAPI ToolHandler
{
public:
/// Returns the list of official TOPP tools contained in the OpenMS/TOPP release.
static ToolListType getTOPPToolList(const bool includeGenericWrapper = false);
/// get all types of a tool (empty if none)
static StringList getTypes(const String& toolname);
/// Returns the category string from TOPP tools
/// @return empty string if tool was not found
static String getCategory(const String& toolname);
/// get getOpenMSDataPath() + "/TOOLS/EXTERNAL"
static String getExternalToolsPath();
/// get File::getOpenMSDataPath() + "/TOOLS/INTERNAL"
static String getInternalToolsPath();
private:
static Internal::ToolDescription getExternalTools_();
static QStringList getExternalToolConfigFiles_();
static void loadExternalToolConfig_();
static Internal::ToolDescription tools_external_;
static bool tools_external_loaded_;
static std::vector<Internal::ToolDescription> getInternalTools_();
static QStringList getInternalToolConfigFiles_();
static void loadInternalToolConfig_();
static std::vector<Internal::ToolDescription> tools_internal_;
static bool tools_internal_loaded_;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/APPLICATIONS/OpenSwathBase.h | .h | 11,315 | 224 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hannes Roest, Justin Sing$
// $Authors: Hannes Roest, Justin Sing$
// --------------------------------------------------------------------------
#pragma once
// Consumers
#include <OpenMS/FORMAT/DATAACCESS/MSDataWritingConsumer.h>
#include <OpenMS/FORMAT/DATAACCESS/MSDataSqlConsumer.h>
// Files
#include <OpenMS/FORMAT/FileHandler.h>
#include <OpenMS/FORMAT/FileTypes.h>
#include <OpenMS/FORMAT/SwathFile.h>
#include <OpenMS/ANALYSIS/OPENSWATH/SwathWindowLoader.h>
#include <OpenMS/ANALYSIS/OPENSWATH/TransitionTSVFile.h>
#include <OpenMS/ANALYSIS/OPENSWATH/TransitionPQPFile.h>
#include <OpenMS/ANALYSIS/OPENSWATH/OpenSwathOSWWriter.h>
// Kernel and implementations
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/SpectrumAccessOpenMS.h>
#include <OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/SpectrumAccessTransforming.h>
#include <OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/SpectrumAccessOpenMSInMemory.h>
#include <OpenMS/OPENSWATHALGO/DATAACCESS/SwathMap.h>
// Helpers
#include <OpenMS/ANALYSIS/OPENSWATH/OpenSwathHelper.h>
#include <OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/DataAccessHelper.h>
#include <OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/SimpleOpenMSSpectraAccessFactory.h>
// Algorithms
#include <OpenMS/ANALYSIS/OPENSWATH/MRMRTNormalizer.h>
#include <OpenMS/ANALYSIS/OPENSWATH/ChromatogramExtractor.h>
#include <OpenMS/ANALYSIS/OPENSWATH/MRMFeatureFinderScoring.h>
#include <OpenMS/ANALYSIS/OPENSWATH/MRMTransitionGroupPicker.h>
#include <OpenMS/ANALYSIS/OPENSWATH/SwathMapMassCorrection.h>
#include <OpenMS/ANALYSIS/OPENSWATH/OpenSwathWorkflow.h>
#include <cassert>
#include <limits>
#include <OpenMS/APPLICATIONS/TOPPBase.h>
namespace OpenMS
{
class OPENMS_DLLAPI TOPPOpenSwathBase : public TOPPBase
{
public:
/// Outputs of RT, m/z, IM calibration
struct CalibrationResult
{
/// RT normalization transformation (fitted Trafo)
OpenMS::TransformationDescription rt_trafo;
/// MS2 m/z extraction window (full width, ppm). -1 if not computed.
double ms2_mz_window_ppm{ -1.0 };
/// MS2 ion mobility extraction window (full width, native IM units). -1 if not computed/applicable.
double ms2_im_window{ -1.0 };
/// MS1 m/z extraction window (full width, ppm). -1 if not computed.
double ms1_mz_window_ppm{ -1.0 };
/// MS1 ion mobility extraction window (full width, native IM units). -1 if not computed/applicable.
double ms1_im_window{ -1.0 };
};
/**
@brief Constructor
Must match TOPPBase' Ctor!
@param[in] name Tool name.
@param[in] description Short description of the tool (one line).
@param[in] official If this is an official TOPP tool contained in the OpenMS/TOPP release.
If @em true the tool name is checked against the list of TOPP tools and a warning printed if missing.
@param[in] citations Add one or more citations if they are associated specifically to this TOPP tool; they will be printed during `--help`
*/
TOPPOpenSwathBase(String name, String description, bool official = true, const std::vector<Citation>& citations = {});
/// Destructor
~TOPPOpenSwathBase() override;
protected:
/**
* @brief Load the DIA files into internal data structures.
*
* Loads SWATH files into the provided OpenSwath::SwathMap data structures. It
* uses the SwathFile class to load files from either mzML, mzXML or SqMass.
* The files will be either loaded into memory or cached to disk (depending on
* the readoptions parameter).
*
* @param[in] file_list The input file(s)
* @param[out] exp_meta The output (meta data about experiment)
* @param[out] swath_maps The output (ptr to raw data)
* @param[in] split_file If loading a single file that contains a single SWATH window
* @param[in] tmp Temporary directory
* @param[in] readoptions Description on how to read the data ("normal", "cache")
* @param[in] swath_windows_file Provided file containing the SWATH windows which will be mapped to the experimental windows
* @param[in] min_upper_edge_dist Distance for each assay to the upper edge of the SWATH window
* @param[in] force Whether to override the sanity check
* @param[in] sort_swath_maps Whether to sort the provided windows first before mapping
* @param[in] prm Whether data is in prm format; allows for overlap
* @param[in] pasef Whether data is in PASEF format; allows for overlap
* @param[in,out] plugin_consumer Intermediate consumer for mzML input. See SwathFile::loadMzML() for details.
*
* @return Returns whether loading and sanity check was successful
*
*/
bool loadSwathFiles(const StringList& file_list,
std::shared_ptr<ExperimentalSettings >& exp_meta,
std::vector< OpenSwath::SwathMap >& swath_maps,
const bool split_file,
const String& tmp,
const String& readoptions,
const String& swath_windows_file,
const double min_upper_edge_dist,
const bool force,
const bool sort_swath_maps,
const bool prm,
const bool pasef,
Interfaces::IMSDataConsumer* plugin_consumer = nullptr);
/**
* @brief Prepare chromatogram output
*
* Sets up the chromatogram output, either sqMass or mzML (using numpress
* lossy compression). This assumes that 0.05 accuracy in RT is sufficient
* for all purposes.
*
* @param[out] chromatogramConsumer The consumer to process chromatograms
* @param[in] exp_meta meta data about experiment
* @param[in] transition_exp The spectral library
* @param[in] out_chrom The output file for the chromatograms
* @param[in] run_id Unique identifier which links the sqMass and OSW file
*/
void prepareChromOutput(Interfaces::IMSDataConsumer ** chromatogramConsumer,
const std::shared_ptr<ExperimentalSettings>& exp_meta,
const OpenSwath::LightTargetedExperiment& transition_exp,
const String& out_chrom,
const UInt64 run_id);
/**
* @brief Loads transition list from TraML / TSV or PQP
*
* @param[in] tr_type Input file type
* @param[in] tr_file Input file name
* @param[in] tsv_reader_param Parameters on how to interpret spectral data
*
*/
OpenSwath::LightTargetedExperiment loadTransitionList(const FileTypes::Type& tr_type,
const String& tr_file,
const Param& tsv_reader_param);
/**
* @brief Perform retention time and m/z calibration
*
* This function will create the retention time transformation either by
* loading a provided .trafoXML file or determine it from the data itself by
* extracting the transitions specified in the irt_tr_file TraML file. It
* will also perform the m/z calibration (when an irt_tr_file is provided).
*
* @note Internally, the retention time and @p m/z calibration are performed
* by OpenMS::OpenSwathCalibrationWorkflow::performRTNormalization
*
* @param[in] trafo_in Input trafoXML file (if not empty, transformation will be
* loaded from this file)
* @param[in] irt_transitions Input iRT transition experiment (if trafo_in
* is empty, this will be used for iRT extraction)
* @param[in,out] swath_maps The raw data (swath maps)
* @param[in] min_rsq Minimal R^2 value that is expected for the RT regression
* @param[in] min_coverage Minimal coverage of the chromatographic space that needs to be achieved
* @param[in] feature_finder_param Parameter set for the feature finding in chromatographic dimension
* @param[in] cp_irt Parameter set for the chromatogram extraction
* @param[in] irt_detection_param Parameter set for the detection of the iRTs (outlier detection, peptides per bin etc)
* @param[in] calibration_param Parameter for the m/z and im calibration (see SwathMapMassCorrection)
* @param[in] debug_level Debug level (writes out the RT normalization chromatograms if larger than 1)
* @param[in] pasef whether the data is PASEF data with possible overlapping m/z windows (with different ion mobility). In this case, the "best" SWATH window (with precursor centered around IM) is chosen.
* @param[in] load_into_memory Whether to cache the current SWATH map in memory
* @param[in] irt_trafo_out Output trafoXML file (if not empty and no input trafoXML file is given,
* the transformation parameters will be stored in this file)
* @param[in] irt_mzml_out Output Chromatogram mzML containing the iRT peptides (if not empty,
* iRT chromatograms will be stored in this file)
*
* @return CalibrationResult with: \n
* - rt_trafo : the RT normalization transformation \n
* - ms2_mz_window_ppm : auto-estimated MS2 m/z window (full width, ppm) \n
* - ms2_im_window : auto-estimated MS2 IM window (full width, native units) \n
* - ms1_mz_window_ppm : auto-estimated MS1 m/z window (full width, ppm) \n
* - ms1_im_window : auto-estimated MS1 IM window (full width, native units)
*/
CalibrationResult performCalibration(String trafo_in,
const OpenSwath::LightTargetedExperiment& irt_transitions,
std::vector< OpenSwath::SwathMap > & swath_maps,
double min_rsq,
double min_coverage,
const Param& feature_finder_param,
const ChromExtractParams& cp_irt,
const Param& irt_detection_param,
const Param& calibration_param,
Size debug_level,
bool pasef,
bool load_into_memory,
const String& irt_trafo_out,
const String& irt_mzml_out);
private:
void loadSwathFiles_(const StringList& file_list,
const bool split_file,
const String& tmp,
const String& readoptions,
std::shared_ptr<ExperimentalSettings > & exp_meta,
std::vector< OpenSwath::SwathMap > & swath_maps,
Interfaces::IMSDataConsumer* plugin_consumer);
}; // end TOPPOpenSwathBase
} // end NS OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/APPLICATIONS/MapAlignerBase.h | .h | 10,672 | 255 | // 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, Clemens Groepl, Hendrik Weisser $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/FORMAT/FileHandler.h>
#include <OpenMS/FORMAT/FileTypes.h>
#include <OpenMS/ANALYSIS/MAPMATCHING/MapAlignmentAlgorithmIdentification.h>
#include <OpenMS/ANALYSIS/MAPMATCHING/MapAlignmentTransformer.h>
#include <OpenMS/ANALYSIS/MAPMATCHING/TransformationModelBSpline.h>
#include <OpenMS/ANALYSIS/MAPMATCHING/TransformationModelLinear.h>
#include <OpenMS/ANALYSIS/MAPMATCHING/TransformationModelLowess.h>
#include <OpenMS/ANALYSIS/MAPMATCHING/TransformationModelInterpolated.h>
#include <OpenMS/APPLICATIONS/TOPPBase.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <vector>
//-------------------------------------------------------------
// Doxygen docu
//-------------------------------------------------------------
/**
@page TOPP_MapAlignerBase MapAlignerBase
@brief Base class for different MapAligner TOPP tools.
*/
// We do not want this class to show up in the docu:
/// @cond TOPPCLASSES
namespace OpenMS
{
// @brief stores model defaults for map aligner algorithms
struct MapAlignerBase
{
// "public" so it can be used in DefaultParamHandlerDocumenter to get docu
static Param getModelDefaults(const String& default_model)
{
Param params;
params.setValue("type", default_model, "Type of model");
// TODO: avoid referring to each TransformationModel subclass explicitly
std::vector<std::string> model_types = {"linear","b_spline","lowess","interpolated"};
if (!ListUtils::contains(model_types, default_model))
{
model_types.insert(model_types.begin(), default_model);
}
params.setValidStrings("type", model_types);
Param model_params;
TransformationModelLinear::getDefaultParameters(model_params);
params.insert("linear:", model_params);
params.setSectionDescription("linear", "Parameters for 'linear' model");
TransformationModelBSpline::getDefaultParameters(model_params);
params.insert("b_spline:", model_params);
params.setSectionDescription("b_spline", "Parameters for 'b_spline' model");
TransformationModelLowess::getDefaultParameters(model_params);
params.insert("lowess:", model_params);
params.setSectionDescription("lowess", "Parameters for 'lowess' model");
TransformationModelInterpolated::getDefaultParameters(model_params);
params.insert("interpolated:", model_params);
params.setSectionDescription("interpolated",
"Parameters for 'interpolated' model");
return params;
}
};
class TOPPMapAlignerBase :
public TOPPBase, public MapAlignerBase
{
public:
TOPPMapAlignerBase(String name, String description, bool official = true) :
TOPPBase(name, description, official), ref_params_(REF_NONE)
{
}
protected:
// Kind of reference parameters that the tool offers:
// - REF_NONE: no reference
// - REF_RESTRICTED: reference file must have same type as input files
// - REF_FLEXIBLE: reference file can have any supported file type
enum ReferenceParameterKind { REF_NONE, REF_RESTRICTED, REF_FLEXIBLE }
ref_params_;
void registerOptionsAndFlagsMapAligners_(const String& file_formats,
enum ReferenceParameterKind ref_params)
{
registerInputFileList_("in", "<files>", StringList(), "Input files to align (all must have the same file type)", true);
setValidFormats_("in", ListUtils::create<String>(file_formats));
registerOutputFileList_("out", "<files>", StringList(), "Output files (same file type as 'in'). This option or 'trafo_out' has to be provided; they can be used together.", false);
setValidFormats_("out", ListUtils::create<String>(file_formats));
registerOutputFileList_("trafo_out", "<files>", StringList(), "Transformation output files. This option or 'out' has to be provided; they can be used together.", false);
setValidFormats_("trafo_out", ListUtils::create<String>("trafoXML"));
// Optional spectra files for transformation
registerInputFileList_("in_spectra_files", "<files>", StringList(), "Optional input spectra files (mzML) that will be transformed along with the alignment. Size must match the number of input files.", false);
setValidFormats_("in_spectra_files", ListUtils::create<String>("mzML"));
registerOutputFileList_("out_spectra_files", "<files>", StringList(), "Optional output spectra files (mzML) corresponding to transformed in_spectra_files. Size must match in_spectra_files.", false);
setValidFormats_("out_spectra_files", ListUtils::create<String>("mzML"));
if (ref_params != REF_NONE)
{
registerTOPPSubsection_("reference", "Options to define a reference file (use either 'file' or 'index', not both)");
String description = "File to use as reference";
if (ref_params == REF_RESTRICTED)
{
description += " (same file format as input files required)";
}
registerInputFile_("reference:file", "<file>", "", description, false);
setValidFormats_("reference:file", ListUtils::create<String>(file_formats));
registerIntOption_("reference:index", "<number>", 0, "Use one of the input files as reference ('1' for the first file, etc.).\nIf '0', no explicit reference is set - the algorithm will select a reference.", false);
setMinInt_("reference:index", 0);
}
ref_params_ = ref_params;
}
ExitCodes checkParameters_()
{
//-------------------------------------------------------------
// parameter handling
//-------------------------------------------------------------
StringList ins = getStringList_("in");
StringList outs = getStringList_("out");
StringList trafos = getStringList_("trafo_out");
StringList in_spectra = getStringList_("in_spectra_files");
StringList out_spectra = getStringList_("out_spectra_files");
//-------------------------------------------------------------
// check for valid input
//-------------------------------------------------------------
// check whether some kind of output file is given:
if (outs.empty() && trafos.empty())
{
writeLogError_("Error: Data output or transformation output files have to be provided (parameters 'out'/'trafo_out')");
return ILLEGAL_PARAMETERS;
}
// check whether number of input files equals number of output files:
if (!outs.empty() && (ins.size() != outs.size()))
{
writeLogError_("Error: The number of data input and output files has to be equal (parameters 'in'/'out')");
return ILLEGAL_PARAMETERS;
}
if (!trafos.empty() && (ins.size() != trafos.size()))
{
writeLogError_("Error: The number of data input and transformation output files has to be equal (parameters 'in'/'trafo_out')");
return ILLEGAL_PARAMETERS;
}
// check whether all input files have the same type (this type is used to store the output type too):
FileTypes::Type in_type = FileHandler::getType(ins[0]);
for (Size i = 1; i < ins.size(); ++i)
{
if (FileHandler::getType(ins[i]) != in_type)
{
writeLogError_("Error: All input files (parameter 'in') must have the same format!");
return ILLEGAL_PARAMETERS;
}
}
// check optional spectra files
if (!in_spectra.empty() || !out_spectra.empty())
{
if (in_spectra.size() != ins.size())
{
writeLogError_("Error: The number of spectra input files has to be equal to the number of main input files (parameters 'in_spectra_files'/'in')");
return ILLEGAL_PARAMETERS;
}
if (out_spectra.size() != in_spectra.size())
{
writeLogError_("Error: The number of spectra input and output files has to be equal (parameters 'in_spectra_files'/'out_spectra_files')");
return ILLEGAL_PARAMETERS;
}
}
if (ref_params_ != REF_NONE) // a valid ref. index OR file should be given
{
Size reference_index = getIntOption_("reference:index");
String reference_file = getStringOption_("reference:file");
if (reference_index > ins.size())
{
writeLogError_("Error: Value of parameter 'reference:index' must not be higher than the number of input files");
return ILLEGAL_PARAMETERS;
}
if (reference_index && !reference_file.empty())
{
writeLogError_("Error: Parameters 'reference:index' and 'reference:file' cannot be used together");
return ILLEGAL_PARAMETERS;
}
if ((ref_params_ == REF_RESTRICTED) && !reference_file.empty() &&
(FileHandler::getType(reference_file) != in_type))
{
writeLogError_("Error: Reference file must have the same format as other input files (parameters 'reference:file'/'in')");
return ILLEGAL_PARAMETERS;
}
}
return EXECUTION_OK;
}
void transformSpectraFiles_(const StringList& in_spectra_files,
const StringList& out_spectra_files,
const std::vector<TransformationDescription>& transformations,
bool store_original_rt)
{
if (in_spectra_files.empty() || out_spectra_files.empty())
{
return; // Nothing to do
}
OPENMS_PRECONDITION(in_spectra_files.size() == transformations.size(),
"Number of spectra files must match number of transformations");
OPENMS_PRECONDITION(in_spectra_files.size() == out_spectra_files.size(),
"Number of input and output spectra files must match");
ProgressLogger progresslogger;
progresslogger.setLogType(log_type_);
progresslogger.startProgress(0, in_spectra_files.size(), "transforming spectra files");
for (Size i = 0; i < in_spectra_files.size(); ++i)
{
progresslogger.setProgress(i);
PeakMap exp;
FileHandler().loadExperiment(in_spectra_files[i], exp, {FileTypes::MZML}, log_type_);
MapAlignmentTransformer::transformRetentionTimes(exp, transformations[i], store_original_rt);
addDataProcessing_(exp, getProcessingInfo_(DataProcessing::ALIGNMENT));
FileHandler().storeExperiment(out_spectra_files[i], exp, {FileTypes::MZML}, log_type_);
}
progresslogger.endProgress();
}
};
}
/// @endcond
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/APPLICATIONS/ConsoleUtils.h | .h | 3,160 | 80 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/ListUtils.h> // for StringList definition
#include <limits>
namespace OpenMS
{
/**
*
* Determines the width of the console automatically.
*
* To manually force a certain width set the environment variable 'COLUMNS' to a desired value.
*
*/
class OPENMS_DLLAPI ConsoleUtils
{
private:
/// C'tor (private) -- use ConsoleUtils::getInstance()
ConsoleUtils();
public:
/// Copy C'tor (deleted)
ConsoleUtils(const ConsoleUtils&) = delete;
/// Assignment operator (deleted)
void operator=(ConsoleUtils const&) = delete;
/// returns the singleton -- the only instanciation of this class
static const ConsoleUtils& getInstance();
/// Make a string console-friendly
/// by breaking it into multiple lines according to the console width.
/// The 'indentation' gives the number of spaces which is prepended beginning at the second (!)
/// line, so one gets a left aligned block which has some space to the left.
/// An indentation of 0 results in the native console's default behaviour: just break at the end of
/// its width and start a new line.
/// @p max_lines gives the upper limit of lines returned after breaking is finished.
/// Excess lines are removed and replaced by '...', BUT the last line will be preserved.
///
/// @param[in] input String to be split
/// @param[in] indentation Number of spaces to use for lines 2 until last line (should not exceed the console width)
/// @param[in] max_lines Limit of output lines (all others are removed)
/// @param[in] first_line_prefill Assume this many chars were already written in the current line of the console (should not exceed the console width)
static StringList breakStringList(const String& input, const Size indentation, const Size max_lines, const Size first_line_prefill = 0);
/// same as breakStringList(), but concatenates the result using '\n' for convenience
static String breakString(const String& input, const Size indentation, const Size max_lines, const Size first_line_prefill = 0);
/// width of the console (or INTMAX on internal error)
int getConsoleWidth() const
{
return console_width_;
}
friend struct ConsoleWidthTest; ///< allows us to set console_width to a fixed value for testing
private:
/// width of console we are currently in (if not determinable, set to INTMAX, i.e. not breaks)
int console_width_ = std::numeric_limits<int>::max();
/// read console settings for output shaping
int readConsoleSize_();
/// returns a console friendly version of input
StringList breakString_(const String& input, const Size indentation, const Size max_lines, Size first_line_prefill) const;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/APPLICATIONS/ParameterInformation.h | .h | 2,914 | 83 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Marc Sturm, Clemens Groepl $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/String.h>
#include <OpenMS/DATASTRUCTURES/StringListUtils.h>
#include <OpenMS/DATASTRUCTURES/ParamValue.h>
namespace OpenMS
{
/**
@brief Struct that captures all information of a command line parameter
*/
struct OPENMS_DLLAPI ParameterInformation
{
/// Parameter types
enum ParameterTypes
{
NONE = 0, ///< Undefined type
STRING, ///< String parameter
INPUT_FILE, ///< String parameter that denotes an input file
OUTPUT_FILE, ///< String parameter that denotes an output file
OUTPUT_PREFIX, ///< String parameter that denotes an output file prefix
OUTPUT_DIR, ///< String parameter that denotes an output directory
DOUBLE, ///< Floating point number parameter
INT, ///< Integer parameter
STRINGLIST, ///< More than one String Parameter
INTLIST, ///< More than one Integer Parameter
DOUBLELIST, ///< More than one String Parameter
INPUT_FILE_LIST, ///< More than one String Parameter that denotes input files
OUTPUT_FILE_LIST, ///< More than one String Parameter that denotes output files
FLAG, ///< Parameter without argument
TEXT, ///< Left aligned text, see addText_
NEWLINE ///< An empty line, see addEmptyLine_
};
/// name of the parameter (internal and external)
String name;
/// type of the parameter
ParameterTypes type;
/// default value of the parameter stored as string
ParamValue default_value;
/// description of the parameter
String description;
/// argument in the description
String argument;
/// flag that indicates if this parameter is required i.e. it must differ from the default value
bool required;
/// flag the indicates that the parameter is advanced (this is used for writing the INI file only)
bool advanced;
/// StringList for special tags
StringList tags;
///@name Restrictions for different parameter types
//@{
StringList valid_strings;
Int min_int;
Int max_int;
double min_float;
double max_float;
//@}
/// Constructor that takes all members in declaration order
ParameterInformation(const String& n, ParameterTypes t, const String& arg, const ParamValue& def, const String& desc, bool req, bool adv, const StringList& tag_values = StringList());
ParameterInformation();
ParameterInformation(const ParameterInformation& rhs) = default;
ParameterInformation& operator=(const ParameterInformation& rhs);
};
} // namespace
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/APPLICATIONS/SearchEngineBase.h | .h | 4,061 | 99 | // 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/METADATA/ProteinIdentification.h>
#include <OpenMS/APPLICATIONS/TOPPBase.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
namespace OpenMS
{
/**
@brief Base class for Search Engine Adapters
It is build on top of TOPPBase and provides convenience functions for regular tasks in SearchEngines.
This base class enforces a common parameter scheme upon each adapter.
E.g. '-database' and '-in'.
This might be extended/changed in the future.
*/
class OPENMS_DLLAPI SearchEngineBase : public TOPPBase
{
public:
/// No default constructor
SearchEngineBase() = delete;
/// No default copy constructor.
SearchEngineBase(const SearchEngineBase&) = delete;
/**
@brief Constructor
Must match TOPPBase' Ctor!
@param[in] name Tool name.
@param[in] description Short description of the tool (one line).
@param[in] official If this is an official TOPP tool contained in the OpenMS/TOPP release.
If @em true the tool name is checked against the list of TOPP tools and a warning printed if missing.
@param[in] citations Add one or more citations if they are associated specifically to this TOPP tool; they will be printed during `--help`
@param[in] toolhandler_test Check if this tool is registered with the ToolHandler (disable for unit tests only)
*/
SearchEngineBase(const String& name, const String& description, bool official = true, const std::vector<Citation>& citations = {}, bool toolhandler_test = true);
/// Destructor
~SearchEngineBase() override;
/**
@brief Reads the '-in' argument from internal parameters (usually an mzML file) and checks if MS2 spectra are present and are centroided.
If the file is an mzML file, the spectra annotation can be checked. If no MS2 or profile MS2 data is found, an exception is thrown.
If the file is any other format, the overhead of reading in the file is too large and we just issue a general warning that centroided data should be used.
@param[in] ms_level The MS level to check for their type (centroided/profile)
@return A filename (might be a relative or absolute path)
@throws OpenMS::Exception::FileEmpty if no spectra are found (mzML only)
@throws OpenMS::Exception::IllegalArgument if spectra are not centroided (mzML only)
*/
String getRawfileName(int ms_level = 2) const;
/**
@brief Reads the '-database' argument from internal parameters (or from @p db) and tries to find the db in search directories (if it cannot be found immediately). If not found, an exception is thrown.
@param[in] db [Optional] Instead of reading the '-database', you can provide a custom name here (might be required for special db formats, see OMSSA)
@return filename for DB (might be a relative or absolute path)
@throws OpenMS::Exception::FileNotFound if database name could not be resolved
*/
String getDBFilename(const String& db = "") const;
/**
@brief Adds option to reassociate peptides with proteins (and annotate target/decoy information)
@param[in] peptide_indexing_parameter peptide indexer settings. May be modified to enable search engine specific defaults (e.g., not-tryptic etc.).
*/
virtual void registerPeptideIndexingParameter_(Param peptide_indexing_parameter);
/**
@brief Reindex peptide to protein association
*/
virtual SearchEngineBase::ExitCodes reindex_(
std::vector<ProteinIdentification>& protein_identifications,
PeptideIdentificationList& peptide_identifications) const;
}; // end SearchEngineBase
} // end NS OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/PROCESSING/FEATURE/FeatureOverlapFilter.h | .h | 9,841 | 189 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Julianus Pfeuffer $
// $Authors: Julianus Pfeuffer $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/CONCEPT/Constants.h>
namespace OpenMS
{
/// Enum to specify the overlap detection mode
enum class FeatureOverlapMode
{
CONVEX_HULL, ///< Use convex hull bounding boxes (default)
TRACE_LEVEL, ///< Check overlap at trace level
CENTROID_BASED ///< Check overlap based on centroid distances
};
/// Enum to specify how intensities are combined when merging features
enum class MergeIntensityMode
{
SUM, ///< Sum intensities of merged features (default)
MAX ///< Keep maximum intensity
};
/// Structure to hold centroid-based overlap tolerances
struct CentroidTolerances
{
double rt_tolerance = 5.0; ///< Maximum RT difference in seconds
double mz_tolerance = 0.05; ///< Maximum m/z difference in Da
bool require_same_charge = true; ///< Whether to require identical charge states
bool require_same_im = false; ///< Whether to require identical FAIMS CV (or both missing)
};
class OPENMS_DLLAPI FeatureOverlapFilter
{
public:
/// Enum to specify the overlap detection mode (alias for backward compatibility)
using OverlapMode = FeatureOverlapMode;
/*
@brief Filter overlapping features using a spatial datastructure (quadtree).
Retains only the best feature in each cluster of overlapping features.
@param[in] FeatureComparator must implement the concept of a less comparator.
If several features overlap, the feature that evaluates as "smallest" is considered the best (according to the passed comparator) and is kept.
The other overlapping features are removed and FeatureOverlapCallback evaluated on them.
Default: overall feature quality.
@param[in] FeatureOverlapCallback(best_in_cluster, f) is called if a feature f overlaps with a feature best_in_cluster.
FeatureOverlapCallback provides a customization point to e.g.:
- transfer information from the soon-to-be-removed feature f over to the best_in_cluster feature
- gather overlap statistics
- help in debugging
- etc.
in form of a callable.
If the FeatureOverlapCallback returns false, the overlapping feature will be treated as not overlapping with best_in_cluster (and not removed).
Default: function that just returns true.
@ingroup Datareduction
*/
static void filter(FeatureMap& fmap,
std::function<bool(const Feature&, const Feature&)> FeatureComparator = [](const Feature& left, const Feature& right){ return left.getOverallQuality() > right.getOverallQuality(); },
std::function<bool(Feature&, Feature&)> FeatureOverlapCallback = [](Feature&, Feature&){ return true; },
bool check_overlap_at_trace_level = true);
/*
@brief Filter overlapping features with configurable overlap detection mode.
Extended version that allows choosing between different overlap detection strategies.
@param[in,out] fmap The feature map to filter
@param[in] FeatureComparator Comparator to determine the best feature in overlapping clusters
@param[in] FeatureOverlapCallback Callback function called when features overlap
@param[in] mode The overlap detection mode to use
@param[in] tolerances Tolerances for centroid-based overlap detection (only used when mode == CENTROID_BASED)
@ingroup Datareduction
*/
static void filter(FeatureMap& fmap,
std::function<bool(const Feature&, const Feature&)> FeatureComparator,
std::function<bool(Feature&, Feature&)> FeatureOverlapCallback,
FeatureOverlapMode mode,
const CentroidTolerances& tolerances = CentroidTolerances());
/**
@brief Create a callback function for merging overlapping features.
Creates a callback suitable for use with filter() that merges feature information
when features overlap. The callback:
- Combines intensities according to intensity_mode (SUM or MAX)
- Optionally stores merge tracking information as meta values:
- "merged_centroid_rts": vector of RT positions from all merged features
- "merged_centroid_mzs": vector of m/z positions from all merged features
- "merged_centroid_IMs": vector of FAIMS CV values (only if FAIMS_CV present on features)
- "FAIMS_merge_count": count of merged FAIMS CV values
This callback is designed to work with features that may or may not have FAIMS CV
annotations. Features without FAIMS_CV will simply not contribute to merged_centroid_IMs.
@param[in] intensity_mode How to combine intensities: SUM adds all intensities,
MAX keeps the highest intensity (default: SUM)
@param[in] write_meta_values If true, write merge tracking meta values to the surviving
feature for debugging/analysis (default: true)
@return A callback function suitable for use with filter()
*/
static std::function<bool(Feature&, Feature&)> createFAIMSMergeCallback(
MergeIntensityMode intensity_mode = MergeIntensityMode::SUM,
bool write_meta_values = true);
/**
@brief Merge overlapping features based on centroid distances.
Identifies features whose centroids are within the specified RT and m/z tolerances
and merges them into a single representative feature. This is primarily designed for
FAIMS data where the same analyte is detected at multiple compensation voltages.
The feature with the highest intensity is kept as the representative. Depending on
intensity_mode, intensities are either summed or the maximum is kept.
When write_meta_values is true, the following meta values are stored on merged features:
- "merged_centroid_rts": RT positions of all features that were merged
- "merged_centroid_mzs": m/z positions of all features that were merged
- "merged_centroid_IMs": FAIMS CV values (if present on the original features)
- "FAIMS_merge_count": number of FAIMS CV values that were merged
@param[in,out] feature_map The feature map to process (modified in place)
@param[in] max_rt_diff Maximum RT difference in seconds for considering features as
overlapping (default: 5.0)
@param[in] max_mz_diff Maximum m/z difference in Da for considering features as
overlapping (default: 0.05)
@param[in] require_same_charge If true, only merge features with identical charge states.
If false, features with different charges can be merged
(default: true)
@param[in] require_same_im If true, only merge features with identical FAIMS CV values.
Features without FAIMS_CV are treated as a separate group and
can only merge with other features lacking FAIMS_CV (default: false)
@param[in] intensity_mode How to combine intensities: SUM adds all intensities,
MAX keeps the highest intensity (default: SUM)
@param[in] write_meta_values If true, write merge tracking meta values to merged features
(default: true)
*/
static void mergeOverlappingFeatures(FeatureMap& feature_map,
double max_rt_diff = 5.0,
double max_mz_diff = 0.05,
bool require_same_charge = true,
bool require_same_im = false,
MergeIntensityMode intensity_mode = MergeIntensityMode::SUM,
bool write_meta_values = true);
/**
@brief Merge FAIMS features that represent the same analyte detected at different CV values.
This is a convenience function specifically designed for FAIMS data. It only merges
features that have the FAIMS_CV meta value annotation AND have DIFFERENT CV values.
Features without FAIMS_CV are left unchanged, and features with the same CV are
never merged (they are considered different analytes).
This makes it safe to call on any data:
- Non-FAIMS data: no merging occurs
- Single-CV FAIMS data: no merging occurs (all features have same CV)
- Multi-CV FAIMS data: only features at different CVs are merged
Features are considered the same analyte if they:
- Have DIFFERENT FAIMS_CV values (same CV = different analytes)
- Are within max_rt_diff seconds in RT
- Are within max_mz_diff Da in m/z
- Have the same charge state
The feature with highest intensity is kept, and intensities are summed.
@param[in,out] feature_map The feature map to process (modified in place)
@param[in] max_rt_diff Maximum RT difference in seconds (default: 5.0)
@param[in] max_mz_diff Maximum m/z difference in Da (default: 0.05)
*/
static void mergeFAIMSFeatures(FeatureMap& feature_map,
double max_rt_diff = 5.0,
double max_mz_diff = 0.05);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/PROCESSING/CALIBRATION/PrecursorCorrection.h | .h | 9,695 | 191 | // 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, Oliver Alka $
// --------------------------------------------------------------------------
//
#pragma once
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/CONCEPT/Constants.h>
#include <OpenMS/MATH/MathFunctions.h>
#include <OpenMS/METADATA/Precursor.h>
#include <string>
#include <vector>
#include <set>
namespace OpenMS
{
/**
@brief This class provides methods for precursor correction.
Supported methods:
getPrecursors: Extract precursors and associated information (mz, scan index).
writeHist: Write output .csv for validation purposes (corrected, uncorrected).
correctToNearestMS1Peak: Correct to the peak in closest proximity in a certain mass range.
correctToHighestIntensityMS1Peak: Correct to the peak with the highest intensity in a certain mass range.
correctToNearestFeature: Use feature information to re-annotate a precursor (e.g. falsely assigned to non mono-isotopic trace).
*/
class OPENMS_DLLAPI PrecursorCorrection
{
public:
static const std::string csv_header;
/**
@brief Extract precursors and associated information (precursor retention time and precursor scan index).
@param[in] exp: Spectra with precursors
@param[out] precursors: vector of all precursors in @p exp (can be more than one per MSn spectrum)
@param[out] precursors_rt: vector double of precursors retention time (same length as @p precursors)
@param[out] precursor_scan_index: Indices into @p exp, which have a precursor
*/
static void getPrecursors(const MSExperiment & exp,
std::vector<Precursor> & precursors,
std::vector<double> & precursors_rt,
std::vector<Size> & precursor_scan_index);
/**
@brief Writer can be used in association with correctToNearestMS1Peak or correctToHighestIntensityMS1Peak.
A csv file with additional information (RT, uncorrectedMZ, correctedMZ, deltaMZ).
Format:
RT uncorrectedMZ correctedMZ deltaMZ
100.1 509.9999 510 0.0001
180.9 610.0001 610 -0.0001
183.92 611.0035 611.0033 -0.0002
@param[out] out_csv: constant String for csv output.
@param[in] delta_mzs: delta m/z column values.
@param[in] mzs: m/z column vector (uncorrectedMZ)
@param[in] rts: retention time column vector
*/
static void writeHist(const String& out_csv,
const std::vector<double> & delta_mzs,
const std::vector<double> & mzs,
const std::vector<double> & rts);
/**
@brief Selection of the peak in closest proximity as corrected precursor mass in a given mass range (e.g. precursor mass +/- 0.2 Da).
For each MS2 spectrum the corresponding MS1 spectrum is determined by using the rt information of the precursor.
In the MS1, the peak closest to the uncorrected precursor m/z is selected and used as corrected precursor m/z.
@param[in] exp: MSExperiment.
@param[in] mz_tolerance: double tolerance used for precursor correction in mass range.
@param[in] ppm: bool enables usage of ppm.
@param[in] delta_mzs: vector double delta mass to charge.
@param[in] mzs: vector double mass to charge.
@param[in] rts: vector double retention time.
@return set of Size with corrected precursor information.
*/
static std::set<Size> correctToNearestMS1Peak(MSExperiment & exp,
double mz_tolerance,
bool ppm,
std::vector<double> & delta_mzs,
std::vector<double> & mzs,
std::vector<double> & rts);
/**
@brief Selection of the peak with the highest intensity as corrected precursor mass in a given mass range (e.g. precursor mass +/- 0.2 Da)
For each MS2 spectrum the corresponding MS1 spectrum is determined by using the rt information of the precursor.
In the MS1, the peak with the highest intensity in a given mass range to the uncorrected precursor m/z is selected and used as corrected precursor m/z.
@param[in] exp: MSExperiment.
@param[in] mz_tolerance: double tolerance used for precursor correction in mass range.
@param[in] ppm: bool enables usage of ppm.
@param[in] delta_mzs: vector double delta mass to charge.
@param[in] mzs: vector double mass to charge.
@param[in] rts: vector double retention time.
@return set of Size with corrected precursor information.
*/
static std::set<Size> correctToHighestIntensityMS1Peak(MSExperiment & exp,
double mz_tolerance,
bool ppm,
std::vector<double> & delta_mzs,
std::vector<double> & mzs,
std::vector<double> & rts);
/**
@brief Reassigns a precursor to the nearest feature in a given rt and mass range.
Wrong assignment of the mono-isotopic mass for precursors are assumed:
- if precursor_mz matches the mz of a non-monoisotopic feature mass trace
- and in the case that believe_charge is true: if feature_charge matches the precursor_charge
In the case of wrong mono-isotopic assignment several options for correction are available:
keep_original will create a copy of the precursor and tandem spectrum for the new mono-isotopic mass trace and retain the original one.
all_matching_features does this not for only the closest feature but all features in a question.
@param[in] features: constant FeatureMap.
@param[in] exp: MSExperiment.
@param[in] rt_tolerance_s: double retention time tolerance in seconds.
@param[in] mz_tolerance: double tolerance used for precursor correction in mass range.
@param[in] ppm: bool enables usage of ppm.
@param[in] believe_charge: bool only add features that match the precursor charge.
@param[in] keep_original: bool this will create a copy of the precursor and tandem spectrum for the new mono-isotopic trace and retain the original one.
@param[in] all_matching_features: bool correction is performed for all features in question not only the closest one.
@param[in] max_trace: integer maximum isotopic peak offset from the monoisotopic peak to consider (e.g., 2 allows corrections from M+0, M+1, M+2).
@param[in] debug_level: integer debug level.
@return set of Size with corrected precursor information.
*/
static std::set<Size> correctToNearestFeature(const FeatureMap& features,
MSExperiment & exp,
double rt_tolerance_s = 0.0,
double mz_tolerance = 0.0,
bool ppm = true,
bool believe_charge = false,
bool keep_original = false,
bool all_matching_features = false,
int max_trace = 2,
int debug_level = 0);
protected:
/**
@brief Check if precursor is located in the bounding box of a features convex hull.
Here the bounding box of the feature is extended by the retention time tolerance and
afterwards the precursor location is validated.
@param[in] feature: constant Feature.
@param[in] rt: constant double retention time.
@param[in] pc_mz: constant double precursor mass to charge.
@param[in] rt_tolerance: constant double retention time tolerance in seconds.
@return static boolean to check if the precursor is located in the bounding box of a features convex hull.
*/
static bool overlaps_(const Feature& feature,
const double rt,
const double pc_mz,
const double rt_tolerance);
/**
@brief Check precursor and feature compatibility
If the precursor mz is in one of the masstraces the feature is compatible.
Dependent on 13C mass difference and charge.
@param[in] feature: constant Feature.
@param[in] pc_mz: double precursor mass to charge.
@param[in] mz_tolerance: double mass to charge tolerance.
@param[in] max_trace_number: Size maximum isotopic peak offset from the monoisotopic peak to consider.
@param[in] debug_level: integer debug level.
@return static boolean if the precursor mass to charge is in one of the features masstraces.
*/
static bool compatible_(const Feature& feature,
double pc_mz,
double mz_tolerance,
Size max_trace_number = 2,
int debug_level = 0);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/PROCESSING/CALIBRATION/MZTrafoModel.h | .h | 10,960 | 283 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/CalibrationData.h>
#include <OpenMS/ML/RANSAC/RANSAC.h>
#include <vector>
namespace OpenMS
{
/**
@brief Create and apply models of a mass recalibration function.
The input is a list of calibration points (ideally spanning a wide m/z range to prevent extrapolation when applying to model).
Models (LINEAR, LINEAR_WEIGHTED, QUADRATIC, QUADRATIC_WEIGHTED) can be trained using CalData points (or a subset of them).
Calibration points can have different retention time points, and a model should be build such that it captures
the local (in time) decalibration of the instrument, i.e. choose appropriate time windows along RT to calibrate the
spectra in this RT region.
From the available calibrant data, a model is build. Later, any uncalibrated m/z value can be fed to the model, to obtain
a calibrated m/z.
The input domain can either be absolute mass differences in [Th], or relative differences in [ppm].
The models are build based on this input.
Outlier detection before model building via the RANSAC algorithm is supported for LINEAR and QUADRATIC models.
*/
class OPENMS_DLLAPI MZTrafoModel
{
private:
std::vector<double> coeff_; ///< Model coefficients (for both linear and quadratic models), estimated from the data
bool use_ppm_; ///< during training, model is build on absolute or relative(ppm) predictions. predict(), i.e. applying the model, requires this information too
double rt_; ///< retention time associated to the model (i.e. where the calibrant data was taken from)
static Math::RANSACParam* ransac_params_; ///< global pointer, init to NULL at startup; set class-global RANSAC params
static int ransac_seed_; ///< seed used for all RANSAC invocations
static double limit_offset_; ///< acceptable boundary for the estimated offset; if estimated offset is larger (absolute) the model does not validate (isValidModel())
static double limit_scale_; ///< acceptable boundary for the estimated scale; if estimated scale is larger (absolute) the model does not validate (isValidModel())
static double limit_power_; ///< acceptable boundary for the estimated power; if estimated power is larger (absolute) the model does not validate (isValidModel())
public:
/**
@brief Default constructor
*/
MZTrafoModel();
/**
@brief Default constructor
If you have external coefficients, use this constructor and the setCoefficients() method to
build a 'manual' model.
Afterwards, use applyTransformation() or predict() to calibrate your data.
If you call train(), the ppm-setting will be overwritten, depending on the type of training data.
@param[in] ppm_model Are the coefficients derived from ppm calibration data, or from absolute deltas?
*/
MZTrafoModel(bool ppm_model);
enum class MODELTYPE { LINEAR, LINEAR_WEIGHTED, QUADRATIC, QUADRATIC_WEIGHTED, SIZE_OF_MODELTYPE };
static const std::string names_of_modeltype[]; ///< strings corresponding to enum class MODELTYPE
/**
@brief Convert string to enum
Returns 'SIZE_OF_MODELTYPE' if string is unknown.
@param[in] name A string from names_of_modeltype[].
@return The corresponding enum value.
*/
static MODELTYPE nameToEnum(const std::string& name);
/**
@brief Convert enum to string
@param[in] mt The enum value
@return Stringified version
*/
static const std::string& enumToName(MODELTYPE mt);
/**
@brief Set the global (program wide) parameters for RANSAC.
This is not done via member, to keep a small memory footprint since hundreds of
MZTrafoModels are expected to be build at the same time and the RANSAC params
should be identical for all of them.
@param[in] p RANSAC params
*/
static void setRANSACParams(const Math::RANSACParam& p);
/**
@brief Set RANSAC seed
*/
static void setRANSACSeed(int seed);
/**
@brief Set coefficient boundaries for which the model coefficient must not exceed to be considered a valid model
Use std::numeric_limits<double>::max() for no limit (default).
If isValidModel() is called these limits are checked.
Negative input run through fabs() to get positive values (since comparison is done in absolute terms).
*/
static void setCoefficientLimits(double offset, double scale, double power);
/**
@brief Predicate to decide if the model has valid parameters, i.e. coefficients.
If the model coefficients are empty, no model was trained yet (or unsuccessful),
causing a return value of 'false'.
Also, if the model has coefficients, we check if they are within the
acceptable boundaries (if boundaries were given via setCoeffientLimits()).
*/
static bool isValidModel(const MZTrafoModel& trafo);
/**
@brief Does the model have coefficients (i.e. was trained successfully).
Having coefficients does not mean its valid (see isValidModel(); since coeffs might be too large).
*/
bool isTrained() const;
/**
@brief Get RT associated with the model (training region)
*/
double getRT() const;
/**
@brief Apply the model to an uncalibrated m/z value.
Make sure the model was trained (train()) and is valid (isValidModel()) before calling this function!
Applies the function y = intercept + slope*mz + power*mz^2
and returns y.
@param[in] mz The uncalibrated m/z value
@return The calibrated m/z value
*/
double predict(double mz) const;
/**
@brief Binary search for the model nearest to a specific RT
@param[in] tms Vector of models, sorted by RT
@param[in] rt The target retention time
@return Returns the index into 'tms' with the closest RT.
@note Make sure the vector is sorted with respect to RT! Otherwise the result is undefined.
@exception Exception::Precondition is thrown if the vector is empty (not only in debug mode)
*/
static Size findNearest(const std::vector<MZTrafoModel>& tms, double rt);
/// Comparator by position. As this class has dimension 1, this is basically an alias for MZLess.
struct RTLess
{
inline bool operator()(const double& left, const MZTrafoModel& right) const
{
return left < right.rt_;
}
inline bool operator()(const MZTrafoModel& left, const double& right) const
{
return left.rt_ < right;
}
inline bool operator()(const MZTrafoModel& left, const MZTrafoModel& right) const
{
return left.rt_ < right.rt_;
}
};
/**
@brief Train a model using calibrant data
If the CalibrationData was created using peak groups (usually corresponding to mass traces),
the median for each group is used as a group representative. This
is more robust, and reduces the number of data points drastically, i.e. one value per group.
Internally, these steps take place:
- apply RT filter
- [compute median per group] (only if groups were given in 'cd')
- set Model's rt position
- call train() (see overloaded method)
@param[in] cd List of calibrants
@param[in] md Type of model (linear, quadratic, ...)
@param[in] use_RANSAC Remove outliers before computing the model?
@param[in] rt_left Filter 'cd' by RT; all calibrants with RT < 'rt_left' are removed
@param[in] rt_right Filter 'cd' by RT; all calibrants with RT > 'rt_right' are removed
@return True if model was build, false otherwise
*/
bool train(const CalibrationData& cd, MODELTYPE md, bool use_RANSAC,
double rt_left = -std::numeric_limits<double>::max(),
double rt_right = std::numeric_limits<double>::max()
);
/**
@brief Train a model using calibrant data
Given theoretical and observed mass values (and corresponding weights),
a model (linear, quadratic, ...) is build.
Outlier removal is applied before.
The 'obs_mz' can be either given as absolute masses in [Th] or relative deviations in [ppm].
The MZTrafoModel must be constructed accordingly (see constructor). This has no influence on the model building itself, but
rather on how 'predict()' works internally.
Outlier detection before model building via the RANSAC algorithm is supported for LINEAR and QUADRATIC models.
Internally, these steps take place:
- [apply RANSAC] (depending on 'use_RANSAC')
- build model and store its parameters internally
@param[in] error_mz Observed Mass error (in ppm or Th)
@param[in] theo_mz Theoretical m/z values, corresponding to 'error_mz'
@param[in] weights For weighted models only: weight of calibrants; ignored otherwise
@param[in] md Type of model (linear, quadratic, ...)
@param[in] use_RANSAC Remove outliers before computing the model?
@return True if model was build, false otherwise
*/
bool train(std::vector<double> error_mz,
std::vector<double> theo_mz,
std::vector<double> weights,
MODELTYPE md,
bool use_RANSAC);
/**
@brief Get model coefficients.
Parameters will be filled with internal model parameters.
The model must be trained before; Exception is thrown otherwise!
@param[out] intercept The intercept
@param[out] slope The slope
@param[out] power The coefficient for x*x (will be 0 for linear models)
@throw Exception::Precondition if model is not trained yet
*/
void getCoefficients(double& intercept, double& slope, double& power);
/**
@brief Copy model coefficients from another model.
*/
void setCoefficients(const MZTrafoModel& rhs);
/**
@brief Manually set model coefficients
Can be used instead of train(), so manually set coefficients.
It must be exactly three values. If you want a linear model, set 'power' to zero.
If you want a constant model, set slope to zero in addition.
@param[in] intercept The offset
@param[in] slope The slope
@param[in] power The x*x coefficient (for quadratic models)
*/
void setCoefficients(double intercept, double slope, double power);
/**
@brief String representation of the model parameters.
Empty if model is not trained.
*/
String toString() const;
}; // MZTrafoModel
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/PROCESSING/CALIBRATION/InternalCalibration.h | .h | 12,777 | 278 | // 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/KERNEL/StandardTypes.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/DATASTRUCTURES/CalibrationData.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
#include <OpenMS/PROCESSING/CALIBRATION/MZTrafoModel.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <vector>
namespace OpenMS
{
class FeatureMap;
/**
@brief A mass recalibration method using linear/quadratic interpolation (robust/weighted) of given reference masses.
@ingroup SignalProcessing
*/
class OPENMS_DLLAPI InternalCalibration
: public ProgressLogger
{
public:
/// Default constructor
InternalCalibration();
/// Destructor
~InternalCalibration() override{}
/// helper class, describing a lock mass
struct LockMass
{
double mz; ///< m/z of the lock mass (incl. adducts)
unsigned int ms_level; ///< MS level where it occurs
int charge; ///< charge of the ion (to find isotopes)
LockMass(double mz_, int lvl_, int charge_)
: mz(mz_),
ms_level(lvl_),
charge(charge_)
{}
};
/**
@brief Extract calibrants from Raw data (mzML)
Lock masses are searched in each spectrum and added to the internal calibrant database.
Filters can be used to exclude spurious peaks, i.e. require the calibrant peak to be monoisotopic or
to have a +1 isotope (should not be used for very low abundant calibrants).
If a calibrant is not found, it is added to a 'failed_lock_masses' database which is returned and not stored internally.
The intensity of the peaks describe the reason for failed detection: 0.0 - peak not found with the given ppm tolerance;
1.0 - peak is not monoisotopic (can only occur if 'lock_require_mono' is true)
2.0 - peak has no +1 isotope (can only occur if 'lock_require_iso' is true)
@param[in] exp Peak map containing the lock masses
@param[in] ref_masses List of lock masses
@param[in] tol_ppm Search window for lock masses in 'exp'
@param[in] lock_require_mono Require that a lock mass is the monoisotopic peak (i.e. not an isotope peak) -- lock mass is rejected otherwise
@param[in] lock_require_iso Require that a lock mass has isotope peaks to its right -- lock mass is rejected otherwise
@param[out] failed_lock_masses Set of calibration masses which were not found, i.e. their expected m/z and RT positions;
@param[in] verbose Print information on 'lock_require_XXX' matches during search
@return Number of calibration masses found
*/
Size fillCalibrants(const PeakMap& exp,
const std::vector<InternalCalibration::LockMass>& ref_masses,
double tol_ppm,
bool lock_require_mono,
bool lock_require_iso,
CalibrationData& failed_lock_masses,
bool verbose = true);
/**
@brief Extract calibrants from identifications
Extracts only the first hit from the first peptide identification of each feature.
Hits are sorted beforehand.
Ambiguities should be resolved before, e.g. using IDFilter.
RT and m/z are taken from the features, not from the identifications (for an exception see below)!
Unassigned peptide identifications are also taken into account!
RT and m/z are naturally taken from the IDs, since to feature is assigned.
If you do not want these IDs, remove them from the feature map before calling this function.
A filtering step is done in the m/z dimension using @p tol_ppm.
Since precursor masses could be annotated wrongly (e.g. isotope peak instead of mono),
larger outliers are removed before accepting an ID as calibrant.
@param[in] fm FeatureMap with peptide identifications
@param[in] tol_ppm Only accept ID's whose theoretical mass deviates at most this much from annotated
@return Number of calibration masses found
*/
Size fillCalibrants(const FeatureMap& fm, double tol_ppm);
/**
@brief Extract calibrants from identifications
Extracts only the first hit from each peptide identification.
Hits are sorted beforehand.
Ambiguities should be resolved before, e.g. using IDFilter.
A filtering step is done in the m/z dimension using @p tol_ppm.
Since precursor masses could be annotated wrongly (e.g. isotope peak instead of mono),
larger outliers are removed before accepting an ID as calibrant.
@param[in] pep_ids Peptide ids (e.g. from an idXML file)
@param[in] tol_ppm Only accept ID's whose theoretical mass deviates at most this much from annotated
@return Number of calibration masses found
*/
Size fillCalibrants(const PeptideIdentificationList& pep_ids, double tol_ppm);
/**
@brief Get container of calibration points
Filled using fillCalibrants() methods.
@return Container of calibration points
*/
const CalibrationData& getCalibrationPoints() const;
/**
@brief Apply calibration to data
For each spectrum, a calibration model will be computed and applied.
Make sure to call fillCalibrants() before, so a model can be created.
The MSExperiment will be sorted by RT and m/z if unsorted.
@param[in,out] exp MSExperiment holding the Raw data to calibrate
@param[in] target_mslvl MS-levels where calibration should be applied to
@param[in] model_type Linear or quadratic model; select based on your instrument
@param[in] rt_chunk RT-window size (one-sided) of calibration points to collect around each spectrum.
Set to negative values, to build one global model instead.
@param[in] use_RANSAC Remove outliers before fitting a model?!
@param[in] post_ppm_median The median ppm error of the calibrants must be at least this good after calibration; otherwise this method returns false(fail)
@param[in] post_ppm_MAD The median absolute deviation of the calibrants must be at least this good after calibration; otherwise this method returns false(fail)
@param[in] file_models Output CSV filename, where model parameters are written to (pass empty string to skip)
@param[in] file_models_plot Output PNG image model parameters (pass empty string to skip)
@param[in] file_residuals Output CSV filename, where ppm errors of calibrants before and after model fitting parameters are written to (pass empty string to skip)
@param[in] file_residuals_plot Output PNG image of the ppm errors of calibrants (pass empty string to skip)
@param[in] rscript_executable Full path to the Rscript executable
@return true upon successful calibration
*/
bool calibrate(PeakMap& exp,
const IntList& target_mslvl,
MZTrafoModel::MODELTYPE model_type,
double rt_chunk,
bool use_RANSAC,
double post_ppm_median,
double post_ppm_MAD,
const String& file_models = "",
const String& file_models_plot = "",
const String& file_residuals = "",
const String& file_residuals_plot = "",
const String& rscript_executable = "Rscript");
/**
@brief Transform a precursor's m/z
Calibrate m/z of precursors.
@param[in,out] pcs Uncalibrated Precursors
@param[in] trafo The calibration function to apply
*/
static void applyTransformation(std::vector<Precursor>& pcs, const MZTrafoModel& trafo);
/**
@brief Transform a spectrum (data+precursor)
See applyTransformation(MSExperiment, ...) for details.
@param[in,out] spec Uncalibrated MSSpectrum
@param[in] target_mslvl List (can be unsorted) of MS levels to calibrate
@param[in] trafo The calibration function to apply
*/
static void applyTransformation(PeakMap::SpectrumType& spec, const IntList& target_mslvl, const MZTrafoModel& trafo);
/**
@brief Transform spectra from a whole map (data+precursor)
All data peaks and precursor information (if present) are calibrated in m/z.
Only spectra whose MS-level is contained in 'target_mslvl' are calibrated.
In addition, if a fragmentation spectrum's precursor information originates from an MS level in 'target_mslvl',
the precursor (not the spectrum itself) is also subjected to calibration.
E.g., If we only have MS and MS/MS spectra: for 'target_mslvl' = {1} then all MS1 spectra and MS2 precursors are calibrated.
If 'target_mslvl' = {2}, only MS2 spectra (not their precursors) are calibrated.
If 'target_mslvl' = {1,2} all spectra and precursors are calibrated.
@param[in,out] exp Uncalibrated peak map
@param[in] target_mslvl List (can be unsorted) of MS levels to calibrate
@param[in] trafo The calibration function to apply
*/
static void applyTransformation(PeakMap& exp, const IntList& target_mslvl, const MZTrafoModel& trafo);
protected:
/// statistics when adding peptide calibrants
struct CalibrantStats_
{
CalibrantStats_(const double tol_ppm)
: tol_ppm_(tol_ppm)
{};
Size cnt_empty = 0; ///< cases of empty PepIDs (no hits)
Size cnt_nomz = 0; ///< cases of no m/z value
Size cnt_nort = 0; ///< cases of no RT value
Size cnt_decal = 0; ///< cases of large gap (>tol_ppm) between theoretical peptide weight (from sequence) and precursor mass
Size cnt_total = 0; ///< total number of cases
void print() const
{
if (cnt_empty > 0) OPENMS_LOG_WARN << "Warning: " << cnt_empty << "/" << cnt_total << " calibrations points were skipped, since they have no peptide sequence!" << std::endl;
if (cnt_nomz > 0) OPENMS_LOG_WARN << "Warning: " << cnt_nomz << "/" << cnt_total << " calibrations points were skipped, since they have no m/z value!" << std::endl;
if (cnt_nort > 0) OPENMS_LOG_WARN << "Warning: " << cnt_nort << "/" << cnt_total << " calibrations points were skipped, since they have no RT value!" << std::endl;
if (cnt_decal > 0) OPENMS_LOG_WARN << "Warning: " << cnt_decal << "/" << cnt_total << " calibrations points were skipped, since their theoretical weight is more than " << tol_ppm_ << " ppm away from their measured mass!" << std::endl;
}
private:
const double tol_ppm_; ///< tolerance used for counting cnt_decal
};
/**
@brief Add(no prior clear) calibrants to internal list.
Extracts only the first hit from each peptide identification.
Hits are sorted beforehand.
Ambiguities should be resolved before, e.g. using IDFilter.
A filtering step is done in the m/z dimension using @p tol_ppm.
Since precursor masses could be annotated wrongly (e.g. isotope peak instead of mono),
larger outliers are removed before accepting an ID as calibrant.
@param[in] pep_id A single PeptideID (e.g. from an idXML file); only the top peptide hit is used
@param[in] tol_ppm Only accept ID's whose theoretical mass deviates at most this much from annotated
@param[in,out] stats Update stats, if calibrant cannot be used (no RT, no MZ, no sequence, out-of tolerance)
*/
void fillID_( const PeptideIdentification& pep_id, const double tol_ppm, CalibrantStats_& stats);
/// calls fillID_ on all PeptideIDs
void fillIDs_(const PeptideIdentificationList& pep_ids, const double tol_ppm, CalibrantStats_& stats);
/// determine if sequence is within tol_ppm and update stats; fills mz_ref with the theoretical m/z of the sequence
bool isDecalibrated_(const PeptideIdentification& pep_id, const double mz_obs, const double tol_ppm, CalibrantStats_& stats, double& mz_ref);
/**
@brief Calibrate m/z of a spectrum, ignoring precursors!
This method is not exposed as public, because its easy to be misused on spectra while forgetting about the precursors of high-level spectra.
*/
static void applyTransformation_(PeakMap::SpectrumType& spec, const MZTrafoModel& trafo);
private:
CalibrationData cal_data_;
}; // class InternalCalibration
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/PROCESSING/FILTERING/WindowMower.h | .h | 6,535 | 200 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Mathias Walzer $
// $Authors: Mathias Walzer, Timo Sachsenberg$
// --------------------------------------------------------------------------
//
#pragma once
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/KERNEL/MSSpectrum.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <set>
namespace OpenMS
{
/**
@brief Retains the highest peaks in a sliding or jumping window
@htmlinclude OpenMS_WindowMower.parameters
@ingroup SpectraPreprocessers
*/
class OPENMS_DLLAPI WindowMower :
public DefaultParamHandler
{
public:
// @name Constructors, destructors and assignment operators
// @{
/// default constructor
WindowMower();
/// destructor
~WindowMower() override;
/// copy constructor
WindowMower(const WindowMower& source);
/// assignment operator
WindowMower& operator=(const WindowMower& source);
// @}
/// sliding window version (slower)
template <typename SpectrumType>
void filterPeakSpectrumForTopNInSlidingWindow(SpectrumType& spectrum)
{
typedef typename SpectrumType::ConstIterator ConstIterator;
windowsize_ = (double)param_.getValue("windowsize");
peakcount_ = (UInt)param_.getValue("peakcount");
//copy spectrum
SpectrumType old_spectrum = spectrum;
old_spectrum.sortByPosition();
//find high peak positions
bool end = false;
std::set<double> positions;
for (ConstIterator it = old_spectrum.begin(); it != old_spectrum.end(); ++it)
{
// copy the window from the spectrum
SpectrumType window;
for (ConstIterator it2 = it; (it2->getPosition() - it->getPosition() < windowsize_); )
{
window.push_back(*it2);
if (++it2 == old_spectrum.end())
{
end = true;
break;
}
}
//extract peakcount most intense peaks
window.sortByIntensity(true);
for (Size i = 0; i < peakcount_; ++i)
{
if (i < window.size())
{
positions.insert(window[i].getMZ());
}
}
//abort at the end of the spectrum
if (end) break;
}
// select peaks that were retained
std::vector<Size> indices;
for (ConstIterator it = spectrum.begin(); it != spectrum.end(); ++it)
{
if (positions.find(it->getMZ()) != positions.end())
{
Size index(it - spectrum.begin());
indices.push_back(index);
}
}
spectrum.select(indices);
}
void filterPeakSpectrum(PeakSpectrum& spectrum);
void filterPeakMap(PeakMap& exp);
// jumping window version (faster)
template <typename SpectrumType>
void filterPeakSpectrumForTopNInJumpingWindow(SpectrumType& spectrum)
{
if (spectrum.empty())
{
return;
}
spectrum.sortByPosition();
windowsize_ = static_cast<double>(param_.getValue("windowsize"));
peakcount_ = static_cast<UInt>(param_.getValue("peakcount"));
// copy meta data
SpectrumType out = spectrum;
out.clear(false);
SpectrumType peaks_in_window;
double window_start = spectrum[0].getMZ();
for (Size i = 0; i != spectrum.size(); ++i)
{
if (spectrum[i].getMZ() - window_start < windowsize_) // collect peaks in window
{
peaks_in_window.push_back(spectrum[i]);
}
else // step over window boundaries
{
window_start = spectrum[i].getMZ(); // as there might be large gaps between peaks resulting in empty windows, set new window start to next peak
// copy N highest peaks to out
if (peaks_in_window.size() > peakcount_)
{
std::partial_sort(peaks_in_window.begin(), peaks_in_window.begin() + peakcount_, peaks_in_window.end(), [](auto &left, auto &right) {typename SpectrumType::PeakType::IntensityLess cmp; return cmp(right, left);});
copy(peaks_in_window.begin(), peaks_in_window.begin() + peakcount_, back_inserter(out));
}
else
{
std::sort(peaks_in_window.begin(), peaks_in_window.end(), [](auto &left, auto &right) {typename SpectrumType::PeakType::IntensityLess cmp; return cmp(right, left);});
copy(peaks_in_window.begin(), peaks_in_window.end(), back_inserter(out));
}
peaks_in_window.clear(false);
peaks_in_window.push_back(spectrum[i]);
}
}
if (!peaks_in_window.empty()) // last window is not empty
{
// Note that the last window might be much smaller than windowsize.
// Therefore the number of peaks copied from this window should be adapted accordingly.
// Otherwise a lot of noise peaks are copied from each end of a spectrum.
double last_window_size = peaks_in_window.back().getMZ() - window_start;
double last_window_size_fraction = last_window_size / windowsize_;
Size last_window_peakcount = static_cast<Size>(std::round(last_window_size_fraction * peakcount_));
if (peaks_in_window.size() > last_window_peakcount)
{ // sort for last_window_peakcount highest peaks
std::partial_sort(peaks_in_window.begin(), peaks_in_window.begin() + last_window_peakcount, peaks_in_window.end(),
[](auto &left, auto &right) {typename SpectrumType::PeakType::IntensityLess cmp; return cmp(right, left);});
std::copy(peaks_in_window.begin(), peaks_in_window.begin() + last_window_peakcount, back_inserter(out));
}
else
{
std::copy(peaks_in_window.begin(), peaks_in_window.end(), std::back_inserter(out));
}
}
// select peaks that were retained
std::vector<Size> indices;
for (typename SpectrumType::ConstIterator it = spectrum.begin(); it != spectrum.end(); ++it)
{
if (std::find(out.begin(), out.end(), *it) != out.end())
{
Size index(it - spectrum.begin());
indices.push_back(index);
}
}
spectrum.select(indices);
return;
}
//TODO reimplement DefaultParamHandler::updateMembers_()
private:
double windowsize_;
UInt peakcount_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/PROCESSING/FILTERING/ThresholdMower.h | .h | 1,789 | 77 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Mathias Walzer $
// $Authors: Timo Sachsenberg $
// --------------------------------------------------------------------------
//
#pragma once
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/KERNEL/MSSpectrum.h>
#include <OpenMS/KERNEL/MSExperiment.h>
namespace OpenMS
{
/**
@brief Removes all peaks below an intensity threshold.
@htmlinclude OpenMS_ThresholdMower.parameters
@ingroup SpectraPreprocessers
*/
class OPENMS_DLLAPI ThresholdMower :
public DefaultParamHandler
{
public:
// @name Constructors and Destructors
// @{
/// default constructor
ThresholdMower();
/// destructor
~ThresholdMower() override;
/// copy constructor
ThresholdMower(const ThresholdMower & source);
/// assignment operator
ThresholdMower & operator=(const ThresholdMower & source);
// @}
// @name Accessors
// @{
///
///
template <typename SpectrumType>
void filterSpectrum(SpectrumType & spectrum)
{
threshold_ = ((double)param_.getValue("threshold"));
std::vector<Size> indices;
for (Size i = 0; i != spectrum.size(); ++i)
{
if (spectrum[i].getIntensity() >= threshold_)
{
indices.push_back(i);
}
}
spectrum.select(indices);
}
void filterPeakSpectrum(PeakSpectrum & spectrum);
void filterPeakMap(PeakMap & exp);
//TODO reimplement DefaultParamHandler::updateMembers_()
private:
double threshold_;
// @}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/PROCESSING/FILTERING/NLargest.h | .h | 1,958 | 86 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Mathias Walzer $
// $Authors: $
// --------------------------------------------------------------------------
//
#pragma once
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/KERNEL/MSSpectrum.h>
#include <OpenMS/KERNEL/MSExperiment.h>
namespace OpenMS
{
/**
@brief NLargest removes all but the n largest peaks
@htmlinclude OpenMS_NLargest.parameters
@ingroup SpectraPreprocessers
*/
class OPENMS_DLLAPI NLargest :
public DefaultParamHandler
{
public:
// @name Constructors and Destructors
// @{
/// default constructor
NLargest();
/// detailed constructor
NLargest(UInt n);
/// destructor
~NLargest() override;
/// copy constructor
NLargest(const NLargest & source);
/// assignment operator
NLargest & operator=(const NLargest & source);
// @}
///
template <typename SpectrumType>
void filterSpectrum(SpectrumType & spectrum)
{
if (spectrum.size() <= peakcount_) return;
// sort by reverse intensity
spectrum.sortByIntensity(true);
// keep the n largest peaks if more than n are present
std::vector<Size> indices;
for (Size i = 0; i != peakcount_; ++i)
{
indices.push_back(i);
}
spectrum.select(indices);
}
void filterPeakSpectrum(PeakSpectrum & spectrum);
void filterPeakMap(PeakMap & exp);
//TODO reimplement DefaultParamHandler::updateMembers_()
// @}
protected:
void updateMembers_() override;
UInt peakcount_;
/// handles the initialization of the default parameters for the 2 constructors
void init_();
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/PROCESSING/MISC/SplinePackage.h | .h | 2,108 | 90 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Lars Nilse $
// $Authors: Lars Nilse $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/DATASTRUCTURES/DRange.h>
#include <OpenMS/MATH/MISC/CubicSpline2d.h>
#include <vector>
namespace OpenMS
{
/**
* @brief fundamental data structure for SplineInterpolatedPeaks
*
* In many cases, data points in MS spectra (or chromatograms) are not equidistant in m/z (or RT)
* but consist of packages of data points separated by wide m/z (or RT) ranges with zero intensity.
* SplinePackage contains the spline fit of a single set of such data points.
*
* @see SplineInterpolatedPeaks
*/
class OPENMS_DLLAPI SplinePackage
{
public:
/**
* @brief constructor
*/
SplinePackage(std::vector<double> pos, const std::vector<double>& intensity);
/**
* @brief destructor
*/
~SplinePackage();
/**
* @brief returns the minimum position for which the spline fit is valid
*/
double getPosMin() const;
/**
* @brief returns the maximum position for which the spline fit is valid
*/
double getPosMax() const;
/**
* @brief returns a sensible position step width for the package
*/
double getPosStepWidth() const;
/**
* @brief returns true if position in [posMin:posMax] interval else false
*/
bool isInPackage(double pos) const;
/**
* @brief returns interpolated intensity position `pos`
*/
double eval(double pos) const;
private:
/**
* @brief position limits of the package in the raw data spectrum
*/
double pos_min_;
double pos_max_;
/**
* @brief sensible position step width with which to scan through the package
*
* @note The step width is rescaled individually in each navigator.
* @see SplineInterpolatedPeaks::Navigator::getNextPos()
*/
double pos_step_width_;
/**
* @brief spline object for interpolation of intensity profile
*/
CubicSpline2d spline_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/PROCESSING/MISC/SplineInterpolatedPeaks.h | .h | 5,966 | 191 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Lars Nilse $
// $Authors: Lars Nilse $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/DATASTRUCTURES/DRange.h>
#include <OpenMS/PROCESSING/MISC/SplinePackage.h>
#include <vector>
namespace OpenMS
{
/**
* @brief Data structure for spline interpolation of MS1 spectra and chromatograms
*
* The data structure consists of a set of splines, each interpolating the MS1 spectrum (or chromatogram) in a
* certain m/z (or RT) range. Between these splines no raw data points exist and the intensity is identical to zero.
*
* A spline on non-equi-distant input data is not well supported in regions without data points. Hence, a spline tends to
* swing wildly in these regions and cannot be used for reliable interpolation. We assume that in m/z (or RT) regions
* without data points, the spectrum (or chromatogram) is identical to zero.
*
* @see SplinePackage
* @see MSSpectrum
* @see MSChromatogram
*/
class OPENMS_DLLAPI SplineInterpolatedPeaks
{
public:
/**
* @brief constructor taking two vectors
* (and an optional scaling factor for the m/z (or RT) step width)
*
* @note Vectors are assumed to be sorted by m/z (or RT)!
*/
SplineInterpolatedPeaks(const std::vector<double>& pos, const std::vector<double>& intensity);
/**
* @brief constructor taking an MSSpectrum
* (and an optional scaling factor for the m/z step width)
*/
SplineInterpolatedPeaks(const MSSpectrum& raw_spectrum);
/**
* @brief constructor taking an MSChromatogram
* (and an optional scaling factor for the RT step width)
*/
SplineInterpolatedPeaks(const MSChromatogram& raw_chromatogram);
/**
* @brief destructor
*/
~SplineInterpolatedPeaks();
/**
* @brief returns the minimum m/z (or RT) of the spectrum
*/
double getPosMin() const;
/**
* @brief returns the maximum m/z (or RT) of the spectrum
*/
double getPosMax() const;
/**
* @brief Get number of spline packages found during initialization
*
* Note that this function should be called right after the C'tor to ensure the spectrum
* has some usable data to work on.
* In case there are no packages, a subsequent call to getNavigator() will throw an exception.
*/
size_t size() const;
/**
* @brief iterator class for access of spline packages
*/
class OPENMS_DLLAPI Navigator
{
public:
/**
* @brief constructor of iterator
*
* @param[in] packages Spline packages to be accessed
* @param[in] pos_max Maximum in m/z (or RT) of the spectrum (or chromatogram)
* @param[in] scaling The step width can be scaled by this factor. Often it is advantageous to iterate
* in slightly smaller steps over the spectrum (or chromatogram).
*/
Navigator(const std::vector<SplinePackage>* packages, double pos_max, double scaling);
/**
* @brief constructor (for pyOpenMS)
*/
Navigator();
/**
* @brief destructor
*/
~Navigator();
/**
* @brief returns spline interpolated intensity at this position
* (fast access since we can start search from lastPackage)
*/
double eval(double pos);
/**
* @brief returns the next sensible m/z (or RT) position for scanning through a spectrum (or chromatogram)
* (fast access since we can start search from lastPackage)
*
* In the middle of a package, we increase the position by the average spacing of the input data (times a scaling factor).
* At the end of a package, we jump straight to the beginning of the next package.
*/
double getNextPos(double pos);
private:
/**
* @brief list of spline packages to be accessed
*/
const std::vector<SplinePackage> * packages_;
/**
* @brief index of spline package last accessed
*/
size_t last_package_;
/**
* @brief m/z (or RT) limits of the spectrum (or chromatogram)
*/
double pos_max_;
/**
* @brief scaling of the step width
*
* Each package stores its own step width, which is the average spacing of the input data points.
* This step width can be adjusted by the scaling factor. Often it is advantageous to use a step width
* which is somewhat smaller than the average raw data spacing.
*
* @see getNextPos()
*/
double pos_step_width_scaling_;
};
/**
* @brief returns an iterator for access of spline packages
*
* Will throw an exception if no packages were found during construction.
* Check using getSplineCount().
*
* Make sure that the underlying SplineInterpolatedPeaks does not run out-of-scope since the
* Navigator relies on its data.
*
* @param[in] scaling step width scaling parameter
*
* @throw Exception::InvalidSize if packages is empty
*/
SplineInterpolatedPeaks::Navigator getNavigator(double scaling = 0.7);
private:
/// hide default C'tor
SplineInterpolatedPeaks();
/**
* @brief m/z (or RT) limits of the spectrum
*/
double pos_min_;
double pos_max_;
/**
* @brief set of spline packages each interpolating in a certain m/z (or RT) range
*/
std::vector<SplinePackage> packages_;
/**
* @brief section common for all constructors
*/
void init_(const std::vector<double>& pos, const std::vector<double>& intensity);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/PROCESSING/MISC/DataFilters.h | .h | 11,876 | 368 | // 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/KERNEL/Mobilogram.h>
#include <OpenMS/KERNEL/MSSpectrum.h>
#include <OpenMS/KERNEL/MSChromatogram.h>
namespace OpenMS
{
class Feature;
class ConsensusFeature;
/**
@brief DataFilter array providing some convenience functions
@note For features the meta data filtering works on the MetaDataInterface of the Feature.
For peaks it works on the FloatDataArrays defined in MSSpectrum.
*/
class OPENMS_DLLAPI DataFilters
{
public:
DataFilters() = default;
/// Equality operator
bool operator==(const DataFilters&) const = default;
///Information to filter
enum FilterType
{
INTENSITY, ///< Filter the intensity value
QUALITY, ///< Filter the overall quality value
CHARGE, ///< Filter the charge value
SIZE, ///< Filter the number of subordinates/elements
META_DATA ///< Filter meta data
};
///Filter operation
enum FilterOperation
{
GREATER_EQUAL, ///< Greater than the value or equal to the value
EQUAL, ///< Equal to the value
LESS_EQUAL, ///< Less than the value or equal to the value
EXISTS ///< Only for META_DATA filter type, tests if meta data exists
};
/// Representation of a peak/feature filter combining FilterType, FilterOperation and a value (either double or String)
struct OPENMS_DLLAPI DataFilter
{
DataFilter(){};
/// ctor for common case of numerical filter
DataFilter(const FilterType type, const FilterOperation op, const double val, const String& meta_name = "")
: field(type), op(op), value(val), value_string(), meta_name(meta_name), value_is_numerical(true)
{};
/// ctor for common case of string filter
DataFilter(const FilterType type, const FilterOperation op, const String& val, const String& meta_name = "")
: field(type), op(op), value(0.0), value_string(val), meta_name(meta_name), value_is_numerical(false)
{};
/// Field to filter
FilterType field{ DataFilters::INTENSITY };
/// Filter operation
FilterOperation op{ DataFilters::GREATER_EQUAL} ;
/// Value for comparison
double value{ 0.0 };
/// String value for comparison (for meta data)
String value_string;
/// Name of the considered meta information (key)
String meta_name;
/// use @p value or @p value_string ?
bool value_is_numerical{ false };
/// Returns a string representation of the filter
String toString() const;
/**
@brief Parses @p filter and sets the filter properties accordingly
This method accepts the format provided by toString().
@exception Exception::InvalidValue is thrown when the filter is not formatted properly
*/
void fromString(const String & filter);
///Equality operator
bool operator==(const DataFilter & rhs) const;
///Inequality operator
bool operator!=(const DataFilter & rhs) const;
};
/// Filter count
Size size() const;
/**
@brief Filter accessor
@exception Exception::IndexOverflow is thrown for invalid indices
*/
const DataFilter & operator[](Size index) const;
/// Adds a filter
void add(const DataFilter & filter);
/**
@brief Removes the filter corresponding to @p index
@exception Exception::IndexOverflow is thrown for invalid indices
*/
void remove(Size index);
/**
@brief Replaces the filter corresponding to @p index
@exception Exception::IndexOverflow is thrown for invalid indices
*/
void replace(Size index, const DataFilter & filter);
/// Removes all filters
void clear();
/// Enables/disables the all the filters
void setActive(bool is_active);
/**
@brief Returns if the filters are enabled
They are automatically enabled when a filter is added and
automatically disabled when the last filter is removed
*/
inline bool isActive() const
{
return is_active_;
}
/// Returns if the @p feature fulfills the current filter criteria
bool passes(const Feature& feature) const;
/// Returns if the @p consensus_feature fulfills the current filter criteria
bool passes(const ConsensusFeature& consensus_feature) const;
/// Returns if the a peak in a @p spectrum at @p peak_index fulfills the current filter criteria
inline bool passes(const MSSpectrum& spectrum, Size peak_index) const
{
if (!is_active_) return true;
for (Size i = 0; i < filters_.size(); i++)
{
const DataFilters::DataFilter & filter = filters_[i];
if (filter.field == INTENSITY)
{
switch (filter.op)
{
case GREATER_EQUAL:
if (spectrum[peak_index].getIntensity() < filter.value) return false;
break;
case EQUAL:
if (spectrum[peak_index].getIntensity() != filter.value) return false;
break;
case LESS_EQUAL:
if (spectrum[peak_index].getIntensity() > filter.value) return false;
break;
default:
break;
}
}
else if (filter.field == META_DATA)
{
const auto& f_arrays = spectrum.getFloatDataArrays();
//find the right meta data array
SignedSize f_index = -1;
for (Size j = 0; j < f_arrays.size(); ++j)
{
if (f_arrays[j].getName() == filter.meta_name)
{
f_index = j;
break;
}
}
//if it is present, compare it
if (f_index != -1)
{
if (filter.op == EQUAL && f_arrays[f_index][peak_index] != filter.value) return false;
else if (filter.op == LESS_EQUAL && f_arrays[f_index][peak_index] > filter.value) return false;
else if (filter.op == GREATER_EQUAL && f_arrays[f_index][peak_index] < filter.value) return false;
}
//if float array not found, search in integer arrays
const typename MSSpectrum::IntegerDataArrays & i_arrays = spectrum.getIntegerDataArrays();
//find the right meta data array
SignedSize i_index = -1;
for (Size j = 0; j < i_arrays.size(); ++j)
{
if (i_arrays[j].getName() == filter.meta_name)
{
i_index = j;
break;
}
}
//if it is present, compare it
if (i_index != -1)
{
if (filter.op == EQUAL && i_arrays[i_index][peak_index] != filter.value) return false;
else if (filter.op == LESS_EQUAL && i_arrays[i_index][peak_index] > filter.value) return false;
else if (filter.op == GREATER_EQUAL && i_arrays[i_index][peak_index] < filter.value) return false;
}
//if it is not present, abort
if (f_index == -1 && i_index == -1) return false;
}
}
return true;
}
/// Returns if the a peak in a @p chrom at @p peak_index fulfills the current filter criteria
inline bool passes(const MSChromatogram& chrom, Size peak_index) const
{
if (!is_active_) return true;
for (Size i = 0; i < filters_.size(); i++)
{
const DataFilters::DataFilter& filter = filters_[i];
if (filter.field == INTENSITY)
{
switch (filter.op)
{
case GREATER_EQUAL:
if (chrom[peak_index].getIntensity() < filter.value)
return false;
break;
case EQUAL:
if (chrom[peak_index].getIntensity() != filter.value)
return false;
break;
case LESS_EQUAL:
if (chrom[peak_index].getIntensity() > filter.value)
return false;
break;
default:
break;
}
}
else if (filter.field == META_DATA)
{
const auto& f_arrays = chrom.getFloatDataArrays();
// find the right meta data array
SignedSize f_index = -1;
for (Size j = 0; j < f_arrays.size(); ++j)
{
if (f_arrays[j].getName() == filter.meta_name)
{
f_index = j;
break;
}
}
// if it is present, compare it
if (f_index != -1)
{
if (filter.op == EQUAL && f_arrays[f_index][peak_index] != filter.value) return false;
else if (filter.op == LESS_EQUAL && f_arrays[f_index][peak_index] > filter.value) return false;
else if (filter.op == GREATER_EQUAL && f_arrays[f_index][peak_index] < filter.value) return false;
}
// if float array not found, search in integer arrays
const typename MSSpectrum::IntegerDataArrays& i_arrays = chrom.getIntegerDataArrays();
// find the right meta data array
SignedSize i_index = -1;
for (Size j = 0; j < i_arrays.size(); ++j)
{
if (i_arrays[j].getName() == filter.meta_name)
{
i_index = j;
break;
}
}
// if it is present, compare it
if (i_index != -1)
{
if (filter.op == EQUAL && i_arrays[i_index][peak_index] != filter.value) return false;
else if (filter.op == LESS_EQUAL && i_arrays[i_index][peak_index] > filter.value) return false;
else if (filter.op == GREATER_EQUAL && i_arrays[i_index][peak_index] < filter.value) return false;
}
// if it is not present, abort
if (f_index == -1 && i_index == -1) return false;
}
}
return true;
}
/// Returns if the a peak in a @p mobilogram at @p peak_index fulfills the current filter criteria
inline bool passes(const Mobilogram& mobilogram, Size peak_index) const
{
if (!is_active_) {
return true;
}
for (Size i = 0; i < filters_.size(); i++)
{
const DataFilters::DataFilter& filter = filters_[i];
if (filter.field == INTENSITY)
{
switch (filter.op)
{
case GREATER_EQUAL:
if (mobilogram[peak_index].getIntensity() < filter.value)
return false;
break;
case EQUAL:
if (mobilogram[peak_index].getIntensity() != filter.value)
return false;
break;
case LESS_EQUAL:
if (mobilogram[peak_index].getIntensity() > filter.value)
return false;
break;
default:
break;
}
}
else if (filter.field == META_DATA)
{ // no metadata arrays so far...
return false;
}
}
return true;
}
protected:
///Array of DataFilters
std::vector<DataFilter> filters_;
///Vector of meta indices acting as index cache
std::vector<Size> meta_indices_;
///Determines if the filters are activated
bool is_active_ = false;
///Returns if the meta value at @p index of @p meta_interface (a peak or feature) passes the @p filter
bool metaPasses_(const MetaInfoInterface& meta_interface, const DataFilters::DataFilter& filter, Size index) const;
};
} //namespace
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/PROCESSING/SPECTRAMERGING/SpectraMerger.h | .h | 35,536 | 990 | // 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, Andreas Bertsch, Lars Nilse $
// --------------------------------------------------------------------------
//
#pragma once
#include <OpenMS/ML/CLUSTERING/ClusterAnalyzer.h>
#include <OpenMS/ML/CLUSTERING/ClusterHierarchical.h>
#include <OpenMS/ML/CLUSTERING/SingleLinkage.h>
#include <OpenMS/COMPARISON/SpectrumAlignment.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/PROCESSING/MISC/SplineInterpolatedPeaks.h>
#include <OpenMS/KERNEL/BaseFeature.h>
#include <vector>
namespace OpenMS
{
/**
@brief Offers spectra merging and averaging algorithms to increase the quality of a spectrum.
Spectra merging is to merge multiple related spectra into a single one - thus, we often end up with a reduced number of spectra.
For instance, MS1 spectra within a pre-defined retention time window or MS2 spectra from the same precursor ion.
Merging can be done block wise or by precursor.
Spectra averaging incorporates the signal from neighbouring spectra for each spectrum.
Thus, the number of spectra remains the same after spectra averaging.
The weights of neighbouring spectra (in RT) are either determined by a Gaussian or all identical (TopHat method).
Both merging and averaging attempt to increase the quality of a spectrum by increasing its signal to noise ratio.
Parameters are accessible via the DefaultParamHandler.
@htmlinclude OpenMS_SpectraMerger.parameters
*/
class OPENMS_DLLAPI SpectraMerger :
public DefaultParamHandler, public ProgressLogger
{
protected:
/* Determine distance between two spectra
Distance is determined as
(d_rt/rt_max_ + d_mz/mz_max_) / 2
*/
class SpectraDistance_ :
public DefaultParamHandler
{
public:
SpectraDistance_() :
DefaultParamHandler("SpectraDistance")
{
defaults_.setValue("rt_tolerance", 10.0, "Maximal RT distance (in [s]) for two spectra's precursors.");
defaults_.setValue("mz_tolerance", 1.0, "Maximal m/z distance (in Da) for two spectra's precursors.");
defaultsToParam_(); // calls updateMembers_
}
void updateMembers_() override
{
rt_max_ = (double) param_.getValue("rt_tolerance");
mz_max_ = (double) param_.getValue("mz_tolerance");
}
double getSimilarity(const double d_rt, const double d_mz) const
{
// 1 - distance
return 1 - ((d_rt / rt_max_ + d_mz / mz_max_) / 2);
}
// measure of SIMILARITY (not distance, i.e. 1-distance)!!
double operator()(const BaseFeature& first, const BaseFeature& second) const
{
// get RT distance:
double d_rt = fabs(first.getRT() - second.getRT());
double d_mz = fabs(first.getMZ() - second.getMZ());
if (d_rt > rt_max_ || d_mz > mz_max_)
{
return 0;
}
// calculate similarity (0-1):
double sim = getSimilarity(d_rt, d_mz);
return sim;
}
protected:
double rt_max_;
double mz_max_;
}; // end of SpectraDistance
public:
/// blocks of spectra (master-spectrum index to sacrifice-spectra(the ones being merged into the master-spectrum))
typedef std::map<Size, std::vector<Size> > MergeBlocks;
/// blocks of spectra (master-spectrum index to update to spectra to average over)
typedef std::map<Size, std::vector<std::pair<Size, double> > > AverageBlocks;
// @name Constructors and Destructors
// @{
/// default constructor
SpectraMerger();
/// copy constructor
SpectraMerger(const SpectraMerger& source);
/// move constructor
SpectraMerger(SpectraMerger&& source) = default;
/// destructor
~SpectraMerger() override;
// @}
// @name Operators
// @{
/// assignment operator
SpectraMerger& operator=(const SpectraMerger& source);
/// move-assignment operator
SpectraMerger& operator=(SpectraMerger&& source) = default;
// @}
// @name Merging functions
// @{
/// Merges spectra block-wise, i.e. spectra are merged if they are close in RT. Each block consists of at most @p block_method:rt_block_size spectra and spans at most @p block_method:rt_max_length seconds.
/// The MS levels to be merged are specified by @p block_method:ms_levels. Spectra with other MS levels remain untouched.
template <typename MapType>
void mergeSpectraBlockWise(MapType& exp)
{
IntList ms_levels = param_.getValue("block_method:ms_levels");
// now actually using an UNSIGNED int, so we can increase it by 1 even if the value is INT_MAX without overflow
UInt rt_block_size(param_.getValue("block_method:rt_block_size"));
double rt_max_length = (param_.getValue("block_method:rt_max_length"));
if (rt_max_length == 0) // no rt restriction set?
{
rt_max_length = (std::numeric_limits<double>::max)(); // set max rt span to very large value
}
for (IntList::iterator it_mslevel = ms_levels.begin(); it_mslevel < ms_levels.end(); ++it_mslevel)
{
MergeBlocks spectra_to_merge;
Size idx_block(0);
UInt block_size_count(rt_block_size + 1);
Size idx_spectrum(0);
for (typename MapType::const_iterator it1 = exp.begin(); it1 != exp.end(); ++it1)
{
if (Int(it1->getMSLevel()) == *it_mslevel)
{
// block full if it contains a maximum number of scans or if maximum rt length spanned
if (++block_size_count >= rt_block_size ||
exp[idx_spectrum].getRT() - exp[idx_block].getRT() > rt_max_length)
{
block_size_count = 0;
idx_block = idx_spectrum;
}
else
{
spectra_to_merge[idx_block].push_back(idx_spectrum);
}
}
++idx_spectrum;
}
// check if last block had sacrifice spectra
if (block_size_count == 0) //block just got initialized
{
spectra_to_merge[idx_block] = std::vector<Size>();
}
// merge spectra, remove all old MS spectra and add new consensus spectra
mergeSpectra_(exp, spectra_to_merge, *it_mslevel);
}
exp.sortSpectra();
}
/// merges spectra with similar precursors (must have MS2 level)
template <typename MapType>
void mergeSpectraPrecursors(MapType& exp)
{
// convert spectra's precursors to clusterizable data
Size data_size;
std::vector<BinaryTreeNode> tree;
std::map<Size, Size> index_mapping;
// local scope to save memory - we do not need the clustering stuff later
{
std::vector<BaseFeature> data;
for (Size i = 0; i < exp.size(); ++i)
{
if (exp[i].getMSLevel() != 2)
{
continue;
}
// remember which index in distance data ==> experiment index
index_mapping[data.size()] = i;
// make cluster element
BaseFeature bf;
bf.setRT(exp[i].getRT());
const auto& pcs = exp[i].getPrecursors();
// keep the first Precursor
if (pcs.empty())
{
throw Exception::MissingInformation(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Scan #") + String(i) + " does not contain any precursor information! Unable to cluster!");
}
if (pcs.size() > 1)
{
OPENMS_LOG_WARN << "More than one precursor found. Using first one!" << std::endl;
}
bf.setMZ(pcs[0].getMZ());
data.push_back(bf);
}
data_size = data.size();
SpectraDistance_ llc;
llc.setParameters(param_.copy("precursor_method:", true));
SingleLinkage sl;
DistanceMatrix<float> dist; // will be filled
ClusterHierarchical ch;
// clustering ; threshold is implicitly at 1.0, i.e. distances of 1.0 (== similarity 0) will not be clustered
ch.cluster<BaseFeature, SpectraDistance_>(data, llc, sl, tree, dist);
}
// extract the clusters
ClusterAnalyzer ca;
std::vector<std::vector<Size> > clusters;
// count number of real tree nodes (not the -1 ones):
Size node_count = 0;
for (Size ii = 0; ii < tree.size(); ++ii)
{
if (tree[ii].distance >= 1)
{
tree[ii].distance = -1; // manually set to disconnect, as SingleLinkage does not support it
}
if (tree[ii].distance != -1)
{
++node_count;
}
}
ca.cut(data_size - node_count, tree, clusters);
// convert to blocks
MergeBlocks spectra_to_merge;
for (Size i_outer = 0; i_outer < clusters.size(); ++i_outer)
{
if (clusters[i_outer].size() <= 1)
{
continue;
}
// init block with first cluster element
Size cl_index0 = clusters[i_outer][0];
spectra_to_merge[index_mapping[cl_index0]] = std::vector<Size>();
// add all other elements
for (Size i_inner = 1; i_inner < clusters[i_outer].size(); ++i_inner)
{
spectra_to_merge[index_mapping[cl_index0]].push_back(index_mapping[clusters[i_outer][i_inner]]);
}
}
// do it
mergeSpectra_(exp, spectra_to_merge, 2);
exp.sortSpectra();
}
/**
* @brief check if the first and second mzs might be from the same mass
*
* @param[in] mz1 the first m/z value
* @param[in] mz2 the second m/z value
* @param[in] tol_ppm tolerance in ppm
* @param[in] max_c maximum possible charge value
*/
static bool areMassesMatched(double mz1, double mz2, double tol_ppm, int max_c)
{
if (mz1 == mz2 || tol_ppm <= 0)
{
return true;
}
const int min_c = 1;
const int max_iso_diff = 5; // maximum charge difference 5 is more than enough
const double max_charge_diff_ratio = 3.0; // maximum ratio between charges (large / small charge)
for (int c1 = min_c; c1 <= max_c; ++c1)
{
double mass1 = (mz1 - Constants::PROTON_MASS_U) * c1;
for (int c2 = min_c; c2 <= max_c; ++c2)
{
if (c1 / c2 > max_charge_diff_ratio)
{
continue;
}
if (c2 / c1 > max_charge_diff_ratio)
{
break;
}
double mass2 = (mz2 - Constants::PROTON_MASS_U) * c2;
if (fabs(mass1 - mass2) > max_iso_diff)
{
continue;
}
for (int i = -max_iso_diff; i <= max_iso_diff; ++i)
{
if (fabs(mass1 - mass2 + i * Constants::ISOTOPE_MASSDIFF_55K_U) < mass1 * tol_ppm * 1e-6)
{
return true;
}
}
}
}
return false;
}
/**
* @brief average over neighbouring spectra
*
* @param[in,out] exp experimental data to be averaged
* @param[in] average_type averaging type to be used ("gaussian" or "tophat")
* @param[in] ms_level target MS level. If it is -1, ms_level will be determined by the '<average_type>ms_level' parameter of the DefaultParamHandler
*/
template <typename MapType>
void average(MapType& exp, const String& average_type, int ms_level = -1)
{
// MS level to be averaged
if (ms_level < 0)
{
ms_level = param_.getValue("average_gaussian:ms_level");
if (average_type == "tophat")
{
ms_level = param_.getValue("average_tophat:ms_level");
}
}
// spectrum type (profile, centroid or automatic)
std::string spectrum_type = param_.getValue("average_gaussian:spectrum_type");
if (average_type == "tophat")
{
spectrum_type = std::string(param_.getValue("average_tophat:spectrum_type"));
}
// parameters for Gaussian averaging
double fwhm(param_.getValue("average_gaussian:rt_FWHM"));
double factor = -4 * log(2.0) / (fwhm * fwhm); // numerical factor within Gaussian
double cutoff(param_.getValue("average_gaussian:cutoff"));
double precursor_mass_ppm = param_.getValue("average_gaussian:precursor_mass_tol");
int precursor_max_charge = param_.getValue("average_gaussian:precursor_max_charge");
// parameters for Top-Hat averaging
bool unit(param_.getValue("average_tophat:rt_unit") == "scans"); // true if RT unit is 'scans', false if RT unit is 'seconds'
double range(param_.getValue("average_tophat:rt_range")); // range of spectra to be averaged over
double range_seconds = range / 2; // max. +/- <range_seconds> seconds from master spectrum
int range_scans = static_cast<int>(range); // in case of unit scans, the param is used as integer
if ((range_scans % 2) == 0)
{
++range_scans;
}
range_scans = (range_scans - 1) / 2; // max. +/- <range_scans> scans from master spectrum
AverageBlocks spectra_to_average_over;
// loop over RT
int n(0); // spectrum index
int cntr(0); // spectrum counter
for (typename MapType::const_iterator it_rt = exp.begin(); it_rt != exp.end(); ++it_rt)
{
if (Int(it_rt->getMSLevel()) == ms_level)
{
int m; // spectrum index
int steps;
bool terminate_now;
typename MapType::const_iterator it_rt_2;
// go forward (start at next downstream spectrum; the current spectrum will be covered when looking backwards)
steps = 0;
m = n + 1;
it_rt_2 = it_rt + 1;
terminate_now = false;
while (it_rt_2 != exp.end() && !terminate_now)
{
if (Int(it_rt_2->getMSLevel()) == ms_level)
{
bool add = true;
// if precursor_mass_ppm >=0, two spectra should have the same mass. otherwise it_rt_2 is skipped.
if (precursor_mass_ppm >= 0 && ms_level >= 2 && it_rt->getPrecursors().size() > 0 &&
it_rt_2->getPrecursors().size() > 0)
{
double mz1 = it_rt->getPrecursors()[0].getMZ();
double mz2 = it_rt_2->getPrecursors()[0].getMZ();
add = areMassesMatched(mz1, mz2, precursor_mass_ppm, precursor_max_charge);
}
if (add)
{
double weight = 1;
if (average_type == "gaussian")
{
//factor * (rt_2 -rt)^2
double base = it_rt_2->getRT() - it_rt->getRT();
weight = std::exp(factor * base * base);
}
std::pair<Size, double> p(m, weight);
spectra_to_average_over[n].push_back(p);
}
++steps;
}
if (average_type == "gaussian")
{
// Gaussian
double base = it_rt_2->getRT() - it_rt->getRT();
terminate_now = std::exp(factor * base * base) < cutoff;
}
else if (unit)
{
// Top-Hat with RT unit = scans
terminate_now = (steps > range_scans);
}
else
{
// Top-Hat with RT unit = seconds
terminate_now = (std::abs(it_rt_2->getRT() - it_rt->getRT()) > range_seconds);
}
++m;
++it_rt_2;
}
// go backward
steps = 0;
m = n;
it_rt_2 = it_rt;
terminate_now = false;
while (it_rt_2 != exp.begin() && !terminate_now)
{
if (Int(it_rt_2->getMSLevel()) == ms_level)
{
bool add = true;
// if precursor_mass_ppm >=0, two spectra should have the same mass. otherwise it_rt_2 is skipped.
if (precursor_mass_ppm >= 0 && ms_level >= 2 && it_rt->getPrecursors().size() > 0 &&
it_rt_2->getPrecursors().size() > 0)
{
double mz1 = it_rt->getPrecursors()[0].getMZ();
double mz2 = it_rt_2->getPrecursors()[0].getMZ();
add = areMassesMatched(mz1, mz2, precursor_mass_ppm, precursor_max_charge);
}
if (add)
{
double weight = 1;
if (average_type == "gaussian")
{
double base = it_rt_2->getRT() - it_rt->getRT();
weight = std::exp(factor * base * base);
}
std::pair<Size, double> p(m, weight);
spectra_to_average_over[n].push_back(p);
}
++steps;
}
if (average_type == "gaussian")
{
// Gaussian
double base = it_rt_2->getRT() - it_rt->getRT();
terminate_now = std::exp(factor * base * base) < cutoff;
}
else if (unit)
{
// Top-Hat with RT unit = scans
terminate_now = (steps > range_scans);
}
else
{
// Top-Hat with RT unit = seconds
terminate_now = (std::abs(it_rt_2->getRT() - it_rt->getRT()) > range_seconds);
}
--m;
--it_rt_2;
}
++cntr;
}
++n;
}
if (cntr == 0)
{
//return;
throw Exception::InvalidParameter(__FILE__,
__LINE__,
OPENMS_PRETTY_FUNCTION,
"Input mzML does not have any spectra of MS level specified by ms_level.");
}
// normalize weights (such that their sum == 1)
for (AverageBlocks::iterator it = spectra_to_average_over.begin(); it != spectra_to_average_over.end(); ++it)
{
double sum(0.0);
for (const auto& weight: it->second)
{
sum += weight.second;
}
for (auto& weight: it->second)
{
weight.second /= sum;
}
}
// determine type of spectral data (profile or centroided)
SpectrumSettings::SpectrumType type;
if (spectrum_type == "automatic")
{
Size idx = spectra_to_average_over.begin()->first; // index of first spectrum to be averaged
type = exp[idx].getType(true);
}
else if (spectrum_type == "profile")
{
type = SpectrumSettings::SpectrumType::PROFILE;
}
else if (spectrum_type == "centroid")
{
type = SpectrumSettings::SpectrumType::CENTROID;
}
else
{
throw Exception::InvalidParameter(__FILE__,__LINE__,OPENMS_PRETTY_FUNCTION, "Spectrum type has to be one of automatic, profile or centroid.");
}
// generate new spectra
if (type == SpectrumSettings::SpectrumType::CENTROID)
{
averageCentroidSpectra_(exp, spectra_to_average_over, ms_level);
}
else
{
averageProfileSpectra_(exp, spectra_to_average_over, ms_level);
}
exp.sortSpectra();
}
// @}
protected:
/**
@brief merges blocks of spectra of a certain level
Merges spectra belonging to the same block, setting their MS level to @p ms_level.
All old spectra of level @p ms_level are removed, and the new consensus spectra (one per block)
are added.
All spectra with other MS levels remain untouched.
The resulting map is NOT sorted!
*/
template <typename MapType>
void mergeSpectra_(MapType& exp, const MergeBlocks& spectra_to_merge, const UInt ms_level)
{
double mz_binning_width(param_.getValue("mz_binning_width"));
std::string mz_binning_unit(param_.getValue("mz_binning_width_unit"));
// merge spectra
MapType merged_spectra;
std::map<Size, Size> cluster_sizes;
std::set<Size> merged_indices;
// set up alignment
SpectrumAlignment sas;
Param p;
p.setValue("tolerance", mz_binning_width);
if (!(mz_binning_unit == "Da" || mz_binning_unit == "ppm"))
{
throw Exception::IllegalSelfOperation(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION); // sanity check
}
p.setValue("is_relative_tolerance", mz_binning_unit == "Da" ? "false" : "true");
sas.setParameters(p);
std::vector<std::pair<Size, Size> > alignment;
Size count_peaks_aligned(0);
Size count_peaks_overall(0);
// each BLOCK
for (auto it = spectra_to_merge.begin(); it != spectra_to_merge.end(); ++it)
{
++cluster_sizes[it->second.size() + 1]; // for stats
typename MapType::SpectrumType consensus_spec = exp[it->first];
consensus_spec.setMSLevel(ms_level);
merged_indices.insert(it->first);
double rt_average = consensus_spec.getRT();
double precursor_mz_average = 0.0;
Size precursor_count(0);
if (!consensus_spec.getPrecursors().empty())
{
precursor_mz_average = consensus_spec.getPrecursors()[0].getMZ();
++precursor_count;
}
count_peaks_overall += consensus_spec.size();
String consensus_native_id = consensus_spec.getNativeID();
// block elements
for (auto sit = it->second.begin(); sit != it->second.end(); ++sit)
{
consensus_spec.unify(exp[*sit]); // append meta info
merged_indices.insert(*sit);
rt_average += exp[*sit].getRT();
if (ms_level >= 2 && exp[*sit].getPrecursors().size() > 0)
{
precursor_mz_average += exp[*sit].getPrecursors()[0].getMZ();
++precursor_count;
}
// add native ID to consensus native ID, comma separated
consensus_native_id += ",";
consensus_native_id += exp[*sit].getNativeID();
// merge data points
sas.getSpectrumAlignment(alignment, consensus_spec, exp[*sit]);
count_peaks_aligned += alignment.size();
count_peaks_overall += exp[*sit].size();
Size align_index(0);
Size spec_b_index(0);
// sanity check for number of peaks
Size spec_a = consensus_spec.size(), spec_b = exp[*sit].size(), align_size = alignment.size();
for (auto pit = exp[*sit].begin(); pit != exp[*sit].end(); ++pit)
{
if (alignment.empty() || alignment[align_index].second != spec_b_index)
// ... add unaligned peak
{
consensus_spec.push_back(*pit);
}
// or add aligned peak height to ALL corresponding existing peaks
else
{
Size counter(0);
Size copy_of_align_index(align_index);
while (!alignment.empty() &&
copy_of_align_index < alignment.size() &&
alignment[copy_of_align_index].second == spec_b_index)
{
++copy_of_align_index;
++counter;
} // Count the number of peaks which correspond to a single b peak.
while (!alignment.empty() &&
align_index < alignment.size() &&
alignment[align_index].second == spec_b_index)
{
consensus_spec[alignment[align_index].first].setIntensity(consensus_spec[alignment[align_index].first].getIntensity() +
(pit->getIntensity() / (double)counter)); // add the intensity divided by the number of peaks
++align_index; // this aligned peak was explained, wait for next aligned peak ...
if (align_index == alignment.size())
{
alignment.clear(); // end reached -> avoid going into this block again
}
}
align_size = align_size + 1 - counter; //Decrease align_size by number of
}
++spec_b_index;
}
consensus_spec.sortByPosition(); // sort, otherwise next alignment will fail
if (spec_a + spec_b - align_size != consensus_spec.size())
{
OPENMS_LOG_WARN << "wrong number of features after merge. Expected: " << spec_a + spec_b - align_size << " got: " << consensus_spec.size() << "\n";
}
}
rt_average /= it->second.size() + 1;
consensus_spec.setRT(rt_average);
// set new consensus native ID
consensus_spec.setNativeID(consensus_native_id);
if (ms_level >= 2)
{
if (precursor_count)
{
precursor_mz_average /= precursor_count;
}
auto& pcs = consensus_spec.getPrecursors();
pcs.resize(1);
pcs[0].setMZ(precursor_mz_average);
consensus_spec.setPrecursors(pcs);
}
if (consensus_spec.empty())
{
continue;
}
else
{
merged_spectra.addSpectrum(std::move(consensus_spec));
}
}
OPENMS_LOG_INFO << "Cluster sizes:\n";
for (const auto& cl_size : cluster_sizes)
{
OPENMS_LOG_INFO << " size " << cl_size.first << ": " << cl_size.second << "x\n";
}
char buffer[200];
sprintf(buffer, "%d/%d (%.2f %%) of blocked spectra", (int)count_peaks_aligned,
(int)count_peaks_overall, float(count_peaks_aligned) / float(count_peaks_overall) * 100.);
OPENMS_LOG_INFO << "Number of merged peaks: " << String(buffer) << "\n";
// remove all spectra that were within a cluster
typename MapType::SpectrumType empty_spec;
MapType exp_tmp;
for (Size i = 0; i < exp.size(); ++i)
{
if (merged_indices.count(i) == 0) // save unclustered ones
{
exp_tmp.addSpectrum(exp[i]);
exp[i] = empty_spec;
}
}
//Meta_Data will not be cleared
exp.clear(false);
exp.getSpectra().insert(exp.end(), std::make_move_iterator(exp_tmp.begin()),
std::make_move_iterator(exp_tmp.end()));
// ... and add consensus spectra
exp.getSpectra().insert(exp.end(), std::make_move_iterator(merged_spectra.begin()),
std::make_move_iterator(merged_spectra.end()));
}
/**
* @brief average spectra (profile mode)
*
* Averages spectra in profile mode of one MS level in an experiment. The
* blocks of spectra to be combined and their relative weights have
* previously been determined. The averaged spectra are generated in two
* steps:
* (1) The m/z of all spectra in a block are collected and sorted. m/z
* positions closer than mz_binning_width are removed.
* (2) At these positions the weighted sum of all spline interpolations is
* calculated.
*
* The first step ensures roughly the same sampling rate as the one of the
* original spectra. The exact m/z position is not crucial, since not the
* original intensities but the spline-interpolated intensities are used.
*
* @param[in,out] exp experimental data to be averaged
* @param[in] spectra_to_average_over mapping of spectral index to set of spectra to average over with corresponding weights
* @param[in] ms_level MS level of spectra to be averaged
*/
template <typename MapType>
void averageProfileSpectra_(MapType& exp, const AverageBlocks& spectra_to_average_over, const UInt ms_level)
{
MapType exp_tmp; // temporary experiment for averaged spectra
double mz_binning_width(param_.getValue("mz_binning_width"));
std::string mz_binning_unit(param_.getValue("mz_binning_width_unit"));
unsigned progress = 0;
std::stringstream progress_message;
progress_message << "averaging profile spectra of MS level " << ms_level;
startProgress(0, spectra_to_average_over.size(), progress_message.str());
// loop over blocks
for (AverageBlocks::const_iterator it = spectra_to_average_over.begin(); it != spectra_to_average_over.end(); ++it)
{
setProgress(++progress);
// loop over spectra in blocks
std::vector<double> mz_positions_all; // m/z positions from all spectra
for (const auto& spec : it->second)
{
// loop over m/z positions
for (typename MapType::SpectrumType::ConstIterator it_mz = exp[spec.first].begin(); it_mz < exp[spec.first].end(); ++it_mz)
{
mz_positions_all.push_back(it_mz->getMZ());
}
}
sort(mz_positions_all.begin(), mz_positions_all.end());
std::vector<double> mz_positions; // positions at which the averaged spectrum should be evaluated
std::vector<double> intensities;
double last_mz = std::numeric_limits<double>::min(); // last m/z position pushed through from mz_position to mz_position_2
double delta_mz(mz_binning_width); // for m/z unit Da
for (const auto mz_pos : mz_positions_all)
{
if (mz_binning_unit == "ppm")
{
delta_mz = mz_binning_width * mz_pos / 1000000;
}
if ((mz_pos - last_mz) > delta_mz)
{
mz_positions.push_back(mz_pos);
intensities.push_back(0.0);
last_mz = mz_pos;
}
}
// loop over spectra in blocks
for (const auto& spec : it->second)
{
SplineInterpolatedPeaks spline(exp[spec.first]);
SplineInterpolatedPeaks::Navigator nav = spline.getNavigator();
// loop over m/z positions
for (Size i = spline.getPosMin(); i < mz_positions.size(); ++i)
{
if ((spline.getPosMin() < mz_positions[i]) && (mz_positions[i] < spline.getPosMax()))
{
intensities[i] += nav.eval(mz_positions[i]) * (spec.second); // spline-interpolated intensity * weight
}
}
}
// update spectrum
typename MapType::SpectrumType average_spec = exp[it->first];
average_spec.clear(false); // Precursors are part of the meta data, which are not deleted.
// refill spectrum
for (Size i = 0; i < mz_positions.size(); ++i)
{
typename MapType::PeakType peak;
peak.setMZ(mz_positions[i]);
peak.setIntensity(intensities[i]);
average_spec.push_back(peak);
}
// store spectrum temporarily
exp_tmp.addSpectrum(std::move(average_spec));
}
endProgress();
// loop over blocks
int n(0);
for (AverageBlocks::const_iterator it = spectra_to_average_over.begin(); it != spectra_to_average_over.end(); ++it)
{
exp[it->first] = exp_tmp[n];
++n;
}
}
/**
* @brief average spectra (centroid mode)
*
* Averages spectra in centroid mode of one MS level in an experiment. The
* blocks of spectra to be combined and their relative weights have
* previously determined. The averaged spectra are generated in two steps:
* (1) The m/z of all spectra in a block are collected and sorted. Their
* corresponding intensities are weighted.
* (2) m/z positions closer than mz_binning_width are combined to a single
* peak. The m/z are averaged and the corresponding intensities summed.
*
* @param[in,out] exp experimental data to be averaged
* @param[in] spectra_to_average_over mapping of spectral index to set of spectra to average over with corresponding weights
* @param[in] ms_level MS level of spectra to be averaged
*/
template <typename MapType>
void averageCentroidSpectra_(MapType& exp, const AverageBlocks& spectra_to_average_over, const UInt ms_level)
{
MapType exp_tmp; // temporary experiment for averaged spectra
double mz_binning_width(param_.getValue("mz_binning_width"));
std::string mz_binning_unit(param_.getValue("mz_binning_width_unit"));
unsigned progress = 0;
ProgressLogger logger;
std::stringstream progress_message;
progress_message << "averaging centroid spectra of MS level " << ms_level;
logger.startProgress(0, spectra_to_average_over.size(), progress_message.str());
// loop over blocks
for (AverageBlocks::const_iterator it = spectra_to_average_over.begin(); it != spectra_to_average_over.end(); ++it)
{
logger.setProgress(++progress);
// collect peaks from all spectra
// loop over spectra in blocks
std::vector<std::pair<double, double> > mz_intensity_all; // m/z positions and peak intensities from all spectra
for (const auto& weightedMZ: it->second)
{
// loop over m/z positions
for (typename MapType::SpectrumType::ConstIterator it_mz = exp[weightedMZ.first].begin(); it_mz < exp[weightedMZ.first].end(); ++it_mz)
{
std::pair<double, double> mz_intensity(it_mz->getMZ(), (it_mz->getIntensity() * weightedMZ.second)); // m/z, intensity * weight
mz_intensity_all.push_back(mz_intensity);
}
}
sort(mz_intensity_all.begin(), mz_intensity_all.end());
// generate new spectrum
std::vector<double> mz_new;
std::vector<double> intensity_new;
double last_mz = std::numeric_limits<double>::min();
double delta_mz = mz_binning_width;
double sum_mz(0);
double sum_intensity(0);
Size count(0);
for (const auto& mz_pos : mz_intensity_all)
{
if (mz_binning_unit == "ppm")
{
delta_mz = mz_binning_width * (mz_pos.first) / 1000000;
}
if (((mz_pos.first - last_mz) > delta_mz) && (count > 0))
{
mz_new.push_back(sum_mz / count);
intensity_new.push_back(sum_intensity); // intensities already weighted
sum_mz = 0;
sum_intensity = 0;
last_mz = mz_pos.first;
count = 0;
}
sum_mz += mz_pos.first;
sum_intensity += mz_pos.second;
++count;
}
if (count > 0)
{
mz_new.push_back(sum_mz / count);
intensity_new.push_back(sum_intensity); // intensities already weighted
}
// update spectrum
typename MapType::SpectrumType average_spec = exp[it->first];
average_spec.clear(false); // Precursors are part of the meta data, which are not deleted.
// refill spectrum
for (Size i = 0; i < mz_new.size(); ++i)
{
typename MapType::PeakType peak;
peak.setMZ(mz_new[i]);
peak.setIntensity(intensity_new[i]);
average_spec.push_back(peak);
}
// store spectrum temporarily
exp_tmp.addSpectrum(std::move(average_spec));
}
logger.endProgress();
// loop over blocks
int n(0);
for (const auto& spectral_index : spectra_to_average_over)
{
exp[spectral_index.first] = std::move(exp_tmp[n]);
++n;
}
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/PROCESSING/SCALING/RankScaler.h | .h | 1,957 | 81 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Mathias Walzer $
// $Authors: $
// --------------------------------------------------------------------------
//
#pragma once
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/KERNEL/MSSpectrum.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <map>
namespace OpenMS
{
/**
@brief Scales each peak by ranking the peaks per spectrum and assigning intensity according to rank
@ingroup SpectraPreprocessers
*/
class OPENMS_DLLAPI RankScaler :
public DefaultParamHandler
{
public:
// @name Constructors and Destructors
// @{
/// default constructor
RankScaler();
/// destructor
~RankScaler() override;
/// copy constructor
RankScaler(const RankScaler & source);
/// assignment operator
RankScaler & operator=(const RankScaler & source);
// @}
// @name Accessors
// @{
template <typename SpectrumType>
void filterSpectrum(SpectrumType & spectrum)
{
if (spectrum.empty()) return;
spectrum.sortByIntensity();
typename SpectrumType::size_type count = spectrum.size();
++count;
typename SpectrumType::PeakType::IntensityType last_int = 0.0;
typename SpectrumType::Iterator it = spectrum.end();
do
{
--it;
if (it->getIntensity() != last_int)
{
--count;
}
last_int = it->getIntensity();
it->setIntensity(count);
}
while (it != spectrum.begin());
}
void filterPeakSpectrum(PeakSpectrum & spectrum);
void filterPeakMap(PeakMap & exp);
//TODO reimplement DefaultParamHandler::updateMembers_() when introducing member variables
// @}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/PROCESSING/SCALING/Normalizer.h | .h | 3,004 | 115 | // 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 $
// --------------------------------------------------------------------------
//
#pragma once
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/KERNEL/MSSpectrum.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <vector>
namespace OpenMS
{
/**
@brief Normalizes the peak intensities spectrum-wise.
Either to a total intensity-sum of one (i.e. to total-ion-count; TIC) or to a maximum intensity of one.
@htmlinclude OpenMS_Normalizer.parameters
@ingroup SpectraPreprocessers
*/
class OPENMS_DLLAPI Normalizer :
public DefaultParamHandler
{
public:
// @name Constructors and Destructors
// @{
/// default constructor
Normalizer();
/// destructor
~Normalizer() override;
/// assignment operator
Normalizer & operator=(const Normalizer & source);
/// copy constructor
Normalizer(const Normalizer & source);
// @}
// @name Accessors
// @{
/**
@brief Workhorse of this class.
@param[in,out] spectrum Input/output spectrum containing peaks
@throws Exception::InvalidValue if 'method_' has unknown value
*/
template <typename SpectrumType>
void filterSpectrum(SpectrumType& spectrum) const
{
if (spectrum.empty()) return;
typedef typename SpectrumType::Iterator Iterator;
typedef typename SpectrumType::ConstIterator ConstIterator;
double divisor(0);
// find divisor
if (method_ == "to_one")
{ // normalizes the max peak to 1 and the remaining peaks to values relative to max
divisor = spectrum.begin()->getIntensity(); // safety measure: if all intensities are negative, divisor would stay 0 (as constructed)
for (ConstIterator it = spectrum.begin(); it != spectrum.end(); ++it)
{
if (divisor < it->getIntensity()) divisor = it->getIntensity();
}
}
else if (method_ == "to_TIC")
{ // normalizes the peak intensities to the TIC
for (ConstIterator it = spectrum.begin(); it != spectrum.end(); ++it)
{
divisor += it->getIntensity();
}
}
// method unknown
else
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Method not known", method_);
}
// normalize
for (Iterator it = spectrum.begin(); it != spectrum.end(); ++it)
{
it->setIntensity(it->getIntensity() / divisor);
}
return;
}
///
void filterPeakSpectrum(PeakSpectrum & spectrum) const;
///
void filterPeakMap(PeakMap & exp) const;
void updateMembers_() override;
// @}
private:
String method_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/PROCESSING/SCALING/SqrtScaler.h | .h | 1,789 | 77 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Mathias Walzer $
// $Authors: $
// --------------------------------------------------------------------------
//
#pragma once
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/KERNEL/MSSpectrum.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <cmath>
namespace OpenMS
{
/**
@brief Scales the intensity of peaks to the sqrt
@ingroup SpectraPreprocessers
*/
class OPENMS_DLLAPI SqrtScaler :
public DefaultParamHandler
{
public:
// @name Constructors and Destructors
// @{
/// default constructor
SqrtScaler();
/// destructor
~SqrtScaler() override;
/// copy constructor
SqrtScaler(const SqrtScaler & source);
/// assignment operator
SqrtScaler & operator=(const SqrtScaler & source);
// @}
///
template <typename SpectrumType>
void filterSpectrum(SpectrumType & spectrum)
{
bool warning = false;
for (typename SpectrumType::Iterator it = spectrum.begin(); it != spectrum.end(); ++it)
{
double intens = it->getIntensity();
if (intens < 0)
{
intens = 0;
warning = true;
}
it->setIntensity(std::sqrt(intens));
}
if (warning)
{
std::cerr << "Warning negative intensities were set to zero" << std::endl;
}
return;
}
void filterPeakSpectrum(PeakSpectrum & spectrum);
void filterPeakMap(PeakMap & exp);
//TODO reimplement DefaultParamHandler::updateMembers_()
// @}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/PROCESSING/DEISOTOPING/Deisotoper.h | .h | 8,604 | 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/Constants.h>
#include <OpenMS/CONCEPT/Types.h>
#include <OpenMS/KERNEL/StandardTypes.h>
namespace OpenMS
{
class MSSpectrum;
class OPENMS_DLLAPI Deisotoper
{
public:
/** @brief Detect isotopic clusters in a mass spectrum.
This algorithm is in parts taken from Guo Ci Teo et al, DOI: 10.1021/acs.jproteome.0c00544
and is closely related to deisotopeAndSingleCharge by Timo Sachsenberg.
Deisotoping is based on C13 abundance and will try to identify isotopic
clusters fitting to an averagine model, taking in account the corresponding
charge state. This only makes sense for peptide fragment ion spectra.
The algorithm considers each peak in the spectrum and will try to form
isotopic clusters for every charge state from @p min_charge to @p max_charge.
Of the clusters that pass an averaginge check based on KL-divergence (for all
subclusters starting at the base peak as well), the cluster with most peaks (and
in case of equality, also highest charge) is kept.
Deisotoping is done in-place, and the algorithm removes peaks with
intensity 0. If @p rem_low_intensity is true,
peaks not belonging to the highest 1000/5000 peaks are removed (see
@p used_for_open_search). If @p annotate_charge is true,
an additional IntegerDataArray "charge" will be appended. If
@p annotate_iso_peak_count is true, an additional IntegerDataArray
"iso_peak_count" containing the number of isotopic peaks will be
appended. Existing DataArrays are kept and shrunken to the peaks which
remain in the spectrum.
* @param [spectrum] Input spectrum (sorted by m/z)
* @param [fragment_tolerance] The tolerance used to match isotopic peaks
* @param [fragment_unit_ppm] Whether ppm or m/z is used as tolerance
* @param [number_of_final_peaks] Only the largest @p number_of_final_peaks peaks are kept in any spectrum. If 0, no filtering is performed. For open search, 1000 is recommended, else 5000.
* @param [min_charge] The minimum charge considered
* @param [max_charge] The maximum charge considered
* @param [keep_only_deisotoped] Only monoisotopic peaks of fragments with isotopic pattern are retained
* @param [min_isopeaks] The minimum number of isotopic peaks (at least 2) required for an isotopic cluster
* @param [max_isopeaks] The maximum number of isotopic peaks (at least 2) considered for an isotopic cluster
* @param [make_single_charged] Convert deisotoped monoisotopic peak to single charge, the original charge (>=1) gets annotated
* @param [annotate_charge] Annotate the charge to the peaks in the IntegerDataArray: "charge" (0 for unknown charge)
* @param [annotate_iso_peak_count] Annotate the number of isotopic peaks in a pattern for each monoisotopic peak in the IntegerDataArray: "iso_peak_count"
* @param [add_up_intensity] Sum up the total intensity of each isotopic pattern into the intensity of the reported monoisotopic peak
*/
static void deisotopeWithAveragineModel(MSSpectrum& spectrum,
double fragment_tolerance,
bool fragment_unit_ppm,
int number_of_final_peaks = 5000,
int min_charge = 1,
int max_charge = 3,
bool keep_only_deisotoped = false,
unsigned int min_isopeaks = 2,
unsigned int max_isopeaks = 10,
bool make_single_charged = true,
bool annotate_charge = false,
bool annotate_iso_peak_count = false,
bool add_up_intensity = false);
/** @brief Detect isotopic clusters in a mass spectrum.
Deisotoping is based on C13 abundance and will try to identify a simple
model based on the C12-C13 distance and charge state. This is often a good
approximation for peptide fragment ion spectra but may not work well for
other spectra. The algorithm will consider each peak (starting from the
right of a spectrum) and, for each peak, attempt to add isotopic peaks to
its envelope until either no peak is found, the maximum number of isotopic
peaks is reached or (only when using @p use_decreasing_model) the intensity
of the peak is higher than the previous peak.
Deisotoping is done in-place and if @p annotate_charge is true,
an additional IntegerDataArray "charge" will be appended. If
@p annotate_iso_peak_count is true, an additional IntegerDataArray
"iso_peak_count" containing the number of isotopic peaks will be
appended. If @p annotate_features is true, an addtional IntegerData Array
"feature_number" containing the feature index will be appended.
Existing DataArrays are kept and shrunken to the peaks which
remain in the spectrum.
* @param [spectrum] Input spectrum (sorted by m/z)
* @param [fragment_tolerance] The tolerance used to match isotopic peaks
* @param [fragment_unit_ppm] Whether ppm or m/z is used as tolerance
* @param [min_charge] The minimum charge considered
* @param [max_charge] The maximum charge considered
* @param [keep_only_deisotoped] Only monoisotopic peaks of fragments with isotopic pattern are retained
* @param [min_isopeaks] The minimum number of isotopic peaks (at least 2) required for an isotopic cluster
* @param [max_isopeaks] The maximum number of isotopic peaks (at least 2) considered for an isotopic cluster
* @param [make_single_charged] Convert deisotoped monoisotopic peak to single charge
* @param [annotate_charge] Annotate the charge to the peaks in the IntegerDataArray: "charge" (0 for unknown charge)
* @param [annotate_iso_peak_count] Annotate the number of isotopic peaks in a pattern for each monoisotopic peak in the IntegerDataArray: "iso_peak_count"
* @param [use_decreasing_model] Use a simple averagine model that expects heavier isotopes to have less intensity. If false, no intensity checks are applied.
* @param [start_intensity_check] Number of the isotopic peak from which the decreasing model should be applied. <= 1 will force the monoisotopic peak to be the most intense.
2 will allow the monoisotopic peak to be less intense than the second peak.
3 will allow the monoisotopic and the second peak to be less intense than the third, etc.
A number higher than max_isopeaks will effectively disable use_decreasing_model completely.
* @param [add_up_intensity] Sum up the total intensity of each isotopic pattern into the intensity of the reported monoisotopic peak
* @param [annotate_features] Annotates the feature index in the IntegerDataArray: "feature_number".
*
* Note: If @p make_single_charged is selected, the original charge (>=1) gets annotated.
*/
static void deisotopeAndSingleCharge(MSSpectrum& spectrum,
double fragment_tolerance,
bool fragment_unit_ppm,
int min_charge = 1,
int max_charge = 3,
bool keep_only_deisotoped = false,
unsigned int min_isopeaks = 3,
unsigned int max_isopeaks = 10,
bool make_single_charged = true,
bool annotate_charge = false,
bool annotate_iso_peak_count = false,
bool use_decreasing_model = true,
unsigned int start_intensity_check = 2,
bool add_up_intensity = false,
bool annotate_features = false);
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/PROCESSING/CENTROIDING/PeakPickerIM.h | .h | 6,583 | 147 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Author: Timo Sachsenberg, Mohammed Alhigaylan $
// $Maintainer: Timo Sachsenberg $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/MSSpectrum.h>
#include <OpenMS/DATASTRUCTURES/Param.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
namespace OpenMS
{
/**
@brief Peak picking algorithm for ion mobility data
This class provides three specialized methods for peak picking in ion mobility (IM) data:
1. **pickIMTraces**: Mobilogram-based peak picking that extracts ion mobility traces
from raw IM data and performs centroiding on the extracted mobilograms. This method
processes IM data by analyzing intensity profiles along the ion mobility dimension.
2. **pickIMCluster**: Clustering-based peak picking that groups peaks close in both
m/z and ion mobility space. Peaks within specified m/z (ppm) and IM tolerances are
averaged together using intensity-weighted averaging, reducing an IM frame to a
single spectrum with representative peak positions.
3. **pickIMElutionProfiles**: Elution profile-based peak picking that extracts peaks
based on their elution characteristics across the ion mobility dimension. This method
uses m/z tolerance (ppm) to identify and pick peaks from IM elution profiles.
@ingroup PeakPicking
*/
class OPENMS_DLLAPI PeakPickerIM : public DefaultParamHandler
{
public:
/// Default constructor initializing parameters with default values.
PeakPickerIM();
/// Destructor.
~PeakPickerIM() override = default;
/**
* @brief Centroids ion mobility data by iteratively extracting mobilograms for each m/z peak centroid
*
* This function processes an MS spectrum containing ion mobility data (geared towards TimsTOF data)
* Peaks in a given MS spectrum are projected to the m/z axis and centroided.
* Then, the mobilogram of each m/z peak centroid is retrieved using the m/z peak FWHM.
* Peak picking algorithm is applied to the mobilogram to resolve isobaric species with different ion mobility measurement.
*
* @param[in,out] spectrum Spectrum containing ion mobility data in its FloatDataArrays
*/
void pickIMTraces(MSSpectrum& spectrum);
/// Sets the parameters for peak picking.
using DefaultParamHandler::setParameters;
using DefaultParamHandler::getParameters;
/**
* @brief Converts an ion mobility frame to a single spectrum with averaged IM values
*
* This function takes an MS spectrum containing ion mobility data and reduces it to
* a single spectrum where peaks that are close in both m/z and ion mobility space
* are averaged together. The averaging is intensity-weighted for both m/z and ion
* mobility values.
*
* The algorithm processes peaks sequentially and groups them based on two criteria:
* 1. m/z tolerance: peaks must be within the configured ppm tolerance of each other
* 2. ion mobility tolerance: the range of IM values must not exceed the configured tolerance
*
* Uses parameters pickIMCluster:ppm_tolerance_cluster and pickIMCluster:im_tolerance_cluster.
*
* @param[in,out] spec Spectrum containing ion mobility data in its FloatDataArrays
*
* @throws Exception::MissingInformation if input spectrum lacks ion mobility data
*
* @note The input spectrum should contain ion mobility data in its FloatDataArrays.
* The output spectrum will contain averaged peaks with their corresponding
* intensity-weighted average ion mobility values.
*
* Example:
* @code
* MSSpectrum spectrum; // spectrum with IM FloatDataArrays
* PeakPickerIM picker;
* picker.pickIMCluster(spectrum);
* @endcode
*/
void pickIMCluster(MSSpectrum& spec) const;
/**
* @brief Picks ion mobility elution profiles from the given spectrum using eluting profiles.
*
* This function processes an MS spectrum containing ion mobility data and
* extracts IM elution profiles based on the configured ppm tolerance.
*
* @param[in,out] input Spectrum containing ion mobility data in its FloatDataArrays
*/
void pickIMElutionProfiles(MSSpectrum& input) const;
protected:
void updateMembers_() override;
private:
/// determine sampling rate for linear resampler
double computeOptimalSamplingRate(const std::vector<MSSpectrum>& spectra);
/**
* @brief Sum up the intensity of data points with nearly identical float values.
*
* By default, this function assumes the tolerance provided is in parts per million.
* But it can be adjusted to use absolute value tolerance.
* @param[in] input_spectrum Sorted raw spectrum with duplicate peaks due to scan merging or presence of ion mobility data.
* @param[out] output_spectrum Output spectrum containing the summed peaks.
* @param[in] tolerance Mass tolerance between peaks
* @param[in] use_ppm Whether to use parts per million tolerance. If set to False, absolute tolerance will be used.
*/
void sumFrame_(const MSSpectrum& input_spectrum, MSSpectrum& output_spectrum, double tolerance = 0.01, bool use_ppm = true);
/// Compute lower and upper m/z bounds based on ppm
std::pair<double, double> ppmBounds(double mz, double ppm);
/// Extract ion mobility traces as MSSpectra from the raw TimsTOF frame
/// Ion mobility is temporarily written in place of m/z inside Peak1D object.
/// raw m/z values are allocated to float data arrays with the label 'raw_mz'
std::vector<MSSpectrum> extractIonMobilityTraces(
const MSSpectrum& picked_spectrum,
const MSSpectrum& raw_spectrum);
/// compute m/z and ion mobility centers for picked traces. Returns centroided spectrum.
MSSpectrum computeCentroids_(const std::vector<MSSpectrum>& mobilogram_traces,
const std::vector<MSSpectrum>& picked_traces);
double sum_tolerance_mz_{1.0};
double gauss_ppm_tolerance_{5.0};
double sum_tolerance_im_{0.0006};
int sgolay_frame_length_{5};
int sgolay_polynomial_order_{3};
double ppm_tolerance_cluster_{50.0};
double im_tolerance_cluster_{0.1};
double ppm_tolerance_elution_{50.0};
};
} // namespace OpenMS | Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/PROCESSING/CENTROIDING/PeakPickerHiRes.h | .h | 8,323 | 202 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Author: Erhan Kenar $
// $Maintainer: Timo Sachsenberg $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#define DEBUG_PEAK_PICKING
#undef DEBUG_PEAK_PICKING
//#undef DEBUG_DECONV
namespace OpenMS
{
class MSChromatogram;
class Mobilogram;
class OnDiscMSExperiment;
/**
@brief This class implements a fast peak-picking algorithm best suited for
high resolution MS data (FT-ICR-MS, Orbitrap). In high resolution data, the
signals of ions with similar mass-to-charge ratios (m/z) exhibit little or
no overlapping and therefore allow for a clear separation. Furthermore, ion
signals tend to show well-defined peak shapes with narrow peak width.
This peak-picking algorithm detects ion signals in profile data and
reconstructs the corresponding peak shape by cubic spline interpolation.
Signal detection depends on the signal-to-noise ratio which is adjustable
by the user (see parameter signal_to_noise). A picked peak's m/z and
intensity value is given by the maximum of the underlying peak spline.
So far, this peak picker was mainly tested on high resolution data. With
appropriate preprocessing steps (e.g. noise reduction and baseline
subtraction), it might be also applied to low resolution data.
This implementation performs peak picking in a single dimension (m/z);
two-dimensional data such as ion mobility separated data needs additional
pre-processing. The current implementation treats these data as
one-dimensional data, performs peak picking in the m/z dimension and
reports the intensity weighted ion mobility of the picked peaks (which will
produce correct results if the data has been binned previously but
incorrect results if fully 2D data is provided as input).
@htmlinclude OpenMS_PeakPickerHiRes.parameters
@note The peaks must be sorted according to ascending m/z!
@ingroup PeakPicking
*/
class OPENMS_DLLAPI PeakPickerHiRes :
public DefaultParamHandler,
public ProgressLogger
{
public:
/// Constructor
PeakPickerHiRes();
/// Destructor
~PeakPickerHiRes() override;
/// structure for peak boundaries
struct PeakBoundary
{
double mz_min;
double mz_max;
};
/**
@brief Applies the peak-picking algorithm to a single spectrum
(MSSpectrum). The resulting picked peaks are written to the output
spectrum.
@param[in] input input spectrum in profile mode
@param[out] output output spectrum with picked peaks
*/
void pick(const MSSpectrum& input, MSSpectrum& output) const;
/**
@brief Applies the peak-picking algorithm to a single chromatogram
(MSChromatogram). The resulting picked peaks are written to the output chromatogram.
@param[in] input input chromatogram in profile mode
@param[out] output output chromatogram with picked peaks
*/
void pick(const MSChromatogram& input, MSChromatogram& output) const;
/**
@brief Applies the peak-picking algorithm to a map (Mobilogram). The resulting picked peaks are written to the output mobilogram.
*/
void pick(const Mobilogram& input, Mobilogram& output) const;
/**
@brief Applies the peak-picking algorithm to a single spectrum
(MSSpectrum). The resulting picked peaks are written to the output
spectrum. Peak boundaries are written to a separate structure.
@param[in] input input spectrum in profile mode
@param[out] output output spectrum with picked peaks
@param[out] boundaries boundaries of the picked peaks
@param[in] check_spacings check spacing constraints? (yes for spectra, no for chromatograms)
*/
void pick(const MSSpectrum& input, MSSpectrum& output, std::vector<PeakBoundary>& boundaries, bool check_spacings = true) const;
/**
@brief Applies the peak-picking algorithm to a single chromatogram
(MSChromatogram). The resulting picked peaks are written to the output chromatogram.
@param[in] input input chromatogram in profile mode
@param[out] output output chromatogram with picked peaks
@param[out] boundaries boundaries of the picked peaks
@param[in] check_spacings check spacing constraints? (yes for spectra, no for chromatograms)
*/
void pick(const MSChromatogram& input, MSChromatogram& output, std::vector<PeakBoundary>& boundaries, bool check_spacings = false) const;
/**
@brief Applies the peak-picking algorithm to a single mobilogram
(Mobilogram). The resulting picked peaks are written to the output mobilogram.
@param[in] input input mobilogram in profile mode
@param[out] output output mobilogram with picked peaks
@param[out] boundaries boundaries of the picked peaks
@param[in] check_spacings check spacing constraints? (yes for spectra, no for chromatogram and mobilogram)
*/
void pick(const Mobilogram& input, Mobilogram& output, std::vector<PeakBoundary>& boundaries, bool check_spacings = false) const;
/**
@brief Applies the peak-picking algorithm to a map (MSExperiment). This
method picks peaks for each scan in the map consecutively. The resulting
picked peaks are written to the output map.
@param[in] input input map in profile mode
@param[out] output output map with picked peaks
@param[in] check_spectrum_type if set, checks spectrum type and throws an exception if a centroided spectrum is passed
*/
void pickExperiment(const PeakMap& input, PeakMap& output, const bool check_spectrum_type = true) const;
/**
@brief Applies the peak-picking algorithm to a map (MSExperiment). This
method picks peaks for each scan in the map consecutively. The resulting
picked peaks are written to the output map.
@param[in] input input map in profile mode
@param[out] output output map with picked peaks
@param[out] boundaries_spec boundaries of the picked peaks in spectra
@param[out] boundaries_chrom boundaries of the picked peaks in chromatograms
@param[in] check_spectrum_type if set, checks spectrum type and throws an exception if a centroided spectrum is passed
*/
void pickExperiment(const PeakMap& input,
PeakMap& output,
std::vector<std::vector<PeakBoundary> >& boundaries_spec,
std::vector<std::vector<PeakBoundary> >& boundaries_chrom,
const bool check_spectrum_type = true) const;
/**
@brief Applies the peak-picking algorithm to a map (MSExperiment). This
method picks peaks for each scan in the map consecutively. The resulting
picked peaks are written to the output map.
Currently we have to give up const-correctness but we know that everything on disc is constant
*/
void pickExperiment(/* const */ OnDiscMSExperiment& input, PeakMap& output, const bool check_spectrum_type = true) const;
protected:
template <typename ContainerType>
void pick_(const ContainerType& input, ContainerType& output, std::vector<PeakBoundary>& boundaries, bool check_spacings = true, int im_index = -1) const;
// signal-to-noise parameter
double signal_to_noise_;
// maximal spacing difference defining a large gap
double spacing_difference_gap_;
// maximal spacing difference defining a missing data point
double spacing_difference_;
// maximum number of missing points
unsigned missing_;
// MS levels to which peak picking is applied
std::vector<Int> ms_levels_;
/// add floatDataArray 'FWHM'/'FWHM_ppm' to spectra with peak FWHM
bool report_FWHM_;
/// unit of 'FWHM' float data array (can be absolute or ppm).
bool report_FWHM_as_ppm_;
// docu in base class
void updateMembers_() override;
}; // end PeakPickerHiRes
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/PROCESSING/CENTROIDING/PeakPickerIterative.h | .h | 16,399 | 405 | // 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/PROCESSING/CENTROIDING/PeakPickerHiRes.h>
#include <OpenMS/PROCESSING/NOISEESTIMATION/SignalToNoiseEstimatorMedian.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/KERNEL/SpectrumHelper.h>
// #define DEBUG_PEAK_PICKING
namespace OpenMS
{
/**
* @brief A small structure to hold peak candidates
*
*/
struct PeakCandidate
{
int index;
double peak_apex_intensity;
double integrated_intensity;
double leftWidth;
double rightWidth;
float mz;
};
bool sort_peaks_by_intensity(const PeakCandidate& a, const PeakCandidate& b); // prototype
bool sort_peaks_by_intensity(const PeakCandidate& a, const PeakCandidate& b)
{
return a.peak_apex_intensity > b.peak_apex_intensity;
}
/**
@brief This class implements a peak-picking algorithm for high-resolution MS
data (specifically designed for TOF-MS data).
This peak-picking algorithm detects ion signals in profile data and
reconstructs the corresponding peak shape by identifying the left and right
borders of the peak. It reports the area under the peak as intensity and the
weighted m/z values as the m/z value as well as left/right border.
Furthermore, it next tries to improve the peak positioning iteratively using
the m/z center computed in the last iteration. This allows for refinement in
the peak boundaries and more accurate determination of peak center and borders.
Its approach is similar to the PeakPickerHiRes but additionally uses an
iterative approach to find and re-center peaks.
- First, it uses the PeakPickerHiRes to find seeds or candidate peaks.
- Next it uses n iterations to re-center those peaks and compute left/right
borders for each peak.
- Finally it removes peaks that are within the borders of other peaks.
So far, this peak picker was mainly tested on high resolution TOF-MS data.
@htmlinclude OpenMS_PeakPickerIterative.parameters
@note The peaks must be sorted according to ascending m/z!
@ingroup PeakPicking
*/
class OPENMS_DLLAPI PeakPickerIterative :
public DefaultParamHandler,
public ProgressLogger
{
private:
double signal_to_noise_;
double peak_width_;
double spacing_difference_;
int sn_bin_count_;
int nr_iterations_;
double sn_win_len_;
bool check_width_internally_;
public:
/// Constructor
PeakPickerIterative() :
DefaultParamHandler("PeakPickerIterative"),
ProgressLogger()
{
defaults_.setValue("signal_to_noise_", 1.0, "Signal to noise value, each peak is required to be above this value (turn off by setting it to 0.0)");
defaults_.setValue("peak_width", 0.0, "Expected peak width half width in Dalton - peaks will be extended until this half width is reached (even if the intensitity is increasing). In conjunction with check_width_internally it will also be used to remove peaks whose spacing is larger than this value.");
defaults_.setValue("spacing_difference", 1.5, "Difference between peaks in multiples of the minimal difference to continue. The higher this value is set, the further apart peaks are allowed to be to still extend a peak. E.g. if the value is set to 1.5 and in a current peak the minimal spacing between peaks is 10 mDa, then only peaks at most 15 mDa apart will be added to the peak.", {"advanced"});
defaults_.setValue("sn_bin_count_", 30, "Bin count for the Signal to Noise estimation.", {"advanced"});
defaults_.setValue("nr_iterations_", 5, "Nr of iterations to perform (how many times the peaks are re-centered).", {"advanced"});
defaults_.setMinInt("nr_iterations_", 1);
defaults_.setValue("sn_win_len_", 20.0, "Window length for the Signal to Noise estimation.", {"advanced"});
defaults_.setValue("check_width_internally", "false", "Delete peaks where the spacing is larger than the peak width (should be set to true to avoid artefacts)", {"advanced"});
defaults_.setValidStrings("check_width_internally", {"true","false"});
defaults_.setValue("ms1_only", "false", "Only do MS1");
defaults_.setValidStrings("ms1_only", {"true","false"});
defaults_.setValue("clear_meta_data", "false", "Delete meta data about peak width");
defaults_.setValidStrings("clear_meta_data", {"true","false"});
// write defaults into Param object param_
defaultsToParam_();
}
void updateMembers_() override
{
signal_to_noise_ = (double)param_.getValue("signal_to_noise_");
peak_width_ = (double)param_.getValue("peak_width");
spacing_difference_ = (double)param_.getValue("spacing_difference");
sn_bin_count_ = (double)param_.getValue("sn_bin_count_");
nr_iterations_ = (double)param_.getValue("nr_iterations_");
sn_win_len_ = (double)param_.getValue("sn_win_len_");
check_width_internally_ = param_.getValue("check_width_internally").toBool();
}
/// Destructor
~PeakPickerIterative() override {}
private:
/*
* This will re-center the peaks by using the seeds (ordered by intensity) to
* find raw signals that may belong to this peak. Then the peak is centered
* using a weighted average.
* Signals are added to the peak as long as they are still inside the
* peak_width or as long as the signal intensity keeps falling. Also the
* distance to the previous signal and the whether the signal is below the
* noise level is taken into account.
* This function implements a single iteration of this algorithm.
*
*/
void pickRecenterPeaks_(const MSSpectrum& input,
std::vector<PeakCandidate>& PeakCandidates,
SignalToNoiseEstimatorMedian<MSSpectrum>& snt) const
{
for (Size peak_it = 0; peak_it < PeakCandidates.size(); peak_it++)
{
int i = PeakCandidates[peak_it].index;
double central_peak_mz = input[i].getMZ(), central_peak_int = input[i].getIntensity();
double left_neighbor_mz = input[i - 1].getMZ(), left_neighbor_int = input[i - 1].getIntensity();
double right_neighbor_mz = input[i + 1].getMZ(), right_neighbor_int = input[i + 1].getIntensity();
// MZ spacing sanity checks
double left_to_central = std::fabs(central_peak_mz - left_neighbor_mz);
double central_to_right = std::fabs(right_neighbor_mz - central_peak_mz);
double min_spacing = (left_to_central < central_to_right) ? left_to_central : central_to_right;
double est_peak_width = peak_width_;
if (check_width_internally_ && (left_to_central > est_peak_width || central_to_right > est_peak_width))
{
// something has gone wrong, the points are further away than the peak width -> delete this peak
PeakCandidates[peak_it].integrated_intensity = -1;
PeakCandidates[peak_it].leftWidth = -1;
PeakCandidates[peak_it].rightWidth = -1;
PeakCandidates[peak_it].mz = -1;
continue;
}
std::map<double, double> peak_raw_data;
peak_raw_data[central_peak_mz] = central_peak_int;
peak_raw_data[left_neighbor_mz] = left_neighbor_int;
peak_raw_data[right_neighbor_mz] = right_neighbor_int;
// // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // //
// COPY - from PeakPickerHiRes
// peak core found, now extend it to the left
Size k = 2;
while ((i - k + 1) > 0
&& std::fabs(input[i - k].getMZ() - peak_raw_data.begin()->first) < spacing_difference_ * min_spacing
&& (input[i - k].getIntensity() < peak_raw_data.begin()->second
|| std::fabs(input[i - k].getMZ() - central_peak_mz) < est_peak_width)
)
{
if (signal_to_noise_ > 0.0)
{
if (snt.getSignalToNoise(i - k) < signal_to_noise_)
{
break;
}
}
peak_raw_data[input[i - k].getMZ()] = input[i - k].getIntensity();
++k;
}
double leftborder = input[i - k + 1].getMZ();
// to the right
k = 2;
while ((i + k) < input.size()
&& std::fabs(input[i + k].getMZ() - peak_raw_data.rbegin()->first) < spacing_difference_ * min_spacing
&& (input[i + k].getIntensity() < peak_raw_data.rbegin()->second
|| std::fabs(input[i + k].getMZ() - central_peak_mz) < est_peak_width)
)
{
if (signal_to_noise_ > 0.0)
{
if (snt.getSignalToNoise(i + k) < signal_to_noise_)
{
break;
}
}
peak_raw_data[input[i + k].getMZ()] = input[i + k].getIntensity();
++k;
}
// END COPY - from PeakPickerHiRes
// // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // // //
double rightborder = input[i + k - 1].getMZ();
double weighted_mz = 0;
double integrated_intensity = 0;
for (std::map<double, double>::const_iterator map_it = peak_raw_data.begin(); map_it != peak_raw_data.end(); ++map_it)
{
weighted_mz += map_it->first * map_it->second;
integrated_intensity += map_it->second;
}
weighted_mz /= integrated_intensity;
// store the data
PeakCandidates[peak_it].integrated_intensity = integrated_intensity;
PeakCandidates[peak_it].leftWidth = leftborder;
PeakCandidates[peak_it].rightWidth = rightborder;
PeakCandidates[peak_it].mz = weighted_mz;
// find the closest raw signal peak to where we just put our peak and store it
double min_diff = std::fabs(weighted_mz - input[i].getMZ());
int min_i = i;
// Search to the left
for (int m = 1; i - m > 0 && leftborder < input[i - m].getMZ(); m++)
{
if (std::fabs(weighted_mz - input[i - m].getMZ()) < min_diff)
{
min_diff = std::fabs(weighted_mz - input[i - m].getMZ());
min_i = i - m;
}
}
// Search to the right
for (int m = 1; i - m > 0 && rightborder > input[i + m].getMZ(); m++)
{
if (std::fabs(weighted_mz - input[i + m].getMZ()) < min_diff)
{
min_diff = std::fabs(weighted_mz - input[i + m].getMZ());
min_i = i + m;
}
}
PeakCandidates[peak_it].index = min_i;
}
}
public:
/*
This will pick one single spectrum. The PeakPickerHiRes is used to
generate seeds, these seeds are then used to re-center the mass and
compute peak width and integrated intensity of the peak.
Finally, other peaks that would fall within the primary peak are
discarded
The output are the remaining peaks.
*/
void pick(const MSSpectrum& input, MSSpectrum& output)
{
// don't pick a spectrum with less than 3 data points
if (input.size() < 3) return;
// copy the spectrum meta data
copySpectrumMeta(input, output);
output.setType(SpectrumSettings::SpectrumType::CENTROID);
output.getFloatDataArrays().clear();
std::vector<PeakCandidate> PeakCandidates;
MSSpectrum picked_spectrum;
// Use the PeakPickerHiRes to find candidates ...
OpenMS::PeakPickerHiRes pp;
Param pepi_param = OpenMS::PeakPickerHiRes().getDefaults();
pepi_param.setValue("signal_to_noise", signal_to_noise_);
pepi_param.setValue("spacing_difference", spacing_difference_);
pp.setParameters(pepi_param);
pp.pick(input, picked_spectrum);
// after picking peaks, we store the closest index of the raw spectrum and the picked intensity
std::vector<PeakCandidate> newPeakCandidates_;
Size j = 0;
OPENMS_LOG_DEBUG << "Candidates " << picked_spectrum.size() << std::endl;
for (Size k = 0; k < input.size() && j < picked_spectrum.size(); k++)
{
if (input[k].getMZ() > picked_spectrum[j].getMZ())
{
OPENMS_LOG_DEBUG << "got a value " << k << " @ " << input[k] << std::endl;
PeakCandidate pc = { /*.index=*/ static_cast<int>(k), /*.intensity=*/ picked_spectrum[j].getIntensity(), -1, -1, -1, -1};
newPeakCandidates_.push_back(pc);
j++;
}
}
PeakCandidates = newPeakCandidates_;
std::sort(PeakCandidates.begin(), PeakCandidates.end(), sort_peaks_by_intensity);
// signal-to-noise estimation
SignalToNoiseEstimatorMedian<MSSpectrum > snt;
if (signal_to_noise_ > 0.0)
{
Param snt_parameters = snt.getParameters();
snt_parameters.setValue("win_len", sn_win_len_);
snt_parameters.setValue("bin_count", sn_bin_count_);
snt.setParameters(snt_parameters);
snt.init(input);
}
// The peak candidates are re-centered and the width is computed for each peak
for (int i = 0; i < nr_iterations_; i++)
{
pickRecenterPeaks_(input, PeakCandidates, snt);
}
output.getFloatDataArrays().resize(3);
output.getFloatDataArrays()[0].setName("IntegratedIntensity");
output.getFloatDataArrays()[1].setName("leftWidth");
output.getFloatDataArrays()[2].setName("rightWidth");
// Go through all candidates and exclude all lower-intensity candidates
// that are within the borders of another peak
OPENMS_LOG_DEBUG << "Will now merge candidates" << std::endl;
for (Size peak_it = 0; peak_it < PeakCandidates.size(); peak_it++)
{
if (PeakCandidates[peak_it].leftWidth < 0) continue;
//Remove all peak candidates that are enclosed by this peak
for (Size m = peak_it + 1; m < PeakCandidates.size(); m++)
{
if (PeakCandidates[m].mz >= PeakCandidates[peak_it].leftWidth && PeakCandidates[m].mz <= PeakCandidates[peak_it].rightWidth)
{
OPENMS_LOG_DEBUG << "Remove peak " << m << " : " << PeakCandidates[m].mz << " " <<
PeakCandidates[m].peak_apex_intensity << " (too close to " << PeakCandidates[peak_it].mz <<
" " << PeakCandidates[peak_it].peak_apex_intensity << ")" << std::endl;
PeakCandidates[m].leftWidth = PeakCandidates[m].rightWidth = -1;
}
}
Peak1D peak;
peak.setMZ(PeakCandidates[peak_it].mz);
peak.setIntensity(PeakCandidates[peak_it].integrated_intensity);
output.push_back(peak);
OPENMS_LOG_DEBUG << "Push peak " << peak_it << " " << peak << std::endl;
output.getFloatDataArrays()[0].push_back(PeakCandidates[peak_it].integrated_intensity);
output.getFloatDataArrays()[1].push_back(PeakCandidates[peak_it].leftWidth);
output.getFloatDataArrays()[2].push_back(PeakCandidates[peak_it].rightWidth);
}
OPENMS_LOG_DEBUG << "Found seeds: " << PeakCandidates.size() << " / Found peaks: " << output.size() << std::endl;
output.sortByPosition();
}
void pickExperiment(const PeakMap& input, PeakMap& output)
{
// make sure that output is clear
output.clear(true);
// copy experimental settings
static_cast<ExperimentalSettings&>(output) = input;
// resize output with respect to input
output.resize(input.size());
bool ms1_only = param_.getValue("ms1_only").toBool();
bool clear_meta_data = param_.getValue("clear_meta_data").toBool();
Size progress = 0;
startProgress(0, input.size(), "picking peaks");
for (Size scan_idx = 0; scan_idx != input.size(); ++scan_idx)
{
if (ms1_only && (input[scan_idx].getMSLevel() != 1))
{
output[scan_idx] = input[scan_idx];
}
else
{
pick(input[scan_idx], output[scan_idx]);
if (clear_meta_data) {output[scan_idx].getFloatDataArrays().clear();}
}
setProgress(progress++);
}
endProgress();
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/PROCESSING/BASELINE/MorphologicalFilter.h | .h | 20,936 | 585 | // 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/ProgressLogger.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/MATH/MathFunctions.h>
#include <algorithm>
#include <iterator>
namespace OpenMS
{
namespace Internal
{
/**
@brief An iterator wrapper to access peak intensities instead of the peak itself.
It is using unary operator *, and the like. This is not a full implementation of the
iterator concept, it can only do what is needed for MorphologicalFilter.
*/
template<typename IteratorT>
class /* OPENMS_DLLAPI */ IntensityIteratorWrapper
{
public:
typedef std::forward_iterator_tag iterator_category;
typedef typename IteratorT::value_type::IntensityType value_type;
typedef typename IteratorT::value_type::IntensityType& reference;
typedef typename IteratorT::value_type::IntensityType* pointer;
typedef typename IteratorT::difference_type difference_type;
IntensityIteratorWrapper(const IteratorT& rhs) : base(rhs)
{
}
value_type operator*()
{
return base->getIntensity();
}
template<typename IndexT>
value_type operator[](const IndexT& index)
{
return base[index].getIntensity();
}
difference_type operator-(IntensityIteratorWrapper& rhs) const
{
return base - rhs.base;
}
IntensityIteratorWrapper& operator++()
{
++base;
return *this;
}
IntensityIteratorWrapper operator++(int)
{
IteratorT tmp = *this;
++(*this);
return tmp;
}
bool operator==(const IntensityIteratorWrapper& rhs) const
{
return base == rhs.base;
}
bool operator!=(const IntensityIteratorWrapper& rhs) const
{
return base != rhs.base;
}
protected:
IteratorT base;
};
/// make-function so that we need no write out all those type names to get the wrapped iterator.
template<typename IteratorT>
IntensityIteratorWrapper<IteratorT> intensityIteratorWrapper(const IteratorT& rhs)
{
return IntensityIteratorWrapper<IteratorT>(rhs);
}
} // namespace Internal
/**
@brief This class implements baseline filtering operations using methods
from mathematical morphology.
The fundamental operations are erosion and dilation. These are defined with
respect to a structuring element. In our case, this is just a straight line
and the definitions can be given as follows:
Assume that the input is \f$x_0, x_1, x_2, ...\f$. Then the <i>erosion</i>
of \f$x\f$ contains the minima of a sliding window of size struc_size around
\f$ i \f$, i.e. \f[ \mathrm{erosion}_i = \min\{x_{i-\mathrm{struc\_size}/2},
\ldots, x_{i+\mathrm{struc\_size}/2}\} \f]. The <i>dilation</i> of \f$x\f$
contains the maxima of a sliding window of size struc_size around \f$ i \f$,
i.e. \f[ \mathrm{dilation}_i = \max\{x_{i-\mathrm{struc\_size}/2}, \ldots,
x_{i+\mathrm{struc\_size}/2}\} \f].
For morphological baseline filtering the <i>tophat</i> method is used. The
tophat transform is defined as signal minus opening, where the opening is
the dilation of the erosion of the signal.
@image html MorphologicalFilter_tophat.png
Several other morphological operations are implemented as well. See the
image below and the documentation for further explanation.
@image html MorphologicalFilter_all.png
@note The class #MorphologicalFilter is designed for uniformly spaced profile data.
@note The data must be sorted according to ascending m/z!
@htmlinclude OpenMS_MorphologicalFilter.parameters
@ingroup SignalProcessing
*/
class OPENMS_DLLAPI MorphologicalFilter : public ProgressLogger, public DefaultParamHandler
{
public:
/// Constructor
MorphologicalFilter() : ProgressLogger(), DefaultParamHandler("MorphologicalFilter"), struct_size_in_datapoints_(0)
{
// structuring element
defaults_.setValue("struc_elem_length", 3.0, "Length of the structuring element. This should be wider than the expected peak width.");
defaults_.setValue("struc_elem_unit", "Thomson", "The unit of the 'struct_elem_length'.");
defaults_.setValidStrings("struc_elem_unit", {"Thomson", "DataPoints"});
// methods
defaults_.setValue("method", "tophat",
"Method to use, the default is 'tophat'. Do not change this unless you know what you are doing. The other methods may be useful for tuning the parameters, see the class "
"documentation of MorpthologicalFilter.");
defaults_.setValidStrings("method", {"identity", "erosion", "dilation", "opening", "closing", "gradient", "tophat", "bothat", "erosion_simple", "dilation_simple"});
defaultsToParam_();
}
/// Destructor
~MorphologicalFilter() override
{
}
/** @brief Applies the morphological filtering operation to an iterator range.
Input and output range must be valid, i.e. allocated before.
InputIterator must be a random access iterator type.
@param[in] input_begin the begin of the input range
@param[in] input_end the end of the input range
@param[out] output_begin the begin of the output range
@exception Exception::IllegalArgument The given method is not one of the values defined in the @em method parameter.
*/
template<typename InputIterator, typename OutputIterator>
void filterRange(InputIterator input_begin, InputIterator input_end, OutputIterator output_begin)
{
// the buffer is static only to avoid reallocation
static std::vector<typename InputIterator::value_type> buffer;
const UInt size = input_end - input_begin;
// determine the struct size in data points if not already set
if (struct_size_in_datapoints_ == 0)
{
struct_size_in_datapoints_ = (UInt)(double)param_.getValue("struc_elem_length");
}
// apply the filtering
std::string method = param_.getValue("method");
if (method == "identity")
{
std::copy(input_begin, input_end, output_begin);
}
else if (method == "erosion")
{
applyErosion_(struct_size_in_datapoints_, input_begin, input_end, output_begin);
}
else if (method == "dilation")
{
applyDilation_(struct_size_in_datapoints_, input_begin, input_end, output_begin);
}
else if (method == "opening")
{
if (buffer.size() < size)
buffer.resize(size);
applyErosion_(struct_size_in_datapoints_, input_begin, input_end, buffer.begin());
applyDilation_(struct_size_in_datapoints_, buffer.begin(), buffer.begin() + size, output_begin);
}
else if (method == "closing")
{
if (buffer.size() < size)
buffer.resize(size);
applyDilation_(struct_size_in_datapoints_, input_begin, input_end, buffer.begin());
applyErosion_(struct_size_in_datapoints_, buffer.begin(), buffer.begin() + size, output_begin);
}
else if (method == "gradient")
{
if (buffer.size() < size)
buffer.resize(size);
applyErosion_(struct_size_in_datapoints_, input_begin, input_end, buffer.begin());
applyDilation_(struct_size_in_datapoints_, input_begin, input_end, output_begin);
for (UInt i = 0; i < size; ++i)
output_begin[i] -= buffer[i];
}
else if (method == "tophat")
{
if (buffer.size() < size)
buffer.resize(size);
applyErosion_(struct_size_in_datapoints_, input_begin, input_end, buffer.begin());
applyDilation_(struct_size_in_datapoints_, buffer.begin(), buffer.begin() + size, output_begin);
for (UInt i = 0; i < size; ++i)
output_begin[i] = input_begin[i] - output_begin[i];
}
else if (method == "bothat")
{
if (buffer.size() < size)
buffer.resize(size);
applyDilation_(struct_size_in_datapoints_, input_begin, input_end, buffer.begin());
applyErosion_(struct_size_in_datapoints_, buffer.begin(), buffer.begin() + size, output_begin);
for (UInt i = 0; i < size; ++i)
output_begin[i] = input_begin[i] - output_begin[i];
}
else if (method == "erosion_simple")
{
applyErosionSimple_(struct_size_in_datapoints_, input_begin, input_end, output_begin);
}
else if (method == "dilation_simple")
{
applyDilationSimple_(struct_size_in_datapoints_, input_begin, input_end, output_begin);
}
struct_size_in_datapoints_ = 0;
}
/**
@brief Applies the morphological filtering operation to an MSSpectrum.
If the size of the structuring element is given in 'Thomson', the number of data points for
the structuring element is computed as follows:
<ul>
<li>The data points are assumed to be uniformly spaced. We compute the
average spacing from the position of the first and the last peak and the
total number of peaks in the input range.
<li>The number of data points in the structuring element is computed
from struc_size and the average spacing, and rounded up to an odd
number.
</ul>
*/
void filter(MSSpectrum& spectrum)
{
// make sure the right peak type is set
spectrum.setType(SpectrumSettings::SpectrumType::PROFILE);
// Abort if there is nothing to do
if (spectrum.size() <= 1)
{
return;
}
// Determine structuring element size in datapoints (depending on the unit)
if (param_.getValue("struc_elem_unit") == "Thomson")
{
const double struc_elem_length = (double)param_.getValue("struc_elem_length");
const double mz_diff = spectrum.back().getMZ() - spectrum.begin()->getMZ();
struct_size_in_datapoints_ = (UInt)(ceil(struc_elem_length * (double)(spectrum.size() - 1) / mz_diff));
}
else
{
struct_size_in_datapoints_ = (UInt)(double)param_.getValue("struc_elem_length");
}
// make it odd (needed for the algorithm)
if (!Math::isOdd(struct_size_in_datapoints_))
++struct_size_in_datapoints_;
// apply the filtering and overwrite the input data
std::vector<Peak1D::IntensityType> output(spectrum.size());
filterRange(Internal::intensityIteratorWrapper(spectrum.begin()), Internal::intensityIteratorWrapper(spectrum.end()), output.begin());
// overwrite output with data
for (Size i = 0; i < spectrum.size(); ++i)
{
spectrum[i].setIntensity(output[i]);
}
}
/**
@brief Applies the morphological filtering operation to an MSExperiment.
The size of the structuring element is computed for each spectrum individually, if it is given in 'Thomson'.
See the filtering method for MSSpectrum for details.
*/
void filterExperiment(PeakMap& exp)
{
startProgress(0, exp.size(), "filtering baseline");
for (UInt i = 0; i < exp.size(); ++i)
{
filter(exp[i]);
setProgress(i);
}
endProgress();
}
protected:
/// Member for struct size in data points
UInt struct_size_in_datapoints_;
/** @brief Applies erosion. This implementation uses van Herk's method.
Only 3 min/max comparisons are required per data point, independent of
struc_size.
*/
template<typename InputIterator, typename OutputIterator>
void applyErosion_(Int struc_size, InputIterator input, InputIterator input_end, OutputIterator output)
{
typedef typename InputIterator::value_type ValueType;
const Int size = input_end - input;
const Int struc_size_half = struc_size / 2; // yes, integer division
static std::vector<ValueType> buffer;
if (Int(buffer.size()) < struc_size)
buffer.resize(struc_size);
Int anchor; // anchoring position of the current block
Int i; // index relative to anchor, used for 'for' loops
Int ii = 0; // input index
Int oi = 0; // output index
ValueType current; // current value
// we just can't get the case distinctions right in these cases, resorting to simple method.
if (size <= struc_size || size <= 5)
{
applyErosionSimple_(struc_size, input, input_end, output);
return;
}
{
// lower margin area
current = input[0];
for (++ii; ii < struc_size_half; ++ii)
if (current > input[ii])
current = input[ii];
for (; ii < std::min(Int(struc_size), size); ++ii, ++oi)
{
if (current > input[ii])
current = input[ii];
output[oi] = current;
}
}
{
// middle (main) area
for (anchor = struc_size; anchor <= size - struc_size; anchor += struc_size)
{
ii = anchor;
current = input[ii];
buffer[0] = current;
for (i = 1; i < struc_size; ++i, ++ii)
{
if (current > input[ii])
current = input[ii];
buffer[i] = current;
}
ii = anchor - 1;
oi = ii + struc_size_half;
current = input[ii];
for (i = 1; i < struc_size; ++i, --ii, --oi)
{
if (current > input[ii])
current = input[ii];
output[oi] = std::min(buffer[struc_size - i], current);
}
if (current > input[ii])
current = input[ii];
output[oi] = current;
}
}
{
// higher margin area
ii = size - 1;
oi = ii;
current = input[ii];
for (--ii; ii >= size - struc_size_half; --ii)
if (current > input[ii])
current = input[ii];
for (; ii >= std::max(size - Int(struc_size), 0); --ii, --oi)
{
if (current > input[ii])
current = input[ii];
output[oi] = current;
}
anchor = size - struc_size;
ii = anchor;
current = input[ii];
buffer[0] = current;
for (i = 1; i < struc_size; ++i, ++ii)
{
if (current > input[ii])
current = input[ii];
buffer[i] = current;
}
ii = anchor - 1;
oi = ii + struc_size_half;
current = input[ii];
for (i = 1; (ii >= 0) && (i < struc_size); ++i, --ii, --oi)
{
if (current > input[ii])
current = input[ii];
output[oi] = std::min(buffer[struc_size - i], current);
}
if (ii >= 0)
{
if (current > input[ii])
current = input[ii];
output[oi] = current;
}
}
return;
}
/** @brief Applies dilation. This implementation uses van Herk's method.
Only 3 min/max comparisons are required per data point, independent of
struc_size.
*/
template<typename InputIterator, typename OutputIterator>
void applyDilation_(Int struc_size, InputIterator input, InputIterator input_end, OutputIterator output)
{
typedef typename InputIterator::value_type ValueType;
const Int size = input_end - input;
const Int struc_size_half = struc_size / 2; // yes, integer division
static std::vector<ValueType> buffer;
if (Int(buffer.size()) < struc_size)
buffer.resize(struc_size);
Int anchor; // anchoring position of the current block
Int i; // index relative to anchor, used for 'for' loops
Int ii = 0; // input index
Int oi = 0; // output index
ValueType current; // current value
// we just can't get the case distinctions right in these cases, resorting to simple method.
if (size <= struc_size || size <= 5)
{
applyDilationSimple_(struc_size, input, input_end, output);
return;
}
{
// lower margin area
current = input[0];
for (++ii; ii < struc_size_half; ++ii)
if (current < input[ii])
current = input[ii];
for (; ii < std::min(Int(struc_size), size); ++ii, ++oi)
{
if (current < input[ii])
current = input[ii];
output[oi] = current;
}
}
{
// middle (main) area
for (anchor = struc_size; anchor <= size - struc_size; anchor += struc_size)
{
ii = anchor;
current = input[ii];
buffer[0] = current;
for (i = 1; i < struc_size; ++i, ++ii)
{
if (current < input[ii])
current = input[ii];
buffer[i] = current;
}
ii = anchor - 1;
oi = ii + struc_size_half;
current = input[ii];
for (i = 1; i < struc_size; ++i, --ii, --oi)
{
if (current < input[ii])
current = input[ii];
output[oi] = std::max(buffer[struc_size - i], current);
}
if (current < input[ii])
current = input[ii];
output[oi] = current;
}
}
{
// higher margin area
ii = size - 1;
oi = ii;
current = input[ii];
for (--ii; ii >= size - struc_size_half; --ii)
if (current < input[ii])
current = input[ii];
for (; ii >= std::max(size - Int(struc_size), 0); --ii, --oi)
{
if (current < input[ii])
current = input[ii];
output[oi] = current;
}
anchor = size - struc_size;
ii = anchor;
current = input[ii];
buffer[0] = current;
for (i = 1; i < struc_size; ++i, ++ii)
{
if (current < input[ii])
current = input[ii];
buffer[i] = current;
}
ii = anchor - 1;
oi = ii + struc_size_half;
current = input[ii];
for (i = 1; (ii >= 0) && (i < struc_size); ++i, --ii, --oi)
{
if (current < input[ii])
current = input[ii];
output[oi] = std::max(buffer[struc_size - i], current);
}
if (ii >= 0)
{
if (current < input[ii])
current = input[ii];
output[oi] = current;
}
}
return;
}
/// Applies erosion. Simple implementation, possibly faster if struc_size is very small, and used in some special cases.
template<typename InputIterator, typename OutputIterator>
void applyErosionSimple_(Int struc_size, InputIterator input_begin, InputIterator input_end, OutputIterator output_begin)
{
typedef typename InputIterator::value_type ValueType;
const int size = input_end - input_begin;
const Int struc_size_half = struc_size / 2; // yes integer division
for (Int index = 0; index < size; ++index)
{
Int start = std::max(0, index - struc_size_half);
Int stop = std::min(size - 1, index + struc_size_half);
ValueType value = input_begin[start];
for (Int i = start + 1; i <= stop; ++i)
if (value > input_begin[i])
value = input_begin[i];
output_begin[index] = value;
}
return;
}
/// Applies dilation. Simple implementation, possibly faster if struc_size is very small, and used in some special cases.
template<typename InputIterator, typename OutputIterator>
void applyDilationSimple_(Int struc_size, InputIterator input_begin, InputIterator input_end, OutputIterator output_begin)
{
typedef typename InputIterator::value_type ValueType;
const int size = input_end - input_begin;
const Int struc_size_half = struc_size / 2; // yes integer division
for (Int index = 0; index < size; ++index)
{
Int start = std::max(0, index - struc_size_half);
Int stop = std::min(size - 1, index + struc_size_half);
ValueType value = input_begin[start];
for (Int i = start + 1; i <= stop; ++i)
if (value < input_begin[i])
value = input_begin[i];
output_begin[index] = value;
}
return;
}
private:
/// copy constructor not implemented
MorphologicalFilter(const MorphologicalFilter& source);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/PROCESSING/SMOOTHING/LowessSmoothing.h | .h | 1,697 | 60 | // 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 $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
namespace OpenMS
{
/**
@brief LOWESS (locally weighted scatterplot smoothing).
A smoothing technique that a quadratic model to localized subsets of the
data, point by point.
This is particularly useful for smoothing intensities in spectra or
chromatograms. In this case, the window size for the smoothing
should be set proportional to the peak width (see LowessSmoothing parameters).
Note that this should work best for few datapoints that have strong
non-linear behavior. For large datasets with mostly linear behavior, use
FastLowessSmoothing
@htmlinclude OpenMS_LowessSmoothing.parameters
@ingroup SignalProcessing
*/
class OPENMS_DLLAPI LowessSmoothing :
public DefaultParamHandler
{
public:
/// Default constructor
LowessSmoothing();
/// Destructor
~LowessSmoothing() override;
typedef std::vector<double> DoubleVector;
/// Smoothing method that receives x and y coordinates (e.g., RT and intensities) and computes smoothed intensities.
void smoothData(const DoubleVector &, const DoubleVector &, DoubleVector &);
protected:
void updateMembers_() override;
private:
double window_size_;
double tricube_(double, double);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/PROCESSING/SMOOTHING/FastLowessSmoothing.h | .h | 3,820 | 93 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hannes Roest $
// $Authors: Hannes Roest $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CONCEPT/Macros.h>
#include <vector>
namespace OpenMS
{
/**
@brief LOWESS (locally weighted scatterplot smoothing).
A non-parametric smoothing technique that fits a simple linear regression
model to localized subsets of the data, point by point. This is often used
for retention time alignments.
The implementation here is optimized for speed and many datapoints. Note
that it performs a linear fit, it does not implement quadratic fits. It is
based on the initial FORTRAN code by W. S. Cleveland published at NETLIB.
Note that this should work best for for large datasets with mostly linear
behavior. For small datasets with non-linear behavior, use the
LowessSmoothing class.
@ingroup SignalProcessing
*/
namespace FastLowessSmoothing
{
/**
@brief Computes a lowess smoothing fit on the input vectors
This is a fast implementation of a lowess fit that is based on the original
Fortran code by W. S. Cleveland and it uses some optimizations.
@param[in] x The input vector in the first dimension
@param[in] y The input vector in the second dimension
@param[in] f Fraction of datapoints to use for each local regression (the span, recommended value: 2/3)
@param[in] nsteps The number of robustifying iterations (recommended value: 3)
@param[in] delta nonnegative parameter which may be used to save computations (recommended value: 0.01 * range of x)
@param[out] result Result of fit
\pre The size of the vectors x and y needs to be equal
\pre The vector needs to have at least 2 elements
\pre The vector x needs to be sorted
\pre The f value needs to be between 0 and 1
\pre The nsteps parameter needs to be zero or larger
\pre The delta parameter needs to be zero or larger
The delta parameter allows the algorithm to not perform the regression at
every data point, as it assumes that points that are close to each other
will have the same regression parameters. A linear interpolation is used
to fill in the skipped points, larger values lead to increased speed up.
The f parameter allows the caller to influence the smoothness. A larger
values will increase smoothness (recommended value: 2/3) It is the
fraction of points used to compute each fitted value. Choosing F in the
range .2 to .8 usually results in a good fit
The nsteps parameter controls how many iterations are performed in the
robust fit (setting it to zero turns off the robust fit and the nonrobust
fit is returned). A value of 2 or 3 should be sufficient for most purposes.
*/
int OPENMS_DLLAPI lowess(const std::vector<double>& x, const std::vector<double>& y,
double f, int nsteps, double delta, std::vector<double>& result);
/**
@brief Computes a lowess smoothing fit on the input vectors with the recommended values
@param[in] x The input vector in the first dimension
@param[in] y The input vector in the second dimension
@param[out] result Result of fit
\pre The size of the vectors x and y needs to be equal
\pre The vector needs to have at least 2 elements
\pre The vector x needs to be sorted
*/
int OPENMS_DLLAPI lowess(const std::vector<double>& x, const std::vector<double>& y,
std::vector<double>& result);
}
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/PROCESSING/SMOOTHING/GaussFilter.h | .h | 3,099 | 89 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Eva Lange $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CONCEPT/Constants.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/PROCESSING/SMOOTHING/GaussFilterAlgorithm.h>
#include <OpenMS/KERNEL/StandardTypes.h>
namespace OpenMS
{
/**
@brief This class represents a Gaussian lowpass-filter which works on uniform as well as on non-uniform profile data.
Gaussian filters are important in many signal processing,
image processing, and communication applications. These filters are characterized by narrow bandwidths,
sharp cutoffs, and low passband ripple. A key feature of Gaussian filters is that the Fourier transform of a
Gaussian is also a Gaussian, so the filter has the same response shape in both the time and frequency domains.
The coefficients \f$ \emph{coeffs} \f$ of the Gaussian-window with length \f$ \emph{frameSize} \f$ are calculated
from the gaussian distribution
\f[ \emph{coeff}(x) = \frac{1}{\sigma \sqrt{2\pi}} e^{\frac{-x^2}{2\sigma^2}} \f]
where \f$ x=[-\frac{frameSize}{2},...,\frac{frameSize}{2}] \f$ represents the window area and \f$ \sigma \f$
is the standard derivation.
@note The wider the kernel width the smoother the signal (the more detail information get lost!).
Use a Gaussian filter kernel which has approximately the same width as your mass peaks,
whereas the Gaussian peak width corresponds approximately to 8*sigma.
@note The data must be sorted according to ascending m/z!
@htmlinclude OpenMS_GaussFilter.parameters
@ingroup SignalProcessing
*/
//#define DEBUG_FILTERING
class OPENMS_DLLAPI GaussFilter :
public ProgressLogger,
public DefaultParamHandler
{
public:
/// Constructor
GaussFilter();
/// Destructor
~GaussFilter() override = default;
/**
@brief Smoothes an MSSpectrum containing profile data.
Convolutes the filter and the profile data and writes the result back to the spectrum.
@exception Exception::IllegalArgument is thrown, if the @em gaussian_width parameter is too small.
*/
void filter(MSSpectrum & spectrum);
void filter(MSChromatogram & chromatogram);
void filter(Mobilogram & mobilogram);
/**
@brief Smoothes an MSExperiment containing profile data.
@exception Exception::IllegalArgument is thrown, if the @em gaussian_width parameter is too small.
*/
void filterExperiment(PeakMap & map);
protected:
GaussFilterAlgorithm gauss_algo_;
/// The spacing of the pre-tabulated kernel coefficients
double spacing_;
bool write_log_messages_ = false;
// Docu in base class
void updateMembers_() override;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/PROCESSING/SMOOTHING/GaussFilterAlgorithm.h | .h | 15,090 | 365 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hannes Roest $
// $Authors: Eva Lange $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CONCEPT/Types.h>
#include <OpenMS/CONCEPT/Constants.h>
#include <OpenMS/INTERFACES/DataStructures.h>
#include <OpenMS/MATH/MathFunctions.h>
#include <cmath>
#include <vector>
#include <iostream>
namespace OpenMS
{
/**
@brief This class represents a Gaussian lowpass-filter which works on uniform as well as on non-uniform profile data.
Gaussian filters are important in many signal processing,
image processing, and communication applications. These filters are characterized by narrow bandwidths,
sharp cutoffs, and low passband ripple. A key feature of Gaussian filters is that the Fourier transform of a
Gaussian is also a Gaussian, so the filter has the same response shape in both the time and frequency domains.
The coefficients \f$ \emph{coeffs} \f$ of the Gaussian-window with length \f$ \emph{frameSize} \f$ are calculated
from the gaussian distribution
\f[ \emph{coeff}(x) = \frac{1}{\sigma \sqrt{2\pi}} e^{\frac{-x^2}{2\sigma^2}} \f]
where \f$ x=[-\frac{frameSize}{2},...,\frac{frameSize}{2}] \f$ represents the window area and \f$ \sigma \f$
is the standard derivation.
@note The wider the kernel width the smoother the signal (the more detail information get lost!).
Use a gaussian filter kernel which has approximately the same width as your mass peaks,
whereas the gaussian peak width corresponds approximately to 8*sigma.
@note The data must be sorted according to ascending m/z!
@ingroup SignalProcessing
*/
// #define DEBUG_FILTERING
class OPENMS_DLLAPI GaussFilterAlgorithm
{
public:
/// Constructor
GaussFilterAlgorithm();
/// Destructor
virtual ~GaussFilterAlgorithm();
/**
@brief Smoothes an Spectrum containing profile data.
*/
bool filter(OpenMS::Interfaces::SpectrumPtr spectrum)
{
// create new arrays for mz / intensity data and set their size
OpenMS::Interfaces::BinaryDataArrayPtr intensity_array(new OpenMS::Interfaces::BinaryDataArray);
OpenMS::Interfaces::BinaryDataArrayPtr mz_array(new OpenMS::Interfaces::BinaryDataArray);
mz_array->data.resize(spectrum->getMZArray()->data.size());
intensity_array->data.resize(spectrum->getMZArray()->data.size());
// apply the filter
bool ret_val = filter(
spectrum->getMZArray()->data.begin(),
spectrum->getMZArray()->data.end(),
spectrum->getIntensityArray()->data.begin(),
mz_array->data.begin(), intensity_array->data.begin()
);
// set the data of the spectrum to the new mz / int arrays
spectrum->setMZArray(mz_array);
spectrum->setIntensityArray(intensity_array);
return ret_val;
}
/**
@brief Smoothes an Chromatogram containing profile data.
*/
bool filter(OpenMS::Interfaces::ChromatogramPtr chromatogram)
{
// create new arrays for rt / intensity data and set their size
OpenMS::Interfaces::BinaryDataArrayPtr intensity_array(new OpenMS::Interfaces::BinaryDataArray);
OpenMS::Interfaces::BinaryDataArrayPtr rt_array(new OpenMS::Interfaces::BinaryDataArray);
rt_array->data.resize(chromatogram->getTimeArray()->data.size());
intensity_array->data.resize(chromatogram->getTimeArray()->data.size());
// apply the filter
bool ret_val = filter(
chromatogram->getTimeArray()->data.begin(),
chromatogram->getTimeArray()->data.end(),
chromatogram->getIntensityArray()->data.begin(),
rt_array->data.begin(), intensity_array->data.begin()
);
// set the data of the chromatogram to the new rt / int arrays
chromatogram->setTimeArray(rt_array);
chromatogram->setIntensityArray(intensity_array);
return ret_val;
}
/**
@brief Smoothes two data arrays.
Convolutes the filter and the profile data and writes the results into the output iterators mz_out and int_out.
*/
template <typename ConstIterT, typename IterT>
bool filter(
ConstIterT mz_in_start,
ConstIterT mz_in_end,
ConstIterT int_in_start,
IterT mz_out,
IterT int_out)
{
bool found_signal = false;
ConstIterT mz_it = mz_in_start;
ConstIterT int_it = int_in_start;
for (; mz_it != mz_in_end; mz_it++, int_it++)
{
// if ppm tolerance is used, calculate a reasonable width value for this m/z
if (use_ppm_tolerance_)
{
initialize(Math::ppmToMass(ppm_tolerance_, *mz_it), spacing_, ppm_tolerance_, use_ppm_tolerance_);
}
double new_int = integrate_(mz_it, int_it, mz_in_start, mz_in_end);
// store new intensity and m/z into output iterator
*mz_out = *mz_it;
*int_out = new_int;
++mz_out;
++int_out;
if (fabs(new_int) > 0) found_signal = true;
}
return found_signal;
}
void initialize(double gaussian_width, double spacing, double ppm_tolerance, bool use_ppm_tolerance);
protected:
///Coefficients
std::vector<double> coeffs_;
/// The standard derivation \f$ \sigma \f$.
double sigma_;
/// The spacing of the pre-tabulated kernel coefficients
double spacing_;
// tolerance in ppm
bool use_ppm_tolerance_;
double ppm_tolerance_;
/// Computes the convolution of the raw data at position x and the gaussian kernel
template <typename InputPeakIterator>
double integrate_(InputPeakIterator x /* mz */, InputPeakIterator y /* int */, InputPeakIterator first, InputPeakIterator last)
{
double v = 0.;
// norm the gaussian kernel area to one
double norm = 0.;
Size middle = coeffs_.size();
double start_pos = (( (*x) - (middle * spacing_)) > (*first)) ? ((*x) - (middle * spacing_)) : (*first);
double end_pos = (( (*x) + (middle * spacing_)) < (*(last - 1))) ? ((*x) + (middle * spacing_)) : (*(last - 1));
InputPeakIterator help_x = x;
InputPeakIterator help_y = y;
#ifdef DEBUG_FILTERING
std::cout << "integrate from middle to start_pos " << *help_x << " until " << start_pos << std::endl;
#endif
//integrate from middle to start_pos
while ((help_x != first) && (*(help_x - 1) > start_pos))
{
// search for the corresponding datapoint of help in the gaussian (take the left most adjacent point)
double distance_in_gaussian = fabs(*x - *help_x);
Size left_position = (Size)floor(distance_in_gaussian / spacing_);
// search for the true left adjacent data point (because of rounding errors)
for (int j = 0; ((j < 3) && (distance(first, help_x - j) >= 0)); ++j)
{
if (((left_position - j) * spacing_ <= distance_in_gaussian) && ((left_position - j + 1) * spacing_ >= distance_in_gaussian))
{
left_position -= j;
break;
}
if (((left_position + j) * spacing_ < distance_in_gaussian) && ((left_position + j + 1) * spacing_ < distance_in_gaussian))
{
left_position += j;
break;
}
}
// interpolate between the left and right data points in the gaussian to get the true value at position distance_in_gaussian
Size right_position = left_position + 1;
double d = fabs((left_position * spacing_) - distance_in_gaussian) / spacing_;
// check if the right data point in the gaussian exists
double coeffs_right = (right_position < middle) ? (1 - d) * coeffs_[left_position] + d * coeffs_[right_position]
: coeffs_[left_position];
#ifdef DEBUG_FILTERING
std::cout << "distance_in_gaussian " << distance_in_gaussian << std::endl;
std::cout << " right_position " << right_position << std::endl;
std::cout << " left_position " << left_position << std::endl;
std::cout << "coeffs_ at left_position " << coeffs_[left_position] << std::endl;
std::cout << "coeffs_ at right_position " << coeffs_[right_position] << std::endl;
std::cout << "interpolated value left " << coeffs_right << std::endl;
#endif
// search for the corresponding datapoint for (help-1) in the gaussian (take the left most adjacent point)
distance_in_gaussian = fabs((*x) - (*(help_x - 1)));
left_position = (Size)floor(distance_in_gaussian / spacing_);
// search for the true left adjacent data point (because of rounding errors)
for (UInt j = 0; ((j < 3) && (distance(first, help_x - j) >= 0)); ++j)
{
if (((left_position - j) * spacing_ <= distance_in_gaussian) && ((left_position - j + 1) * spacing_ >= distance_in_gaussian))
{
left_position -= j;
break;
}
if (((left_position + j) * spacing_ < distance_in_gaussian) && ((left_position + j + 1) * spacing_ < distance_in_gaussian))
{
left_position += j;
break;
}
}
// start the interpolation for the true value in the gaussian
right_position = left_position + 1;
d = fabs((left_position * spacing_) - distance_in_gaussian) / spacing_;
double coeffs_left = (right_position < middle) ? (1 - d) * coeffs_[left_position] + d * coeffs_[right_position]
: coeffs_[left_position];
#ifdef DEBUG_FILTERING
std::cout << " help_x-1 " << *(help_x - 1) << " distance_in_gaussian " << distance_in_gaussian << std::endl;
std::cout << " right_position " << right_position << std::endl;
std::cout << " left_position " << left_position << std::endl;
std::cout << "coeffs_ at left_position " << coeffs_[left_position] << std::endl;
std::cout << "coeffs_ at right_position " << coeffs_[right_position] << std::endl;
std::cout << "interpolated value right " << coeffs_left << std::endl;
std::cout << " intensity " << fabs(*(help_x - 1) - (*help_x)) / 2. << " * " << *(help_y - 1) << " * " << coeffs_left << " + " << *help_y << "* " << coeffs_right
<< std::endl;
#endif
norm += fabs((*(help_x - 1)) - (*help_x)) / 2. * (coeffs_left + coeffs_right);
v += fabs((*(help_x - 1)) - (*help_x)) / 2. * (*(help_y - 1) * coeffs_left + (*help_y) * coeffs_right);
--help_x;
--help_y;
}
//integrate from middle to end_pos
help_x = x;
help_y = y;
#ifdef DEBUG_FILTERING
std::cout << "integrate from middle to endpos " << *help_x << " until " << end_pos << std::endl;
#endif
while ((help_x != (last - 1)) && (*(help_x + 1) < end_pos))
{
// search for the corresponding datapoint for help in the gaussian (take the left most adjacent point)
double distance_in_gaussian = fabs((*x) - (*help_x));
int left_position = (UInt)floor(distance_in_gaussian / spacing_);
// search for the true left adjacent data point (because of rounding errors)
for (int j = 0; ((j < 3) && (distance(help_x + j, last - 1) >= 0)); ++j)
{
if (((left_position - j) * spacing_ <= distance_in_gaussian) && ((left_position - j + 1) * spacing_ >= distance_in_gaussian))
{
left_position -= j;
break;
}
if (((left_position + j) * spacing_ < distance_in_gaussian) && ((left_position + j + 1) * spacing_ < distance_in_gaussian))
{
left_position += j;
break;
}
}
// start the interpolation for the true value in the gaussian
Size right_position = left_position + 1;
double d = fabs((left_position * spacing_) - distance_in_gaussian) / spacing_;
double coeffs_left = (right_position < middle) ? (1 - d) * coeffs_[left_position] + d * coeffs_[right_position]
: coeffs_[left_position];
#ifdef DEBUG_FILTERING
std::cout << " help " << *help_x << " distance_in_gaussian " << distance_in_gaussian << std::endl;
std::cout << " left_position " << left_position << std::endl;
std::cout << "coeffs_ at right_position " << coeffs_[left_position] << std::endl;
std::cout << "coeffs_ at left_position " << coeffs_[right_position] << std::endl;
std::cout << "interpolated value left " << coeffs_left << std::endl;
#endif
// search for the corresponding datapoint for (help+1) in the gaussian (take the left most adjacent point)
distance_in_gaussian = fabs((*x) - (*(help_x + 1)));
left_position = (UInt)floor(distance_in_gaussian / spacing_);
// search for the true left adjacent data point (because of rounding errors)
for (int j = 0; ((j < 3) && (distance(help_x + j, last - 1) >= 0)); ++j)
{
if (((left_position - j) * spacing_ <= distance_in_gaussian) && ((left_position - j + 1) * spacing_ >= distance_in_gaussian))
{
left_position -= j;
break;
}
if (((left_position + j) * spacing_ < distance_in_gaussian) && ((left_position + j + 1) * spacing_ < distance_in_gaussian))
{
left_position += j;
break;
}
}
// start the interpolation for the true value in the gaussian
right_position = left_position + 1;
d = fabs((left_position * spacing_) - distance_in_gaussian) / spacing_;
double coeffs_right = (right_position < middle) ? (1 - d) * coeffs_[left_position] + d * coeffs_[right_position]
: coeffs_[left_position];
#ifdef DEBUG_FILTERING
std::cout << " (help + 1) " << *(help_x + 1) << " distance_in_gaussian " << distance_in_gaussian << std::endl;
std::cout << " left_position " << left_position << std::endl;
std::cout << "coeffs_ at right_position " << coeffs_[left_position] << std::endl;
std::cout << "coeffs_ at left_position " << coeffs_[right_position] << std::endl;
std::cout << "interpolated value right " << coeffs_right << std::endl;
std::cout << " intensity " << fabs(*help_x - *(help_x + 1)) / 2.
<< " * " << *help_y << " * " << coeffs_left << " + " << *(help_y + 1)
<< "* " << coeffs_right
<< std::endl;
#endif
norm += fabs((*help_x) - (*(help_x + 1)) ) / 2. * (coeffs_left + coeffs_right);
v += fabs((*help_x) - (*(help_x + 1)) ) / 2. * ((*help_y) * coeffs_left + (*(help_y + 1)) * coeffs_right);
++help_x;
++help_y;
}
if (v > 0)
{
return v / norm;
}
else
{
return 0;
}
}
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/PROCESSING/SMOOTHING/SavitzkyGolayFilter.h | .h | 8,729 | 234 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Eva Lange $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/KERNEL/Mobilogram.h>
#include <OpenMS/KERNEL/MSExperiment.h>
namespace OpenMS
{
/**
@brief Computes the Savitzky-Golay filter coefficients using QR decomposition.
This class represents a Savitzky-Golay lowpass-filter. The idea of the Savitzky-Golay filter
is to find filtercoefficients that preserve higher moments, which means to approximate the underlying
function within the moving window by a polynomial of higher order (typically quadratic or quartic).
Therefore we least-squares fit for each data point a polynomial to all points \f$ f_i \f$ in the window
and set \f$g_i\f$ to be the value of that polynomial at position \f$ i \f$. This method is superior
to adjacent averaging because it tends to preserve features of the data such as peak height and width, which
are usually 'washed out' by adjacent averaging.
Because of the linearity of the problem, we can reduce the work computing by fitting in advance, for fictious data
consisting of all zeros except for a singe 1 and then do the fits on the real data just by taking linear
combinations. There are a particular sets of filter coefficients \f$ c_n \f$ which accomplish the process of
polynomial least-squares fit inside a moving window. To get the symmetric coefficient-matrix
\f$C \in R^{frameSize \times frameSize}\f$ with
\f[ C= \left[ \begin{array}{cccc} c_{0,0} & c_{0,1} & \cdots & c_{0,frameSize-1} \\
\vdots & & & \vdots \\
c_{frameSize-1,0} & c_{frameSize-1,2} & \ldots & c_{frameSize-1,frameSize-1} \end{array} \right]\f]
The first (last) \f$ \frac{frameSize}{2} \f$ rows of \f$ C \f$ we need to smooth the first (last)
\f$ frameSize \f$ data points of the signal. So we use for the smoothing of the first data point the data
point itself and the next \f$ frameSize-1 \f$ future points. For the second point we take the first datapoint,
the data point itself and \f$ frameSize-2 \f$ of rightward data points... .
We compute the Matrix \f$ C \f$ by solving the underlying least-squares problems with the singular value decomposition.
Here we demonstrate the computation of the first row of a coefficient-matrix \f$ C \f$ for a Savitzky-Golay Filter
of order=3 and frameSize=5:
The design-matrix for the least-squares fit of a linear combination of 3 basis functions to 5 data points is:
\f[ A=\left[ \begin{array}{ccc} x_0^0 & x_0^1 & x_0^2 \\ \\
x_1^0 & x_1^1 & x_1^2 \\ \\
x_2^0 & x_2^1 & x_2^2 \\ \\
x_3^0 & x_3^1 & x_3^2 \\ \\
x_4^0 & x_4^1 & x_4^2 \end{array} \right]. \f]
To smooth the first data point we have to create a design-matrix with \f$ x=[0,\ldots, frameSize-1] \f$.
Now we have to solve the over-determined set of \f$ frameSize \f$ linear equations
\f[ Ac=b \f]
where \f$ b=[1,0,\ldots,0] \f$ represents the fictious data.
Therefore we solve the normal equations of the least-squares problem
\f[ A^TAc=A^Tb. \f]
Now, it is possible to get
\f[ c_n=\sum_{m=0}^8 \{(A^TA)^{-1}\}_{0,m} n^m, \f]
with \f$ 0\le n \le 8\f$. Because we only need one row of the inverse matrix, it is possible to use LU decomposition with
only a single backsubstitution.
The vector \f$c=[c_0,\ldots,c_8] \f$ represents the wanted coefficients.
Note that the solution of a least-squares problem directly from the normal equations is faster than the singular value
decomposition but rather susceptible to roundoff error!
@note This filter works only for uniform profile data!
A polynomial order of 4 is recommended.
The bigger the frame size the smoother the signal (the more detail information get lost!). The frame size corresponds to the number
of filter coefficients, so the width of the smoothing interval is given by frame_size*spacing of the profile data.
@note The data must be sorted according to ascending m/z!
@htmlinclude OpenMS_SavitzkyGolayFilter.parameters
@ingroup SignalProcessing
*/
class OPENMS_DLLAPI SavitzkyGolayFilter :
public ProgressLogger,
public DefaultParamHandler
{
public:
/// Constructor
SavitzkyGolayFilter();
/// Destructor
~SavitzkyGolayFilter() override;
// low level template to filters spectra and chromatograms
// raw data and meta data needs to be copied to the output container before calling this function
template<class InputIt, class OutputIt>
void filter(InputIt first, InputIt last, OutputIt d_first)
{
size_t n = std::distance(first, last);
if (frame_size_ > n) { return; }
int i;
UInt j;
int mid = (frame_size_ / 2);
double help;
// compute the transient on
OutputIt out_it = d_first;
for (i = 0; i <= mid; ++i)
{
InputIt it_forward = (first - i);
help = 0;
for (j = 0; j < frame_size_; ++j)
{
help += it_forward->getIntensity() * coeffs_[(i + 1) * frame_size_ - 1 - j];
++it_forward;
}
out_it->setPosition(first->getPosition());
out_it->setIntensity(std::max(0.0, help));
++out_it;
++first;
}
// compute the steady state output
InputIt it_help = (last - mid);
while (first != it_help)
{
InputIt it_forward = (first - mid);
help = 0;
for (j = 0; j < frame_size_; ++j)
{
help += it_forward->getIntensity() * coeffs_[mid * frame_size_ + j];
++it_forward;
}
out_it->setPosition(first->getPosition());
out_it->setIntensity(std::max(0.0, help));
++out_it;
++first;
}
// compute the transient off
for (i = (mid - 1); i >= 0; --i)
{
InputIt it_forward = (first - (frame_size_ - i - 1));
help = 0;
for (j = 0; j < frame_size_; ++j)
{
help += it_forward->getIntensity() * coeffs_[i * frame_size_ + j];
++it_forward;
}
out_it->setPosition(first->getPosition());
out_it->setIntensity(std::max(0.0, help));
++out_it;
++first;
}
}
/**
@brief Removed the noise from an MSSpectrum containing profile data.
*/
void filter(MSSpectrum & spectrum)
{
// copy the data AND META DATA to the output container
MSSpectrum output = spectrum;
// filter
filter(spectrum.begin(), spectrum.end(), output.begin());
// swap back
std::swap(spectrum, output);
}
/**
@brief Removed the noise from an MSChromatogram
*/
void filter(MSChromatogram & chromatogram)
{
// copy the data AND META DATA to the output container
MSChromatogram output = chromatogram;
// filter
filter(chromatogram.begin(), chromatogram.end(), output.begin());
// swap back
std::swap(chromatogram, output);
}
/**
@brief Removed the noise from an Mobilogram
*/
void filter(Mobilogram & mobilogram)
{
// copy the data AND META DATA to the output container
Mobilogram output = mobilogram;
// filter
filter(mobilogram.begin(), mobilogram.end(), output.begin());
// swap back
std::swap(mobilogram, output);
}
/**
@brief Removed the noise from an MSExperiment containing profile data.
*/
void filterExperiment(PeakMap & map)
{
Size progress = 0;
startProgress(0, map.size() + map.getChromatograms().size(), "smoothing data");
for (Size i = 0; i < map.size(); ++i)
{
filter(map[i]);
setProgress(++progress);
}
for (Size i = 0; i < map.getChromatograms().size(); ++i)
{
filter(map.getChromatogram(i));
setProgress(++progress);
}
endProgress();
}
protected:
/// Coefficients
std::vector<double> coeffs_;
/// UInt of the filter kernel (number of pre-tabulated coefficients)
UInt frame_size_;
/// The order of the smoothing polynomial.
UInt order_;
// Docu in base class
void updateMembers_() override;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/PROCESSING/NOISEESTIMATION/SignalToNoiseEstimatorMedian.h | .h | 17,741 | 416 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: $
// --------------------------------------------------------------------------
//
#pragma once
#include <OpenMS/PROCESSING/NOISEESTIMATION/SignalToNoiseEstimator.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
#include <vector>
#include <algorithm> //for std::max_element
namespace OpenMS
{
/**
@brief Estimates the signal/noise (S/N) ratio of each data point in a scan by using the median (histogram based)
For each datapoint in the given scan, we collect a range of data points
around it (param: <i>win_len</i>). The noise for a datapoint is estimated
to be the median of the intensities of the current window. If the number
of elements in the current window is not sufficient (param:
<i>MinReqElements</i>), the noise level is set to a default value (param:
<i>noise_for_empty_window</i>). The whole computation is histogram based,
so the user will need to supply a number of bins (param: <i>bin_count</i>),
which determines the level of error and runtime. The maximal intensity for
a datapoint to be included in the histogram can be either determined
automatically (params: <i>AutoMaxIntensity</i>, <i>auto_mode</i>) by two
different methods or can be set directly by the user (param:
<i>max_intensity</i>).
If the (estimated) <i>max_intensity</i> value is too low and the median is
found to be in the last (&highest) bin, a warning will be given. In this
case you should increase <i>max_intensity</i> (and optionally the
<i>bin_count</i>).
Changing any of the parameters will invalidate the S/N values (which will invoke a recomputation on the next request).
@note If more than 20 percent of windows have less than <i>min_required_elements</i> of elements, a warning is issued to <i>OPENMS_LOG_WARN</i> and noise estimates in those windows are set to the constant <i>noise_for_empty_window</i>.
@note If more than 1 percent of median estimations had to rely on the last(=rightmost) bin (which gives an unreliable result), a warning is issued to <i>OPENMS_LOG_WARN</i>. In this case you should increase <i>max_intensity</i> (and optionally the <i>bin_count</i>).
@note You can disable logging this error by setting <i>write_log_messages</i> and read out the values
@htmlinclude OpenMS_SignalToNoiseEstimatorMedian.parameters
@ingroup SignalProcessing
*/
template <typename Container = MSSpectrum>
class SignalToNoiseEstimatorMedian :
public SignalToNoiseEstimator<Container>
{
public:
/// method to use for estimating the maximal intensity that is used for histogram calculation
enum IntensityThresholdCalculation {MANUAL = -1, AUTOMAXBYSTDEV = 0, AUTOMAXBYPERCENT = 1};
using SignalToNoiseEstimator<Container>::stn_estimates_;
using SignalToNoiseEstimator<Container>::defaults_;
using SignalToNoiseEstimator<Container>::param_;
typedef typename SignalToNoiseEstimator<Container>::PeakIterator PeakIterator;
typedef typename SignalToNoiseEstimator<Container>::PeakType PeakType;
typedef typename SignalToNoiseEstimator<Container>::GaussianEstimate GaussianEstimate;
/// default constructor
inline SignalToNoiseEstimatorMedian()
{
//set the name for DefaultParamHandler error messages
this->setName("SignalToNoiseEstimatorMedian");
defaults_.setValue("max_intensity", -1, "maximal intensity considered for histogram construction. By default, it will be calculated automatically (see auto_mode)." \
" Only provide this parameter if you know what you are doing (and change 'auto_mode' to '-1')!" \
" All intensities EQUAL/ABOVE 'max_intensity' will be added to the LAST histogram bin." \
" If you choose 'max_intensity' too small, the noise estimate might be too small as well. " \
" If chosen too big, the bins become quite large (which you could counter by increasing 'bin_count', which increases runtime)." \
" In general, the Median-S/N estimator is more robust to a manual max_intensity than the MeanIterative-S/N.", {"advanced"});
defaults_.setMinInt("max_intensity", -1);
defaults_.setValue("auto_max_stdev_factor", 3.0, "parameter for 'max_intensity' estimation (if 'auto_mode' == 0): mean + 'auto_max_stdev_factor' * stdev", {"advanced"});
defaults_.setMinFloat("auto_max_stdev_factor", 0.0);
defaults_.setMaxFloat("auto_max_stdev_factor", 999.0);
defaults_.setValue("auto_max_percentile", 95, "parameter for 'max_intensity' estimation (if 'auto_mode' == 1): auto_max_percentile th percentile", {"advanced"});
defaults_.setMinInt("auto_max_percentile", 0);
defaults_.setMaxInt("auto_max_percentile", 100);
defaults_.setValue("auto_mode", 0, "method to use to determine maximal intensity: -1 --> use 'max_intensity'; 0 --> 'auto_max_stdev_factor' method (default); 1 --> 'auto_max_percentile' method", {"advanced"});
defaults_.setMinInt("auto_mode", -1);
defaults_.setMaxInt("auto_mode", 1);
defaults_.setValue("win_len", 200.0, "window length in Thomson");
defaults_.setMinFloat("win_len", 1.0);
defaults_.setValue("bin_count", 30, "number of bins for intensity values");
defaults_.setMinInt("bin_count", 3);
defaults_.setValue("min_required_elements", 10, "minimum number of elements required in a window (otherwise it is considered sparse)");
defaults_.setMinInt("min_required_elements", 1);
defaults_.setValue("noise_for_empty_window", std::pow(10.0, 20), "noise value used for sparse windows", {"advanced"});
defaults_.setValue("write_log_messages", "true", "Write out log messages in case of sparse windows or median in rightmost histogram bin");
defaults_.setValidStrings("write_log_messages", {"true","false"});
SignalToNoiseEstimator<Container>::defaultsToParam_();
}
/// Copy Constructor
inline SignalToNoiseEstimatorMedian(const SignalToNoiseEstimatorMedian & source) :
SignalToNoiseEstimator<Container>(source)
{
updateMembers_();
}
/** @name Assignment
*/
//@{
///
inline SignalToNoiseEstimatorMedian & operator=(const SignalToNoiseEstimatorMedian & source)
{
if (&source == this) return *this;
SignalToNoiseEstimator<Container>::operator=(source);
updateMembers_();
return *this;
}
//@}
/// Destructor
~SignalToNoiseEstimatorMedian() override
{}
/// Returns how many percent of the windows were sparse
double getSparseWindowPercent() const
{
return sparse_window_percent_;
}
/// Returns the percentage where the median was found in the rightmost bin
double getHistogramRightmostPercent() const
{
return histogram_oob_percent_;
}
protected:
/** Calculate signal-to-noise values for all data points given, by using a sliding window approach
@param[in] c Raw data, usually an MSSpectrum
@exception Throws Exception::InvalidValue
*/
void computeSTN_(const Container& c) override
{
//first element in the scan
PeakIterator scan_first_ = c.begin();
//last element in the scan
PeakIterator scan_last_ = c.end();
// reset counter for sparse windows
sparse_window_percent_ = 0;
// reset counter for histogram overflow
histogram_oob_percent_ = 0;
// reset the results
stn_estimates_.clear();
stn_estimates_.resize(c.size());
// maximal range of histogram needs to be calculated first
if (auto_mode_ == AUTOMAXBYSTDEV)
{
// use MEAN+auto_max_intensity_*STDEV as threshold
GaussianEstimate gauss_global = SignalToNoiseEstimator<Container>::estimate_(scan_first_, scan_last_);
max_intensity_ = gauss_global.mean + std::sqrt(gauss_global.variance) * auto_max_stdev_Factor_;
}
else if (auto_mode_ == AUTOMAXBYPERCENT)
{
// get value at "auto_max_percentile_"th percentile
// we use a histogram approach here as well.
if ((auto_max_percentile_ < 0) || (auto_max_percentile_ > 100))
{
String s = auto_max_percentile_;
throw Exception::InvalidValue(__FILE__,
__LINE__,
OPENMS_PRETTY_FUNCTION,
"auto_mode is on AUTOMAXBYPERCENT! auto_max_percentile is not in [0,100]. Use setAutoMaxPercentile(<value>) to change it!",
s);
}
std::vector<int> histogram_auto(100, 0);
// find maximum of current scan
auto maxIt = std::max_element(c.begin(), c.end() ,[](const PeakType& a, const PeakType& b){ return a.getIntensity() > b.getIntensity();});
typename PeakType::IntensityType maxInt = maxIt->getIntensity();
double bin_size = maxInt / 100;
// fill histogram
for(const auto& peak : c)
{
++histogram_auto[(int) ((peak.getIntensity() - 1) / bin_size)];
}
// add up element counts in histogram until ?th percentile is reached
int elements_below_percentile = (int) (auto_max_percentile_ * c.size() / 100);
int elements_seen = 0;
int i = -1;
PeakIterator run = scan_first_;
while (run != scan_last_ && elements_seen < elements_below_percentile)
{
++i;
elements_seen += histogram_auto[i];
++run;
}
max_intensity_ = (((double)i) + 0.5) * bin_size;
}
else //if (auto_mode_ == MANUAL)
{
if (max_intensity_ <= 0)
{
String s = max_intensity_;
throw Exception::InvalidValue(__FILE__,
__LINE__,
OPENMS_PRETTY_FUNCTION,
"auto_mode is on MANUAL! max_intensity is <=0. Needs to be positive! Use setMaxIntensity(<value>) or enable auto_mode!",
s);
}
}
if (max_intensity_ < 0)
{
std::cerr << "TODO SignalToNoiseEstimatorMedian: the max_intensity_ value should be positive! " << max_intensity_ << std::endl;
return;
}
PeakIterator window_pos_center = scan_first_;
PeakIterator window_pos_borderleft = scan_first_;
PeakIterator window_pos_borderright = scan_first_;
double window_half_size = win_len_ / 2;
double bin_size = std::max(1.0, max_intensity_ / bin_count_); // at least size of 1 for intensity bins
int bin_count_minus_1 = bin_count_ - 1;
std::vector<int> histogram(bin_count_, 0);
std::vector<double> bin_value(bin_count_, 0);
// calculate average intensity that is represented by a bin
for (int bin = 0; bin < bin_count_; bin++)
{
histogram[bin] = 0;
bin_value[bin] = (bin + 0.5) * bin_size;
}
// bin in which a datapoint would fall
int to_bin = 0;
// index of bin where the median is located
int median_bin = 0;
// additive number of elements from left to x in histogram
int element_inc_count = 0;
// tracks elements in current window, which may vary because of unevenly spaced data
int elements_in_window = 0;
// number of windows
int window_count = 0;
// number of elements where we find the median
int element_in_window_half = 0;
double noise; // noise value of a datapoint
///start progress estimation
SignalToNoiseEstimator<Container>::startProgress(0, c.size(), "noise estimation of data");
// MAIN LOOP
while (window_pos_center != scan_last_)
{
// erase all elements from histogram that will leave the window on the LEFT side
while ((*window_pos_borderleft).getPos() < (*window_pos_center).getPos() - window_half_size)
{
to_bin = std::max(std::min<int>((int)((*window_pos_borderleft).getIntensity() / bin_size), bin_count_minus_1), 0);
--histogram[to_bin];
--elements_in_window;
++window_pos_borderleft;
}
// add all elements to histogram that will enter the window on the RIGHT side
while ((window_pos_borderright != scan_last_)
&& ((*window_pos_borderright).getPos() <= (*window_pos_center).getPos() + window_half_size))
{
//std::cerr << (*window_pos_borderright).getIntensity() << " " << bin_size << " " << bin_count_minus_1 << std::endl;
to_bin = std::max(std::min<int>((int)((*window_pos_borderright).getIntensity() / bin_size), bin_count_minus_1), 0);
++histogram[to_bin];
++elements_in_window;
++window_pos_borderright;
}
if (elements_in_window < min_required_elements_)
{
noise = noise_for_empty_window_;
++sparse_window_percent_;
}
else
{
// find bin i where ceil[elements_in_window/2] <= sum_c(0..i){ histogram[c] }
median_bin = -1;
element_inc_count = 0;
element_in_window_half = (elements_in_window + 1) / 2;
while (median_bin < bin_count_minus_1 && element_inc_count < element_in_window_half)
{
++median_bin;
element_inc_count += histogram[median_bin];
}
// increase the error count
if (median_bin == bin_count_minus_1) {++histogram_oob_percent_; }
// just avoid division by 0
noise = std::max(1.0, bin_value[median_bin]);
}
// store result
stn_estimates_[window_count] = (*window_pos_center).getIntensity() / noise;
// advance the window center by one datapoint
++window_pos_center;
++window_count;
// update progress
SignalToNoiseEstimator<Container>::setProgress(window_count);
} // end while
SignalToNoiseEstimator<Container>::endProgress();
sparse_window_percent_ = sparse_window_percent_ * 100 / window_count;
histogram_oob_percent_ = histogram_oob_percent_ * 100 / window_count;
// warn if percentage of sparse windows is above 20%
if (sparse_window_percent_ > 20 && write_log_messages_)
{
OPENMS_LOG_WARN << "WARNING in SignalToNoiseEstimatorMedian: "
<< sparse_window_percent_
<< "% of all windows were sparse. You should consider increasing 'win_len' or decreasing 'min_required_elements'"
<< std::endl;
}
// warn if percentage of possibly wrong median estimates is above 1%
if (histogram_oob_percent_ > 1 && write_log_messages_)
{
OPENMS_LOG_WARN << "WARNING in SignalToNoiseEstimatorMedian: "
<< histogram_oob_percent_
<< "% of all Signal-to-Noise estimates are too high, because the median was found in the rightmost histogram-bin. "
<< "You should consider increasing 'max_intensity' (and maybe 'bin_count' with it, to keep bin width reasonable)"
<< std::endl;
}
} // end of shiftWindow_
/// overridden function from DefaultParamHandler to keep members up to date, when a parameter is changed
void updateMembers_() override
{
max_intensity_ = (double)param_.getValue("max_intensity");
auto_max_stdev_Factor_ = (double)param_.getValue("auto_max_stdev_factor");
auto_max_percentile_ = param_.getValue("auto_max_percentile");
auto_mode_ = param_.getValue("auto_mode");
win_len_ = (double)param_.getValue("win_len");
bin_count_ = param_.getValue("bin_count");
min_required_elements_ = param_.getValue("min_required_elements");
noise_for_empty_window_ = (double)param_.getValue("noise_for_empty_window");
write_log_messages_ = (bool)param_.getValue("write_log_messages").toBool();
stn_estimates_.clear();
}
/// maximal intensity considered during binning (values above get discarded)
double max_intensity_;
/// parameter for initial automatic estimation of "max_intensity_": a stdev multiplier
double auto_max_stdev_Factor_;
/// parameter for initial automatic estimation of "max_intensity_" percentile or a stdev
double auto_max_percentile_;
/// determines which method shall be used for estimating "max_intensity_". valid are MANUAL=-1, AUTOMAXBYSTDEV=0 or AUTOMAXBYPERCENT=1
int auto_mode_;
/// range of data points which belong to a window in Thomson
double win_len_;
/// number of bins in the histogram
int bin_count_;
/// minimal number of elements a window needs to cover to be used
int min_required_elements_;
/// used as noise value for windows which cover less than "min_required_elements_"
/// use a very high value if you want to get a low S/N result
double noise_for_empty_window_;
// whether to write out log messages in the case of failure
bool write_log_messages_;
// counter for sparse windows
double sparse_window_percent_;
// counter for histogram overflow
double histogram_oob_percent_;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/PROCESSING/NOISEESTIMATION/SignalToNoiseEstimatorMeanIterative.h | .h | 17,076 | 406 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: $
// --------------------------------------------------------------------------
//
#pragma once
#include <OpenMS/PROCESSING/NOISEESTIMATION/SignalToNoiseEstimator.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/DATASTRUCTURES/ListUtils.h>
#include <vector>
#include <algorithm> //for std::max_element
namespace OpenMS
{
/**
@brief Estimates the signal/noise (S/N) ratio of each data point in a scan
based on an iterative scheme which discards high intensities
For each datapoint in the given scan, we collect a range of data points around it (param: <i>win_len</i>).
The noise for a datapoint is estimated iteratively by discarding peaks which are more than
(<i>stdev_mp</i> * StDev) above the mean value. After three iterations, the mean value is
considered to be the noise level. If the number of elements in the current window is not sufficient (param: <i>min_required_elements</i>),
the noise level is set to a default value (param: <i>noise_for_empty_window</i>).
The whole computation is histogram based, so the user will need to supply a number of bins (param: <i>bin_count</i>), which determines
the level of error and runtime. The maximal intensity for a datapoint to be included in the histogram can be either determined
automatically (param: <i>auto_mode</i>) by two different methods or can be set directly by the user (param: <i>max_intensity</i>).
Changing any of the parameters will invalidate the S/N values (which will invoke a recomputation on the next request).
@note If more than 20 percent of windows have less than <i>min_required_elements</i> of elements, a warning is issued to <i>stderr</i> and noise estimates in those windows are set to the constant <i>noise_for_empty_window</i>.
@htmlinclude OpenMS_SignalToNoiseEstimatorMeanIterative.parameters
@ingroup SignalProcessing
*/
template <typename Container = MSSpectrum>
class SignalToNoiseEstimatorMeanIterative :
public SignalToNoiseEstimator<Container>
{
public:
/// method to use for estimating the maximal intensity that is used for histogram calculation
enum IntensityThresholdCalculation {MANUAL = -1, AUTOMAXBYSTDEV = 0, AUTOMAXBYPERCENT = 1};
using SignalToNoiseEstimator<Container>::stn_estimates_;
using SignalToNoiseEstimator<Container>::defaults_;
using SignalToNoiseEstimator<Container>::param_;
typedef typename SignalToNoiseEstimator<Container>::PeakIterator PeakIterator;
typedef typename SignalToNoiseEstimator<Container>::PeakType PeakType;
typedef typename SignalToNoiseEstimator<Container>::GaussianEstimate GaussianEstimate;
/// default constructor
inline SignalToNoiseEstimatorMeanIterative()
{
//set the name for DefaultParamHandler error messages
this->setName("SignalToNoiseEstimatorMeanIterative");
defaults_.setValue("max_intensity", -1, "maximal intensity considered for histogram construction. By default, it will be calculated automatically (see auto_mode)." \
" Only provide this parameter if you know what you are doing (and change 'auto_mode' to '-1')!" \
" All intensities EQUAL/ABOVE 'max_intensity' will not be added to the histogram." \
" If you choose 'max_intensity' too small, the noise estimate might be too small as well." \
" If chosen too big, the bins become quite large (which you could counter by increasing 'bin_count', which increases runtime).", {"advanced"});
defaults_.setMinInt("max_intensity", -1);
defaults_.setValue("auto_max_stdev_factor", 3.0, "parameter for 'max_intensity' estimation (if 'auto_mode' == 0): mean + 'auto_max_stdev_factor' * stdev", {"advanced"});
defaults_.setMinFloat("auto_max_stdev_factor", 0.0);
defaults_.setMaxFloat("auto_max_stdev_factor", 999.0);
defaults_.setValue("auto_max_percentile", 95, "parameter for 'max_intensity' estimation (if 'auto_mode' == 1): auto_max_percentile th percentile", {"advanced"});
defaults_.setMinInt("auto_max_percentile", 0);
defaults_.setMaxInt("auto_max_percentile", 100);
defaults_.setValue("auto_mode", 0, "method to use to determine maximal intensity: -1 --> use 'max_intensity'; 0 --> 'auto_max_stdev_factor' method (default); 1 --> 'auto_max_percentile' method", {"advanced"});
defaults_.setMinInt("auto_mode", -1);
defaults_.setMaxInt("auto_mode", 1);
defaults_.setValue("win_len", 200.0, "window length in Thomson");
defaults_.setMinFloat("win_len", 1.0);
defaults_.setValue("bin_count", 30, "number of bins for intensity values");
defaults_.setMinInt("bin_count", 3);
defaults_.setValue("stdev_mp", 3.0, "multiplier for stdev", {"advanced"});
defaults_.setMinFloat("stdev_mp", 0.01);
defaults_.setMaxFloat("stdev_mp", 999.0);
defaults_.setValue("min_required_elements", 10, "minimum number of elements required in a window (otherwise it is considered sparse)");
defaults_.setMinInt("min_required_elements", 1);
defaults_.setValue("noise_for_empty_window", std::pow(10.0, 20), "noise value used for sparse windows", {"advanced"});
SignalToNoiseEstimator<Container>::defaultsToParam_();
}
/// Copy Constructor
inline SignalToNoiseEstimatorMeanIterative(const SignalToNoiseEstimatorMeanIterative & source) :
SignalToNoiseEstimator<Container>(source)
{
updateMembers_();
}
/** @name Assignment
*/
//@{
///
inline SignalToNoiseEstimatorMeanIterative & operator=(const SignalToNoiseEstimatorMeanIterative & source)
{
if (&source == this) return *this;
SignalToNoiseEstimator<Container>::operator=(source);
updateMembers_();
return *this;
}
//@}
/// Destructor
~SignalToNoiseEstimatorMeanIterative() override
{}
protected:
/** calculate StN values for all datapoints given, by using a sliding window approach
@param[in] c raw data
@exception Throws Exception::InvalidValue
*/
void computeSTN_(const Container& c) override
{
//first element in the scan
PeakIterator scan_first_ = c.begin();
//last element in the scan
PeakIterator scan_last_ = c.end();
// reset counter for sparse windows
double sparse_window_percent = 0;
// reset the results
stn_estimates_.clear();
stn_estimates_.resize(c.size());
// maximal range of histogram needs to be calculated first
if (auto_mode_ == AUTOMAXBYSTDEV)
{
// use MEAN+auto_max_intensity_*STDEV as threshold
GaussianEstimate gauss_global = SignalToNoiseEstimator<Container>::estimate_(scan_first_, scan_last_);
max_intensity_ = gauss_global.mean + std::sqrt(gauss_global.variance) * auto_max_stdev_Factor_;
}
else if (auto_mode_ == AUTOMAXBYPERCENT)
{
// get value at "auto_max_percentile_"th percentile
// we use a histogram approach here as well.
if ((auto_max_percentile_ < 0) || (auto_max_percentile_ > 100))
{
String s = auto_max_percentile_;
throw Exception::InvalidValue(__FILE__,
__LINE__,
OPENMS_PRETTY_FUNCTION,
"auto_mode is on AUTOMAXBYPERCENT! auto_max_percentile is not in [0,100]. Use setAutoMaxPercentile(<value>) to change it!",
s);
}
std::vector<int> histogram_auto(100, 0);
// find maximum of current scan
auto maxIt = std::max_element(c.begin(), c.end() ,[](const PeakType& a, const PeakType& b){ return a.getIntensity() > b.getIntensity();});
typename PeakType::IntensityType maxInt = maxIt->getIntensity();
double bin_size = maxInt / 100;
// fill histogram
for(auto& run : c)
{
++histogram_auto[(int) (((run).getIntensity() - 1) / bin_size)];
}
// add up element counts in histogram until ?th percentile is reached
int elements_below_percentile = (int) (auto_max_percentile_ * c.size() / 100);
int elements_seen = 0;
int i = -1;
PeakIterator run = scan_first_;
while (run != scan_last_ && elements_seen < elements_below_percentile)
{
++i;
elements_seen += histogram_auto[i];
++run;
}
max_intensity_ = (((double)i) + 0.5) * bin_size;
}
else //if (auto_mode_ == MANUAL)
{
if (max_intensity_ <= 0)
{
String s = max_intensity_;
throw Exception::InvalidValue(__FILE__,
__LINE__,
OPENMS_PRETTY_FUNCTION,
"auto_mode is on MANUAL! max_intensity is <=0. Needs to be positive! Use setMaxIntensity(<value>) or enable auto_mode!",
s);
}
}
if (max_intensity_ < 0)
{
std::cerr << "TODO SignalToNoiseEstimatorMedian: the max_intensity_ value should be positive! " << max_intensity_ << std::endl;
return;
}
PeakIterator window_pos_center = scan_first_;
PeakIterator window_pos_borderleft = scan_first_;
PeakIterator window_pos_borderright = scan_first_;
double window_half_size = win_len_ / 2;
double bin_size = std::max(1.0, max_intensity_ / bin_count_); // at least size of 1 for intensity bins
std::vector<int> histogram(bin_count_, 0);
std::vector<double> bin_value(bin_count_, 0);
// calculate average intensity that is represented by a bin
for (int bin = 0; bin < bin_count_; bin++)
{
histogram[bin] = 0;
bin_value[bin] = (bin + 0.5) * bin_size;
}
// index of last valid bin during iteration
int hist_rightmost_bin;
// bin in which a datapoint would fall
int to_bin;
// mean & stdev of the histogram
double hist_mean;
double hist_stdev;
// tracks elements in current window, which may vary because of unevenly spaced data
int elements_in_window = 0;
int window_count = 0;
double noise; // noise value of a datapoint
///start progress estimation
SignalToNoiseEstimator<Container>::startProgress(0, c.size(), "noise estimation of data");
// MAIN LOOP
while (window_pos_center != scan_last_)
{
// erase all elements from histogram that will leave the window on the LEFT side
while ((*window_pos_borderleft).getMZ() < (*window_pos_center).getMZ() - window_half_size)
{
//std::cout << "S: " << (*window_pos_borderleft).getMZ() << " " << ( (*window_pos_center).getMZ() - window_half_size ) << "\n";
to_bin = (int) ((std::max((*window_pos_borderleft).getIntensity(), 0.0f)) / bin_size);
if (to_bin < bin_count_)
{
--histogram[to_bin];
--elements_in_window;
}
++window_pos_borderleft;
}
//std::printf("S1: %E %E\n", (*window_pos_borderright).getMZ(), (*window_pos_center).getMZ() + window_half_size);
// add all elements to histogram that will enter the window on the RIGHT side
while ((window_pos_borderright != scan_last_)
&& ((*window_pos_borderright).getMZ() < (*window_pos_center).getMZ() + window_half_size))
{
//std::printf("Sb: %E %E %E\n", (*window_pos_borderright).getMZ(), (*window_pos_center).getMZ() + window_half_size, (*window_pos_borderright).getMZ() - ((*window_pos_center).getMZ() + window_half_size));
to_bin = (int) ((std::max((*window_pos_borderright).getIntensity(), 0.0f)) / bin_size);
if (to_bin < bin_count_)
{
++histogram[to_bin];
++elements_in_window;
}
++window_pos_borderright;
}
if (elements_in_window < min_required_elements_)
{
noise = noise_for_empty_window_;
++sparse_window_percent;
}
else
{
hist_rightmost_bin = bin_count_;
// do iteration on histogram and find threshold
for (int i = 0; i < 3; ++i)
{
// mean
hist_mean = 0;
for (int bin = 0; bin < hist_rightmost_bin; ++bin)
{
//std::cout << "V: " << bin << " " << hist_mean << " " << histogram[bin] << " " << elements_in_window << " " << bin_value[bin] << "\n";
// immediate division is numerically more stable
hist_mean += histogram[bin] / (double) elements_in_window * bin_value[bin];
}
//hist_mean = hist_mean / elements_in_window;
// stdev
hist_stdev = 0;
for (int bin = 0; bin < hist_rightmost_bin; ++bin)
{
double tmp(bin_value[bin] - hist_mean);
hist_stdev += histogram[bin] / (double) elements_in_window * tmp * tmp;
}
hist_stdev = std::sqrt(hist_stdev);
//determine new threshold (i.e. the rightmost bin we consider)
int estimate = (int) ((hist_mean + hist_stdev * stdev_ - 1) / bin_size + 1);
//std::cout << "E: " << hist_mean << " " << hist_stdev << " " << stdev_ << " " << bin_size<< " " << estimate << "\n";
hist_rightmost_bin = std::min(estimate, bin_count_);
}
// just avoid division by 0
noise = std::max(1.0, hist_mean);
}
// store result
stn_estimates_[window_count] = (*window_pos_center).getIntensity() / noise;
// advance the window center by one datapoint
++window_pos_center;
++window_count;
// update progress
SignalToNoiseEstimator<Container>::setProgress(window_count);
} // end while
SignalToNoiseEstimator<Container>::endProgress();
sparse_window_percent = sparse_window_percent * 100 / window_count;
// warn if percentage of sparse windows is above 20%
if (sparse_window_percent > 20)
{
std::cerr << "WARNING in SignalToNoiseEstimatorMeanIterative: "
<< sparse_window_percent
<< "% of all windows were sparse. You should consider increasing 'win_len' or increasing 'min_required_elements'"
<< " You should also check the MaximalIntensity value (or the parameters for its heuristic estimation)"
<< " If it is too low, then too many high intensity peaks will be discarded, which leads to a sparse window!"
<< std::endl;
}
return;
} // end of shiftWindow_
/// overridden function from DefaultParamHandler to keep members up to date, when a parameter is changed
void updateMembers_() override
{
max_intensity_ = (double)param_.getValue("max_intensity");
auto_max_stdev_Factor_ = (double)param_.getValue("auto_max_stdev_factor");
auto_max_percentile_ = param_.getValue("auto_max_percentile");
auto_mode_ = param_.getValue("auto_mode");
win_len_ = (double)param_.getValue("win_len");
bin_count_ = param_.getValue("bin_count");
stdev_ = (double)param_.getValue("stdev_mp");
min_required_elements_ = param_.getValue("min_required_elements");
noise_for_empty_window_ = (double)param_.getValue("noise_for_empty_window");
stn_estimates_.clear();
}
/// maximal intensity considered during binning (values above get discarded)
double max_intensity_;
/// parameter for initial automatic estimation of "max_intensity_": a stdev multiplier
double auto_max_stdev_Factor_;
/// parameter for initial automatic estimation of "max_intensity_" percentile or a stdev
double auto_max_percentile_;
/// determines which method shall be used for estimating "max_intensity_". valid are MANUAL=-1, AUTOMAXBYSTDEV=0 or AUTOMAXBYPERCENT=1
int auto_mode_;
/// range of data points which belong to a window in Thomson
double win_len_;
/// number of bins in the histogram
int bin_count_;
/// multiplier for the stdev of intensities
double stdev_;
/// minimal number of elements a window needs to cover to be used
int min_required_elements_;
/// used as noise value for windows which cover less than "min_required_elements_"
/// use a very high value if you want to get a low S/N result
double noise_for_empty_window_;
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/PROCESSING/NOISEESTIMATION/SignalToNoiseEstimatorMedianRapid.h | .h | 6,873 | 190 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hannes Roest $
// $Authors: Hannes Roest $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/INTERFACES/DataStructures.h>
#include <OpenMS/INTERFACES/ISpectrumAccess.h>
#include <cassert>
#include <vector>
namespace OpenMS
{
/**
@brief Estimates the signal/noise (S/N) ratio of each data point in a scan by using the median (window based)
For each scan, we define a set of windows of a pre-defined size (param:
<i>window_length_</i>) in m/z domain for which the intensity median is
calculated. The noise for a data point is estimated to be the median of the
intensities of the current window.
To get a more robust noise estimate, the nose value is calculated two times
for two sets of windows that are shifted by 1/2 of the window size and the
reported noise value is the average of the two.
A call to estimateNoise will return an object of type NoiseEstimator which
then provides a function get_noise_value which will return the noise value
for a given m/z value.
The idea behind this class is to have an estimator for signal to noise that
gives similar results to SignalToNoiseEstimatorMedian but performs faster.
Note that it will not give identical results as SignalToNoiseEstimatorMedian
but for many application the results from this class will be sufficient.
@ingroup SignalProcessing
*/
class OPENMS_DLLAPI SignalToNoiseEstimatorMedianRapid
{
/// Window length parameter
double window_length_;
public:
/**
@brief Class to compute the noise value at a given position
This class implements a method to obtain the noise value at any given m/z
position. For a median based noise estimator, the noise at position m/z
is given by the median intensity in a window around this position. This
noise estimator has median estimates for a set of precomputed windows and
retrieves the appropriate noise value from the closest window. To lower
errors at the bin borders, two noise binning values are provided (for a
set of windows offset by 1/2 of the window width) and the reported value
is the average of these two values.
*/
struct OPENMS_DLLAPI NoiseEstimator
{
/// Number of windows in m/z direction for which noise values are stored
int nr_windows;
/// Start of m/z domain
double mz_start;
/// Length of the window in m/z direction
double window_length;
/// Noise values for window starting at mz_start (length = nr_windows)
std::vector<double> result_windows_even;
/// Noise values for window starting at mz_start - 0.5 * window_length (length = nr_windows + 1)
std::vector<double> result_windows_odd;
/// Constructor
NoiseEstimator() {}
/// Constructor
NoiseEstimator(double nr_windows_, double mz_start_, double win_len_) :
nr_windows(nr_windows_),
mz_start(mz_start_),
window_length(win_len_),
result_windows_even(nr_windows_),
result_windows_odd(nr_windows_+1)
{}
/**
@brief Return the noise value at a given m/z position
Will return the noise value at a given m/z position.
@note Will return 1.0 if the noise would be lower than 1.0
*/
double get_noise_value (double mz)
{
// Take the average of the two stored values
// Avoid division by 0 (since most clients will divide by the noise value)
return std::max(1.0, (get_noise_even(mz)+get_noise_odd(mz))/2.0 );
}
double get_noise_even (double mz)
{
// PRECONDITION
int window_nr = (int)((mz - mz_start)/window_length);
assert(window_nr >= 0);
assert(window_nr < (int)result_windows_even.size());
double noise = result_windows_even[window_nr];
return noise;
}
double get_noise_odd (double mz)
{
// PRECONDITION
int window_nr = (int)((mz - mz_start + window_length/2.0)/window_length);
assert(window_nr >= 0);
assert(window_nr < (int)result_windows_odd.size());
double noise = result_windows_odd[window_nr];
return noise;
}
};
/// default constructor
SignalToNoiseEstimatorMedianRapid(double window_length) :
window_length_(window_length)
{
}
/** @brief Compute noise estimator for an m/z and intensity array using windows
*
* Will return a noise estimator object.
*/
inline NoiseEstimator estimateNoise(OpenMS::Interfaces::SpectrumPtr spectrum)
{
return estimateNoise(spectrum->getMZArray()->data, spectrum->getIntensityArray()->data);
}
/** @brief Compute noise estimator for an m/z and intensity array using windows
*
* Will return a noise estimator object.
*/
inline NoiseEstimator estimateNoise(OpenMS::Interfaces::ChromatogramPtr chrom)
{
return estimateNoise(chrom->getTimeArray()->data, chrom->getIntensityArray()->data);
}
/** @brief Compute noise estimator for an m/z and intensity array using windows
*
* Will return a noise estimator object.
*/
NoiseEstimator estimateNoise(const std::vector<double>& mz_array, const std::vector<double>& int_array)
{
// PRECONDITION
assert(mz_array.size() == int_array.size());
assert(mz_array.size() > 2);
int nr_windows = (int)((mz_array[mz_array.size()-1] - mz_array[0])/window_length_) + 1;
NoiseEstimator eval(nr_windows, mz_array[0], window_length_);
// Compute even windows
computeNoiseInWindows_(mz_array, int_array, eval.result_windows_even, mz_array[0]);
// Compute odd windows
computeNoiseInWindows_(mz_array, int_array, eval.result_windows_odd, mz_array[0] - window_length_/2.0);
return eval;
}
private:
/** @brief Computes the noise in windows for two input arrays and stores the median intensity in the result (internal)
*
* Note that int_array is copied on purpose, since it is modified while sorting, a copy is needed.
*
*/
void computeNoiseInWindows_(const std::vector<double>& mz_array, std::vector<double> int_array, std::vector<double> & result, double mz_start);
/** @brief Median computation on a part of an array [first,last)
*
* @note Does not guarantee that the elements between [first, last) are in the
* same order as before (they most likely will not be).
*
*/
double computeMedian_(std::vector<double>::iterator & first, std::vector<double>::iterator & last);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/PROCESSING/NOISEESTIMATION/SignalToNoiseEstimator.h | .h | 4,252 | 155 | // 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/KERNEL/MSSpectrum.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <vector>
#include <cmath>
namespace OpenMS
{
class MSExperiment;
/**
@brief This class represents the abstract base class of a signal to noise estimator.
A signal to noise estimator should provide the signal to noise ratio of all raw data points
in a given interval [first_,last_).
*/
template <typename Container = MSSpectrum>
class SignalToNoiseEstimator :
public DefaultParamHandler, public ProgressLogger
{
public:
/** @name Type definitions
*/
//@{
typedef typename Container::const_iterator PeakIterator;
typedef typename PeakIterator::value_type PeakType;
//@}
/// Constructor
inline SignalToNoiseEstimator() :
DefaultParamHandler("SignalToNoiseEstimator"),
ProgressLogger()
{
}
/// Copy constructor
inline SignalToNoiseEstimator(const SignalToNoiseEstimator & source) :
DefaultParamHandler(source),
ProgressLogger(source),
stn_estimates_(source.stn_estimates_)
{}
/// Assignment operator
inline SignalToNoiseEstimator & operator=(const SignalToNoiseEstimator & source)
{
if (&source == this) return *this;
DefaultParamHandler::operator=(source);
ProgressLogger::operator=(source);
stn_estimates_ = source.stn_estimates_;
return *this;
}
/// Destructor
~SignalToNoiseEstimator() override
{}
/// Set the start and endpoint of the raw data interval, for which signal to noise ratios will be estimated immediately
virtual void init(const Container& c)
{
computeSTN_(c);
}
///Return to signal/noise estimate for date point @p index
///@note you will get a warning to stderr if more than 20% of the
/// noise estimates used sparse windows
virtual double getSignalToNoise(const Size index) const
{
OPENMS_POSTCONDITION(index < stn_estimates_.size(),"SignalToNoiseEstimator estimates beyond container size was requested.");
return stn_estimates_[index];
}
protected:
/**
* @brief computes the S/N values when init() is called
*
* @exception Throws Exception::InvalidValue
*/
virtual void computeSTN_(const Container& c) = 0;
/**
@brief protected struct to store parameters my, sigma for a Gaussian distribution
Accessors are : mean and variance
*/
struct GaussianEstimate
{
double mean; ///< mean of estimated Gaussian
double variance; ///< variance of estimated Gaussian
};
/// calculate mean & stdev of intensities of a spectrum
inline GaussianEstimate estimate_(const PeakIterator & scan_first_, const PeakIterator & scan_last_) const
{
int size = 0;
// add up
double v = 0;
double m = 0;
PeakIterator run = scan_first_;
while (run != scan_last_)
{
m += (*run).getIntensity();
++size;
++run;
}
//average
m = m / size;
//determine variance
run = scan_first_;
while (run != scan_last_)
{
double tmp(m - (*run).getIntensity());
v += tmp * tmp;
++run;
}
v = v / ((double)size); // divide by n
GaussianEstimate value = {m, v};
return value;
}
//MEMBERS:
/// stores the noise estimate for each peak
std::vector<double> stn_estimates_;
};
/// Picks @p n_scans from the given @p ms_level randomly and returns either average intensity at a certain @p percentile.
/// If no scans with the required level are present, 0.0 is returned
OPENMS_DLLAPI float estimateNoiseFromRandomScans(const MSExperiment& exp, const UInt ms_level, const UInt n_scans = 10, const double percentile = 80);
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/PROCESSING/ID/IDFilter.h | .h | 60,104 | 1,514 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Mathias Walzer $
// $Authors: Nico Pfeifer, Mathias Walzer, Hendrik Weisser $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CHEMISTRY/ProteaseDigestion.h>
#include <OpenMS/CONCEPT/LogStream.h>
#include <OpenMS/FORMAT/FASTAFile.h>
#include <OpenMS/KERNEL/ConsensusMap.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/METADATA/AnnotatedMSRun.h>
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/METADATA/ID/IdentificationData.h>
#include <OpenMS/ANALYSIS/ID/IDScoreSwitcherAlgorithm.h>
#include <OpenMS/METADATA/PeptideEvidence.h>
#include <OpenMS/METADATA/PeptideIdentificationList.h>
#include <OpenMS/METADATA/PeptideIdentification.h>
#include <OpenMS/METADATA/ProteinIdentification.h>
#include <OpenMS/config.h>
#include <algorithm>
#include <climits>
#include <functional>
#include <map>
#include <set>
#include <unordered_set>
#include <vector>
namespace OpenMS
{
template<typename T>
concept IsPeptideOrProteinIdentification =
std::is_same_v<T, PeptideIdentification> || std::is_same_v<T, ProteinIdentification>;
template<typename T>
concept IsFeatureOrConsensusMap =
std::is_same_v<T, FeatureMap> || std::is_same_v<T, ConsensusMap>;
/// Concept to exclude std::vector of identification types (used to disambiguate template overloads)
template<typename T>
concept IsNotIdentificationVector =
!std::is_same_v<T, std::vector<PeptideIdentification>> &&
!std::is_same_v<T, std::vector<ProteinIdentification>> &&
!std::is_same_v<T, PeptideIdentificationList>;
/**
@brief Collection of functions for filtering peptide and protein identifications.
This class provides functions for filtering collections of peptide or protein identifications according to various criteria.
It also contains helper functions and classes (functors that implement predicates) that are used in this context.
The filter functions modify their inputs, rather than creating filtered copies.
Most filters work on the hit level, i.e. they remove peptide or protein hits from peptide or protein identifications (IDs).
A few filters work on the ID level instead, i.e. they remove peptide or protein IDs from vectors thereof.
Independent of this, the inputs for all filter functions are vectors of IDs, because the data most often comes in this form.
This design also allows many helper objects to be set up only once per vector, rather than once per ID.
The filter functions for vectors of peptide/protein IDs do not include clean-up steps (e.g. removal of IDs without hits, reassignment of hit ranks, ...).
They only carry out their specific filtering operations.
This is so filters can be chained without having to repeat clean-up operations.
The group of clean-up functions provides helpers that are useful to ensure data integrity after filters have been applied, but it is up to the individual developer to use them when necessary.
The filter functions for MS/MS experiments do include clean-up steps, because they filter peptide and protein IDs in conjunction and potential contradictions between the two must be eliminated.
*/
class OPENMS_DLLAPI IDFilter
{
public:
/// Constructor
IDFilter() = default;
/// Destructor
virtual ~IDFilter() = default;
/// Typedefs
typedef std::map<Int, PeptideHit*> ChargeToPepHitP;
typedef std::unordered_map<std::string, ChargeToPepHitP> SequenceToChargeToPepHitP;
typedef std::map<std::string, SequenceToChargeToPepHitP> RunToSequenceToChargeToPepHitP;
/**
@name Predicates for peptide or protein hits
These functors test for some property of a peptide or protein hit
*/
///@{
/// Is the score of this hit at least as good as the given value?
template<class HitType>
struct HasGoodScore {
typedef HitType argument_type; // for use as a predicate
double score;
bool higher_score_better;
HasGoodScore(double score_, bool higher_score_better_) : score(score_), higher_score_better(higher_score_better_)
{
}
bool operator()(const HitType& hit) const
{
if (higher_score_better)
{
return hit.getScore() >= score;
}
return hit.getScore() <= score;
}
};
/**
@brief Is a meta value with given key and value set on this hit?
If the value is empty (DataValue::EMPTY), only the existence of a meta value with the given key is checked.
*/
template<class HitType>
struct HasMetaValue {
typedef HitType argument_type; // for use as a predicate
String key;
DataValue value;
HasMetaValue(const String& key_, const DataValue& value_) : key(key_), value(value_)
{
}
bool operator()(const HitType& hit) const
{
DataValue found = hit.getMetaValue(key);
if (found.isEmpty())
return false; // meta value "key" not set
if (value.isEmpty())
return true; // "key" is set, value doesn't matter
return found == value;
}
};
/// Does a meta value of this hit have at most the given value?
template<class HitType>
struct HasMaxMetaValue {
typedef HitType argument_type; // for use as a predicate
String key;
double value;
HasMaxMetaValue(const String& key_, const double& value_) : key(key_), value(value_)
{
}
bool operator()(const HitType& hit) const
{
DataValue found = hit.getMetaValue(key);
if (found.isEmpty())
return false; // meta value "key" not set
return double(found) <= value;
}
};
/**
* @brief Predicate to check if a HitType object has a minimum meta value.
*
* This struct is used as a predicate in filtering operations to check if a HitType object
* has a meta value with a value greater than or equal to a specified threshold.
* Can be used with any HitType object that has a meta value with a double value.
*/
template<class HitType>
struct HasMinMetaValue
{
typedef HitType argument_type; // for use as a predicate
String key;
double value;
/**
* @brief Constructor for HasMinMetaValue.
*
* @param[in] key_ The key of the meta value to check.
* @param[in] value_ The minimum value threshold.
*/
HasMinMetaValue(const String& key_, const double& value_) :
key(key_),
value(value_)
{
}
/**
* @brief Operator() function to check if a HitType object has a minimum meta value.
*
* @param[in] hit The HitType object to check.
* @return True if the HitType object has a meta value with a value greater than or equal to the threshold, false otherwise.
*/
bool operator()(const HitType& hit) const
{
DataValue found = hit.getMetaValue(key);
if (found.isEmpty())
{
return false; // meta value "key" not set
}
return static_cast<double>(found) >= value;
}
};
/// Is this a decoy hit?
/**
* @brief A predicate to check if a HitType has decoy annotation.
*
* This struct is used as a predicate to check if a HitType object has decoy annotation.
* It checks for the presence of "target_decoy" or "isDecoy" meta values in the HitType object.
*
* Example usage:
* @code
* PeptideHit hit;
* HasDecoyAnnotation<PeptideHit> hasDecoy;
* bool hasDecoyAnnotation = hasDecoy(hit);
* @endcode
*
* @tparam HitType The type of the Hit object to be checked.
*/
template<class HitType>
struct HasDecoyAnnotation
{
typedef HitType argument_type; // for use as a predicate
struct HasMetaValue<HitType> target_decoy, is_decoy;
/**
* @brief Default constructor.
*
* Initializes the "target_decoy" and "is_decoy" meta value objects.
*/
HasDecoyAnnotation() :
target_decoy("target_decoy", "decoy"),
is_decoy("isDecoy", "true")
{
}
/**
* @brief Operator to check if a HitType object has decoy annotation.
*
* This operator checks if the given HitType object has either "target_decoy" or "isDecoy" meta values.
*
* @param[in] hit The HitType object to be checked.
* @return True if the HitType object has decoy annotation, false otherwise.
*/
bool operator()(const HitType& hit) const
{
// @TODO: this could be done slightly more efficiently by returning
// false if the "target_decoy" meta value is "target" or "target+decoy",
// without checking for an "isDecoy" meta value in that case
return target_decoy(hit) || is_decoy(hit);
}
};
/**
@brief Given a list of protein accessions, do any occur in the annotation(s) of this hit?
@note This predicate also works for peptide evidence (class PeptideEvidence).
*/
template<class HitType>
struct HasMatchingAccessionUnordered {
typedef HitType argument_type; // for use as a predicate
const std::unordered_set<String>& accessions;
HasMatchingAccessionUnordered(const std::unordered_set<String>& accessions_) :
accessions(accessions_)
{
}
bool operator()(const PeptideHit& hit) const
{
for (const auto& it : hit.extractProteinAccessionsSet())
{
if (accessions.count(it) > 0)
return true;
}
return false;
}
bool operator()(const ProteinHit& hit) const
{
return (accessions.count(hit.getAccession()) > 0);
}
bool operator()(const PeptideEvidence& evidence) const
{
return (accessions.count(evidence.getProteinAccession()) > 0);
}
};
/**
@brief Given a list of protein accessions, do any occur in the annotation(s) of this hit?
@note This predicate also works for peptide evidence (class PeptideEvidence).
*/
template<class HitType>
struct HasMatchingAccession {
typedef HitType argument_type; // for use as a predicate
const std::set<String>& accessions;
HasMatchingAccession(const std::set<String>& accessions_) : accessions(accessions_)
{
}
bool operator()(const PeptideHit& hit) const
{
for (const auto& it : hit.extractProteinAccessionsSet())
{
if (accessions.count(it) > 0)
return true;
}
return false;
}
bool operator()(const ProteinHit& hit) const
{
return (accessions.count(hit.getAccession()) > 0);
}
bool operator()(const PeptideEvidence& evidence) const
{
return (accessions.count(evidence.getProteinAccession()) > 0);
}
};
/**
@brief Builds a map index of data that have a String index to find matches and return the objects
@note Currently implemented for Fasta Entries and Peptide Evidences
*/
template<class HitType, class Entry>
struct GetMatchingItems {
typedef HitType argument_type; // for use as a predicate
typedef std::map<String, Entry*> ItemMap; // Store pointers to avoid copying data
ItemMap items;
GetMatchingItems(std::vector<Entry>& records)
{
for (typename std::vector<Entry>::iterator rec_it = records.begin(); rec_it != records.end(); ++rec_it)
{
items[getKey(*rec_it)] = &(*rec_it);
}
}
GetMatchingItems()
{
}
const String& getKey(const FASTAFile::FASTAEntry& entry) const
{
return entry.identifier;
}
bool exists(const HitType& hit) const
{
return items.count(getHitKey(hit)) > 0;
}
const String& getHitKey(const PeptideEvidence& p) const
{
return p.getProteinAccession();
}
const Entry& getValue(const PeptideEvidence& evidence) const
{
if (!exists(evidence))
{
throw Exception::InvalidParameter(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Accession: '" + getHitKey(evidence) + "'. peptide evidence accession not in data");
}
return *(items.find(getHitKey(evidence))->second);
}
};
///@}
/**
@name Predicates for peptide hits only
These functors test for some property of peptide hits
*/
///@{
/// Does the sequence of this peptide hit have at least the given length?
struct HasMinPeptideLength;
/// Does the charge of this peptide hit have at least the given value?
struct HasMinCharge;
/// Is the m/z error of this peptide hit below the given value?
struct HasLowMZError;
/**
@brief Given a list of modifications, do any occur in the sequence of this peptide hit?
If the list of modifications is empty, return true if the sequence is modified at all.
*/
struct HasMatchingModification;
/**
@brief Is the sequence of this peptide hit among a list of given sequences?
With @p ignore_mods, the sequence without modifications is compared.
*/
struct HasMatchingSequence;
/// Is the list of peptide evidences of this peptide hit empty?
struct HasNoEvidence;
/**
@brief Filter Peptide Hit by its digestion product
*/
class PeptideDigestionFilter
{
private:
EnzymaticDigestion& digestion_;
Int min_cleavages_;
Int max_cleavages_;
public:
typedef PeptideHit argument_type;
PeptideDigestionFilter(EnzymaticDigestion& digestion, Int min, Int max) : digestion_(digestion), min_cleavages_(min), max_cleavages_(max)
{
}
static inline Int disabledValue()
{
return -1;
}
/// Filter function on min max cutoff values to be used with remove_if
/// returns true if peptide should be removed (does not pass filter)
bool operator()(PeptideHit& p) const
{
const auto& fun = [&](const Int missed_cleavages) {
bool max_filter = max_cleavages_ != disabledValue() ? missed_cleavages > max_cleavages_ : false;
bool min_filter = min_cleavages_ != disabledValue() ? missed_cleavages < min_cleavages_ : false;
return max_filter || min_filter;
};
return digestion_.filterByMissedCleavages(p.getSequence().toUnmodifiedString(), fun);
}
void filterPeptideSequences(std::vector<PeptideHit>& hits)
{
hits.erase(std::remove_if(hits.begin(), hits.end(), (*this)), hits.end());
}
};
/**
@brief Is peptide evidence digestion product of some protein
Keeps all valid products
*/
struct DigestionFilter {
typedef PeptideEvidence argument_type;
// Build an accession index to avoid the linear search cost
GetMatchingItems<PeptideEvidence, FASTAFile::FASTAEntry> accession_resolver_;
ProteaseDigestion& digestion_;
bool ignore_missed_cleavages_;
bool methionine_cleavage_;
DigestionFilter(std::vector<FASTAFile::FASTAEntry>& entries, ProteaseDigestion& digestion, bool ignore_missed_cleavages, bool methionine_cleavage) :
accession_resolver_(entries), digestion_(digestion), ignore_missed_cleavages_(ignore_missed_cleavages), methionine_cleavage_(methionine_cleavage)
{
}
bool operator()(const PeptideEvidence& evidence) const
{
if (!evidence.hasValidLimits())
{
OPENMS_LOG_WARN << "Invalid limits! Peptide '" << evidence.getProteinAccession() << "' not filtered" << std::endl;
return true;
}
if (accession_resolver_.exists(evidence))
{
return digestion_.isValidProduct(AASequence::fromString(accession_resolver_.getValue(evidence).sequence), evidence.getStart(), evidence.getEnd() - evidence.getStart(),
ignore_missed_cleavages_, methionine_cleavage_);
}
else
{
if (evidence.getProteinAccession().empty())
{
OPENMS_LOG_WARN << "Peptide accession not available! Skipping Evidence." << std::endl;
}
else
{
OPENMS_LOG_WARN << "Peptide accession '" << evidence.getProteinAccession() << "' not found in fasta file!" << std::endl;
}
return true;
}
}
void filterPeptideEvidences(PeptideIdentificationList& peptides)
{
IDFilter::FilterPeptideEvidences<IDFilter::DigestionFilter>(*this, peptides);
}
};
///@}
/// @name Predicates for peptide or protein identifications
///@{
/// Is the list of hits of this peptide/protein ID empty?
template<class IdentificationType>
struct HasNoHits {
typedef IdentificationType argument_type; // for use as a predicate
bool operator()(const IdentificationType& id) const
{
return id.getHits().empty();
}
};
///@}
/// @name Predicates for peptide identifications only
///@{
/// Is the retention time of this peptide ID in the given range?
struct HasRTInRange;
/// Is the precursor m/z value of this peptide ID in the given range?
struct HasMZInRange;
///@}
/**
@name Higher-order filter functions
Functions for filtering a container based on a predicate
*/
///@{
/// Remove items that satisfy a condition from a container (e.g. vector)
template<class Container, class Predicate>
static void removeMatchingItems(Container& items, const Predicate& pred)
{
items.erase(std::remove_if(items.begin(), items.end(), pred), items.end());
}
/// Keep items that satisfy a condition in a container (e.g. vector), removing all others
template<class Container, class Predicate>
static void keepMatchingItems(Container& items, const Predicate& pred)
{
items.erase(std::remove_if(items.begin(), items.end(), std::not_fn(pred)), items.end());
}
/// Move items that satisfy a condition to a container (e.g. vector)
template<class Container, class Predicate>
static void moveMatchingItems(Container& items, const Predicate& pred, Container& target)
{
auto part = std::partition(items.begin(), items.end(), std::not_fn(pred));
std::move(part, items.end(), std::back_inserter(target));
items.erase(part, items.end());
}
/// Remove Hit items that satisfy a condition in one of our ID containers (e.g. vector of Peptide or ProteinIDs)
template<class IDContainer, class Predicate>
static void removeMatchingItemsUnroll(IDContainer& items, const Predicate& pred)
{
for (auto& item : items)
{
removeMatchingItems(item.getHits(), pred);
}
}
/// Keep Hit items that satisfy a condition in one of our ID containers (e.g. vector of Peptide or ProteinIDs)
template<class IDContainer, class Predicate>
static void keepMatchingItemsUnroll(IDContainer& items, const Predicate& pred)
{
for (auto& item : items)
{
keepMatchingItems(item.getHits(), pred);
}
}
template<class MapType, class Predicate>
static void keepMatchingPeptideHits(MapType& prot_and_pep_ids, Predicate& pred)
{
for (auto& feat : prot_and_pep_ids)
{
keepMatchingItemsUnroll(feat.getPeptideIdentifications(), pred);
}
keepMatchingItemsUnroll(prot_and_pep_ids.getUnassignedPeptideIdentifications(), pred);
}
template<class MapType, class Predicate>
static void removeMatchingPeptideHits(MapType& prot_and_pep_ids, Predicate& pred)
{
for (auto& feat : prot_and_pep_ids)
{
removeMatchingItemsUnroll(feat.getPeptideIdentifications(), pred);
}
removeMatchingItemsUnroll(prot_and_pep_ids.getUnassignedPeptideIdentifications(), pred);
}
template<IsFeatureOrConsensusMap MapType, class Predicate>
static void removeMatchingPeptideIdentifications(MapType& prot_and_pep_ids, Predicate& pred)
{
for (auto& feat : prot_and_pep_ids)
{
removeMatchingItems(feat.getPeptideIdentifications(), pred);
}
removeMatchingItems(prot_and_pep_ids.getUnassignedPeptideIdentifications(), pred);
}
// Specialization for PeptideIdentificationList
template<class Predicate>
static void removeMatchingPeptideIdentifications(PeptideIdentificationList& pep_ids, Predicate& pred)
{
removeMatchingItems(pep_ids, pred);
}
///@}
/// @name Helper functions
///@{
/// Returns the total number of peptide/protein hits in a vector of peptide/protein identifications
template<class IdentificationType>
static Size countHits(const std::vector<IdentificationType>& ids)
{
Size counter = 0;
for (typename std::vector<IdentificationType>::const_iterator id_it = ids.begin(); id_it != ids.end(); ++id_it)
{
counter += id_it->getHits().size();
}
return counter;
}
/// @overload
static Size countHits(const PeptideIdentificationList& ids)
{
Size counter = 0;
for (const auto& id : ids)
{
counter += id.getHits().size();
}
return counter;
}
/// @overload
static void filterHitsByRank(PeptideIdentificationList& ids, Size min_rank, Size max_rank)
{
std::vector<PeptideIdentification>& vec = ids.getData();
filterHitsByRank(vec, min_rank, max_rank);
}
/// @overload
static void removeHitsMatchingProteins(PeptideIdentificationList& ids, const std::set<String>& accessions)
{
std::vector<PeptideIdentification>& vec = ids.getData();
removeHitsMatchingProteins(vec, accessions);
}
/// @overload
static void keepHitsMatchingProteins(PeptideIdentificationList& ids, const std::set<String>& accessions)
{
std::vector<PeptideIdentification>& vec = ids.getData();
keepHitsMatchingProteins(vec, accessions);
}
/// @overload
static bool getBestHit(PeptideIdentificationList& ids, bool assume_sorted, PeptideHit& best_hit)
{
std::vector<PeptideIdentification>& vec = ids.getData();
return getBestHit(vec, assume_sorted, best_hit);
}
/// @overload
static void removeEmptyIdentifications(PeptideIdentificationList& ids)
{
std::vector<PeptideIdentification>& vec = ids.getData();
removeEmptyIdentifications(vec);
}
/**
@brief Finds the best-scoring hit in a vector of peptide or protein identifications.
If there are several hits with the best score, the first one is taken.
@param[in] identifications Vector of peptide or protein IDs, each containing one or more (peptide/protein) hits
@param[in] assume_sorted Are hits sorted by score (best score first) already? This allows for faster query, since only the first hit needs to be looked at
@param[in] best_hit Contains the best hit if successful
@throws Exception::InvalidValue if the IDs have different score types (i.e. scores cannot be compared)
@return true if a hit was present, false otherwise
*/
template<class IdentificationType>
static bool getBestHit(const std::vector<IdentificationType>& identifications, bool assume_sorted, typename IdentificationType::HitType& best_hit)
{
if (identifications.empty())
return false;
typename std::vector<IdentificationType>::const_iterator best_id_it = identifications.end();
typename std::vector<typename IdentificationType::HitType>::const_iterator best_hit_it;
for (typename std::vector<IdentificationType>::const_iterator id_it = identifications.begin(); id_it != identifications.end(); ++id_it)
{
if (id_it->getHits().empty())
continue;
if (best_id_it == identifications.end()) // no previous "best" hit
{
best_id_it = id_it;
best_hit_it = id_it->getHits().begin();
}
else if (best_id_it->getScoreType() != id_it->getScoreType())
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Can't compare scores of different types", best_id_it->getScoreType() + "/" + id_it->getScoreType());
}
bool higher_better = best_id_it->isHigherScoreBetter();
for (typename std::vector<typename IdentificationType::HitType>::const_iterator hit_it = id_it->getHits().begin(); hit_it != id_it->getHits().end(); ++hit_it)
{
if ((higher_better && (hit_it->getScore() > best_hit_it->getScore())) || (!higher_better && (hit_it->getScore() < best_hit_it->getScore())))
{
best_hit_it = hit_it;
}
if (assume_sorted)
break; // only consider the first hit
}
}
if (best_id_it == identifications.end())
{
return false; // no hits in any IDs
}
best_hit = *best_hit_it;
return true;
}
/**
@brief Extracts all unique peptide sequences from a list of peptide IDs
@param[in,out] peptides Input
@param[out] sequences Output
@param[in] ignore_mods Extract sequences without modifications?
*/
static void extractPeptideSequences(const PeptideIdentificationList& peptides, std::set<String>& sequences, bool ignore_mods = false);
/**
* @brief Extracts all proteins not matched by PSMs in features
* @param[in] cmap the Input ConsensusMap
* @return extracted ProteinHits for every IDRun
*/
static std::map<String, std::vector<ProteinHit>> extractUnassignedProteins(ConsensusMap& cmap);
/**
@brief remove peptide evidences based on a filter
@param[in] filter filter function that overloads ()(PeptideEvidence&) operator
@param[in] peptides a collection of peptide evidences
*/
template<class EvidenceFilter>
static void FilterPeptideEvidences(EvidenceFilter& filter, PeptideIdentificationList& peptides)
{
for (PeptideIdentificationList::iterator pep_it = peptides.begin(); pep_it != peptides.end(); ++pep_it)
{
for (std::vector<PeptideHit>::iterator hit_it = pep_it->getHits().begin(); hit_it != pep_it->getHits().end(); ++hit_it)
{
std::vector<PeptideEvidence> evidences;
remove_copy_if(hit_it->getPeptideEvidences().begin(), hit_it->getPeptideEvidences().end(), back_inserter(evidences), std::not_fn(filter));
hit_it->setPeptideEvidences(evidences);
}
}
}
///@}
/// @name Clean-up functions
///@{
/// Removes protein hits from the protein IDs in a @p cmap that are not referenced by a peptide in the features
/// or if requested in the unassigned peptide list
static void removeUnreferencedProteins(ConsensusMap& cmap, bool include_unassigned);
/// Removes protein hits from @p proteins that are not referenced by a peptide in @p peptides
static void removeUnreferencedProteins(std::vector<ProteinIdentification>& proteins, const PeptideIdentificationList& peptides);
/// Removes protein hits from @p proteins that are not referenced by a peptide in @p peptides
static void removeUnreferencedProteins(ProteinIdentification& proteins, const PeptideIdentificationList& peptides);
/**
@brief Removes dangling protein references from peptide hits
Cleans up PeptideEvidence entries by removing references to proteins that no longer exist
in the provided protein identifications. This is typically called after filtering protein hits
to maintain consistency between peptide-to-protein mappings.
@param[in,out] peptides The peptide identifications to process
@param[in] proteins The protein identifications containing valid protein hits
@param[in] remove_peptides_without_reference If true, peptide hits that have no remaining
protein references after cleanup are also removed (default: false)
@note Only PeptideEvidence entries referencing protein hits in @p proteins are kept.
The matching is done per identification run using the run identifier.
*/
static void removeDanglingProteinReferences(PeptideIdentificationList& peptides, const std::vector<ProteinIdentification>& proteins, bool remove_peptides_without_reference = false);
/**
@brief Removes dangling protein references from peptide hits in a ConsensusMap
Cleans up PeptideEvidence entries by removing references to proteins that no longer exist
in the ConsensusMap's protein identifications. This is typically called after filtering
protein hits to maintain consistency between peptide-to-protein mappings.
@param[in,out] cmap The ConsensusMap containing peptide and protein identifications
@param[in] remove_peptides_without_reference If true, peptide hits that have no remaining
protein references after cleanup are also removed (default: false)
@note Only PeptideEvidence entries referencing protein hits in the corresponding
protein run of @p cmap are kept. The matching is done per identification run.
*/
static void removeDanglingProteinReferences(ConsensusMap& cmap, bool remove_peptides_without_reference = false);
/**
@brief Removes dangling protein references from peptide hits using a reference protein run
Cleans up PeptideEvidence entries by removing references to proteins that do not exist
in the specified reference protein run. This is typically called after filtering protein
hits to maintain consistency between peptide-to-protein mappings.
@param[in,out] cmap The ConsensusMap containing peptide identifications to process
@param[in] ref_run The reference ProteinIdentification containing valid protein hits
@param[in] remove_peptides_without_reference If true, peptide hits that have no remaining
protein references after cleanup are also removed (default: false)
@note Only PeptideEvidence entries referencing protein hits in @p ref_run are kept.
*/
static void removeDanglingProteinReferences(ConsensusMap& cmap, const ProteinIdentification& ref_run, bool remove_peptides_without_reference = false);
/**
@brief Update protein groups after protein hits were filtered
@param[in] groups Input/output protein groups
@param[in,out] hits Available protein hits (all others are removed from the groups)
@return Returns whether the groups are still valid (which is the case if only whole groups, if any, were removed).
*/
static bool updateProteinGroups(std::vector<ProteinIdentification::ProteinGroup>& groups, const std::vector<ProteinHit>& hits);
/**
@brief Update protein hits after protein groups were filtered
@param[in,out] groups Available protein groups with protein accessions to keep
@param[in] hits Input/output hits (all others are removed from the groups)
*/
static void removeUngroupedProteins(const std::vector<ProteinIdentification::ProteinGroup>& groups, std::vector<ProteinHit>& hits);
///@}
/// @name Filter functions for peptide or protein IDs
///@{
/// Removes peptide or protein identifications that have no hits in them
template<IsPeptideOrProteinIdentification IdentificationType>
static void removeEmptyIdentifications(std::vector<IdentificationType>& ids)
{
struct HasNoHits<IdentificationType> empty_filter;
removeMatchingItems(ids, empty_filter);
}
/**
@brief Filters peptide or protein identifications according to the score of the hits.
Only peptide/protein hits with a (main) score at least as good as @p threshold_score are kept. Score orientation (are higher scores better?) is taken into account.
*/
template<class IdentificationType>
static void filterHitsByScore(std::vector<IdentificationType>& ids, double threshold_score)
{
for (typename std::vector<IdentificationType>::iterator id_it = ids.begin(); id_it != ids.end(); ++id_it)
{
struct HasGoodScore<typename IdentificationType::HitType> score_filter(threshold_score, id_it->isHigherScoreBetter());
keepMatchingItems(id_it->getHits(), score_filter);
}
}
/**
* @brief Filters peptide or protein identifications according to the score of the hits.
*
* Only peptide/protein hits with a score at least as good as @p threshold_score are kept. Score orientation is taken into account.
* This will look for a given @p score_type as the main score or in the secondary scores.
*
* Note: Removes a hit if the @p score_type is not found at all.
*
* @tparam IdentificationType The type of identification.
* @param[in] ids The vector of identifications to filter.
* @param[in] threshold_score The threshold score to filter the hits.
* @param[in] score_type The score type to consider for filtering.
*/
template<class IdentificationType>
static void filterHitsByScore(std::vector<IdentificationType>& ids, double threshold_score, IDScoreSwitcherAlgorithm::ScoreType score_type)
{
IDScoreSwitcherAlgorithm switcher;
bool at_least_one_found = false;
for (IdentificationType& id : ids)
{
if (switcher.isScoreType(id.getScoreType(), score_type))
{
struct HasGoodScore<typename IdentificationType::HitType> score_filter(threshold_score, id.isHigherScoreBetter());
keepMatchingItems(id.getHits(), score_filter);
}
else
{
// If one assumes they are all the same in the vector, this could be done in the beginning.
auto result = switcher.findScoreType<IdentificationType>(id, score_type);
if (!result.score_name.empty())
{
String metaval = result.score_name;
if (switcher.isScoreTypeHigherBetter(score_type))
{
struct HasMinMetaValue<typename IdentificationType::HitType> score_filter(metaval, threshold_score);
keepMatchingItems(id.getHits(), score_filter);
}
else
{
struct HasMaxMetaValue<typename IdentificationType::HitType> score_filter(metaval, threshold_score);
keepMatchingItems(id.getHits(), score_filter);
}
at_least_one_found = true;
}
}
}
if (!at_least_one_found) OPENMS_LOG_WARN << String("Warning: No hit with the given score_type found. All hits removed.") << std::endl;
}
/**
@brief Filters protein groups according to the score of the groups.
Only protein groups with a score at least as good as @p threshold_score are kept.
Score orientation (@p higher_better) should be taken from the protein hits and assumed equal.
*/
static void filterGroupsByScore(std::vector<ProteinIdentification::ProteinGroup>& grps, double threshold_score, bool higher_better);
/**
@brief Filters peptide or protein identifications according to the score of the hits.
Only peptide/protein hits with a score at least as good as @p threshold_score are kept. Score orientation (are higher scores better?) is taken into account.
*/
template<class IdentificationType>
static void filterHitsByScore(IdentificationType& id, double threshold_score)
{
struct HasGoodScore<typename IdentificationType::HitType> score_filter(threshold_score, id.isHigherScoreBetter());
keepMatchingItems(id.getHits(), score_filter);
}
/**
@brief Filters peptide or protein identifications according to the score of the hits, keeping the @p n best hits per ID.
The score orientation (are higher scores better?) is taken into account.
*/
template<class IdentificationType>
static void keepNBestHits(std::vector<IdentificationType>& ids, Size n)
{
for (typename std::vector<IdentificationType>::iterator id_it = ids.begin(); id_it != ids.end(); ++id_it)
{
id_it->sort();
if (n < id_it->getHits().size())
id_it->getHits().resize(n);
}
}
/**
@brief Filters peptide identifications according to the ranking of the hits.
Overload for PeptideIdentificationList to avoid template deduction issues.
@param[in] pep_ids The PeptideIdentificationList to filter.
@param[in] n Maximum number of hits to keep.
*/
static void keepNBestHits(PeptideIdentificationList& pep_ids, Size n)
{
std::vector<PeptideIdentification>& vec = pep_ids.getData();
keepNBestHits(vec, n);
}
/**
@brief Filters peptide or protein identifications according to the ranking of the hits.
The hits between @p min_rank and @p max_rank (both inclusive) in each ID are kept.
Counting starts at 1, i.e. the best (highest/lowest scoring) hit has rank 1.
The ranks are (re-)computed before filtering.
@p max_rank is ignored if it is smaller than @p min_rank.
Note that there may be several hits with the same rank in a peptide or protein ID (if the scores are the same).
This method is useful if a range of higher hits is needed for decoy fairness analysis.
@note The ranks of the hits may be invalidated.
*/
template<class IdentificationType>
static void filterHitsByRank(std::vector<IdentificationType>& ids, Size min_rank, Size max_rank)
{
for (auto& id : ids)
{
auto& hits = id.getHits();
if (hits.empty()) continue;
id.sort(); // Ensure hits are properly sorted
// ignore max_rank?
if (max_rank < min_rank) max_rank = hits.size();
Size rank = 1;
double last_score = hits.front().getScore();
// Remove hits not within [min_rank, max_rank], while computing rank on the fly
hits.erase(
std::remove_if(hits.begin(), hits.end(),
[&](const auto& hit) {
if (hit.getScore() != last_score)
{
++rank;
last_score = hit.getScore();
}
return rank < min_rank || rank > max_rank;
}),
hits.end()
);
}
}
/**
@brief Removes hits annotated as decoys from peptide or protein identifications.
Checks for meta values named "target_decoy" and "isDecoy", and removes protein/peptide hits if the values are "decoy" and "true", respectively.
@note The ranks of the hits may be invalidated.
*/
template<class IdentificationType>
static void removeDecoyHits(std::vector<IdentificationType>& ids)
{
struct HasDecoyAnnotation<typename IdentificationType::HitType> decoy_filter;
for (typename std::vector<IdentificationType>::iterator id_it = ids.begin(); id_it != ids.end(); ++id_it)
{
removeMatchingItems(id_it->getHits(), decoy_filter);
}
}
/**
@brief Filters peptide or protein identifications according to the given proteins (negative).
Hits with a matching protein accession in @p accessions are removed.
@note The ranks of the hits may be invalidated.
*/
template<class IdentificationType>
static void removeHitsMatchingProteins(std::vector<IdentificationType>& ids, const std::set<String> accessions)
{
struct HasMatchingAccession<typename IdentificationType::HitType> acc_filter(accessions);
for (auto& id_it : ids)
{
removeMatchingItems(id_it.getHits(), acc_filter);
}
}
/**
@brief Filters peptide or protein identifications according to the given proteins (positive).
Hits with a matching protein accession in @p accessions are kept.
@note The ranks of the hits may be invalidated.
*/
template<IsPeptideOrProteinIdentification IdentificationType>
static void keepHitsMatchingProteins(IdentificationType& id, const std::set<String>& accessions)
{
struct HasMatchingAccession<typename IdentificationType::HitType> acc_filter(accessions);
keepMatchingItems(id.getHits(), acc_filter);
}
/**
@brief Filters peptide or protein identifications according to the given proteins (positive).
Hits with no matching protein accession in @p accessions are removed.
@note The ranks of the hits may be invalidated.
*/
template<class IdentificationType>
static void keepHitsMatchingProteins(std::vector<IdentificationType>& ids, const std::set<String>& accessions)
{
for (auto& id_it : ids) keepHitsMatchingProteins(id_it, accessions);
}
///@}
/// @name Filter functions for peptide IDs only
///@{
/**
@brief Filters peptide identifications keeping only the single best-scoring hit per ID.
@param[in,out] peptides Input/output
@param[in] strict If set, keep the best hit only if its score is unique - i.e. ties are not allowed. (Otherwise all hits with the best score is kept.)
*/
static void keepBestPeptideHits(PeptideIdentificationList& peptides, bool strict = false);
/**
@brief Filters peptide identifications according to peptide sequence length.
Only peptide hits with a sequence length between @p min_length and @p max_length (both inclusive) are kept.
@p max_length is ignored if it is smaller than @p min_length.
@note The ranks of the hits may be invalidated.
*/
static void filterPeptidesByLength(PeptideIdentificationList& peptides, Size min_length, Size max_length = UINT_MAX);
/**
@brief Filters peptide identifications according to charge state.
Only peptide hits with a charge state between @p min_charge and @p max_charge (both inclusive) are kept.
@p max_charge is ignored if it is smaller than @p min_charge.
@note The ranks of the hits may be invalidated.
*/
static void filterPeptidesByCharge(PeptideIdentificationList& peptides, Int min_charge, Int max_charge);
/// Filters peptide identifications by precursor RT, keeping only IDs in the given range
static void filterPeptidesByRT(PeptideIdentificationList& peptides, double min_rt, double max_rt);
/// Filters peptide identifications by precursor m/z, keeping only IDs in the given range
static void filterPeptidesByMZ(PeptideIdentificationList& peptides, double min_mz, double max_mz);
/**
@brief Filter peptide identifications according to mass deviation.
Only peptide hits with a low mass deviation (between theoretical peptide mass and precursor mass) are kept.
@param[in,out] peptides Input/output
@param[in] mass_error Threshold for the mass deviation
@param[in] unit_ppm Is @p mass_error given in PPM?
@note The ranks of the hits may be invalidated.
*/
static void filterPeptidesByMZError(PeptideIdentificationList& peptides, double mass_error, bool unit_ppm);
/**
@brief Digest a collection of proteins and filter PeptideEvidences based on specificity
PeptideEvidences of peptides are removed if the digest of a protein did not produce the peptide sequence
@param[in] filter filter function on PeptideEvidence level
@param[in] peptides PeptideIdentification that will be scanned and filtered
*/
template<class Filter>
static void filterPeptideEvidences(Filter& filter, PeptideIdentificationList& peptides);
/**
@brief Filters peptide identifications according to p-values from RTPredict.
Filters the peptide hits by the probability (p-value) of a correct peptide identification having a deviation between observed and predicted RT equal to or greater than allowed.
@param[in] peptides Input/output
@param[in] metavalue_key Name of the meta value that holds the p-value: "predicted_RT_p_value" or "predicted_RT_p_value_first_dim"
@param[in] threshold P-value threshold
@note The ranks of the hits may be invalidated.
*/
static void filterPeptidesByRTPredictPValue(PeptideIdentificationList& peptides, const String& metavalue_key, double threshold = 0.05);
/// Removes all peptide hits that have at least one of the given modifications
static void removePeptidesWithMatchingModifications(PeptideIdentificationList& peptides, const std::set<String>& modifications);
static void removePeptidesWithMatchingRegEx(PeptideIdentificationList& peptides, const String& regex);
/// Keeps only peptide hits that have at least one of the given modifications
static void keepPeptidesWithMatchingModifications(PeptideIdentificationList& peptides, const std::set<String>& modifications);
/**
@brief Removes all peptide hits with a sequence that matches one in @p bad_peptides.
If @p ignore_mods is set, unmodified sequences are generated and compared to the given ones.
@note The ranks of the hits may be invalidated.
*/
static void removePeptidesWithMatchingSequences(PeptideIdentificationList& peptides, const PeptideIdentificationList& bad_peptides, bool ignore_mods = false);
/**
@brief Removes all peptide hits with a sequence that does not match one in @p good_peptides.
If @p ignore_mods is set, unmodified sequences are generated and compared to the given ones.
@note The ranks of the hits may be invalidated.
*/
static void keepPeptidesWithMatchingSequences(PeptideIdentificationList& peptides, const PeptideIdentificationList& good_peptides, bool ignore_mods = false);
/// Removes all peptides that are not annotated as unique for a protein (by PeptideIndexer)
static void keepUniquePeptidesPerProtein(PeptideIdentificationList& peptides);
/**
@brief Removes duplicate peptide hits from each peptide identification, keeping only unique hits (per ID).
By default, hits are considered duplicated if they compare as equal using PeptideHit::operator==. However, if @p seq_only is set, only the sequences (incl. modifications) are compared. In both
cases, the first occurrence of each hit in a peptide ID is kept, later ones are removed.
*/
static void removeDuplicatePeptideHits(PeptideIdentificationList& peptides, bool seq_only = false);
///@}
/// @name Filter functions for AnnotatedMSRun
///@{
/// Filters AnnotatedMSRun according to score thresholds
static void filterHitsByScore(AnnotatedMSRun& annotated_data,
double peptide_threshold_score,
double protein_threshold_score)
{
// filter protein hits:
filterHitsByScore(annotated_data.getProteinIdentifications(),
protein_threshold_score);
// don't remove empty protein IDs - they contain search meta data and may
// be referenced by peptide IDs (via run ID)
// filter peptide hits:
for (PeptideIdentification& peptide_id : annotated_data.getPeptideIdentifications())
{
filterHitsByScore(peptide_id, peptide_threshold_score);
}
removeDanglingProteinReferences(annotated_data.getPeptideIdentifications(), annotated_data.getProteinIdentifications());
}
/// Filters AnnotatedMSRun by keeping the N best peptide hits for every spectrum
static void keepNBestHits(AnnotatedMSRun& annotated_data, Size n)
{
// don't filter the protein hits by "N best" here - filter the peptides
// and update the protein hits!
PeptideIdentificationList all_peptides; // IDs from all spectra
// filter peptide hits:
for (PeptideIdentification& peptide_id : annotated_data.getPeptideIdentifications())
{
// Create a temporary vector with a single PeptideIdentification
PeptideIdentificationList temp_vec = {peptide_id};
keepNBestHits(temp_vec, n);
// Copy back the filtered hits
if (!temp_vec.empty())
{
peptide_id = temp_vec[0];
}
else
{
peptide_id.getHits().clear();
}
// Since we're working with individual PeptideIdentifications, we don't need to remove empty ones
// but we still need to update protein references
temp_vec = {peptide_id};
removeDanglingProteinReferences(temp_vec, annotated_data.getProteinIdentifications());
all_peptides.push_back(peptide_id);
}
// update protein hits:
removeUnreferencedProteins(annotated_data.getProteinIdentifications(), all_peptides);
}
/// Filter identifications by "N best" PeptideIdentification objects (better PeptideIdentification means better [best] PeptideHit than other).
/// The vector is sorted and reduced to @p n elements. If the vector's size 's' is less than @p n, only 's' best spectra are kept.
static void keepNBestSpectra(PeptideIdentificationList& peptides, Size n);
/// Filters a Consensus/FeatureMap by keeping the N best peptide hits for every spectrum
template<class MapType>
static void keepNBestPeptideHits(MapType& map, Size n)
{
// The rank predicate needs annotated ranks, not sure if they are always updated. Use the following instead,
// which sorts Hits first.
for (auto& feat : map)
{
keepNBestHits(feat.getPeptideIdentifications(), n);
}
keepNBestHits(map.getUnassignedPeptideIdentifications(), n);
}
template<IsNotIdentificationVector MapType>
static void removeEmptyIdentifications(MapType& prot_and_pep_ids)
{
const auto pred = HasNoHits<PeptideIdentification>();
removeMatchingPeptideIdentifications(prot_and_pep_ids, pred);
}
/// Filters PeptideHits from PeptideIdentification by keeping only the best peptide hits for every peptide sequence
static void keepBestPerPeptide(PeptideIdentificationList& pep_ids, bool ignore_mods, bool ignore_charges, Size nr_best_spectrum)
{
annotateBestPerPeptide(pep_ids, ignore_mods, ignore_charges, nr_best_spectrum);
HasMetaValue<PeptideHit> best_per_peptide {"best_per_peptide", 1};
keepMatchingItemsUnroll(pep_ids, best_per_peptide);
}
static void keepBestPerPeptidePerRun(std::vector<ProteinIdentification>& prot_ids, PeptideIdentificationList& pep_ids, bool ignore_mods, bool ignore_charges, Size nr_best_spectrum)
{
annotateBestPerPeptidePerRun(prot_ids, pep_ids, ignore_mods, ignore_charges, nr_best_spectrum);
HasMetaValue<PeptideHit> best_per_peptide {"best_per_peptide", 1};
keepMatchingItemsUnroll(pep_ids, best_per_peptide);
}
// TODO allow skipping unassigned?
template<class MapType>
static void annotateBestPerPeptidePerRun(MapType& prot_and_pep_ids, bool ignore_mods, bool ignore_charges, Size nr_best_spectrum)
{
const auto& prot_ids = prot_and_pep_ids.getProteinIdentifications();
RunToSequenceToChargeToPepHitP best_peps_per_run;
for (const auto& idrun : prot_ids)
{
best_peps_per_run[idrun.getIdentifier()] = SequenceToChargeToPepHitP();
}
for (auto& feat : prot_and_pep_ids)
{
annotateBestPerPeptidePerRunWithData(best_peps_per_run, feat.getPeptideIdentifications(), ignore_mods, ignore_charges, nr_best_spectrum);
}
annotateBestPerPeptidePerRunWithData(best_peps_per_run, prot_and_pep_ids.getUnassignedPeptideIdentifications(), ignore_mods, ignore_charges, nr_best_spectrum);
}
template<class MapType>
static void keepBestPerPeptidePerRun(MapType& prot_and_pep_ids, bool ignore_mods, bool ignore_charges, Size nr_best_spectrum)
{
annotateBestPerPeptidePerRun(prot_and_pep_ids, ignore_mods, ignore_charges, nr_best_spectrum);
HasMetaValue<PeptideHit> best_per_peptide {"best_per_peptide", 1};
keepMatchingPeptideHits(prot_and_pep_ids, best_per_peptide);
}
/// Annotates PeptideHits from PeptideIdentification if it is the best peptide hit for its peptide sequence
/// Adds metavalue "bestForItsPeps" which can be used for additional filtering.
static void annotateBestPerPeptidePerRun(const std::vector<ProteinIdentification>& prot_ids, PeptideIdentificationList& pep_ids, bool ignore_mods, bool ignore_charges,
Size nr_best_spectrum)
{
RunToSequenceToChargeToPepHitP best_peps_per_run;
for (const auto& id : prot_ids)
{
best_peps_per_run[id.getIdentifier()] = SequenceToChargeToPepHitP();
}
annotateBestPerPeptidePerRunWithData(best_peps_per_run, pep_ids, ignore_mods, ignore_charges, nr_best_spectrum);
}
/// Annotates PeptideHits from PeptideIdentification if it is the best peptide hit for its peptide sequence
/// Adds metavalue "bestForItsPeps" which can be used for additional filtering.
/// To be used when a RunToSequenceToChargeToPepHitP map is already available
static void annotateBestPerPeptidePerRunWithData(RunToSequenceToChargeToPepHitP& best_peps_per_run, PeptideIdentificationList& pep_ids, bool ignore_mods, bool ignore_charges,
Size nr_best_spectrum)
{
for (auto& pep : pep_ids)
{
SequenceToChargeToPepHitP& best_pep = best_peps_per_run[pep.getIdentifier()];
annotateBestPerPeptideWithData(best_pep, pep, ignore_mods, ignore_charges, nr_best_spectrum);
}
}
/// Annotates PeptideHits from PeptideIdentification if it is the best peptide hit for its peptide sequence
/// Adds metavalue "bestForItsPeps" which can be used for additional filtering.
/// Does not check Run information and just goes over all Peptide IDs
static void annotateBestPerPeptide(PeptideIdentificationList& pep_ids, bool ignore_mods, bool ignore_charges, Size nr_best_spectrum)
{
SequenceToChargeToPepHitP best_pep;
for (auto& pep : pep_ids)
{
annotateBestPerPeptideWithData(best_pep, pep, ignore_mods, ignore_charges, nr_best_spectrum);
}
}
/// Annotates PeptideHits from PeptideIdentification if it is the best peptide hit for its peptide sequence
/// Adds metavalue "bestForItsPeps" which can be used for additional filtering.
/// Does not check Run information and just goes over all Peptide IDs
/// To be used when a SequenceToChargeToPepHitP map is already available
static void annotateBestPerPeptideWithData(SequenceToChargeToPepHitP& best_pep, PeptideIdentification& pep, bool ignore_mods, bool ignore_charges, Size nr_best_spectrum)
{
bool higher_score_better = pep.isHigherScoreBetter();
// make sure that first = best hit
pep.sort();
auto pepIt = pep.getHits().begin();
auto pepItEnd = nr_best_spectrum == 0 || pep.getHits().size() <= nr_best_spectrum ? pep.getHits().end() : pep.getHits().begin() + nr_best_spectrum;
for (; pepIt != pepItEnd; ++pepIt)
{
PeptideHit& hit = *pepIt;
String lookup_seq;
if (ignore_mods)
{
lookup_seq = hit.getSequence().toUnmodifiedString();
}
else
{
lookup_seq = hit.getSequence().toString();
}
int lookup_charge = 0;
if (!ignore_charges)
{
lookup_charge = hit.getCharge();
}
// try to insert
auto it_inserted = best_pep.emplace(std::move(lookup_seq), ChargeToPepHitP());
auto it_inserted_chg = it_inserted.first->second.emplace(lookup_charge, &hit);
PeptideHit*& p = it_inserted_chg.first->second; // now this gets either the old one if already present, or this
if (!it_inserted_chg.second) // was already present -> possibly update
{
if ((higher_score_better && (hit.getScore() > p->getScore())) || (!higher_score_better && (hit.getScore() < p->getScore())))
{
p->setMetaValue("best_per_peptide", 0);
hit.setMetaValue("best_per_peptide", 1);
p = &hit;
}
else // note that this was def. not the best
{
// TODO if it is only about filtering, we can omit writing this metavalue (absence = false)
hit.setMetaValue("best_per_peptide", 0);
}
}
else // newly inserted -> first for that sequence (and optionally charge)
{
hit.setMetaValue("best_per_peptide", 1);
}
}
}
/// Filters AnnotatedMSRun according to the given proteins.
static void keepHitsMatchingProteins(
AnnotatedMSRun& experiment,
const std::vector<FASTAFile::FASTAEntry>& proteins)
{
std::set<String> accessions;
for (auto it = proteins.begin(); it != proteins.end(); ++it)
{
accessions.insert(it->identifier);
}
// filter protein hits:
keepHitsMatchingProteins(experiment.getProteinIdentifications(), accessions);
// filter peptide hits:
// std::pair<OpenMS::MSSpectrum&, OpenMS::PeptideIdentification&>
for (auto [spectrum, peptide_id] : experiment)
{
if (spectrum.getMSLevel() == 2)
{
keepHitsMatchingProteins(peptide_id, accessions);
}
}
removeEmptyIdentifications(experiment.getPeptideIdentifications());
}
///@}
/// @name Filter functions for class IdentificationData
///@{
/*!
@brief Filter IdentificationData to keep only the best match (e.g. PSM) for each observation (e.g. spectrum)
The data structure will be cleaned up (IdentificationData::cleanup) to remove any invalidated references at the end of this operation.
@see IdentificationData::getBestMatchPerObservation
@param[in] id_data Data to be filtered
@param[in] score_ref Reference to the score type defining "best" matches
*/
static void keepBestMatchPerObservation(IdentificationData& id_data, IdentificationData::ScoreTypeRef score_ref);
/*!
@brief Filter observation matches (e.g. PSMs) in IdentificationData by score
Matches with scores of the required type that are worse than the cut-off are removed.
Matches without a score of the required type are also removed.
The data structure will be cleaned up (IdentificationData::cleanup) to remove any invalidated references at the end of this operation.
@param[in] id_data Data to be filtered
@param[in] score_ref Reference to the score type used for filtering
@param[in] cutoff Score cut-off for filtering
*/
static void filterObservationMatchesByScore(IdentificationData& id_data, IdentificationData::ScoreTypeRef score_ref, double cutoff);
/*!
@brief Filter IdentificationData to remove parent sequences annotated as decoys
If any were removed, the data structure will be cleaned up (IdentificationData::cleanup) to remove any invalidated references at the end of this operation.
*/
static void removeDecoys(IdentificationData& id_data);
///@}
// Specific overloads for PeptideIdentificationList to ensure correct template resolution
static void removeDecoyHits(PeptideIdentificationList& ids)
{
removeDecoyHits(ids.getData());
}
static void filterHitsByScore(PeptideIdentificationList& ids, double threshold_score)
{
filterHitsByScore(ids.getData(), threshold_score);
}
static void removeUnreferencedProteins(std::vector<ProteinIdentification>& proteins, PeptideIdentificationList& ids)
{
removeUnreferencedProteins(proteins, ids.getData());
}
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/PROCESSING/RESAMPLING/LinearResamplerAlign.h | .h | 15,878 | 360 | // 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/PROCESSING/RESAMPLING/LinearResampler.h>
#include <OpenMS/CONCEPT/Macros.h>
namespace OpenMS
{
/**
@brief Linear Resampling of raw data with alignment.
This class can be used to generate uniform data from non-uniform raw data (e.g. ESI-TOF or MALDI-TOF experiments).
Therefore the intensity at every position x in the input raw data is spread to the two
adjacent resampling points.
This method preserves the area of the input signal and also the centroid position of a peak.
Therefore it is recommended for quantitation as well as for ProteinIdentification experiments.
In addition to the LinearResampler, this class also allows to fix the
points at which resampling will occur. This is useful if the resampling
points are known in advance, e.g. if one needs to resample a chromatogram
at the positions of another chromatogram.
*/
class OPENMS_DLLAPI LinearResamplerAlign :
public LinearResampler
{
public:
LinearResamplerAlign()
{
defaults_.setValue("spacing", 0.05, "Spacing of the resampled output peaks.");
defaults_.setValue("ppm", "false", "Whether spacing is in ppm or Th");
defaultsToParam_();
}
/**
@brief Applies the resampling algorithm to a container (MSSpectrum or MSChromatogram).
The container will be resampled at equally spaced points between the
start and end of the container. The resampling frequency can be
controlled by the "spacing" parameter.
@param[in,out] container The container to be resampled
*/
template <class PeakContainerT>
void raster(PeakContainerT& container)
{
//return if nothing to do
if (container.empty()) return;
auto first = container.begin();
auto last = container.end();
double end_pos = (last - 1)->getPos();
double start_pos = first->getPos();
int number_resampled_points = (int)(ceil((end_pos - start_pos) / spacing_ + 1));
std::vector<typename PeakContainerT::PeakType> resampled_peak_container;
populate_raster_(resampled_peak_container, start_pos, end_pos, number_resampled_points);
raster(container.begin(), container.end(), resampled_peak_container.begin(), resampled_peak_container.end());
container.swap(resampled_peak_container);
}
/**
@brief Applies the resampling algorithm to a container (MSSpectrum or MSChromatogram) with fixed coordinates.
The container will be resampled at equally spaced points between the
supplied start and end positions. The resampling frequency can be
controlled by the "spacing" parameter.
This allows the user to specify the grid for alignment explicitly.
This is especially useful if multiple spectra or chromatograms need to
be resampled according to the same raster.
@param[in,out] container The container to be resampled
@param[in] start_pos The start position to be used for resampling
@param[in] end_pos The end position to be used for resampling
*/
template <typename PeakContainerT>
void raster_align(PeakContainerT& container, double start_pos, double end_pos)
{
//return if nothing to do
if (container.empty()) return;
if (end_pos < start_pos)
{
std::vector<typename PeakContainerT::PeakType> empty;
container.swap(empty);
return;
}
auto first = container.begin();
auto last = container.end();
// get the iterators just before / after the two points start_pos / end_pos
while (first != container.end() && (first)->getPos() < start_pos) {++first;}
while (last != first && (last - 1)->getPos() > end_pos) {--last;}
int number_resampled_points = (int)(ceil((end_pos - start_pos) / spacing_ + 1));
std::vector<typename PeakContainerT::PeakType> resampled_peak_container;
populate_raster_(resampled_peak_container, start_pos, end_pos, number_resampled_points);
raster(first, last, resampled_peak_container.begin(), resampled_peak_container.end());
container.swap(resampled_peak_container);
}
/**
@brief Resample points (e.g. Peak1D) from an input range onto a prepopulated output range with given m/z, modifying the output intensities.
This will use the raster provided by the output container, i.e. with alignment, to resample
the data provided in the input container. The intensities will be added
to the intensities in the output container (which in most cases will be
zero).
The intensities will be distributed between the two closest resampling
points, thus conserving the sum of intensity over the whole container.
Note that all intensity in the input data container that is in peaks
outside the range of the output container will simply be added to the
first or last data point.
@param[in] raw_it Start of the input container to be resampled (containing the data)
@param[in] raw_end End of the input container to be resampled (containing the data)
@param[in,out] resampled_begin Iterator pointing to start of the output spectrum range (m/z need to be populated, intensities should be zero)
@param[in,out] resampled_end Iterator pointing to end of the output spectrum range (m/z need to be populated, intensities should be zero)
*/
template <typename PeakTypeIterator, typename ConstPeakTypeIterator>
void raster(ConstPeakTypeIterator raw_it, ConstPeakTypeIterator raw_end, PeakTypeIterator resampled_begin, PeakTypeIterator resampled_end)
{
OPENMS_PRECONDITION(resampled_begin != resampled_end, "Output iterators cannot be identical") // as we use +1
// OPENMS_PRECONDITION(raw_it != raw_end, "Input iterators cannot be identical")
PeakTypeIterator resample_start = resampled_begin;
// need to get the raw iterator between two resampled iterators of the raw data
while (raw_it != raw_end && raw_it->getPos() < resampled_begin->getPos())
{
resampled_begin->setIntensity(resampled_begin->getIntensity() + raw_it->getIntensity());
raw_it++;
}
while (raw_it != raw_end)
{
//advance the resample iterator until our raw point is between two resampled iterators
while (resampled_begin != resampled_end && resampled_begin->getPos() < raw_it->getPos()) {resampled_begin++;}
if (resampled_begin != resample_start) {resampled_begin--;}
// if we have the last datapoint we break
if ((resampled_begin + 1) == resampled_end) {break;}
double dist_left = fabs(raw_it->getPos() - resampled_begin->getPos());
double dist_right = fabs(raw_it->getPos() - (resampled_begin + 1)->getPos());
// distribute the intensity of the raw point according to the distance to resample_it and resample_it+1
resampled_begin->setIntensity(resampled_begin->getIntensity() + raw_it->getIntensity() * dist_right / (dist_left + dist_right));
(resampled_begin + 1)->setIntensity((resampled_begin + 1)->getIntensity() + raw_it->getIntensity() * dist_left / (dist_left + dist_right));
raw_it++;
}
// add the final intensity to the right
while (raw_it != raw_end)
{
resampled_begin->setIntensity(resampled_begin->getIntensity() + raw_it->getIntensity());
raw_it++;
}
}
/**
@brief Resample points (with m/z and intensity in separate containers, but of same length) from an input range
onto a prepopulated output m/z & intensity range (each in separate containers, but of same length).
This will use the raster provided by the output container, i.e. with alignment,
to resample the data provided in the input container. The intensities will be added
to the intensities in the output container (which in most cases will be
zero).
The intensities will be distributed between the two closest resampling
points, thus conserving the sum of intensity over the whole container.
Note that all intensity in the input data container that is in peaks
outside the range of the output container will simply be added to the
first or last data point.
@param[in] mz_raw_it Start of the input container to be resampled (containing the m/z data)
@param[in] mz_raw_end End of the input container to be resampled (containing the m/z data)
@param[in] int_raw_it Start of the input container to be resampled (containing the intensity data)
@param[in] int_raw_end End of the input container to be resampled (containing the intensity data)
@param[in] mz_resample_it Iterator pointing to start of the output spectrum range (m/z which need to be populated)
@param[in] mz_resample_end Iterator pointing to end of the output spectrum range (m/z which need to be populated)
@param[in,out] int_resample_it Iterator pointing to start of the output spectrum range (intensities)
@param[in,out] int_resample_end Iterator pointing to end of the output spectrum range (intensities)
*/
template <typename PeakTypeIterator, typename ConstPeakTypeIterator>
void raster(ConstPeakTypeIterator mz_raw_it, ConstPeakTypeIterator mz_raw_end,
ConstPeakTypeIterator int_raw_it, ConstPeakTypeIterator int_raw_end,
ConstPeakTypeIterator mz_resample_it, ConstPeakTypeIterator mz_resample_end,
PeakTypeIterator int_resample_it, PeakTypeIterator int_resample_end)
{
(void)int_raw_end; // avoid 'unused parameter' compile error
(void)int_resample_end; // avoid 'unused parameter' compile error
OPENMS_PRECONDITION(mz_resample_it != mz_resample_end, "Output iterators cannot be identical") // as we use +1
OPENMS_PRECONDITION(std::distance(mz_resample_it, mz_resample_end) == std::distance(int_resample_it, int_resample_end),
"Resample m/z and intensity iterators need to cover the same distance")
OPENMS_PRECONDITION(std::distance(mz_raw_it, mz_raw_end) == std::distance(int_raw_it, int_raw_end),
"Raw m/z and intensity iterators need to cover the same distance")
// OPENMS_PRECONDITION(raw_it != raw_end, "Input iterators cannot be identical")
PeakTypeIterator mz_resample_start = mz_resample_it;
// need to get the raw iterator between two resampled iterators of the raw data
while (mz_raw_it != mz_raw_end && (*mz_raw_it) < (*mz_resample_it) )
{
(*int_resample_it) = *int_resample_it + *int_raw_it;
++mz_raw_it;
++int_raw_it;
}
while (mz_raw_it != mz_raw_end)
{
//advance the resample iterator until our raw point is between two resampled iterators
while (mz_resample_it != mz_resample_end && *mz_resample_it < *mz_raw_it)
{
++mz_resample_it; ++int_resample_it;
}
if (mz_resample_it != mz_resample_start)
{
--mz_resample_it; --int_resample_it;
}
// if we have the last datapoint we break
if ((mz_resample_it + 1) == mz_resample_end) {break;}
double dist_left = fabs(*mz_raw_it - *mz_resample_it);
double dist_right = fabs(*mz_raw_it - *(mz_resample_it + 1));
// distribute the intensity of the raw point according to the distance to resample_it and resample_it+1
*(int_resample_it) = *int_resample_it + (*int_raw_it) * dist_right / (dist_left + dist_right);
*(int_resample_it + 1) = *(int_resample_it + 1) + (*int_raw_it) * dist_left / (dist_left + dist_right);
++mz_raw_it;
++int_raw_it;
}
// add the final intensity to the right
while (mz_raw_it != mz_raw_end)
{
*int_resample_it = *int_resample_it + (*int_raw_it);
++mz_raw_it;
++int_raw_it;
}
}
/**
@brief Applies the resampling algorithm using a linear interpolation
This will use the raster provided by the output container to resample
the data provided in the input container. The intensities will be added
to the intensities in the output container (which in most cases will be
zero).
The intensities at the resampling point is computed by a linear
interpolation between the two closest resampling points.
@param[in] raw_it Start of the input (raw) spectrum to be resampled
@param[in] raw_end End of the input (raw) spectrum to be resampled
@param[in,out] resampled_start Iterator pointing to start of the output spectrum range (m/z need to be populated, intensities should be zero)
@param[in,out] resampled_end Iterator pointing to end of the output spectrum range (m/z need to be populated, intensities should be zero)
*/
template <typename PeakTypeIterator>
void raster_interpolate(PeakTypeIterator raw_it, PeakTypeIterator raw_end, PeakTypeIterator resampled_start, PeakTypeIterator resampled_end)
{
// OPENMS_PRECONDITION(resampled_start != resampled_end, "Output iterators cannot be identical")
OPENMS_PRECONDITION(raw_it != raw_end, "Input iterators cannot be identical") // as we use +1
PeakTypeIterator raw_start = raw_it;
// need to get the resampled iterator between two iterators of the raw data
while (resampled_start != resampled_end && resampled_start->getPos() < raw_it->getPos()) {resampled_start++;}
while (resampled_start != resampled_end)
{
//advance the raw_iterator until our current point we want to interpolate is between them
while (raw_it != raw_end && raw_it->getPos() < resampled_start->getPos()) {raw_it++;}
if (raw_it != raw_start) {raw_it--;}
// if we have the last datapoint we break
if ((raw_it + 1) == raw_end) {break;}
// use a linear interpolation between raw_it and raw_it+1
double m = ((raw_it + 1)->getIntensity() - raw_it->getIntensity()) / ((raw_it + 1)->getPos() - raw_it->getPos());
resampled_start->setIntensity(raw_it->getIntensity() + (resampled_start->getPos() - raw_it->getPos()) * m);
resampled_start++;
}
}
protected:
/// Spacing of the resampled data
bool ppm_;
void updateMembers_() override
{
spacing_ = param_.getValue("spacing");
ppm_ = (bool)param_.getValue("ppm").toBool();
}
/// Generate raster for resampled peak container
template <typename PeakType>
void populate_raster_(std::vector<PeakType>& resampled_peak_container,
double start_pos, double end_pos, int number_resampled_points)
{
if (!ppm_)
{
// generate the resampled peaks at positions origin+i*spacing_
resampled_peak_container.resize(number_resampled_points);
typename std::vector<PeakType>::iterator it = resampled_peak_container.begin();
for (int i = 0; i < number_resampled_points; ++i)
{
it->setPos(start_pos + i * spacing_);
++it;
}
}
else
{
// generate resampled peaks with ppm distance (not fixed)
double current_mz = start_pos;
while (current_mz < end_pos)
{
PeakType p;
p.setIntensity(0);
p.setPos(current_mz);
resampled_peak_container.push_back(p);
// increment current_mz
current_mz += current_mz * (spacing_ / 1e6);
}
}
}
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/PROCESSING/RESAMPLING/LinearResampler.h | .h | 4,946 | 146 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Eva Lange $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/KERNEL/StandardTypes.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <limits>
#include <cmath>
namespace OpenMS
{
/**
@brief Linear Resampling of raw data.
This class can be used to generate uniform data from non-uniform raw data (e.g. ESI-TOF or MALDI-TOF experiments).
Therefore the intensity at every position x in the input raw data is spread to the two
adjacent resampling points.
This method preserves the area of the input signal and also the centroid position of a peak.
Therefore it is recommended for quantitation as well as for ProteinIdentification experiments.
@note Use this method only for high resolution data (< 0.1 Th between two adjacent raw data points).
The resampling rate should be >= the precision.
@htmlinclude OpenMS_LinearResampler.parameters
*/
class OPENMS_DLLAPI LinearResampler :
public DefaultParamHandler,
public ProgressLogger
{
public:
/// Constructor
LinearResampler() :
DefaultParamHandler("LinearResampler")
{
defaults_.setValue("spacing", 0.05, "Spacing of the resampled output peaks.");
defaultsToParam_();
}
/// Destructor.
~LinearResampler() override
{
}
/**
@brief Applies the resampling algorithm to an MSSpectrum, without alignment between spectra.
*/
void raster(MSSpectrum& spectrum) const
{
//return if nothing to do
if (spectrum.empty()) return;
typename MSSpectrum::iterator first = spectrum.begin();
typename MSSpectrum::iterator last = spectrum.end();
double end_pos = (last - 1)->getMZ();
double start_pos = first->getMZ();
int number_raw_points = static_cast<int>(spectrum.size());
int number_resampled_points = static_cast<int>(ceil((end_pos - start_pos) / spacing_ + 1));
std::vector<Peak1D> resampled_peak_container;
resampled_peak_container.resize(number_resampled_points);
// generate the resampled peaks at positions origin+i*spacing_
std::vector<Peak1D>::iterator it = resampled_peak_container.begin();
for (int i = 0; i < number_resampled_points; ++i)
{
it->setMZ(start_pos + i * spacing_);
++it;
}
// spread the intensity h of the data point at position x to the left and right
// adjacent resampled peaks
double distance_left = 0.;
double distance_right = 0.;
int left_index = 0;
int right_index = 0;
it = resampled_peak_container.begin();
for (int i = 0; i < number_raw_points; ++i)
{
int help = static_cast<int>(floor(((first + i)->getMZ() - start_pos) / spacing_));
left_index = (help < 0) ? 0 : help;
help = distance(first, last) - 1;
right_index = (left_index >= help) ? help : left_index + 1;
// compute the distance between x and the left adjacent resampled peak
distance_left = fabs((first + i)->getMZ() - (it + left_index)->getMZ()) / spacing_;
//std::cout << "Distance left " << distance_left << std::endl;
// compute the distance between x and the right adjacent resampled peak
distance_right = fabs((first + i)->getMZ() - (it + right_index)->getMZ());
//std::cout << "Distance right " << distance_right << std::endl;
// add the distance_right*h to the left resampled peak and distance_left*h to the right resampled peak
double intensity = static_cast<double>((it + left_index)->getIntensity());
intensity += static_cast<double>((first + i)->getIntensity()) * distance_right / spacing_;
(it + left_index)->setIntensity(intensity);
intensity = static_cast<double>((it + right_index)->getIntensity());
intensity += static_cast<double>((first + i)->getIntensity()) * distance_left;
(it + right_index)->setIntensity(intensity);
}
spectrum.swap(resampled_peak_container);
}
/**
@brief Resamples the data in an MSExperiment, without alignment between spectra.
*/
void rasterExperiment(PeakMap& exp)
{
startProgress(0, exp.size(), "resampling of data");
for (Size i = 0; i < exp.size(); ++i)
{
raster(exp[i]);
setProgress(i);
}
endProgress();
}
protected:
/// Spacing of the resampled data
double spacing_;
void updateMembers_() override
{
spacing_ = param_.getValue("spacing");
}
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ML/NNLS/NonNegativeLeastSquaresSolver.h | .h | 3,854 | 86 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Chris Bielow $
// $Authors: Chris Bielow $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/Matrix.h>
#include <vector>
namespace OpenMS
{
/**
@brief Wrapper for a non-negative least squares (NNLS) solver.
It solves Ax=b, where x>0 in the least squares sense (i.e. minimum residual)
*/
class OPENMS_DLLAPI NonNegativeLeastSquaresSolver
{
public:
enum RETURN_STATUS
{
SOLVED,
ITERATION_EXCEEDED
};
/**
@brief Solve the non-negative least square problem Ax=b, where x>0
This overload copies the input matrix and vector before solving, preserving the originals.
@param[in] A Input matrix A of size m x n
@param[in] b Input vector (OpenMS::Matrix with one column) b of size m x 1
@param[out] x Output vector (OpenMS::Matrix with one column) with non-negative least square solution of size n x 1
@return status of solution (either NonNegativeLeastSquaresSolver::SOLVED, NonNegativeLeastSquaresSolver::ITERATION_EXCEEDED)
@throws Exception::InvalidParameters if Matrix dimensions do not fit
*/
static Int solve(const Matrix<double>& A, const Matrix<double>& b, Matrix<double>& x);
/**
@brief Solve the non-negative least square problem Ax=b, where x>0. Works in-place.
This version works directly on raw buffers and modifies inputs in-place for efficiency.
@param[in,out] A Pointer to matrix data of size m x n (need memory-contiguous representation
in column-major order, i.e., A_rows * A_cols doubles). Must be non-null and
point to a buffer of at least A_rows * A_cols doubles. The caller retains
ownership and must ensure A remains valid for the duration of this call.
Modified in-place by the solver; contents are undefined after the call.
Passing nullptr or an insufficiently sized buffer results in undefined behavior.
@param[in] A_rows Number of rows in A (must be > 0)
@param[in] A_cols Number of columns in A (must be > 0)
@param[in,out] b Input vector b of size m. Modified in-place by the solver.
@param[out] x Output vector with non-negative least square solution of size n.
@return status of solution (either NonNegativeLeastSquaresSolver::SOLVED, NonNegativeLeastSquaresSolver::ITERATION_EXCEEDED)
@throws Exception::InvalidParameters if A_rows does not match b.size()
@note For a safer interface with bounds checking, prefer the Matrix<double>& overload.
A future revision may adopt std::span for improved pointer safety.
*/
static Int solve(double* A, int A_rows, int A_cols,
std::vector<double>& b, std::vector<double>& x);
/**
@brief Solve the non-negative least square problem Ax=b using Matrix and vectors.
This overload works with OpenMS Matrix and std::vector, modifying inputs in-place for efficiency.
@param[in,out] A Input matrix A of size m x n. Modified in-place by the solver.
@param[in,out] b Input vector b of size m. Modified in-place by the solver.
@param[out] x Output vector with non-negative least square solution of size n.
@return status of solution (either NonNegativeLeastSquaresSolver::SOLVED, NonNegativeLeastSquaresSolver::ITERATION_EXCEEDED)
@throws Exception::InvalidParameters if Matrix dimensions do not fit
*/
static Int solve(Matrix<double>& A, std::vector<double>& b, std::vector<double>& x);
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ML/NNLS/NNLS.h | .h | 3,758 | 86 | // 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
{
namespace NNLS
{
typedef int integer;
/* SUBROUTINE NNLS (A,MDA,M,N,B,X,RNORM,W,ZZ,INDEX,MODE) */
/* Algorithm NNLS: NONNEGATIVE LEAST SQUARES */
/* The original version of this code was developed by */
/* Charles L. Lawson and Richard J. Hanson at Jet Propulsion Laboratory */
/* 1973 JUN 15, and published in the book */
/* "SOLVING LEAST SQUARES PROBLEMS", Prentice-Hall, 1974. */
/* Revised FEB 1995 to accompany reprinting of the book by SIAM. */
/* GIVEN AN M BY N MATRIX, A, AND AN M-VECTOR, B, COMPUTE AN */
/* N-VECTOR, X, THAT SOLVES THE LEAST SQUARES PROBLEM */
/* A * X = B SUBJECT TO X .GE. 0 */
/* ------------------------------------------------------------------ */
/* Subroutine Arguments */
/* A(),MDA,M,N MDA IS THE FIRST DIMENSIONING PARAMETER FOR THE */
/* ARRAY, A(). ON ENTRY A() CONTAINS THE M BY N */
/* MATRIX, A. ON EXIT A() CONTAINS */
/* THE PRODUCT MATRIX, Q*A , WHERE Q IS AN */
/* M BY M ORTHOGONAL MATRIX GENERATED IMPLICITLY BY */
/* THIS SUBROUTINE. */
/* B() ON ENTRY B() CONTAINS THE M-VECTOR, B. ON EXIT B() CON- */
/* TAINS Q*B. */
/* X() ON ENTRY X() NEED NOT BE INITIALIZED. ON EXIT X() WILL */
/* CONTAIN THE SOLUTION VECTOR. */
/* RNORM ON EXIT RNORM CONTAINS THE EUCLIDEAN NORM OF THE */
/* RESIDUAL VECTOR. */
/* W() AN N-ARRAY OF WORKING SPACE. ON EXIT W() WILL CONTAIN */
/* THE DUAL SOLUTION VECTOR. W WILL SATISFY W(I) = 0. */
/* FOR ALL I IN SET P AND W(I) .LE. 0. FOR ALL I IN SET Z */
/* ZZ() AN M-ARRAY OF WORKING SPACE. */
/* INDEX() AN INTEGER WORKING ARRAY OF LENGTH AT LEAST N. */
/* ON EXIT THE CONTENTS OF THIS ARRAY DEFINE THE SETS */
/* P AND Z AS FOLLOWS.. */
/* INDEX(1) THRU INDEX(NSETP) = SET P. */
/* INDEX(IZ1) THRU INDEX(IZ2) = SET Z. */
/* IZ1 = NSETP + 1 = NPP1 */
/* IZ2 = N */
/* MODE THIS IS A SUCCESS-FAILURE FLAG WITH THE FOLLOWING */
/* MEANINGS. */
/* 1 THE SOLUTION HAS BEEN COMPUTED SUCCESSFULLY. */
/* 2 THE DIMENSIONS OF THE PROBLEM ARE BAD. */
/* EITHER M .LE. 0 OR N .LE. 0. */
/* 3 ITERATION COUNT EXCEEDED. MORE THAN 3*N ITERATIONS. */
int OPENMS_DLLAPI nnls_(double * a, integer * mda, integer * m, integer *
n, double * b, double * x, double * rnorm, double * w,
double * zz, integer * index, integer * mode);
/* Subroutine */
int OPENMS_DLLAPI g1_(double *, double *, double *, double *, double *);
/* Subroutine */
int OPENMS_DLLAPI h12_(integer *, integer *, integer *, integer *, double *, integer *, double *, double *, integer *, integer *, integer *);
/* Subroutine */
double OPENMS_DLLAPI diff_(double *, double *);
/* Subroutine */
double OPENMS_DLLAPI d_sign_(double & a, double & b);
}
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ML/INTERPOLATION/BilinearInterpolation.h | .h | 24,073 | 788 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/Matrix.h>
#include <cmath>
namespace OpenMS
{
namespace Math
{
/**
@brief Provides access to bilinearly interpolated values (and
derivatives) from discrete data points. Values beyond the given range
of data points are implicitly taken as zero.
The input is just a vector of values ("Data"). These are interpreted
as the y-coordinates at the x-coordinate positions 0,...,data_.size-1.
The interpolated data can also be <i>scaled</i> and <i>shifted</i> in
the x-dimension by an <em>affine mapping</em>. That is, we have "inside" and
"outside" x-coordinates. The affine mapping can be specified in two
ways:
- using setScale() and setOffset(),
- using setMapping()
.
By default the identity mapping (scale=1, offset=0) is used.
Using the value() and derivative() methods you can sample bilinearly
interpolated values for a given x-coordinate position of the data and
the derivative of the data.
@see LinearInterpolation
@ingroup Math
*/
template <typename Key = double, typename Value = Key>
class BilinearInterpolation
{
public:
///@name Typedefs
//@{
typedef Value value_type;
typedef Key key_type;
typedef Matrix<value_type> container_type;
typedef value_type ValueType;
typedef key_type KeyType;
typedef container_type ContainerType;
//@}
public:
/**@brief Constructors and destructor.
*/
//@{
/// Default constructor
BilinearInterpolation() :
scale_0_(1),
offset_0_(0),
scale_1_(1),
offset_1_(0),
inside_0_(0),
outside_0_(0),
inside_1_(0),
outside_1_(0),
data_()
{}
/// Copy constructor
BilinearInterpolation(BilinearInterpolation const & arg) :
scale_0_(arg.scale_0_),
offset_0_(arg.offset_0_),
scale_1_(arg.scale_1_),
offset_1_(arg.offset_1_),
inside_0_(arg.inside_0_),
outside_0_(arg.outside_0_),
inside_1_(arg.inside_1_),
outside_1_(arg.outside_1_),
data_(arg.data_)
{}
/// Assignment operator
BilinearInterpolation & operator=(BilinearInterpolation const & arg)
{
if (&arg == this)
return *this;
scale_0_ = arg.scale_0_;
offset_0_ = arg.offset_0_;
scale_1_ = arg.scale_1_;
offset_1_ = arg.offset_1_;
inside_0_ = arg.inside_0_;
outside_1_ = arg.outside_1_;
inside_1_ = arg.inside_1_;
outside_0_ = arg.outside_0_;
data_ = arg.data_;
return *this;
}
/// Destructor
~BilinearInterpolation()
{}
//@}
// ----------------------------------------------------------------------
///@name Interpolated data
//@{
/// Returns the interpolated value ("backward resampling")
ValueType value(KeyType arg_pos_0, KeyType arg_pos_1) const
{
// apply the key transformations
KeyType const pos_0 = key2index_0(arg_pos_0);
KeyType const pos_1 = key2index_1(arg_pos_1);
// ???? should use modf() here!
SignedSize const size_0 = data_.rows();
SignedSize const lower_0 = SignedSize(pos_0); // this rounds towards zero
SignedSize const size_1 = data_.cols();
SignedSize const lower_1 = SignedSize(pos_1); // this rounds towards zero
// small pos_0
if (pos_0 <= 0)
{
if (lower_0 != 0)
{
return 0;
}
else // that is: -1 < pos_0 <= 0
{ // small pos_1
if (pos_1 <= 0)
{
if (lower_1 != 0)
{
return 0;
}
else // that is: -1 < pos_1 <= 0
{
return data_(0, 0) * (1. + pos_0) * (1. + pos_1);
}
}
// big pos_1
if (lower_1 >= size_1 - 1)
{
if (lower_1 != size_1 - 1)
{
return 0;
}
else
{
return data_(0, lower_1) * (1. + pos_0) * (size_1 - pos_1);
}
}
// medium pos_1
KeyType const factor_1 = pos_1 - KeyType(lower_1);
KeyType const factor_1_complement = KeyType(1.) - factor_1;
return (
data_(0, lower_1 + 1) * factor_1 +
data_(0, lower_1) * factor_1_complement
) * (1. + pos_0);
}
}
// big pos_0
if (lower_0 >= size_0 - 1)
{
if (lower_0 != size_0 - 1)
{
return 0;
}
else // that is: size_0 - 1 <= pos_0 < size_0
{ // small pos_1
if (pos_1 <= 0)
{
if (lower_1 != 0)
{
return 0;
}
else // that is: -1 < pos_1 <= 0
{
return data_(lower_0, 0) * (size_0 - pos_0) * (1. + pos_1);
}
}
// big pos_1
if (lower_1 >= size_1 - 1)
{
if (lower_1 != size_1 - 1)
{
return 0;
}
else
{
return data_(lower_0, lower_1) * (size_0 - pos_0) * (size_1 - pos_1);
}
}
// medium pos_1
KeyType const factor_1 = pos_1 - KeyType(lower_1);
KeyType const factor_1_complement = KeyType(1.) - factor_1;
return (
data_(lower_0, lower_1 + 1) * factor_1 +
data_(lower_0, lower_1) * factor_1_complement
)
* (size_0 - pos_0);
}
}
// medium pos_0
{
KeyType const factor_0 = pos_0 - KeyType(lower_0);
KeyType const factor_0_complement = KeyType(1.) - factor_0;
// small pos_1
if (pos_1 <= 0)
{
if (lower_1 != 0)
{
return 0;
}
else // that is: -1 < pos_1 <= 0
{
return (
data_(lower_0 + 1, 0) * factor_0
+
data_(lower_0, 0) * factor_0_complement
)
* (1. + pos_1);
}
}
// big pos_1
if (lower_1 >= size_1 - 1)
{
if (lower_1 != size_1 - 1)
{
return 0;
}
else
{
return (
data_(lower_0 + 1, lower_1) * factor_0
+
data_(lower_0, lower_1) * factor_0_complement
)
* (size_1 - pos_1);
}
}
KeyType const factor_1 = pos_1 - KeyType(lower_1);
KeyType const factor_1_complement = KeyType(1.) - factor_1;
// medium pos_0 and medium pos_1 --> "within" the matrix
return (
data_(lower_0 + 1, lower_1 + 1) * factor_0
+
data_(lower_0, lower_1 + 1) * factor_0_complement
)
* factor_1
+
(
data_(lower_0 + 1, lower_1) * factor_0
+
data_(lower_0, lower_1) * factor_0_complement
)
* factor_1_complement;
}
}
/**@brief Performs bilinear resampling. The arg_value is split up and
added to the data points around arg_pos. ("forward resampling")
*/
void addValue(KeyType arg_pos_0, KeyType arg_pos_1, ValueType arg_value)
{
typedef typename std::ptrdiff_t DiffType;
// apply key transformation _0
KeyType const pos_0 = key2index_0(arg_pos_0);
KeyType lower_0_key;
KeyType const frac_0 = std::modf(pos_0, &lower_0_key);
DiffType const lower_0 = DiffType(lower_0_key);
// Small pos_0 ?
if (pos_0 < 0)
{
if (lower_0)
{
return;
}
else // lower_0 == 0
{ // apply key transformation _1
KeyType const pos_1 = key2index_1(arg_pos_1);
KeyType lower_1_key;
KeyType const frac_1 = std::modf(pos_1, &lower_1_key);
DiffType const lower_1 = DiffType(lower_1_key);
// Small pos_1 ?
if (pos_1 < 0)
{
if (lower_1)
{
return;
}
else // lower_1 == 0
{
data_(0, 0) += arg_value * (1 + frac_0) * (1 + frac_1);
return;
}
}
else // pos_1 >= 0
{
DiffType const back_1 = data_.cols() - 1;
// big pos_1
if (lower_1 >= back_1)
{
if (lower_1 != back_1)
{
return;
}
else // lower_1 == back_1
{
data_(0, lower_1) += arg_value * (1 + frac_0) * (1 - frac_1);
return;
}
}
else
{
// medium pos_1
KeyType const tmp_prod = KeyType(arg_value * (1. + frac_0));
data_(0, lower_1 + 1) += tmp_prod * frac_1;
data_(0, lower_1) += tmp_prod * (1. - frac_1);
return;
}
}
}
}
else // pos_0 >= 0
{
DiffType const back_0 = data_.rows() - 1;
if (lower_0 >= back_0)
{
if (lower_0 != back_0)
{
return;
}
else // lower_0 == back_0
{
KeyType const tmp_prod = KeyType(arg_value * (1. - frac_0));
// apply key transformation _1
KeyType const pos_1 = key2index_1(arg_pos_1);
KeyType lower_1_key;
KeyType const frac_1 = std::modf(pos_1, &lower_1_key);
DiffType const lower_1 = DiffType(lower_1_key);
// Small pos_1 ?
if (pos_1 < 0)
{
if (lower_1)
{
return;
}
else // lower_1 == 0
{
data_(lower_0, 0) += tmp_prod * (1 + frac_1);
return;
}
}
else // pos_1 >= 0
{
DiffType const back_1 = data_.cols() - 1;
// big pos_1
if (lower_1 >= back_1)
{
if (lower_1 != back_1)
{
return;
}
else // lower_1 == back_1
{
data_(lower_0, lower_1) += tmp_prod * (1 - frac_1);
return;
}
}
else
{
// medium pos_1
data_(lower_0, lower_1 + 1) += tmp_prod * frac_1;
data_(lower_0, lower_1) += tmp_prod * (1 - frac_1);
return;
}
}
}
}
else // lower_0 < back_0
{
// Medium pos_0 !
// apply key transformation _1
KeyType const pos_1 = key2index_1(arg_pos_1);
KeyType lower_1_key;
KeyType const frac_1 = std::modf(pos_1, &lower_1_key);
DiffType const lower_1 = DiffType(lower_1_key);
// Small pos_1 ?
if (pos_1 < 0)
{
if (lower_1)
{
return;
}
else // lower_1 == 0
{
KeyType const tmp_prod = KeyType(arg_value * (1 + frac_1));
data_(lower_0 + 1, 0) += tmp_prod * frac_0;
data_(lower_0, 0) += tmp_prod * (1 - frac_0);
return;
}
}
else // pos_1 >= 0
{
DiffType const back_1 = data_.cols() - 1;
// big pos_1
if (lower_1 >= back_1)
{
if (lower_1 != back_1)
{
return;
}
else // lower_1 == back_1
{
KeyType const tmp_prod = KeyType(arg_value * (1 - frac_1));
data_(lower_0 + 1, lower_1) += tmp_prod * frac_0;
data_(lower_0, lower_1) += tmp_prod * (1 - frac_0);
return;
}
}
else
{
// Medium pos_1 !
// medium pos_0 and medium pos_1 --> "within" the matrix
KeyType tmp_prod = KeyType(arg_value * frac_0);
data_(lower_0 + 1, lower_1 + 1) += tmp_prod * frac_1;
data_(lower_0 + 1, lower_1) += tmp_prod * (1 - frac_1);
tmp_prod = KeyType(arg_value * (1 - frac_0));
data_(lower_0, lower_1 + 1) += tmp_prod * frac_1;
data_(lower_0, lower_1) += tmp_prod * (1 - frac_1);
return;
}
}
}
}
}
//@}
// ----------------------------------------------------------------------
///@name Discrete (non-interpolated) data
//@{
/// Returns the internal random access container storing the data.
ContainerType & getData()
{
return data_;
}
/// Returns the internal random access container storing the data.
ContainerType const & getData() const
{
return data_;
}
/**@brief Assigns data to the internal random access container storing
the data.
SourceContainer must be assignable to ContainerType.
*/
template <typename SourceContainer>
void setData(SourceContainer const & data)
{
data_ = data;
}
/// Returns \c true if getData() is empty.
bool empty() const
{
return data_.empty();
}
//@}
// ----------------------------------------------------------------------
///\name Transformation
//@{
/// The transformation from "outside" to "inside" coordinates.
KeyType key2index_0(KeyType pos) const
{
if (scale_0_)
{
pos -= offset_0_;
pos /= scale_0_;
return pos;
}
else
{
return 0;
}
}
/// The transformation from "inside" to "outside" coordinates.
KeyType index2key_0(KeyType pos) const
{
pos *= scale_0_;
pos += offset_0_;
return pos;
}
/// The transformation from "outside" to "inside" coordinates.
KeyType key2index_1(KeyType pos) const
{
if (scale_1_)
{
pos -= offset_1_;
pos /= scale_1_;
return pos;
}
else
{
return 0;
}
}
/// The transformation from "inside" to "outside" coordinates.
KeyType index2key_1(KeyType pos) const
{
pos *= scale_1_;
pos += offset_1_;
return pos;
}
/// Accessor. "Scale" is the difference (in "outside" units) between consecutive entries in "Data".
KeyType const & getScale_0() const
{
return scale_0_;
}
/// Accessor. "Scale" is the difference (in "outside" units) between consecutive entries in "Data".
KeyType const & getScale_1() const
{
return scale_1_;
}
/**@brief Accessor. "Scale" is the difference (in "outside" units) between consecutive entries in "Data".
<b>Note:</b> Using this invalidates the inside and outside reference
points.
*/
void setScale_0(KeyType const & scale)
{
scale_0_ = scale;
}
/**@brief Accessor. "Scale" is the difference (in "outside" units) between consecutive entries in "Data".
<b>Note:</b> Using this invalidates the inside and outside reference
points.
*/
void setScale_1(KeyType const & scale)
{
scale_1_ = scale;
}
/// Accessor. "Offset" is the point (in "outside" units) which corresponds to "Data(0,0)".
KeyType const & getOffset_0() const
{
return offset_0_;
}
/// Accessor. "Offset" is the point (in "outside" units) which corresponds to "Data(0,0)".
KeyType const & getOffset_1() const
{
return offset_1_;
}
/**@brief Accessor. "Offset" is the point (in "outside" units) which
corresponds to "Data(0,0)".
<b>Note:</b> Using this invalidates the inside and outside reference
points.
*/
void setOffset_0(KeyType const & offset)
{
offset_0_ = offset;
}
/**@brief Accessor. "Offset" is the point (in "outside" units) which
corresponds to "Data(0,0)".
<b>Note:</b> Using this invalidates the inside and outside reference
points.
*/
void setOffset_1(KeyType const & offset)
{
offset_1_ = offset;
}
/**@brief Specifies the mapping from "outside" to "inside" coordinates by the following data:
- <code>scale</code>: the difference in outside coordinates between consecutive values in the data vector.
- <code>inside</code> and <code>outside</code>: these axis positions are mapped onto each other.
For example, when you have a complicated probability distribution
which is in fact centered around zero (but you cannot have negative
indices in the data vector), then you can arrange things such that
inside is the mean of the pre-computed, shifted density values of that
distribution and outside is the centroid position of, say, a peak in
the real world which you want to model by a scaled and shifted version
of the probability distribution.
*/
void setMapping_0(KeyType const & scale, KeyType const & inside_low, KeyType const & outside_low)
{
scale_0_ = scale;
inside_0_ = inside_low;
outside_0_ = outside_low;
offset_0_ = outside_low - scale * inside_low;
return;
}
/**@brief Specifies the mapping from "outside" to "inside" coordinates by the following data:
- <code>inside_low</code> and <code>outside_low</code>: these axis positions are mapped onto each other.
- <code>inside_high</code> and <code>outside_high</code>: these axis positions are mapped onto each other.
This four argument version is just a convenience overload for the three argument version, which see.
*/
void setMapping_0(KeyType const & inside_low, KeyType const & outside_low,
KeyType const & inside_high, KeyType const & outside_high)
{
if (inside_high != inside_low)
{
setMapping_0((outside_high - outside_low) / (inside_high - inside_low),
inside_low, outside_low);
}
else
{
setMapping_0(0, inside_low, outside_low);
}
return;
}
/**@brief Specifies the mapping from "outside" to "inside" coordinates by the following data:
- <code>scale</code>: the difference in outside coordinates between consecutive values in the data vector.
- <code>inside</code> and <code>outside</code>: these axis positions are mapped onto each other.
For example, when you have a complicated probability distribution
which is in fact centered around zero (but you cannot have negative
indices in the data vector), then you can arrange things such that
inside is the mean of the pre-computed, shifted density values of that
distribution and outside is the centroid position of, say, a peak in
the real world which you want to model by a scaled and shifted version
of the probability distribution.
*/
void setMapping_1(KeyType const & scale, KeyType const & inside_low, KeyType const & outside_low)
{
scale_1_ = scale;
inside_1_ = inside_low;
outside_1_ = outside_low;
offset_1_ = outside_low - scale * inside_low;
return;
}
/**@brief Specifies the mapping from "outside" to "inside" coordinates by the following data:
- <code>inside_low</code> and <code>outside_low</code>: these axis positions are mapped onto each other.
- <code>inside_high</code> and <code>outside_high</code>: these axis positions are mapped onto each other.
This four argument version is just a convenience overload for the three argument version, which see.
*/
void setMapping_1(KeyType const & inside_low, KeyType const & outside_low,
KeyType const & inside_high, KeyType const & outside_high)
{
if (inside_high != inside_low)
{
setMapping_1((outside_high - outside_low) / (inside_high - inside_low),
inside_low, outside_low);
}
else
{
setMapping_1(0, inside_low, outside_low);
}
return;
}
/// Accessor. See setMapping().
KeyType const & getInsideReferencePoint_0() const
{
return inside_0_;
}
/// Accessor. See setMapping().
KeyType const & getInsideReferencePoint_1() const
{
return inside_1_;
}
/// Accessor. See setMapping().
KeyType const & getOutsideReferencePoint_0() const
{
return outside_0_;
}
/// Accessor. See setMapping().
KeyType const & getOutsideReferencePoint_1() const
{
return outside_1_;
}
/// Lower boundary of the support, in "outside" coordinates.
KeyType supportMin_0() const
{
return index2key_0(empty() ? KeyType(0.) : KeyType(-1.));
}
/// Lower boundary of the support, in "outside" coordinates.
KeyType supportMin_1() const
{
return index2key_1(empty() ? KeyType(0.) : KeyType(-1.));
}
/// Upper boundary of the support, in "outside" coordinates.
KeyType supportMax_0() const
{
return index2key_0(KeyType(data_.rows()));
}
/// Upper boundary of the support, in "outside" coordinates.
KeyType supportMax_1() const
{
return index2key_1(KeyType(data_.cols()));
}
//@}
protected:
/**@brief Data members*/
//@{
KeyType scale_0_;
KeyType offset_0_;
KeyType scale_1_;
KeyType offset_1_;
KeyType inside_0_;
KeyType outside_0_;
KeyType inside_1_;
KeyType outside_1_;
ContainerType data_;
//@}
};
} // namespace Math
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ML/INTERPOLATION/LinearInterpolation.h | .h | 12,935 | 461 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CONCEPT/Types.h>
#include <cmath> // for modf() (which is an overloaded function in C++)
#include <vector>
namespace OpenMS
{
namespace Math
{
/**
@brief Provides access to linearly interpolated values (and
derivatives) from discrete data points. Values beyond the given range
of data points are implicitly taken as zero.
The input is just a vector of values ("Data"). These are interpreted
as the y-coordinates at the x-coordinate positions 0,...,data_.size-1.
The interpolated data can also be <i>scaled</i> and <i>shifted</i> in
the x-dimension by an <em>affine mapping</em>. That is, we have "inside" and
"outside" x-coordinates. The affine mapping can be specified in two
ways:
- using setScale() and setOffset(),
- using setMapping()
.
By default the identity mapping (scale=1, offset=0) is used.
Using the value() and derivative() methods you can sample linearly
interpolated values for a given x-coordinate position of the data and
the derivative of the data.
@see BilinearInterpolation
@ingroup Math
*/
template <typename Key = double, typename Value = Key>
class LinearInterpolation
{
public:
///\name Typedefs
//@{
typedef Value value_type;
typedef Key key_type;
typedef std::vector<value_type> container_type;
typedef value_type ValueType;
typedef key_type KeyType;
typedef container_type ContainerType;
//@}
public:
/**@brief Constructors and destructor.
The first argument is the scale which is applied to the arguments of
value() and derivative() before looking up the interpolated values in
the container. The second argument is the offset, which is
subtracted before everything else.
*/
LinearInterpolation(KeyType scale = 1., KeyType offset = 0.) :
scale_(scale),
offset_(offset),
inside_(),
outside_(),
data_()
{}
/// Copy constructor.
LinearInterpolation(LinearInterpolation const & arg) :
scale_(arg.scale_),
offset_(arg.offset_),
inside_(arg.inside_),
outside_(arg.outside_),
data_(arg.data_)
{}
/// Assignment operator
LinearInterpolation & operator=(LinearInterpolation const & arg)
{
if (&arg == this)
return *this;
scale_ = arg.scale_;
offset_ = arg.offset_;
inside_ = arg.inside_;
outside_ = arg.outside_;
data_ = arg.data_;
return *this;
}
/// Destructor.
~LinearInterpolation() = default;
// ----------------------------------------------------------------------
///@name Interpolated data
//@{
/// Returns the interpolated value.
ValueType value(KeyType arg_pos) const
{
typedef typename container_type::difference_type DiffType;
// apply the key transformation
KeyType left_key;
KeyType pos = key2index(arg_pos);
KeyType frac = std::modf(pos, &left_key);
DiffType const left = DiffType(left_key);
// At left margin?
if (pos < 0)
{
if (left /* <= -1 */)
{
return 0;
}
else // left == 0
{
return data_[0] * (1 + frac);
}
}
else // pos >= 0
{
// At right margin?
DiffType const back = data_.size() - 1;
if (left >= back)
{
if (left != back)
{
return 0;
}
else
{
return data_[left] * (1 - frac);
}
}
else
{
// In between!
return data_[left + 1] * frac + data_[left] * (1 - frac);
}
}
}
/** @brief Performs linear resampling. The arg_value is split up and
added to the data points around arg_pos.
*/
void addValue(KeyType arg_pos, ValueType arg_value)
{
typedef typename container_type::difference_type DiffType;
// apply the key transformation
KeyType left_key;
KeyType const pos = key2index(arg_pos);
KeyType const frac = std::modf(pos, &left_key);
DiffType const left = DiffType(left_key);
// At left margin?
if (pos < 0)
{
if (left /* <= -1 */)
{
return;
}
else // left == 0
{
data_[0] += (1 + frac) * arg_value;
return;
}
}
else // pos >= 0
{
// At right margin?
DiffType const back = data_.size() - 1;
if (left >= back)
{
if (left != back)
{
return;
}
else // left == back
{
data_[left] += (1 - frac) * arg_value;
return;
}
}
else
{
// In between!
data_[left + 1] += frac * arg_value;
data_[left] += (1 - frac) * arg_value;
return;
}
}
}
/** @brief Returns the interpolated derivative.
Please drop me (= the maintainer) a message if you are using this.
*/
ValueType derivative(KeyType arg_pos) const
{
// apply the key transformation
KeyType const pos = key2index(arg_pos);
SignedSize const size_ = data_.size();
SignedSize const left = int(pos + 0.5); // rounds towards zero
if (left < 0) // quite small
{
return 0;
}
else
{
if (left == 0) // at the border
{
if (pos >= -0.5) // that is: -0.5 <= pos < +0.5
{
return (data_[1] - data_[0]) * (pos + 0.5) + (data_[0]) * (0.5 - pos);
}
else // that is: -1.5 <= pos < -0.5
{
return (data_[0]) * (pos + 1.5);
}
}
}
// "else" case: to the right of the left margin
KeyType factor = KeyType(left) - pos + KeyType(0.5);
if (left > size_) // quite large
{
return 0;
}
else
{
if (left < size_ - 1) // to the left of the right margin
{
// weighted average of derivatives for adjacent intervals
return (data_[left] - data_[left - 1]) * factor + (data_[left + 1] - data_[left]) * (1. - factor);
}
else // somewhat at the border
{
// at the border, first case
if (left == size_ - 1)
{
return (data_[left] - data_[left - 1]) * factor + (-data_[left]) * (1. - factor);
}
}
}
// else // that is: left == size_
// We pull the last remaining case out of the "if" tree to avoid a
// compiler warning ...
// at the border, second case
return (-data_[left - 1]) * factor;
}
//@}
// ----------------------------------------------------------------------
///@name Discrete (non-interpolated) data
//@{
/// Returns the internal random access container from which interpolated values are being sampled.
ContainerType & getData()
{
return data_;
}
/// Returns the internal random access container from which interpolated values are being sampled.
ContainerType const & getData() const
{
return data_;
}
/** @brief Assigns data to the internal random access container from
which interpolated values are being sampled.
SourceContainer must be assignable to ContainerType.
*/
template <typename SourceContainer>
void setData(SourceContainer const & data)
{
data_ = data;
}
/// Returns \c true if getData() is empty.
bool empty() const
{
return data_.empty();
}
//@}
// ----------------------------------------------------------------------
///\name Transformation
//@{
/// The transformation from "outside" to "inside" coordinates.
KeyType key2index(KeyType pos) const
{
if (scale_)
{
pos -= offset_;
pos /= scale_;
return pos;
}
else
{
return 0;
}
}
/// The transformation from "inside" to "outside" coordinates.
KeyType index2key(KeyType pos) const
{
pos *= scale_;
pos += offset_;
return pos;
}
/// Accessor. "Scale" is the difference (in "outside" units) between consecutive entries in "Data".
KeyType const & getScale() const
{
return scale_;
}
/** @brief Accessor. "Scale" is the difference (in "outside" units) between consecutive entries in "Data".
<b>Note:</b> Using this invalidates the inside and outside reference
points.
*/
void setScale(KeyType const & scale)
{
scale_ = scale;
}
/// Accessor. "Offset" is the point (in "outside" units) which corresponds to "Data[0]".
KeyType const & getOffset() const
{
return offset_;
}
/**@brief Accessor. "Offset" is the point (in "outside" units) which
corresponds to "Data[0]".
<b>Note:</b> Using this invalidates the inside and outside reference
points.
*/
void setOffset(KeyType const & offset)
{
offset_ = offset;
}
/** @brief Specifies the mapping from "outside" to "inside" coordinates by the following data:
- <code>scale</code>: the difference in outside coordinates between consecutive values in the data vector.
- <code>inside</code> and <code>outside</code>: these x-axis positions are mapped onto each other.
For example, when you have a complicated probability distribution
which is in fact centered around zero (but you cannot have negative
indices in the data vector), then you can arrange things such that
inside is the mean of the pre-computed, shifted density values of that
distribution and outside is the centroid position of, say, a peak in
the real world which you want to model by a scaled and shifted version
of the probability distribution.
*/
void setMapping(KeyType const & scale, KeyType const & inside, KeyType const & outside)
{
scale_ = scale;
inside_ = inside;
outside_ = outside;
offset_ = outside - scale * inside;
}
/** @brief Specifies the mapping from "outside" to "inside" coordinates by the following data:
- <code>inside_low</code> and <code>outside_low</code>: these axis positions are mapped onto each other.
- <code>inside_high</code> and <code>outside_high</code>: these axis positions are mapped onto each other.
This four argument version is just a convenience overload for the three argument version, which see.
*/
void setMapping(KeyType const & inside_low, KeyType const & outside_low,
KeyType const & inside_high, KeyType const & outside_high)
{
if (inside_high != inside_low)
{
setMapping((outside_high - outside_low) / (inside_high - inside_low),
inside_low, outside_low);
}
else
{
setMapping(0, inside_low, outside_low);
}
return;
}
/// Accessor. See setMapping().
KeyType const & getInsideReferencePoint() const
{
return inside_;
}
/// Accessor. See setMapping().
KeyType const & getOutsideReferencePoint() const
{
return outside_;
}
/// Lower boundary of the support, in "outside" coordinates.
KeyType supportMin() const
{
return index2key(KeyType(empty() ? 0 : -1));
}
/// Upper boundary of the support, in "outside" coordinates.
KeyType supportMax() const
{
return index2key(KeyType(data_.size()));
}
//@}
protected:
KeyType scale_;
KeyType offset_;
KeyType inside_;
KeyType outside_;
ContainerType data_;
};
} // namespace Math
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ML/SVM/SimpleSVM.h | .h | 6,147 | 143 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Hendrik Weisser $
// $Authors: Hendrik Weisser $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h>
// Remove libSVM header include
// #include <svm.h>
#include <map>
#include <vector>
#include <utility> // for "pair"
#include <tuple>
#include <memory> // for std::unique_ptr
namespace OpenMS
{
/**
@brief Simple interface to support vector machines for classification and regression (via LIBSVM).
This class supports:
- (multi-class) classification and regression with an epsilon-SVR.
- linear or RBF kernel.
It uses cross-validation to optimize the respective SVM/SVR parameters @e C, @e p (SVR-only) and (RBF kernel only) @e gamma.
Usage:
SVM models are generated by the the setup() method.
SimpleSVM provides two common use cases for convinience:
- all data: Passing all data (training + test) as @p predictors to setup and training on a subset.
- training only: Passing exclusivly training data as @p predictors to setup.
The parameter @p outcomes of setup() defines in both cases the training set; it contains the indexes of observations
(corresponding to positions in the vectors in @p predictors) together with the class labels (or regression values) for training.
Given @e N observations of @e M predictors, the data are coded as a map of predictors (size @e M), each a numeric vector of values for different observations (size @e N).
To predict class labels (or regression values) based on a model, use one of the predict() methods:
- if setup with all data: the parameter @p indexes of predict() takes a vector of indexes corresponding to the observations for which predictions should be made.
(With an empty vector, the default, predictions are made for all observations, including those used for training.)
- if setup with training data only: by passing a new PredictorMap.
@htmlinclude OpenMS_SimpleSVM.parameters
*/
class OPENMS_DLLAPI SimpleSVM :
public DefaultParamHandler
{
public:
/// Mapping from predictor name to vector of predictor values
typedef std::map<String, std::vector<double> > PredictorMap;
/// Mapping from predictor name to predictor min and max
typedef std::map<String, std::pair<double, double> > ScaleMap;
/// SVM/SVR prediction result
struct Prediction
{
/// Predicted class label (or regression value)
double outcome;
/// Class label (or regression value) and their predicted probabilities
std::map<double, double> probabilities;
};
/// Default constructor
SimpleSVM();
/// Destructor
~SimpleSVM() override;
// Prevent copy and assignment
SimpleSVM(const SimpleSVM&) = delete;
SimpleSVM& operator=(const SimpleSVM&) = delete;
/**
@brief Load data and train a model.
@param[in,out] predictors Mapping from predictor name to vector of predictor values (for different observations). All vectors should have the same length; values will be changed by scaling.
@param[in] outcomes Mapping from observation index to class label or regression value in the training set.
@param[in] classification true (default) if SVM classification should be used, SVR otherwise
@throw Exception::IllegalArgument if @p predictors is empty
@throw Exception::InvalidValue if an invalid index is used in @p outcomes
@throw Exception::MissingInformation if there are fewer than two class labels in @p outcomes, or if there are not enough observations for cross-validation
*/
void setup(PredictorMap& predictors, const std::map<Size, double>& outcomes, bool classification = true);
/**
@brief Predict class labels or regression values (and probabilities).
@param[out] predictions Output vector of prediction results (same order as @p indexes).
@param[in] indexes Vector of observation indexes for which predictions are desired. If empty (default), predictions are made for all observations.
@throw Exception::Precondition if no model has been trained
@throw Exception::InvalidValue if an invalid index is used in @p indexes
*/
void predict(std::vector<Prediction>& predictions,
std::vector<Size> indexes = std::vector<Size>()) const;
/**
@brief Predict class labels or regression values (and probabilities).
@param[in,out] predictors Mapping from predictor name to vector of predictor values (for different observations). All vectors should have the same length; values will be changed by scaling applied to training data in setup.
@param[out] predictions Output vector of prediction results (same order as @p indexes).
@throw Exception::Precondition if no model has been trained
@throw Exception::InvalidValue if an invalid index is used in @p indexes
**/
void predict(PredictorMap& predictors, std::vector<Prediction>& predictions) const;
/**
@brief Get the weights used for features (predictors) in the SVM model
Currently only supported for two-class classification.
If a linear kernel is used, the weights are informative for ranking features.
@throw Exception::Precondition if no model has been trained, or if the classification involves more than two classes
*/
void getFeatureWeights(std::map<String, double>& feature_weights) const;
/// Write cross-validation (parameter optimization) results to a CSV file
void writeXvalResults(const String& path) const;
/// Get data range of predictors before scaling to [0, 1]
const ScaleMap& getScaling() const;
protected:
// Forward declaration of implementation class
class Impl;
// Pointer to implementation (Pimpl pattern)
std::unique_ptr<Impl> pimpl_;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ML/CROSSVALIDATION/CrossValidation.h | .h | 5,747 | 181 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Justin Sing $
// $Authors: Justin Sing $
// --------------------------------------------------------------------------
//
#pragma once
#include <OpenMS/config.h>
#include <OpenMS/CONCEPT/Types.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <algorithm>
#include <cmath>
#include <cstddef>
#include <utility>
#include <vector>
namespace OpenMS
{
/**
@brief Lightweight K-fold / LOO cross-validation utilities and 1-D grid search.
Provides:
- `makeKFolds(n, K)`: deterministic round-robin fold assignment (LOO if K==n)
- `gridSearch1D(...)`: evaluate a 1-D candidate grid via CV and pick the best
Tie-breaking uses a tiny absolute tolerance and (optionally) prefers larger
candidates (useful for smoother/regularized models).
References:
- Stone, M. (1974) Cross-Validatory Choice and Assessment of Statistical Predictions.
J. Roy. Stat. Soc. B, 36(2):111–147.
@see GridSearch
@ingroup Math
*/
class CrossValidation
{
public:
/**
@brief Tie-breaking preference for equal (within tolerance) CV scores.
- PreferLarger : choose the larger candidate value on ties
- PreferSmaller : choose the smaller candidate value on ties
- PreferAny : keep the first encountered (stable, no size preference)
@ingroup Math
*/
enum class CandidateTieBreak
{
PreferLarger,
PreferSmaller,
PreferAny
};
/**
@brief Build @p K folds for indices [0, n).
Deterministic round-robin assignment: fold(i) = i % K.
For leave-one-out (LOO), use K = n.
@param[in] n Number of samples
@param[in] K Requested number of folds (clamped to [1, n])
@exception Exception::InvalidValue if @p n == 0 or @p K == 0
@ingroup Math
*/
static std::vector<std::vector<Size>> makeKFolds(Size n, Size K)
{
if (n == 0)
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"n", String(n));
}
if (K == 0)
{
throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION,
"K", String(K));
}
if (K > n) K = n;
std::vector<std::vector<Size>> folds(K);
for (Size i = 0; i < n; ++i) folds[i % K].push_back(i);
return folds;
}
/**
@brief One-dimensional grid search with external cross-validation evaluation.
Iterates candidates [@p cbegin, @p cend), calls @p train_eval(candidate, folds, abs_errs)
to append absolute errors from all validation points, then scores them via
@p score(abs_errs) (lower is better). Returns the best (candidate, score).
Tie-breaking:
- If |score - best_score| <= @p tie_tol, choose by @p prefer_larger (true → larger wins).
@tparam CandIter Random-access or forward iterator over candidate values
@tparam TrainEval Callable of signature `void(const Cand&, const std::vector<std::vector<Size>>&, std::vector<double>&)`
@tparam ScoreFn Callable of signature `double(const std::vector<double>&)`
@param[in] cbegin Begin iterator of candidate grid
@param[in] cend End iterator of candidate grid
@param[in] folds Fold index sets (e.g., from makeKFolds)
@param[in] train_eval Callback: fit on train folds and append |error| for all held-out points
@param[in] score Callback: convert accumulated errors to a scalar loss (lower is better)
@param[in] tie_tol Absolute tolerance for tie detection (default: 1e-12)
@param[in] tie_break Preference for ties (default: PreferLarger)
@return (best_candidate, best_score)
@exception Exception::InvalidRange if candidate range is empty
@ingroup Math
*/
template <typename CandIter, typename TrainEval, typename ScoreFn>
static std::pair<typename std::iterator_traits<CandIter>::value_type, double>
gridSearch1D(CandIter cbegin, CandIter cend,
const std::vector<std::vector<Size>>& folds,
TrainEval train_eval,
ScoreFn score,
double tie_tol = 1e-12,
CandidateTieBreak tie_break = CandidateTieBreak::PreferLarger)
{
using CandT = typename std::iterator_traits<CandIter>::value_type;
if (cbegin == cend)
{
throw Exception::InvalidRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION);
}
CandT best_cand = *cbegin;
double best_score = std::numeric_limits<double>::infinity();
bool first = true;
for (auto it = cbegin; it != cend; ++it)
{
const CandT cand = *it;
std::vector<double> abs_errs;
abs_errs.reserve(256); // grows as needed
train_eval(cand, folds, abs_errs);
const double s = score(abs_errs);
// Prefer larger candidate on numerical ties (more stable smoothing, etc.)
const bool better = (s < best_score - tie_tol);
const bool tie = (std::fabs(s - best_score) <= tie_tol);
bool wins_on_tie = false;
if (tie)
{
switch (tie_break)
{
case CandidateTieBreak::PreferLarger: wins_on_tie = cand > best_cand; break;
case CandidateTieBreak::PreferSmaller: wins_on_tie = cand < best_cand; break;
case CandidateTieBreak::PreferAny: wins_on_tie = false; break;
}
}
if (first || better || wins_on_tie)
{
best_cand = cand;
best_score = s;
first = false;
}
}
return {best_cand, best_score};
}
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ML/REGRESSION/QuadraticRegression.h | .h | 1,882 | 69 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: Christian Ehrlich, Chris Bielow $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CONCEPT/Types.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <iterator>
#include <vector>
namespace OpenMS
{
namespace Math
{
/*
@brief Estimates model parameters for a quadratic equation
The quadratic equation is of the form
y = a + b*x + c*x^2
Weighted inputs are supported.
*/
class OPENMS_DLLAPI QuadraticRegression
{
public:
QuadraticRegression();
/** compute the quadratic regression over 2D points */
void computeRegression(
std::vector<double>::const_iterator x_begin,
std::vector<double>::const_iterator x_end,
std::vector<double>::const_iterator y_begin);
/** compute the weighted quadratic regression over 2D points */
void computeRegressionWeighted(
std::vector<double>::const_iterator x_begin,
std::vector<double>::const_iterator x_end,
std::vector<double>::const_iterator y_begin,
std::vector<double>::const_iterator w_begin);
/** evaluate the quadratic function */
double eval(double x) const;
/** evaluate using external coefficients */
static double eval(double A, double B, double C, double x);
double getA() const; /// A = the intercept
double getB() const; /// B*X
double getC() const; /// C*X^2
double getChiSquared() const;
protected:
double a_;
double b_;
double c_;
double chi_squared_;
}; //class
} //namespace
} //namespace
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ML/REGRESSION/LinearRegressionWithoutIntercept.h | .h | 1,764 | 75 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Lars Nilse $
// $Authors: Lars Nilse $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CONCEPT/Exception.h>
#include <cmath>
#include <vector>
namespace OpenMS
{
namespace Math
{
/**
@brief This class offers functions to perform least-squares fits to a straight line model, \f$ Y(c,x) = c_0 + c_1 x \f$.
@ingroup Math
*/
class OPENMS_DLLAPI LinearRegressionWithoutIntercept
{
public:
/// Constructor
LinearRegressionWithoutIntercept();
/**
* @brief adds an observation (x,y) to the regression data set.
*
* @param[in] x independent variable value
* @param[in] y dependent variable value
*/
void addData(double x, double y);
/**
* @brief adds observations (x,y) to the regression data set.
*
* @param[in] x vector of independent variable values
* @param[in] y vector of dependent variable values
*/
void addData(std::vector<double>& x, std::vector<double>& y);
/**
* @brief returns the slope of the estimated regression line.
*/
double getSlope() const;
private:
/**
* @brief total variation in x
*/
double sum_xx_;
/**
* @brief sum of products
*/
double sum_xy_;
/**
* @brief number of observations
*/
int n_;
};
} // namespace Math
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ML/REGRESSION/LinearRegression.h | .h | 8,860 | 229 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Timo Sachsenberg $
// $Authors: $
// --------------------------------------------------------------------------
#pragma once
#include <OpenMS/CONCEPT/Types.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/DATASTRUCTURES/String.h>
#include <cmath>
#include <vector>
namespace OpenMS
{
namespace Math
{
/**
@brief This class offers functions to perform least-squares fits to a straight line model, \f$ Y(c,x) = c_0 + c_1 x \f$.
Next to the intercept with the y-axis and the slope of the fitted line, this class computes the:
- squared Pearson coefficient
- value of the t-distribution
- standard deviation of the residuals
- standard error of the slope
- intercept with the x-axis (useful for additive series experiments)
- lower border of confidence interval
- higher border of confidence interval
- chi squared value
- x mean
@ingroup Math
*/
class OPENMS_DLLAPI LinearRegression
{
public:
/// Constructor
LinearRegression() :
intercept_(0),
slope_(0),
x_intercept_(0),
lower_(0),
upper_(0),
t_star_(0),
r_squared_(0),
stand_dev_residuals_(0),
mean_residuals_(0),
stand_error_slope_(0),
chi_squared_(0),
rsd_(0)
{
}
/// Destructor
virtual ~LinearRegression() = default;
/**
@brief This function computes the best-fit linear regression coefficients \f$ (c_0,c_1) \f$
of the model \f$ Y = c_0 + c_1 X \f$ for the dataset \f$ (x, y) \f$.
The values in x-dimension of the dataset \f$ (x,y) \f$ are given by the iterator range [x_begin,x_end)
and the corresponding y-values start at position y_begin.
For a "x %" Confidence Interval use confidence_interval_P = x/100.
For example the 95% Confidence Interval is supposed to be an interval that has a 95% chance of
containing the true value of the parameter.
@param[in] confidence_interval_P Value between 0-1 to determine lower and upper CI borders.
@param[in] x_begin Begin iterator of x values
@param[in] x_end End iterator of x values
@param[in] y_begin Begin iterator of y values (same length as x)
@param[in] compute_goodness Compute meta stats about the fit. If this is not done, none of the members (except slope and intercept) are meaningful.
@exception Exception::UnableToFit is thrown if fitting cannot be performed
*/
void computeRegression(double confidence_interval_P,
std::vector<double>::const_iterator x_begin,
std::vector<double>::const_iterator x_end,
std::vector<double>::const_iterator y_begin,
bool compute_goodness = true);
/**
@brief This function computes the best-fit linear regression coefficients \f$ (c_0,c_1) \f$
of the model \f$ Y = c_0 + c_1 X \f$ for the weighted dataset \f$ (x, y) \f$.
The values in x-dimension of the dataset \f$ (x, y) \f$ are given by the iterator range [x_begin,x_end)
and the corresponding y-values start at position y_begin. They will be weighted by the
values starting at w_begin.
For a "x %" Confidence Interval use confidence_interval_P = x/100.
For example the 95% Confidence Interval is supposed to be an interval that has a 95% chance of
containing the true value of the parameter.
@param[in] confidence_interval_P Value between 0-1 to determine lower and upper CI borders.
@param[in] x_begin Begin iterator of x values
@param[in] x_end End iterator of x values
@param[in] y_begin Begin iterator of y values (same length as x)
@param[in] w_begin Begin iterator of weight values (same length as x)
@param[in] compute_goodness Compute meta stats about the fit. If this is not done, none of the members (except slope and intercept) are meaningful.
@exception Exception::UnableToFit is thrown if fitting cannot be performed
*/
void computeRegressionWeighted(double confidence_interval_P,
std::vector<double>::const_iterator x_begin,
std::vector<double>::const_iterator x_end,
std::vector<double>::const_iterator y_begin,
std::vector<double>::const_iterator w_begin,
bool compute_goodness = true);
/// Non-mutable access to the y-intercept of the straight line
double getIntercept() const;
/// Non-mutable access to the slope of the straight line
double getSlope() const;
/// Non-mutable access to the x-intercept of the straight line
double getXIntercept() const;
/// Non-mutable access to the lower border of confidence interval
double getLower() const;
/// Non-mutable access to the upper border of confidence interval
double getUpper() const;
/// Non-mutable access to the value of the t-distribution
double getTValue() const;
/// Non-mutable access to the squared Pearson coefficient
double getRSquared() const;
/// Non-mutable access to the standard deviation of the residuals
double getStandDevRes() const;
/// Non-mutable access to the residual mean
double getMeanRes() const;
/// Non-mutable access to the standard error of the slope
double getStandErrSlope() const;
/// Non-mutable access to the chi squared value
double getChiSquared() const;
/// Non-mutable access to relative standard deviation
double getRSD() const;
/// given x compute y = slope * x + intercept
static inline double computePointY(double x, double slope, double intercept)
{
return slope * x + intercept;
}
protected:
/// The intercept of the fitted line with the y-axis
double intercept_;
/// The slope of the fitted line
double slope_;
/// The intercept of the fitted line with the x-axis
double x_intercept_;
/// The lower bound of the confidence interval
double lower_;
/// The upper bound of the confidence interval
double upper_;
/// The value of the t-statistic
double t_star_;
/// The squared correlation coefficient (Pearson)
double r_squared_;
/// The standard deviation of the residuals
double stand_dev_residuals_;
/// Mean of residuals
double mean_residuals_;
/// The standard error of the slope
double stand_error_slope_;
/// The value of the Chi Squared statistic
double chi_squared_;
/// the relative standard deviation
double rsd_;
/// Computes the goodness of the fitted regression line
void computeGoodness_(const std::vector<double>& X, const std::vector<double>& Y, double confidence_interval_P);
/// Compute the chi squared of a linear fit
template <typename Iterator>
double computeChiSquare(Iterator x_begin, Iterator x_end, Iterator y_begin, double slope, double intercept);
/// Compute the chi squared of a weighted linear fit
template <typename Iterator>
double computeWeightedChiSquare(Iterator x_begin, Iterator x_end, Iterator y_begin, Iterator w_begin, double slope, double intercept);
private:
/// Not implemented
LinearRegression(const LinearRegression& arg);
/// Not implemented
LinearRegression& operator=(const LinearRegression& arg);
}; //class
//x, y, w must be of same size
template <typename Iterator>
double LinearRegression::computeChiSquare(Iterator x_begin, Iterator x_end, Iterator y_begin, double slope, double intercept)
{
double chi_squared = 0.0;
Iterator xIter = x_begin;
Iterator yIter = y_begin;
for (; xIter != x_end; ++xIter, ++yIter)
{
chi_squared += std::pow(*yIter - computePointY(*xIter, slope, intercept), 2);
}
return chi_squared;
}
//x, y, w must be of same size
template <typename Iterator>
double LinearRegression::computeWeightedChiSquare(Iterator x_begin, Iterator x_end, Iterator y_begin, Iterator w_begin, double slope, double intercept)
{
double chi_squared = 0.0;
Iterator xIter = x_begin;
Iterator yIter = y_begin;
Iterator wIter = w_begin;
for (; xIter != x_end; ++xIter, ++yIter, ++wIter)
{
chi_squared += *wIter * std::pow(*yIter - computePointY(*xIter, slope, intercept), 2);
}
return chi_squared;
}
} // namespace Math
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ML/ROCCURVE/ROCCurve.h | .h | 2,771 | 111 | // 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/config.h>
#include <OpenMS/CONCEPT/Types.h>
#include <list>
#include <vector>
namespace OpenMS
{
namespace Math
{
/**
@brief ROCCurves show the trade-off in sensitivity and specificity for binary classifiers using different cutoff values
[This class is buggy and usage is discouraged!]
@ingroup Math
*/
class OPENMS_DLLAPI ROCCurve
{
public:
// @name Constructors and Destructors
// @{
/// default constructor
ROCCurve();
///constructor with value, class pairs
explicit ROCCurve(const std::vector<std::pair<double,bool>> & pairs);
/// destructor
virtual ~ROCCurve() = default;
/// copy constructor
ROCCurve(const ROCCurve & source);
// @}
// @name Operators
// @{
/// assignment operator
ROCCurve & operator=(const ROCCurve & source);
// @}
// @name Accessors
// @{
/// insert score, type pair
void insertPair(double score, bool clas);
/// returns Area Under Curve
double AUC();
/// returns ROC-N score (e.g. ROC-50). Returns -1 if not enough false positives were found
double rocN(Size N);
/// some points in the ROC Curve
std::vector<std::pair<double, double> > curve(UInt resolution = 10);
/// returns the score at which you would need to set a cutoff to have fraction positives
/// returns -1 if there are not enough positives
double cutoffPos(double fraction = 0.95);
/// returns the score at which you would need to set a cutoff to have fraction positives
/// returns -1 if there are not enough positives
double cutoffNeg(double fraction = 0.95);
// @}
private:
/// sorts data and caches if sorted
inline void sort();
/// counts global pos and neg
inline void count();
/// calculates area with trapezoidal rule
/// @param[in] x1,x2,y1,y2
inline double trapezoidal_area(double x1, double x2, double y1, double y2);
/// predicate for sort()
class OPENMS_DLLAPI simsortdec
{
public:
bool operator()(const std::pair<double, bool> & a, const std::pair<double, bool> & b)
{
return b.first < a.first;
}
};
std::vector<std::pair<double, bool> > score_clas_pairs_;
UInt pos_{};
UInt neg_{};
bool sorted_{};
};
}
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ML/GRIDSEARCH/GridSearch.h | .h | 4,910 | 144 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Julianus Pfeuffer $
// $Authors: Julianus Pfeuffer $
// --------------------------------------------------------------------------
#pragma once
#include <array>
#include <vector>
#include <cmath>
#include <tuple>
#include <concepts>
#include <ranges>
#include <functional>
namespace OpenMS
{
namespace Internal
{
template<typename F, typename... Args>
concept Evaluator = requires(F f, Args... args) {
{ std::invoke(f, args...) } -> std::convertible_to<double>;
};
// The general class template
template <size_t param_index, size_t grid_size, typename EvalResult, typename Tuple, typename... TupleTypes>
struct Looper
{
};
// Specialization for the base case
template <size_t grid_size, typename EvalResult, typename Tuple, typename... TupleTypes>
struct Looper<grid_size, grid_size, EvalResult, Tuple, TupleTypes...>
{
template <typename Functor>
requires Evaluator<Functor, TupleTypes...>
constexpr auto operator()(const Tuple&, Functor functor, EvalResult /*bestValue*/, std::array<size_t, grid_size>& /*bestIndices*/) const
{
return std::invoke(functor);
}
};
// Specialization for the loop case
template <size_t param_index, size_t grid_size, typename EvalResult, typename Tuple, typename FirstTupleType, typename... TupleTypes>
struct Looper<param_index, grid_size, EvalResult, Tuple, FirstTupleType, TupleTypes...>
{
template <typename Functor>
requires Evaluator<Functor, FirstTupleType, TupleTypes...>
constexpr auto operator()(const Tuple& grid, Functor functor, EvalResult bestValue, std::array<size_t, grid_size>& bestIndices) const
{
const auto& current_vector = std::get<param_index>(grid);
for (size_t index = 0; index < current_vector.size(); ++index) {
const auto& value = current_vector[index];
auto currVal = Looper<param_index + 1, grid_size, EvalResult, Tuple, TupleTypes...>{}
(
grid,
[&value, &functor](TupleTypes... rest){
return std::invoke(functor, value, rest...);
},
bestValue,
bestIndices
);
if (currVal > bestValue) {
bestValue = currVal;
bestIndices[param_index] = index;
}
}
return bestValue;
}
};
} // namespace Internal
template <typename... TupleTypes>
class GridSearch
{
public:
explicit GridSearch(std::vector<TupleTypes>... gridValues)
: grid_(std::make_tuple<std::vector<TupleTypes>...>(std::move(gridValues)...))
{}
// Implementation for function objects using concepts
template <typename Functor>
requires Internal::Evaluator<Functor, TupleTypes...>
constexpr auto evaluate(
Functor evaluator,
std::invoke_result_t<Functor, TupleTypes...> startValue,
std::array<size_t, std::tuple_size_v<std::tuple<std::vector<TupleTypes>...>>>& resultIndices) const
{
return Internal::Looper<
0,
std::tuple_size_v<std::tuple<std::vector<TupleTypes>...>>,
std::invoke_result_t<Functor, TupleTypes...>,
std::tuple<std::vector<TupleTypes>...>,
TupleTypes...>{}(grid_, evaluator, startValue, resultIndices);
}
// Implementation for function pointers using concepts
template <typename EvalResult>
requires std::convertible_to<EvalResult, double>
[[nodiscard]] constexpr auto evaluate(
EvalResult (*evaluator)(TupleTypes...),
EvalResult startValue,
std::array<size_t, std::tuple_size_v<std::tuple<std::vector<TupleTypes>...>>>& resultIndices) const
{
return Internal::Looper<
0,
std::tuple_size_v<std::tuple<std::vector<TupleTypes>...>>,
EvalResult,
std::tuple<std::vector<TupleTypes>...>,
TupleTypes...>{}(grid_, evaluator, startValue, resultIndices);
}
[[nodiscard]] constexpr auto getNrCombos() const -> unsigned int
{
if (combos_ready_) {
return combos_;
}
return calculateCombos();
}
private:
std::tuple<std::vector<TupleTypes>...> grid_;
mutable unsigned int combos_ = 1;
mutable bool combos_ready_ = false;
template<std::size_t I = 0>
[[nodiscard]] constexpr unsigned int calculateCombos() const
{
if constexpr (I == sizeof...(TupleTypes)) {
combos_ready_ = true;
return combos_;
} else {
combos_ *= std::get<I>(grid_).size();
return calculateCombos<I + 1>();
}
}
};
} // namespace OpenMS
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ML/CLUSTERING/ClusterFunctor.h | .h | 3,135 | 78 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Mathias Walzer $
// $Authors: $
// --------------------------------------------------------------------------
//
#pragma once
#include <OpenMS/DATASTRUCTURES/DistanceMatrix.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/ML/CLUSTERING/ClusterAnalyzer.h>
#include <vector>
namespace OpenMS
{
/**
@brief Base class for cluster functors
Each cluster functor employs a different method for stepwise merging clusters up to a given threshold, starting from the most elementary partition of data. Elements are represented by indices of a given distance matrix, which also should represent the order of input.
@ingroup SpectraClustering
*/
class OPENMS_DLLAPI ClusterFunctor
{
public:
/**
@brief Exception thrown if not enough data (<2) is used
If the set of data to be clustered contains only one data point,
clustering algorithms would fail for obvious reasons.
*/
class OPENMS_DLLAPI InsufficientInput :
public Exception::BaseException
{
public:
InsufficientInput(const char * file, int line, const char * function, const char * message = "not enough data points to cluster anything") throw();
~InsufficientInput() throw() override;
};
/// default constructor
ClusterFunctor();
/// copy constructor
ClusterFunctor(const ClusterFunctor & source);
/// destructor
virtual ~ClusterFunctor();
/// assignment operator
ClusterFunctor & operator=(const ClusterFunctor & source);
/**
@brief abstract for clustering the indices according to their respective element distances
@param[in,out] original_distance DistanceMatrix<float> containing the distances of the elements to be clustered, will be changed during clustering process, make sure to have a copy or be able to redo
@param[in] cluster_tree vector< BinaryTreeNode >, represents the clustering, each node contains the next merged clusters (not element indices) and their distance, strict order is kept: left_child < right_child,
@param[in] threshold float value, the minimal distance from which on cluster merging is considered unrealistic. By default set to 1, i.e. complete clustering until only one cluster remains
@p original_distance is considered mirrored at the main diagonal, so only entries up the main diagonal are used.
The @p threshold can be taken from the maximal distance of two elements considered related and adapted in a way corresponding to the employed clustering method.
The results are represented by @p cluster_tree, to get the actual clustering (with element indices) from a certain step of the clustering
@see BinaryTreeNode , ClusterAnalyzer::cut
*/
virtual void operator()(DistanceMatrix<float> & original_distance, std::vector<BinaryTreeNode> & cluster_tree, const float threshold = 1) const = 0;
};
}
| Unknown |
3D | OpenMS/OpenMS | src/openms/include/OpenMS/ML/CLUSTERING/SingleLinkage.h | .h | 2,256 | 63 | // Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin
// SPDX-License-Identifier: BSD-3-Clause
//
// --------------------------------------------------------------------------
// $Maintainer: Mathias Walzer $
// $Authors: $
// --------------------------------------------------------------------------
//
#pragma once
#include <vector>
#include <set>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/DATASTRUCTURES/DistanceMatrix.h>
#include <OpenMS/ML/CLUSTERING/ClusterFunctor.h>
namespace OpenMS
{
/**
@brief SingleLinkage ClusterMethod
The details of the method can be found in:
SLINK: An optimally efficient algorithm for the single-link cluster method, The Computer Journal 1973 16(1):30-34; doi:10.1093/comjnl/16.1.30
@see ClusterFunctor() base class.
@ingroup SpectraClustering
*/
class OPENMS_DLLAPI SingleLinkage :
public ClusterFunctor, public ProgressLogger
{
public:
/// default constructor
SingleLinkage();
/// copy constructor
SingleLinkage(const SingleLinkage & source);
/// destructor
~SingleLinkage() override;
/// assignment operator
SingleLinkage & operator=(const SingleLinkage & source);
/**
@brief clusters the indices according to their respective element distances
@param[in] original_distance DistanceMatrix<float> containing the distances of the elements to be clustered
@param[in] cluster_tree vector< BinaryTreeNode >, represents the clustering, each node contains the next two clusters merged and their distance, strict order is kept: left_child < right_child
@param[in] threshold float value to meet Base class interface, will not be used because algorithm used is considerably fast and does not work by growing distances
@throw ClusterFunctor::InsufficientInput thrown if input is <2
The clustering method is single linkage, where the updated distances after merging two clusters are each the minimal distance between the elements of their clusters.
@see ClusterFunctor , BinaryTreeNode
*/
void operator()(DistanceMatrix<float> & original_distance, std::vector<BinaryTreeNode> & cluster_tree, const float threshold = 1) const override;
};
}
| Unknown |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.