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/ML/CLUSTERING/ClusterHierarchical.h
.h
7,498
196
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // // -------------------------------------------------------------------------- // $Maintainer: Mathias Walzer $ // $Authors: $ // -------------------------------------------------------------------------- // #pragma once #include <OpenMS/ML/CLUSTERING/ClusterAnalyzer.h> #include <OpenMS/ML/CLUSTERING/ClusterFunctor.h> #include <OpenMS/KERNEL/BinnedSpectrum.h> #include <OpenMS/COMPARISON/BinnedSpectrumCompareFunctor.h> #include <OpenMS/COMPARISON/PeakSpectrumCompareFunctor.h> #include <OpenMS/CONCEPT/Exception.h> #include <OpenMS/DATASTRUCTURES/DistanceMatrix.h> #include <OpenMS/KERNEL/StandardTypes.h> #include <vector> namespace OpenMS { /** @brief Hierarchical clustering with generic clustering functions ClusterHierarchical clusters objects with corresponding distancemethod and clusteringmethod. @ingroup SpectraClustering */ class OPENMS_DLLAPI ClusterHierarchical { private: /// the threshold given to the ClusterFunctor double threshold_; public: /// default constructor ClusterHierarchical(): threshold_(1.0) { } /// copy constructor ClusterHierarchical(const ClusterHierarchical& source): threshold_(source.threshold_) { } /// destructor virtual ~ClusterHierarchical() { } /** @brief Clustering function Cluster data using SimilarityComparator and ClusterFunctor. Creates a DistanceMatrix (if an empty matrix is passed) and the clustering is started. Clustering stops if the ClusterHierarchical::threshold_ is reached by the ClusterFunctor. First template parameter is the cluster object type, Second template parameter is the similarity functor applicable to the type. For example, @ref PeakSpectrum with a @ref PeakSpectrumCompareFunctor. The similarity functor must provide the similarity calculation with the ()-operator and yield normalized values in range of [0,1] for the type of < Data >. @param[in] data Values to be clustered @param[in] comparator Similarity functor which returns a similarity in [0, 1] for any pair of values in @p data @param[in] clusterer A cluster method implementation, e.g. SingleLinkage or CompleteLinkage. See base class ClusterFunctor. @param[out] cluster_tree The vector that will hold the BinaryTreeNodes representing the clustering (for further investigation with the ClusterAnalyzer methods) @param[in,out] original_distance Precomputed DistanceMatrix holding the pairwise distances of the elements in @p data; if empty or wrong size, it will be re-created using @p comparator @see ClusterFunctor, BinaryTreeNode, ClusterAnalyzer */ template<typename Data, typename SimilarityComparator> void cluster(std::vector<Data>& data, const SimilarityComparator& comparator, const ClusterFunctor& clusterer, std::vector<BinaryTreeNode>& cluster_tree, DistanceMatrix<float>& original_distance) { if (original_distance.dimensionsize() != data.size()) { // create distance matrix for data using comparator original_distance.clear(); original_distance.resize(data.size(), 1); for (Size i = 0; i < data.size(); i++) { for (Size j = 0; j < i; j++) { // distance value is 1-similarity value, since similarity is in range of [0,1] original_distance.setValueQuick(i, j, 1 - comparator(data[i], data[j])); } } } // create clustering with ClusterMethod, DistanceMatrix and Data clusterer(original_distance, cluster_tree, threshold_); } /** @brief clustering function for binned PeakSpectrum A version of the clustering function for PeakSpectra employing binned similarity methods. From the given PeakSpectrum BinnedSpectrum are generated, so the similarity functor @see BinnedSpectrumCompareFunctor can be applied. @param[in] data vector of @ref PeakSpectrum s to be clustered @param[in] comparator a BinnedSpectrumCompareFunctor @param[in] sz Bin size for the @ref BinnedSpectrum s @param[in] sp Bin spread for the @ref BinnedSpectrum s @param[in] offset Bin offset for the @ref BinnedSpectrum s @param[in] clusterer a clustermethod implementation, base class ClusterFunctor @param[out] cluster_tree Vector of BinaryTreeNodes representing the clustering (for further investigation with the ClusterAnalyzer methods) @param[in,out] original_distance The DistanceMatrix holding the pairwise distances of the elements in @p data, will be made newly if given size does not fit to the number of elements given in @p data @see ClusterFunctor, BinaryTreeNode, ClusterAnalyzer, BinnedSpectrum, BinnedSpectrumCompareFunctor @ingroup SpectraClustering */ void cluster(std::vector<PeakSpectrum>& data, const BinnedSpectrumCompareFunctor& comparator, double sz, UInt sp, float offset, const ClusterFunctor& clusterer, std::vector<BinaryTreeNode>& cluster_tree, DistanceMatrix<float>& original_distance) const { std::vector<BinnedSpectrum> binned_data; binned_data.reserve(data.size()); // transform each PeakSpectrum to a corresponding BinnedSpectrum with given settings of size and spread for (Size i = 0; i < data.size(); i++) { // double sz(2), UInt sp(1); binned_data.emplace_back(data[i], sz, false, sp, offset); } // create distancematrix for data with comparator original_distance.clear(); original_distance.resize(data.size(), 1); for (Size i = 0; i < binned_data.size(); i++) { for (Size j = 0; j < i; j++) { // distance value is 1-similarity value, since similarity is in range of [0,1] original_distance.setValue(i, j, 1 - comparator(binned_data[i], binned_data[j])); } } // create Clustering with ClusterMethod, DistanceMatrix and Data clusterer(original_distance, cluster_tree, threshold_); } /// get the threshold double getThreshold() const { return threshold_; } /// set the threshold (in terms of distance) /// The default is 1, i.e. only at similarity 0 the clustering stops. /// Warning: clustering is not supported by all methods yet (e.g. SingleLinkage does ignore it). void setThreshold(double x) { threshold_ = x; } }; /** @brief Exception thrown if clustering is attempted without a normalized compare functor due to similarity - distance conversions that are mandatory in some context, compare functors must return values normalized in the range [0,1] to ensure a clean conversion */ class OPENMS_DLLAPI UnnormalizedComparator : public Exception::BaseException { public: UnnormalizedComparator(const char* file, int line, const char* function, const char* message = "Clustering with unnormalized similarity measurement requested, normalized is mandatory") throw(); ~UnnormalizedComparator() throw() override; }; } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/ML/CLUSTERING/AverageLinkage.h
.h
2,639
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 AverageLinkage ClusterMethod The details of the method can be found in: Backhaus, Erichson, Plinke, Weiber Multivariate Analysemethoden, Springer 2000 and Ellen M. Voorhees: Implementing agglomerative hierarchic clustering algorithms for use in document retrieval. Inf. Process. Manage. 22(6): 465-476 (1986) @see ClusterFunctor @ingroup SpectraClustering */ class OPENMS_DLLAPI AverageLinkage : public ClusterFunctor, public ProgressLogger { public: /// default constructor AverageLinkage(); /// copy constructor AverageLinkage(const AverageLinkage & source); /// destructor ~AverageLinkage() override; /// assignment operator AverageLinkage & operator=(const AverageLinkage & source); /** @brief clusters 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[out] 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 @throw ClusterFunctor::InsufficientInput thrown if input is <2 The clustering method is average linkage, where the updated distances after merging two clusters are each the average distances between the elements of their clusters. After @p threshold is exceeded, @p cluster_tree is filled with dummy clusteringsteps (children: (0,1), distance: -1) to the root. @see ClusterFunctor , BinaryTreeNode */ void operator()(DistanceMatrix<float> & original_distance, std::vector<BinaryTreeNode> & cluster_tree, const float threshold = 1) const override; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/ML/CLUSTERING/HashGrid.h
.h
12,976
514
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Lars Nilse $ // $Authors: Bastian Blank $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/DATASTRUCTURES/DPosition.h> #include <boost/array.hpp> #include <boost/functional/hash.hpp> #include <boost/unordered/unordered_map.hpp> #include <cmath> #include <iterator> #include <limits> #ifndef OPENMS_COMPARISON_CLUSTERING_HASHGRID_H #define OPENMS_COMPARISON_CLUSTERING_HASHGRID_H namespace OpenMS { /** * @brief Container for (2-dimensional coordinate, value) pairs. * * A hash-grid consists of hash-grid cells. The key of each cell is a pair of integers. * Each pair is assigned to a cell using a hash function. * * This container implements most parts of the C++ standard map interface. * * @tparam Cluster Type to be stored in the hash grid. (e.g. HierarchicalClustering::Cluster) */ template<typename Cluster> class HashGrid { public: /** * @brief Coordinate for stored pairs. */ // XXX: Check is there is another type handy in OpenMS already typedef DPosition<2, double> ClusterCenter; /** * @brief Index for cells. */ typedef DPosition<2, Int64> CellIndex; /** * @brief Contents of a cell. */ typedef typename boost::unordered_multimap<ClusterCenter, Cluster> CellContent; /** * @brief Map of (cell-index, cell-content). */ typedef boost::unordered_map<CellIndex, CellContent> Grid; typedef typename CellContent::key_type key_type; typedef typename CellContent::mapped_type mapped_type; typedef typename CellContent::value_type value_type; private: /** * @brief Element iterator for the hash grid. */ class Iterator { private: friend class HashGrid; typedef typename Grid::iterator grid_iterator; typedef typename CellContent::iterator cell_iterator; /** @name Typedefs for STL compliance, these replace std::iterator */ //@{ /// The iterator's category type using iterator_category = std::input_iterator_tag; /// The iterator's value type using value_type = HashGrid::value_type; /// The reference type as returned by operator*() using reference = value_type&; /// The pointer type as returned by operator->() using pointer = value_type*; /// The difference type using difference_type = std::ptrdiff_t; //@} Grid& grid_; grid_iterator grid_it_; cell_iterator cell_it_; // Search for next non-empty cell void searchNextCell_() { while (cell_it_ == grid_it_->second.end()) { grid_it_++; // If we are at the last cell, set cell iterator to something well-known if (grid_it_ == grid_.end()) { cell_it_ = cell_iterator(); return; } cell_it_ = grid_it_->second.begin(); } } public: explicit Iterator(Grid& grid) : grid_(grid), grid_it_(grid.end()) { } Iterator(Grid& grid, grid_iterator grid_it, cell_iterator cell_it) : grid_(grid), grid_it_(grid_it), cell_it_(cell_it) { searchNextCell_(); } Iterator& operator++() { ++cell_it_; searchNextCell_(); return *this; } const Iterator operator++(int) { Iterator ret(*this); operator++(); return ret; } bool operator==(const Iterator& rhs) const { return grid_it_ == rhs.grid_it_ && cell_it_ == rhs.cell_it_; } bool operator!=(const Iterator& rhs) const { return !(*this == rhs); } value_type& operator*() const { return *cell_it_; } value_type* operator->() const { return &*cell_it_; } const CellIndex index() const { return grid_it_->first; } }; /** * @brief Constant element iterator for the hash grid. */ class ConstIterator { private: friend class HashGrid; typedef typename Grid::const_iterator grid_iterator; typedef typename CellContent::const_iterator cell_iterator; /** @name Typedefs for STL compliance, these replace std::iterator */ //@{ /// The iterator's category type using iterator_category = std::input_iterator_tag; /// The iterator's value type using value_type = HashGrid::value_type; /// The reference type as returned by operator*() using reference = value_type&; /// The pointer type as returned by operator->() using pointer = value_type*; /// The difference type using difference_type = std::ptrdiff_t; //@} const Grid& grid_; grid_iterator grid_it_; cell_iterator cell_it_; // Search for next non-empty cell void searchNextCell_() { while (cell_it_ == grid_it_->second.end()) { grid_it_++; // If we are at the last cell, set cell iterator to something well-known if (grid_it_ == grid_.end()) { cell_it_ = cell_iterator(); return; } cell_it_ = grid_it_->second.begin(); } } public: ConstIterator(const Grid& grid) : grid_(grid), grid_it_(grid.end()) { } ConstIterator(const Grid& grid, grid_iterator grid_it, cell_iterator cell_it) : grid_(grid), grid_it_(grid_it), cell_it_(cell_it) { searchNextCell_(); } ConstIterator(const Iterator& it) : grid_(it.grid_), grid_it_(it.grid_it_), cell_it_(it.cell_it_) { } ConstIterator& operator++() { ++cell_it_; searchNextCell_(); return *this; } const ConstIterator operator++(int) { ConstIterator ret(*this); operator++(); return ret; } bool operator==(const ConstIterator& rhs) const { return grid_it_ == rhs.grid_it_ && cell_it_ == rhs.cell_it_; } bool operator!=(const ConstIterator& rhs) const { return !(*this == rhs); } const value_type& operator*() const { return *cell_it_; } const value_type* operator->() const { return &*cell_it_; } const CellIndex index() const { return grid_it_->first; } }; public: typedef ConstIterator const_iterator; typedef Iterator iterator; typedef typename Grid::const_iterator const_grid_iterator; typedef typename Grid::iterator grid_iterator; typedef typename CellContent::const_iterator const_cell_iterator; typedef typename CellContent::iterator cell_iterator; typedef typename CellContent::size_type size_type; private: Grid cells_; CellIndex grid_dimension_; public: /** * @brief Dimension of cells. */ const ClusterCenter cell_dimension; /** * @brief Upper-right corner of key space for cells. */ const CellIndex& grid_dimension; public: explicit HashGrid(const ClusterCenter& c_dimension) : cells_(), grid_dimension_(), cell_dimension(c_dimension), grid_dimension(grid_dimension_) { } /** * @brief Inserts a (2-dimensional coordinate, value) pair. * @param[in] v Pair to be inserted. * @return Iterator that points to the inserted pair. */ cell_iterator insert(const value_type& v) { const CellIndex cellkey = cellIndexAtClusterCenter(v.first); CellContent& cell = cells_[cellkey]; updateGridDimension_(cellkey); return cell.insert(v); } /** * @brief Erases element on given iterator. */ void erase(iterator pos) { CellContent& cell = pos.grid_it_->second; cell.erase(pos.cell_it_); } /** * @brief Erases elements matching the 2-dimensional coordinate. * @param[in] key Key of element to be erased. * @return Number of elements erased. */ size_type erase(const key_type& key) { const CellIndex cellkey = cellIndexAtClusterCenter(key); auto cell = cells_.find(cellkey); if (cell == cells_.end()) return 0; return cell->second.erase(key); } /** * @brief Clears the map. */ void clear() { cells_.clear(); } /** * @brief Returns iterator to first element. */ iterator begin() { grid_iterator grid_it = cells_.begin(); if (grid_it == cells_.end()) return end(); cell_iterator cell_it = grid_it->second.begin(); return iterator(cells_, grid_it, cell_it); } /** * @brief Returns iterator to first element. */ const_iterator begin() const { const_grid_iterator grid_it = cells_.begin(); if (grid_it == cells_.end()) return end(); const_cell_iterator cell_it = grid_it->second.begin(); return const_iterator(cells_, grid_it, cell_it); } /** * @brief Returns iterator to first element. */ iterator end() { return iterator(cells_); } /** * @brief Returns iterator to first element. */ const_iterator end() const { return const_iterator(cells_); } /** * @brief Return true if HashGrid is empty. */ bool empty() const { return size() == 0; } /** * @brief Return number of elements. */ size_type size() const { size_type ret = 0; for (const_grid_iterator it = grid_begin(); it != grid_end(); ++it) { ret += it->second.size(); } return ret; } /** * @brief Returns iterator to first grid cell. */ const_grid_iterator grid_begin() const { return cells_.begin(); } /** * @brief Returns iterator to on after last grid cell. */ const_grid_iterator grid_end() const { return cells_.end(); } /** * @brief Returns the grid cell at given index. */ const typename Grid::mapped_type& grid_at(const CellIndex& x) const { return cells_.at(x); } /** * @warning Currently needed non-const by HierarchicalClustering. */ typename Grid::mapped_type& grid_at(const CellIndex& x) { return cells_.at(x); } /** * @brief Returns the grid cell at given index if present, otherwise the grid_end iterator. */ const_grid_iterator grid_find(const CellIndex& x) const { return cells_.find(x); } /** * @brief Returns the grid cell at given index if present, otherwise the grid_end iterator. */ grid_iterator grid_find(const CellIndex& x) { return cells_.find(x); } /** * @warning Currently needed non-const by HierarchicalClustering. */ grid_iterator grid_begin() { return cells_.begin(); } /** * @warning Currently needed non-const by HierarchicalClustering. */ grid_iterator grid_end() { return cells_.end(); } /** * @brief Computes the cell index for a given cluster center coordinate. * @param[in] key Cluster center coordinate * @return Cell index corresponding to the coordinate * @throws Exception::OutOfRange if computed cell index exceeds Int64 limits */ CellIndex cellIndexAtClusterCenter(const ClusterCenter& key) const { CellIndex ret; typename CellIndex::iterator it = ret.begin(); typename ClusterCenter::const_iterator lit = key.begin(), rit = cell_dimension.begin(); for (; it != ret.end(); ++it, ++lit, ++rit) { double t = std::floor(*lit / *rit); if (t < std::numeric_limits<Int64>::min() || t > std::numeric_limits<Int64>::max()) throw Exception::OutOfRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION); *it = static_cast<Int64>(t); } return ret; } private: void updateGridDimension_(const CellIndex& d) { typename CellIndex::const_iterator it_new = d.begin(); typename CellIndex::iterator it_cur = grid_dimension_.begin(); for (; it_new != d.end(); ++it_new, ++it_cur) { if (*it_cur < *it_new) *it_cur = *it_new; } } }; /** Hash value for OpenMS::DPosition. */ template<UInt N, typename T> std::size_t hash_value(const DPosition<N, T>& b) { boost::hash<T> hasher; std::size_t hash = 0; for (typename DPosition<N, T>::const_iterator it = b.begin(); it != b.end(); ++it) hash ^= hasher(*it); return hash; } } // namespace OpenMS #endif /* OPENMS_COMPARISON_CLUSTERING_HASHGRID_H */
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/ML/CLUSTERING/GridBasedCluster.h
.h
2,917
111
// 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 $ // -------------------------------------------------------------------------- #include <vector> #include <OpenMS/KERNEL/StandardTypes.h> #include <OpenMS/DATASTRUCTURES/DPosition.h> #include <OpenMS/DATASTRUCTURES/DBoundingBox.h> #ifndef OPENMS_COMPARISON_CLUSTERING_GRIDBASEDCLUSTER_H #define OPENMS_COMPARISON_CLUSTERING_GRIDBASEDCLUSTER_H namespace OpenMS { /** * @brief basic data structure for clustering */ class OPENMS_DLLAPI GridBasedCluster { public: /** * centre of a cluster */ typedef DPosition<2> Point; /** * bounding box of a cluster */ typedef DBoundingBox<2> Rectangle; /** * @brief initialises all data structures */ GridBasedCluster(const Point &centre, const Rectangle &bounding_box, const std::vector<int> &point_indices, const int &property_A, const std::vector<int> &properties_B); /** * @brief initialises all data structures */ GridBasedCluster(const Point &centre, const Rectangle &bounding_box, const std::vector<int> &point_indices); /** * @brief returns cluster centre */ const Point& getCentre() const; /** * @brief returns bounding box */ const Rectangle& getBoundingBox() const; /** * @brief returns indices of points in cluster */ const std::vector<int>& getPoints() const; /** * @brief returns property A */ int getPropertyA() const; /** * @brief returns properties B of all points */ const std::vector<int>& getPropertiesB() const; /** * @brief operators for comparisons */ bool operator<(const GridBasedCluster& other) const; bool operator>(const GridBasedCluster& other) const; bool operator==(const GridBasedCluster& other) const; private: /** * @brief centre of the cluster */ Point centre_; /** * @brief bounding box of the cluster * i.e. (min,max) in x and y direction */ Rectangle bounding_box_; /** * @brief set of indices referencing the points in the cluster */ std::vector<int> point_indices_; /** * @brief properties A and B * Each point in a cluster can (optionally) possess two properties A and B. * For two points to be in the same cluster, they need to have the same * property A, e.g. the same charge. For two points to be in the same cluster, * they need to have different properties B, e.g. originate from two * different maps. -1 means properties are not set. */ int property_A_; std::vector<int> properties_B_; }; } #endif /* OPENMS_COMPARISON_CLUSTERING_GRIDBASEDCLUSTER_H */
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/ML/CLUSTERING/EuclideanSimilarity.h
.h
2,142
76
// 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 <cmath> #include <OpenMS/CONCEPT/Exception.h> namespace OpenMS { /** @brief CompareFunctor for 2Dpoints each 2D point as a pair of float holds a float coordinate for each Dimension */ class OPENMS_DLLAPI EuclideanSimilarity { private: float scale_; public: /// default constructor EuclideanSimilarity(); /// copy constructor EuclideanSimilarity(const EuclideanSimilarity & source); /// destructor virtual ~EuclideanSimilarity(); /// assignment operator EuclideanSimilarity & operator=(const EuclideanSimilarity & source); /** @brief calculates similarity between two points in euclidean space @param[in] a a pair of float, giving the x and the y coordinates of the first point @param[in] b a pair of float, giving the x and the y coordinates of the second point calculates similarity from the euclidean distance between given 2D points, scaled in [0,1] @see setScale */ float operator()(const std::pair<float, float> & a, const std::pair<float, float> & b) const; /** @brief calculates self similarity, will yield 0 @param[in] c a pair of float, giving the x and the y coordinates */ float operator()(const std::pair<float, float> & c) const; /** @brief clusters the indices according to their respective element distances @param[in] x float value to scale the result @throw Exception::DivisionByZero if scaling is inapplicable because it is 0 sets the scale so that similarities can be correctly calculated from distances. Should be set so that the greatest distance in a chosen set will be scales to 1 (i.e. @p x = greatest possible distance in the set) */ void setScale(float x); }; }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/ML/CLUSTERING/CompleteLinkage.h
.h
2,507
69
// 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/ML/CLUSTERING/ClusterFunctor.h> #include <OpenMS/CONCEPT/ProgressLogger.h> #include <OpenMS/DATASTRUCTURES/DistanceMatrix.h> #include <cmath> #include <set> #include <vector> namespace OpenMS { /** @brief CompleteLinkage ClusterMethod The details of the method can be found in: Backhaus, Erichson, Plinke, Weiber Multivariate Analysemethoden, Springer 2000 and Ellen M. Voorhees: Implementing agglomerative hierarchic clustering algorithms for use in document retrieval. Inf. Process. Manage. 22(6): 465-476 (1986) @see ClusterFunctor @ingroup SpectraClustering */ class OPENMS_DLLAPI CompleteLinkage : public ClusterFunctor, public ProgressLogger { public: /// default constructor CompleteLinkage(); /// copy constructor CompleteLinkage(const CompleteLinkage& source); /// destructor ~CompleteLinkage() override; /// assignment operator CompleteLinkage& operator=(const CompleteLinkage& source); /** @brief clusters the indices according to their respective element distances Complete linkage updates the distances after merging two clusters using the maximal distance between the elements of their clusters. After @p threshold is exceeded, @p cluster_tree is filled with dummy clusteringsteps (children: (0,1), distance:-1) to the root. @param[in,out] original_distance Contains 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 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 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 @throw ClusterFunctor::InsufficientInput thrown if input is <2. @see ClusterFunctor , BinaryTreeNode */ void operator()(DistanceMatrix<float>& original_distance, std::vector<BinaryTreeNode>& cluster_tree, const float threshold = 1) const override; }; } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/ML/CLUSTERING/GridBasedClustering.h
.h
26,239
665
// 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, Johannes Veit $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/KERNEL/StandardTypes.h> #include <OpenMS/DATASTRUCTURES/DRange.h> #include <OpenMS/DATASTRUCTURES/String.h> #include <OpenMS/CONCEPT/ProgressLogger.h> #include <OpenMS/ML/CLUSTERING/ClusteringGrid.h> #include <OpenMS/ML/CLUSTERING/GridBasedCluster.h> #include <cmath> #include <limits> #include <map> #include <set> #include <queue> #include <vector> #include <algorithm> #include <iostream> #include <unordered_map> namespace OpenMS { /** * @brief basic data structure for distances between clusters */ class OPENMS_DLLAPI MinimumDistance { public: /** * @brief constructor */ MinimumDistance(const int& cluster_index, const int& nearest_neighbour_index, const double& distance); /** * @brief returns cluster index */ int getClusterIndex() const; /** * @brief returns index of nearest cluster */ int getNearestNeighbourIndex() const; /** * @brief operators for comparisons * (for multiset) */ bool operator<(const MinimumDistance& other) const; bool operator>(const MinimumDistance& other) const; bool operator==(const MinimumDistance& other) const; private: /// hide default constructor MinimumDistance(); /** * @brief index in the cluster list */ int cluster_index_; /** * @brief index of the nearest neighbour of the above cluster */ int nearest_neighbour_index_; /** * @brief distance between cluster and its nearest neighbour */ double distance_; }; /** * @brief 2D hierarchical clustering implementation * optimized for large data sets containing many small clusters * i.e. dimensions of clusters << dimension of entire dataset * * The clustering problem therefore simplifies to a number of * local clustering problems. Each of the local problems can be * solved on a couple of adjacent cells on a larger grid. The grid * spacing is determined by the expected typical cluster size * in this region. * * Each data point can have two additional properties A and B. * In each cluster all properties A need to be the same, * all properties B different. */ template <typename Metric> class GridBasedClustering : public ProgressLogger { public: /** * @brief cluster centre, cluster bounding box, grid index */ typedef GridBasedCluster::Point Point; // DPosition<2> typedef GridBasedCluster::Rectangle Rectangle; // DBoundingBox<2> typedef ClusteringGrid::CellIndex CellIndex; // std::pair<int,int> typedef std::multiset<MinimumDistance>::const_iterator MultisetIterator; typedef std::unordered_multimap<int, MultisetIterator>::const_iterator NNIterator; /** * @brief initialises all data structures * * @param[in] metric Metric for measuring the distance between points in the 2D plane * @param[in] data_x x-coordinates of points to be clustered * @param[in] data_y y-coordinates of points to be clustered * @param[in] properties_A property A of points (same in each cluster) * @param[in] properties_B property B of points (different in each cluster) * @param[in] grid_spacing_x grid spacing in x-direction * @param[in] grid_spacing_y grid spacing in y-direction */ GridBasedClustering(Metric metric, const std::vector<double>& data_x, const std::vector<double>& data_y, const std::vector<int>& properties_A, const std::vector<int>& properties_B, std::vector<double> grid_spacing_x, std::vector<double> grid_spacing_y) : metric_(metric), grid_(grid_spacing_x, grid_spacing_y) { init_(data_x, data_y, properties_A, properties_B); } /** * @brief initialises all data structures * * @param[in] metric Metric for measuring the distance between points in the 2D plane * @param[in] data_x x-coordinates of points to be clustered * @param[in] data_y y-coordinates of points to be clustered * @param[in] grid_spacing_x grid spacing in x-direction * @param[in] grid_spacing_y grid spacing in y-direction */ GridBasedClustering(Metric metric, const std::vector<double>& data_x, const std::vector<double>& data_y, std::vector<double> grid_spacing_x, std::vector<double> grid_spacing_y) : metric_(metric), grid_(grid_spacing_x, grid_spacing_y) { // set properties A and B to -1, i.e. ignore properties when clustering std::vector<int> properties_A(data_x.size(), -1); std::vector<int> properties_B(data_x.size(), -1); init_(data_x, data_y, properties_A, properties_B); } /** * @brief performs the hierarchical clustering * (merges clusters until their dimension exceeds that of cell) */ void cluster() { // progress logger // NOTE: for some reason, gcc7 chokes if we remove the OpenMS::String // below, so lets just not change it. Size clusters_start = clusters_.size(); startProgress(0, clusters_start, OpenMS::String("clustering")); MinimumDistance zero_distance(-1, -1, 0); // combine clusters until all have been moved to the final list while (!clusters_.empty()) { setProgress(clusters_start - clusters_.size()); MultisetIterator smallest_distance_it = distances_.lower_bound(zero_distance); int cluster_index1 = smallest_distance_it->getClusterIndex(); int cluster_index2 = smallest_distance_it->getNearestNeighbourIndex(); eraseMinDistance_(smallest_distance_it); // update cluster list std::map<int, GridBasedCluster>::iterator cluster1_it = clusters_.find(cluster_index1); std::map<int, GridBasedCluster>::iterator cluster2_it = clusters_.find(cluster_index2); const GridBasedCluster& cluster1 = cluster1_it->second; const GridBasedCluster& cluster2 = cluster2_it->second; const std::vector<int>& points1 = cluster1.getPoints(); const std::vector<int>& points2 = cluster2.getPoints(); std::vector<int> new_points; new_points.reserve(points1.size() + points2.size()); new_points.insert(new_points.end(), points1.begin(), points1.end()); new_points.insert(new_points.end(), points2.begin(), points2.end()); double new_x = (cluster1.getCentre().getX() * points1.size() + cluster2.getCentre().getX() * points2.size()) / (points1.size() + points2.size()); double new_y = (cluster1.getCentre().getY() * points1.size() + cluster2.getCentre().getY() * points2.size()) / (points1.size() + points2.size()); // update grid CellIndex cell_for_cluster1 = grid_.getIndex(cluster1.getCentre()); CellIndex cell_for_cluster2 = grid_.getIndex(cluster2.getCentre()); CellIndex cell_for_new_cluster = grid_.getIndex(DPosition<2>(new_x, new_y)); grid_.removeCluster(cell_for_cluster1, cluster_index1); grid_.removeCluster(cell_for_cluster2, cluster_index2); grid_.addCluster(cell_for_new_cluster, cluster_index1); // merge clusters const Rectangle& box1 = cluster1.getBoundingBox(); const Rectangle& box2 = cluster2.getBoundingBox(); Rectangle new_box(box1); new_box.enlarge(box2.minPosition()); new_box.enlarge(box2.maxPosition()); // Properties A of both clusters should by now be the same. The merge veto has been checked // when a new entry to the minimum distance list was added, @see findNearestNeighbour_. if (cluster1.getPropertyA() != cluster2.getPropertyA()) { throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Property A of both clusters not the same. ", "A"); } int new_A = cluster1.getPropertyA(); const std::vector<int>& B1 = cluster1.getPropertiesB(); const std::vector<int>& B2 = cluster2.getPropertiesB(); std::vector<int> new_B; new_B.reserve(B1.size() + B2.size()); new_B.insert(new_B.end(), B1.begin(), B1.end()); new_B.insert(new_B.end(), B2.begin(), B2.end()); GridBasedCluster new_cluster(DPosition<2>(new_x, new_y), new_box, new_points, new_A, new_B); clusters_.erase(cluster1_it); clusters_.erase(cluster2_it); clusters_.insert(std::make_pair(cluster_index1, new_cluster)); std::set<int> clusters_to_be_updated; clusters_to_be_updated.insert(cluster_index1); // erase distance object of cluster with cluster_index2 without updating (does not exist anymore!) // (the one with cluster_index1 has already been erased at the top of the while loop) eraseMinDistance_(distance_it_for_cluster_idx_[cluster_index2]); // find out which clusters need to be updated std::pair<NNIterator, NNIterator> nn_range = reverse_nns_.equal_range(cluster_index1); for (NNIterator nn_it = nn_range.first; nn_it != nn_range.second;) { clusters_to_be_updated.insert(nn_it->second->getClusterIndex()); eraseMinDistance_((nn_it++)->second); } nn_range = reverse_nns_.equal_range(cluster_index2); for (NNIterator nn_it = nn_range.first; nn_it != nn_range.second;) { clusters_to_be_updated.insert(nn_it->second->getClusterIndex()); eraseMinDistance_((nn_it++)->second); } // update clusters for (std::set<int>::const_iterator cluster_index = clusters_to_be_updated.begin(); cluster_index != clusters_to_be_updated.end(); ++cluster_index) { std::map<int, GridBasedCluster>::iterator c_it = clusters_.find(*cluster_index); const GridBasedCluster& c = c_it->second; if (findNearestNeighbour_(c, *cluster_index)) { grid_.removeCluster(grid_.getIndex(c.getCentre()), *cluster_index); // remove from grid clusters_.erase(c_it); // remove from cluster list } } } endProgress(); } /** * @brief extends clusters in y-direction if possible * (merges clusters further in y-direction, i.e. clusters can now span multiple cells) */ void extendClustersY() { // construct new grid (grid only in x-direction, single cell in y-direction) std::vector<double> grid_spacing_x = grid_.getGridSpacingX(); std::vector<double> grid_spacing_y = grid_.getGridSpacingY(); std::vector<double> grid_spacing_y_new; grid_spacing_y_new.push_back(grid_spacing_y.front()); grid_spacing_y_new.push_back(grid_spacing_y.back()); ClusteringGrid grid_x_only(grid_spacing_x, grid_spacing_y_new); // register final clusters on the new grid for (std::map<int, GridBasedCluster>::const_iterator it = clusters_final_.begin(); it != clusters_final_.end(); ++it) { int cluster_index = it->first; GridBasedCluster cluster = it->second; grid_x_only.addCluster(grid_x_only.getIndex(cluster.getCentre()), cluster_index); } // scan through x on the grid for (unsigned cell = 0; cell < grid_spacing_x.size(); ++cell) { CellIndex grid_index(cell, 1); if (grid_x_only.isNonEmptyCell(grid_index)) { std::list<int> cluster_indices = grid_x_only.getClusters(grid_index); // indices of clusters in this x-range if (cluster_indices.size() > 1) { // First, order the clusters in ascending y. std::list<GridBasedCluster> cluster_list; // list to order clusters in y std::map<GridBasedCluster, int> index_list; // allows us to keep track of cluster indices after sorting for (std::list<int>::const_iterator it = cluster_indices.begin(); it != cluster_indices.end(); ++it) { cluster_list.push_back(clusters_final_.find(*it)->second); index_list.insert(std::make_pair(clusters_final_.find(*it)->second, *it)); } cluster_list.sort(); // Now check if two adjacent clusters c1 and c2 can be merged. std::list<GridBasedCluster>::const_iterator c1 = cluster_list.begin(); std::list<GridBasedCluster>::const_iterator c2 = cluster_list.begin(); ++c1; while (c1 != cluster_list.end()) { double centre1x = (*c1).getCentre().getX(); double centre1y = (*c1).getCentre().getY(); double centre2x = (*c2).getCentre().getX(); double centre2y = (*c2).getCentre().getY(); double box1x_min = (*c1).getBoundingBox().minX(); double box1x_max = (*c1).getBoundingBox().maxX(); double box1y_min = (*c1).getBoundingBox().minY(); double box1y_max = (*c1).getBoundingBox().maxY(); double box2x_min = (*c2).getBoundingBox().minX(); double box2x_max = (*c2).getBoundingBox().maxX(); double box2y_min = (*c2).getBoundingBox().minY(); double box2y_max = (*c2).getBoundingBox().maxY(); //double y_range1 = box1y_max - box1y_min; //double y_range2 = box2y_max - box2y_min; //double y_gap = box1y_min - box2y_max; // Is there an overlap of the two clusters in x? bool overlap = (box1x_min <= box2x_max && box1x_min >= box2x_min) || (box1x_max >= box2x_min && box1x_max <= box2x_max); // Is the x-centre of one cluster in the x-range of the other? //bool centre_in_range1 = (box2x_min <= centre1x && centre1x <= box2x_max); //bool centre_in_range2 = (box1x_min <= centre2x && centre2x <= box1x_max); // Is the y-gap between the two clusters smaller than 1/s of their average y-range? //double s = 6; // scaling factor //bool clusters_close = (y_gap * s <= (y_range1 - y_range2)/2); // Shall we merge the two adjacent clusters? //if ((centre_in_range1 || centre_in_range2) && clusters_close) if (overlap) { std::vector<int> points1 = (*c1).getPoints(); std::vector<int> points2 = (*c2).getPoints(); std::vector<int> new_points; new_points.reserve(points1.size() + points2.size()); new_points.insert(new_points.end(), points1.begin(), points1.end()); new_points.insert(new_points.end(), points2.begin(), points2.end()); double new_x = (centre1x * points1.size() + centre2x * points2.size()) / (points1.size() + points2.size()); double new_y = (centre1y * points1.size() + centre2y * points2.size()) / (points1.size() + points2.size()); double min_x = std::min(box1x_min, box2x_min); double min_y = std::min(box1y_min, box2y_min); double max_x = std::max(box1x_max, box2x_max); double max_y = std::max(box1y_max, box2y_max); Point new_centre(new_x, new_y); Point position_min(min_x, min_y); Point position_max(max_x, max_y); Rectangle new_bounding_box(position_min, position_max); GridBasedCluster new_cluster(new_centre, new_bounding_box, new_points); // update final cluster list clusters_final_.erase(clusters_final_.find(index_list.find(*c1)->second)); clusters_final_.erase(clusters_final_.find(index_list.find(*c2)->second)); clusters_final_.insert(std::make_pair(index_list.find(*c1)->second, new_cluster)); // update grid CellIndex cell_for_cluster1 = grid_x_only.getIndex((*c1).getCentre()); CellIndex cell_for_cluster2 = grid_x_only.getIndex((*c2).getCentre()); CellIndex cell_for_new_cluster = grid_x_only.getIndex(new_centre); grid_x_only.removeCluster(cell_for_cluster1, index_list.find(*c1)->second); grid_x_only.removeCluster(cell_for_cluster2, index_list.find(*c2)->second); grid_x_only.addCluster(cell_for_new_cluster, index_list.find(*c1)->second); } ++c1; ++c2; } } } } } /** * @brief removes clusters with bounding box dimension in y-direction below certain threshold * @param[in] threshold_y minimal dimension of the cluster bounding box */ void removeSmallClustersY(double threshold_y) { std::map<int, GridBasedCluster>::iterator it = clusters_final_.begin(); while (it != clusters_final_.end()) { Rectangle box = it->second.getBoundingBox(); if (box.maxY() - box.minY() < threshold_y) { clusters_final_.erase(it++); } else { ++it; } } } /** * @brief returns final results (mapping of cluster indices to clusters) */ std::map<int, GridBasedCluster> getResults() const { return clusters_final_; } private: /** * @brief metric for measuring the distance between points in the 2D plane */ Metric metric_; /** * @brief grid on which the position of the clusters are registered * used in cluster method */ ClusteringGrid grid_; /** * @brief list of clusters * maps cluster indices to clusters */ std::map<int, GridBasedCluster> clusters_; /** * @brief list of final clusters * i.e. clusters that are no longer merged */ std::map<int, GridBasedCluster> clusters_final_; /** * @brief list of minimum distances * stores the smallest of the distances in the head */ std::multiset<MinimumDistance> distances_; /** * @brief reverse nearest neighbor lookup table * for finding out which clusters need to be updated faster */ std::unordered_multimap<int, std::multiset<MinimumDistance>::const_iterator> reverse_nns_; /** * @brief cluster index to distance iterator lookup table * for finding out which clusters need to be updated faster */ std::unordered_map<int, std::multiset<MinimumDistance>::const_iterator> distance_it_for_cluster_idx_; /** * @brief initialises all data structures * * @param[in] data_x x-coordinates of points to be clustered * @param[in] data_y y-coordinates of points to be clustered * @param[in] properties_A property A of points (same in each cluster) * @param[in] properties_B property B of points (different in each cluster) */ void init_(const std::vector<double>& data_x, const std::vector<double>& data_y, const std::vector<int>& properties_A, const std::vector<int>& properties_B) { // fill the grid with points to be clustered (initially each cluster contains a single point) for (unsigned i = 0; i < data_x.size(); ++i) { Point position(data_x[i], data_y[i]); Rectangle box(position, position); std::vector<int> pi; // point indices pi.push_back(i); std::vector<int> pb; // properties B pb.push_back(properties_B[i]); // add to cluster list GridBasedCluster cluster(position, box, pi, properties_A[i], pb); clusters_.insert(std::make_pair(i, cluster)); // register on grid grid_.addCluster(grid_.getIndex(position), i); } // fill list of minimum distances std::map<int, GridBasedCluster>::iterator iterator = clusters_.begin(); while (iterator != clusters_.end()) { int cluster_index = iterator->first; const GridBasedCluster& cluster = iterator->second; if (findNearestNeighbour_(cluster, cluster_index)) { // remove from grid grid_.removeCluster(grid_.getIndex(cluster.getCentre()), cluster_index); // remove from cluster list clusters_.erase(iterator++); } else { ++iterator; } } } /** * @brief checks if two clusters can be merged * Each point in a cluster can (optionally) have two properties A and B. * Properties A need to be the same, properties B need to differ in each cluster. * Methods checks if this is violated in the merged cluster. * * @param[in] c1 cluster 1 * @param[in] c2 cluster 2 * * @return veto for merging clusters * true -> clusters can be merged * false -> clusters cannot be merged */ bool mergeVeto_(const GridBasedCluster& c1, const GridBasedCluster& c2) const { int A1 = c1.getPropertyA(); int A2 = c2.getPropertyA(); // check if properties A of both clusters is set or not (not set := -1) if (A1 == -1 || A2 == -1) { return false; } // Will the merged cluster have the same properties A? if (A1 != A2) return true; std::vector<int> B1 = c1.getPropertiesB(); std::vector<int> B2 = c2.getPropertiesB(); // check if properties B of both clusters is set or not (not set := -1) if (std::find(B1.begin(), B1.end(), -1) != B1.end() || std::find(B2.begin(), B2.end(), -1) != B2.end()) { return false; } // Will the merged cluster have different properties B? // (Hence the intersection of properties B of cluster 1 and cluster 2 should be empty.) std::vector<int> B_intersection; sort(B1.begin(), B1.end()); sort(B2.begin(), B2.end()); set_intersection(B1.begin(), B1.end(), B2.begin(), B2.end(), back_inserter(B_intersection)); return !B_intersection.empty(); } /** * @brief determines the nearest neighbour for each cluster * * @note If no nearest neighbour exists, the cluster is removed from the list. * The deletion is done outside of the method, see return boolean. * @note If two clusters cannot be merged (merge veto), they are no * viable nearest neighbours. * * @param[in] cluster cluster for which the nearest neighbour should be found * @param[in] cluster_index index of cluster * * @return Should the cluster be removed from the cluster list? */ bool findNearestNeighbour_(const GridBasedCluster& cluster, int cluster_index) { const Point& centre = cluster.getCentre(); const CellIndex& cell_index = grid_.getIndex(centre); double min_dist = 0; int nearest_neighbour = -1; // search in the grid cell and its 8 neighbouring cells for the nearest neighbouring cluster for (int i = -1; i <= 1; ++i) { for (int j = -1; j <= 1; ++j) { CellIndex cell_index2(cell_index); cell_index2.first += i; cell_index2.second += j; if (grid_.isNonEmptyCell(cell_index2)) { const std::list<int>& cluster_indices = grid_.getClusters(cell_index2); for (std::list<int>::const_iterator cluster_index2 = cluster_indices.begin(); cluster_index2 != cluster_indices.end(); ++cluster_index2) { if (*cluster_index2 != cluster_index) { const GridBasedCluster& cluster2 = clusters_.find(*cluster_index2)->second; const Point& centre2 = cluster2.getCentre(); double distance = metric_(centre, centre2); if (distance < min_dist || nearest_neighbour == -1) { bool veto = mergeVeto_(cluster, cluster2); // If clusters cannot be merged anyhow, they are no nearest neighbours. if (!veto) { min_dist = distance; nearest_neighbour = *cluster_index2; } } } } } } } if (nearest_neighbour == -1) { // no other cluster nearby, hence move the cluster to the final results clusters_final_.insert(std::make_pair(cluster_index, clusters_.find(cluster_index)->second)); return true; } // add to the list of minimal distances std::multiset<MinimumDistance>::const_iterator it = distances_.insert(MinimumDistance(cluster_index, nearest_neighbour, min_dist)); // add to reverse nearest neighbor lookup table reverse_nns_.insert(std::make_pair(nearest_neighbour, it)); // add to cluster index -> distance lookup table distance_it_for_cluster_idx_[cluster_index] = it; return false; } /** * @brief remove minimum distance object and its related data * * Remove the distance object behind @p it from distances_ and remove all * corresponding data from the auxiliary data structures reverse_nns_ and * distance_it_for_cluster_idx_. * * @param[in] it Iterator of distance to be removed from distances_ */ void eraseMinDistance_(const std::multiset<MinimumDistance>::const_iterator it) { // remove corresponding entries from nearest neighbor lookup table std::pair<NNIterator, NNIterator> nn_range = reverse_nns_.equal_range(it->getNearestNeighbourIndex()); for (NNIterator nn_it = nn_range.first; nn_it != nn_range.second; ++nn_it) { if (nn_it->second == it) { reverse_nns_.erase(nn_it); break; } } // remove corresponding entry from cluster index -> distance lookup table distance_it_for_cluster_idx_.erase(it->getClusterIndex()); // remove from distances_ distances_.erase(it); } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/ML/CLUSTERING/ClusteringGrid.h
.h
3,964
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/DATASTRUCTURES/DPosition.h> #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/CONCEPT/Exception.h> #include <OpenMS/CONCEPT/Macros.h> #include <map> #include <vector> #include <list> namespace OpenMS { /** * @brief data structure to store 2D data to be clustered * e.g. (m/z, retention time) coordinates from multiplex filtering * * @see LocalClustering */ class OPENMS_DLLAPI ClusteringGrid { public: /** * coordinates of a grid cell */ typedef std::pair<int,int> CellIndex; /** * coordinates in x-y-plane */ typedef DPosition<2> Point; /** * @brief constructor taking two vectors * @param[in] grid_spacing_x grid spacing in x direction * @param[in] grid_spacing_y grid spacing in y direction * * @note Vectors are assumed to be sorted. */ ClusteringGrid(const std::vector<double> &grid_spacing_x, const std::vector<double> &grid_spacing_y); /** * @brief returns grid spacing in x direction */ std::vector<double> getGridSpacingX() const; /** * @brief returns grid spacing in y direction */ std::vector<double> getGridSpacingY() const; /** * @brief adds a cluster to this grid cell * * @param[in] cell_index cell index (i,j) on the grid * @param[in] cluster_index index of the cluster in the cluster list */ void addCluster(const CellIndex &cell_index, const int &cluster_index); /** * @brief removes a cluster from this grid cell * and removes the cell if no other cluster left * * @param[in] cell_index cell index (i,j) on the grid * @param[in] cluster_index index of the cluster in the cluster list */ void removeCluster(const CellIndex &cell_index, const int &cluster_index); /** * @brief removes all clusters from this grid (and hence all cells) */ void removeAllClusters(); /** * @brief returns clusters in this grid cell * * @param[in] cell_index cell index (i,j) on the grid * @return list of cluster indices (from the list of clusters) which are centred in this cell */ std::list<int> getClusters(const CellIndex &cell_index) const; /** * @brief returns grid cell index (i,j) for the positions (x,y) * * @param[in] position coordinates (x,y) on the grid * @return cell index (i,j) of the cell in which (x,y) lies */ CellIndex getIndex(const Point &position) const; /** * @brief checks if there are clusters at this cell index * * @param[in] cell_index cell index (i,j) on the grid * @return true if there are clusters in this cell * * @throw Exception::IllegalArgument if the coordinates (x,y) lie outside the grid. * @throw Exception::InvalidValue if one of the two indices is negative. */ bool isNonEmptyCell(const CellIndex &cell_index) const; /** * @brief returns number of grid cells occupied by one or more clusters * * @return number of non-empty cells */ int getCellCount() const; private: /** * @brief spacing of the grid in x and y direction */ const std::vector<double> grid_spacing_x_; const std::vector<double> grid_spacing_y_; /** * @brief [min, max] of the grid in x and y direction */ std::pair <double,double> range_x_; std::pair <double,double> range_y_; /** * @brief grid cell index mapped to a list of clusters in it */ std::map<CellIndex, std::list<int> > cells_; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/ML/CLUSTERING/ClusterAnalyzer.h
.h
6,039
128
// 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/DATASTRUCTURES/BinaryTreeNode.h> #include <vector> namespace OpenMS { class String; /** @brief Bundles analyzing tools for a clustering (given as sequence of BinaryTreeNode's) @ingroup SpectraClustering */ class OPENMS_DLLAPI ClusterAnalyzer { public: /// default constructor ClusterAnalyzer(); /// copy constructor ClusterAnalyzer(const ClusterAnalyzer & source); /// destructor virtual ~ClusterAnalyzer(); /** @brief Method to calculate the average silhouette widths for a clustering @param[in] tree vector of BinaryTreeNode's representing the clustering @param[in] original DistanceMatrix for all clustered elements started from @return a vector filled with the average silhouette widths for each cluster step The average silhouette width will be calculated for each clustering step beginning with the first step(n-1 cluster) ending with the last (1 cluster, average silhouette width is 0 by definition). @see BinaryTreeNode */ std::vector<float> averageSilhouetteWidth(const std::vector<BinaryTreeNode> & tree, const DistanceMatrix<float> & original); /** @brief Method to calculate Dunns indices for a clustering @param[in] tree vector of BinaryTreeNode's representing the clustering @param[in] original DistanceMatrix for all clustered elements started from @param[in] tree_from_singlelinkage true if tree was created by SingleLinkage, i.e. the distances are the minimal distances in increasing order and can be used to speed up the calculation @see BinaryTreeNode */ std::vector<float> dunnIndices(const std::vector<BinaryTreeNode> & tree, const DistanceMatrix<float> & original, const bool tree_from_singlelinkage = false); /** @brief Method to calculate the cohesions of a certain partition @param[in] clusters vector of vectors holding the clusters (with indices to the actual elements) @param[in] original DistanceMatrix for all clustered elements started from @return a vector that holds the cohesions of each cluster given with @p clusters (order corresponds to @p clusters) */ std::vector<float> cohesion(const std::vector<std::vector<Size> > & clusters, const DistanceMatrix<float> & original); /** @brief Method to calculate the average aberration from average population in partition resulting from a certain step in clustering @param[in] cluster_quantity desired partition Size analogue to ClusterAnalyzer::cut @param[in] tree vector of BinaryTreeNode's representing the clustering @throw invalid_parameter if desired clustering is invalid @return the average aberration from the average cluster population (number of elements/cluster_quantity) at cluster_quantity @see BinaryTreeNode */ float averagePopulationAberration(Size cluster_quantity, std::vector<BinaryTreeNode> & tree); /** @brief Method to calculate a partition resulting from a certain step in clustering given by the number of clusters If you want to fetch all clusters which were created with a threshold, you simply count the number of tree-nodes which are not -1, and subtract that from the number of leaves, to get the number of clusters formed , i.e. cluster_quantity = data.size() - real_leaf_count; @param[in] cluster_quantity Size giving the number of clusters (i.e. starting elements - cluster_quantity = cluster step) @param[in] tree vector of BinaryTreeNode's representing the clustering @param[in] clusters vector of vectors holding the clusters (with indices to the actual elements) @throw invalid_parameter if desired clusterstep is invalid @see BinaryTreeNode after call of this method the argument clusters is filled corresponding to the given @p cluster_quantity with the indices of the elements clustered */ void cut(const Size cluster_quantity, const std::vector<BinaryTreeNode> & tree, std::vector<std::vector<Size> > & clusters); /** @brief Method to calculate subtrees from a given tree resulting from a certain step in clustering given by the number of clusters @param[in] cluster_quantity Size giving the number of clusters (i.e. starting elements - cluster_quantity = cluster step) @param[in] tree vector of BinaryTreeNode's representing the clustering @param[in] subtrees vector of trees holding the trees, tree is composed of cut at given size @throw invalid_parameter if desired clusterstep is invalid @see BinaryTreeNode after call of this method the argument clusters is filled corresponding to the given @p cluster_quantity with the indices of the elements clustered */ void cut(const Size cluster_quantity, const std::vector<BinaryTreeNode> & tree, std::vector<std::vector<BinaryTreeNode> > & subtrees); /** @brief Returns the hierarchy described by a clustering tree as Newick-String @param[in] tree vector of BinaryTreeNode's representing the clustering @param[in] include_distance bool value indicating whether the distance shall be included to the string @see BinaryTreeNode */ String newickTree(const std::vector<BinaryTreeNode> & tree, const bool include_distance = false); private: /// assignment operator ClusterAnalyzer & operator=(const ClusterAnalyzer & source); }; ///returns the value of (x.distance < y.distance) for use with sort bool compareBinaryTreeNode(const BinaryTreeNode & x, const BinaryTreeNode & y); }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/ML/RANSAC/RANSAC.h
.h
9,742
227
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: George Rosenberger $ // $Authors: George Rosenberger, Hannes Roest, Chris Bielow $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/config.h> #include <OpenMS/ML/RANSAC/RANSACModel.h> #include <OpenMS/CONCEPT/Exception.h> #include <OpenMS/DATASTRUCTURES/String.h> #include <OpenMS/ML/RANSAC/RANSACModelLinear.h> #include <OpenMS/MATH/MathFunctions.h> #include <limits> // std::numeric_limits #include <vector> // std::vector #include <sstream> // stringstream namespace OpenMS { namespace Math { /** @brief A simple struct to carry all the parameters required for a RANSAC run. */ struct RANSACParam { /// Default constructor RANSACParam() : n(0), k(0), t(0), d(0), relative_d(false) { } /// Full constructor RANSACParam(size_t p_n, size_t p_k, double p_t, size_t p_d, bool p_relative_d = false) : n(p_n), k(p_k), t(p_t), d(p_d), relative_d(p_relative_d) { if (relative_d) { if (d >= 100) throw Exception::Precondition(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("RANSAC: Relative 'd' >= 100% given. Use a lower value; the more outliers you expect, the lower it should be.")); } } [[nodiscard]] std::string toString() const { std::stringstream r; r << "RANSAC param:\n n: " << n << "\n k: " << k << " iterations\n t: " << t << " threshold\n d: " << d << " inliers\n\n"; return r.str(); } size_t n; ///< data points: The minimum number of data points required to fit the model size_t k; ///< iterations: The maximum number of iterations allowed in the algorithm double t; ///< Threshold value: for determining when a data point fits a model. Corresponds to the maximal squared deviation in units of the _second_ dimension (dim2). size_t d; ///< The number of close data values (according to 't') required to assert that a model fits well to data bool relative_d; ///< Should 'd' be interpreted as percentages (0-100) of data input size. }; /** @brief This class provides a generic implementation of the RANSAC outlier detection algorithm. Is implemented and tested after the SciPy reference: http://wiki.scipy.org/Cookbook/RANSAC */ template<typename TModelType = RansacModelLinear> class RANSAC { public: explicit RANSAC(uint64_t seed = time(nullptr)): shuffler_(seed) {} ~RANSAC() = default; /// set seed for random shuffle void setSeed(uint64_t seed) { shuffler_.seed(seed); } /// alias for ransac() with full params std::vector<std::pair<double, double> > ransac( const std::vector<std::pair<double, double> >& pairs, const RANSACParam& p) { return ransac(pairs, p.n, p.k, p.t, p.d, p.relative_d); } /** @brief This function provides a generic implementation of the RANSAC outlier detection algorithm. Is implemented and tested after the SciPy reference: http://wiki.scipy.org/Cookbook/RANSAC If possible, restrict 'n' to the minimal number of points which the model requires to make a fit, i.e. n=2 for linear, n=3 for quadratic. Any higher number will result in increasing the chance of including an outlier, hence a lost iteration. While iterating, this RANSAC implementation will consider any model which explains more data points than the currently best model as even better. If the data points are equal, RSS (residual sum of squared error) will be used. Making 'd' a relative measure (1-99%) is useful if you cannot predict how many points RANSAC will actually receive at runtime, but you have a rough idea how many percent will be outliers. E.g. if you expect 20% outliers, then setting d=60, relative_d=true (i.e. 60% inliers with some margin for error) is a good bet for a larger input set. (Consider that 2-3 data points will be used for the initial model already -- they cannot possibly become inliers). @param[in] pairs Input data (paired data of type <dim1, dim2>) @param[in] n The minimum number of data points required to fit the model @param[in] k The maximum number of iterations allowed in the algorithm @param[in] t Threshold value for determining when a data point fits a model. Corresponds to the maximal squared deviation in units of the _second_ dimension (dim2). @param[in] d The number of close data values (according to 't') required to assert that a model fits well to data @param[in] relative_d Should 'd' be interpreted as percentages (0-100) of data input size @return A vector of pairs fitting the model well; data will be unsorted */ std::vector<std::pair<double, double> > ransac( const std::vector<std::pair<double, double> >& pairs, size_t n, size_t k, double t, size_t d, bool relative_d = false) { // translate relative percentages into actual numbers if (relative_d) { if (d >= 100) throw Exception::Precondition(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("RANSAC: Relative 'd' >= 100% given. Use a lower value; the more outliers you expect, the lower it should be.")); d = pairs.size() * d / 100; } // implementation of the RANSAC algorithm according to http://wiki.scipy.org/Cookbook/RANSAC. if (pairs.size() <= n) { throw Exception::Precondition(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("RANSAC: Number of total data points (") + String(pairs.size()) + ") must be larger than number of initial points (n=" + String(n) + ")."); } TModelType model; std::vector< std::pair<double, double> > alsoinliers, betterdata, bestdata; std::vector<std::pair<double, double> > pairs_shuffled = pairs; // mutable data. will be shuffled in every iteration double besterror = std::numeric_limits<double>::max(); typename TModelType::ModelParameters coeff; #ifdef DEBUG_RANSAC std::pair<double, double > bestcoeff; double betterrsq = 0; double bestrsq = 0; #endif for (size_t ransac_int=0; ransac_int<k; ransac_int++) { // check if the model already includes all points if (bestdata.size() == pairs.size()) break; // use portable RNG in test mode shuffler_.portable_random_shuffle(pairs_shuffled.begin(), pairs_shuffled.end()); // test 'maybeinliers' try { // fitting might throw UnableToFit if points are 'unfortunate' coeff = model.rm_fit(pairs_shuffled.begin(), pairs_shuffled.begin()+n); } catch (...) { continue; } // apply model to remaining data; pick inliers alsoinliers = model.rm_inliers(pairs_shuffled.begin()+n, pairs_shuffled.end(), coeff, t); // ... and add data if (alsoinliers.size() > d || alsoinliers.size() >= (pairs_shuffled.size()-n)) // maximum number of inliers we can possibly have (i.e. remaining data) { betterdata.clear(); std::copy( pairs_shuffled.begin(), pairs_shuffled.begin()+n, back_inserter(betterdata) ); betterdata.insert( betterdata.end(), alsoinliers.begin(), alsoinliers.end() ); typename TModelType::ModelParameters bettercoeff = model.rm_fit(betterdata.begin(), betterdata.end()); double bettererror = model.rm_rss(betterdata.begin(), betterdata.end(), bettercoeff); #ifdef DEBUG_RANSAC betterrsq = model.rm_rsq(betterdata); #endif // If the current model explains more points, we assume its better (these points pass the error threshold 't', so they should be ok); // If the number of points is equal, we trust rss. // E.g. imagine gaining a zillion more points (which pass the threshold!) -- then rss will automatically be worse, no matter how good // these points fit, since its a simple absolute SUM() of residual error over all points. if (betterdata.size() > bestdata.size() || (betterdata.size() == bestdata.size() && (bettererror < besterror))) { besterror = bettererror; bestdata = betterdata; #ifdef DEBUG_RANSAC bestcoeff = bettercoeff; bestrsq = betterrsq; std::cout << "RANSAC " << ransac_int << ": Points: " << betterdata.size() << " RSQ: " << bestrsq << " Error: " << besterror << " c0: " << bestcoeff.first << " c1: " << bestcoeff.second << std::endl; #endif } } } #ifdef DEBUG_RANSAC std::cout << "=======STARTPOINTS=======" << std::endl; for (std::vector<std::pair<double, double> >::iterator it = bestdata.begin(); it != bestdata.end(); ++it) { std::cout << it->first << "\t" << it->second << std::endl; } std::cout << "=======ENDPOINTS=======" << std::endl; #endif return(bestdata); } // ransac() private: Math::RandomShuffler shuffler_{}; }; // class } // namespace Math } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/ML/RANSAC/RANSACModelQuadratic.h
.h
1,241
42
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: George Rosenberger $ // $Authors: George Rosenberger, Hannes Roest, Chris Bielow $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/config.h> #include <OpenMS/ML/RANSAC/RANSACModel.h> namespace OpenMS { namespace Math { /** @brief Implementation of a quadratic RANSAC model fit. Using generic plug-in template base class 'RansacModel' using 'Curiously recurring template pattern' (CRTP). */ class OPENMS_DLLAPI RansacModelQuadratic : public RansacModel<RansacModelQuadratic> { public: static ModelParameters rm_fit_impl(const DVecIt& begin, const DVecIt& end); static double rm_rsq_impl(const DVecIt& begin, const DVecIt& end); static double rm_rss_impl(const DVecIt& begin, const DVecIt& end, const ModelParameters& coefficients); static DVec rm_inliers_impl(const DVecIt& begin, const DVecIt& end, const ModelParameters& coefficients, double max_threshold); }; } }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/ML/RANSAC/RANSACModel.h
.h
2,669
79
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: George Rosenberger $ // $Authors: George Rosenberger, Hannes Roest, Chris Bielow $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/config.h> #include <cstddef> // for size_t & ptrdiff_t #include <vector> #include <string> namespace OpenMS { namespace Math { /** @brief Generic plug-in template base class using 'Curiously recurring template pattern' (CRTP) to allow for arbitrary RANSAC models (e.g. linear or quadratic fits). An actual model should derive from this class using CRTP (see RansacModelLinear for an example) and implement the *_impl() functions. */ template<class ModelT = int> // dummy default to allow easy access to public typedefs class RansacModel { public: typedef std::pair<double, double> DPair; typedef std::vector<DPair> DVec; typedef DVec::const_iterator DVecIt; typedef std::vector<double> ModelParameters; /// fit a model and return its parameters ModelParameters rm_fit(const DVecIt& begin, const DVecIt& end) const { return static_cast<const ModelT*>(this)->rm_fit_impl(begin, end); } /** @brief Returns the R-squared of the data applied to the model (computed on-the-fly). Takes as input a standard vector of a standard pair of points in a 2D space. @param[in] begin Iterator to first pair @param[in] end Past-end iterator to last pair @return: R-squared value */ double rm_rsq(const DVecIt& begin, const DVecIt& end) const { return static_cast<const ModelT*>(this)->rm_rsq_impl(begin, end); } /// calculates the residual sum of squares of the input points according to the model double rm_rss(const DVecIt& begin, const DVecIt& end, const ModelParameters& coefficients) const { return static_cast<const ModelT*>(this)->rm_rss_impl(begin, end, coefficients); } /// calculates the squared residual of each input point vs. the model. /// All points with an error <= max_threshold, are accepted as inliers and returned. DVec rm_inliers(const DVecIt& begin, const DVecIt& end, const ModelParameters& coefficients, double max_threshold) const { return static_cast<const ModelT*>(this)->rm_inliers_impl(begin, end, coefficients, max_threshold); } }; } }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/ML/RANSAC/RANSACModelLinear.h
.h
1,240
44
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: George Rosenberger $ // $Authors: George Rosenberger, Hannes Roest, Chris Bielow $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/config.h> #include <OpenMS/ML/RANSAC/RANSACModel.h> namespace OpenMS { namespace Math { /** @brief Implementation of a linear RANSAC model fit. Using generic plug-in template base class 'RansacModel' using 'Curiously recurring template pattern' (CRTP). */ class OPENMS_DLLAPI RansacModelLinear : public RansacModel<RansacModelLinear> { public: static ModelParameters rm_fit_impl(const DVecIt& begin, const DVecIt& end); static double rm_rsq_impl(const DVecIt& begin, const DVecIt& end); static double rm_rss_impl(const DVecIt& begin, const DVecIt& end, const ModelParameters& coefficients); static DVec rm_inliers_impl(const DVecIt& begin, const DVecIt& end, const ModelParameters& coefficients, double max_threshold); }; } }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/COMPARISON/BinnedSumAgreeingIntensities.h
.h
2,306
72
// 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/COMPARISON/BinnedSpectrumCompareFunctor.h> #include <cmath> #include <cfloat> namespace OpenMS { /** @brief Sum of agreeing intensities for similarity measurement Transformation and other factors of the peptide mass spectrometry pairwise peak-list comparison process Witold E Wolski , Maciej Lalowski* , Peter Martus* , Ralf Herwig* , Patrick Giavalisco , Johan Gobom , Albert Sickmann , Hans Lehrach and Knut Reinert* BMC Bioinformatics 2005, 6:285 doi:10.1186/1471-2105-6-285 Bins whose intensity differences are larger than their average intensity receive a weight of zero. Prefect agreement results in a similarity score of 1.0 @htmlinclude OpenMS_BinnedSumAgreeingIntensities.parameters @see BinnedSpectrumCompareFunctor @see BinnedSpectrum @ingroup SpectraComparison */ class OPENMS_DLLAPI BinnedSumAgreeingIntensities : public BinnedSpectrumCompareFunctor { public: /// default constructor BinnedSumAgreeingIntensities(); /// copy constructor BinnedSumAgreeingIntensities(const BinnedSumAgreeingIntensities& source); /// destructor ~BinnedSumAgreeingIntensities() override; /// assignment operator BinnedSumAgreeingIntensities& operator=(const BinnedSumAgreeingIntensities& source); /** function call operator, calculates the similarity of the given arguments @param[in] spec1 First spectrum given as a binned representation @param[in] spec2 Second spectrum given as a binned representation @throw IncompatibleBinning is thrown if the binning of the two input spectra are not the same */ double operator()(const BinnedSpectrum& spec1, const BinnedSpectrum& spec2) const override; /// function call operator, calculates self similarity double operator()(const BinnedSpectrum& spec) const override; protected: void updateMembers_() override; double precursor_mass_tolerance_; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/COMPARISON/SpectrumAlignmentScore.h
.h
2,245
75
// 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/MSSpectrum.h> #include <OpenMS/KERNEL/Peak1D.h> #include <OpenMS/COMPARISON/SpectrumAlignment.h> #include <OpenMS/DATASTRUCTURES/ListUtils.h> #include <OpenMS/KERNEL/StandardTypes.h> #include <OpenMS/COMPARISON/PeakSpectrumCompareFunctor.h> #include <cmath> namespace OpenMS { /** @brief Similarity score via spectra alignment This class implements a simple scoring based on the alignment of spectra. This alignment is implemented in the SpectrumAlignment class and performs a dynamic programming alignment of the peaks, minimizing the distances between the aligned peaks and maximizing the number of peak pairs. The scoring is done via the simple formula score = sum / (sqrt(sum1 * sum2)). sum is the product of the intensities of the aligned peaks, with the given exponent (default is 2). sum1 and sum2 are the sum of the intensities squared for each peak of both spectra respectively. A binned version of this scoring is implemented in the ZhangSimilarityScoring class. @htmlinclude OpenMS_SpectrumAlignmentScore.parameters @ingroup SpectraComparison */ class OPENMS_DLLAPI SpectrumAlignmentScore : public PeakSpectrumCompareFunctor { public: // @name Constructors and Destructors // @{ /// default constructor SpectrumAlignmentScore(); /// copy constructor SpectrumAlignmentScore(const SpectrumAlignmentScore & source); /// destructor ~SpectrumAlignmentScore() override; // @} // @name Operators // @{ /// assignment operator SpectrumAlignmentScore & operator=(const SpectrumAlignmentScore & source); /// double operator()(const PeakSpectrum & spec1, const PeakSpectrum & spec2) const override; double operator()(const PeakSpectrum & spec) const override; // @} // @} }; }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/COMPARISON/PeakAlignment.h
.h
1,884
66
// 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/COMPARISON/PeakSpectrumCompareFunctor.h> #include <vector> namespace OpenMS { /** @brief make a PeakAlignment of two PeakSpectra The alignment is done according to the Needleman-Wunsch Algorithm (local alignment considering gaps). @htmlinclude OpenMS_PeakAlignment.parameters @ingroup SpectraComparison */ class OPENMS_DLLAPI PeakAlignment : public PeakSpectrumCompareFunctor { public: /// default constructor PeakAlignment(); /// copy constructor PeakAlignment(const PeakAlignment & source); /// destructor ~PeakAlignment() override; /// assignment operator PeakAlignment & operator=(const PeakAlignment & source); /** function call operator, calculates the similarity of the given arguments @param[in] spec1 First spectrum given in a binned representation @param[in] spec2 Second spectrum given in a binned representation */ double operator()(const PeakSpectrum & spec1, const PeakSpectrum & spec2) const override; /// function call operator, calculates self similarity double operator()(const PeakSpectrum & spec) const override; /// make alignment and get the traceback std::vector<std::pair<Size, Size> > getAlignmentTraceback(const PeakSpectrum & spec1, const PeakSpectrum & spec2) const; private: /// calculates the score for aligning two peaks double peakPairScore_(double & pos1, double & intens1, double & pos2, double & intens2, const double & sigma) const; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/COMPARISON/SteinScottImproveScore.h
.h
2,992
77
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Vipul Patel $ // -------------------------------------------------------------------------- // #pragma once #include <OpenMS/COMPARISON/PeakSpectrumCompareFunctor.h> #include <cmath> namespace OpenMS { /** @brief Similarity score based of Stein & Scott This is a pairwise based score function. The spectrum contains peaks, and each peak can be defined by two values (mz and the intensity). The score function takes the sum of the product of the peak intensities from Spectrum 1 and Spectrum 2, only if the mz-ratio distance between the two spectra is smaller than a given window size. In the default status, the window size is (accuracy of the mass spectrometer). This sum is normalised by dividing it with a distance function. sqrt(sum of the Intensity of square Spectrum1 sum of the Intensity of square Spectrum2). This is all based on SteinScott score. To distinguish the close from the distant spectra an additional term is calculated. It denotes the expected value of both Spectra under the random placement of all peaks, within the given mass-to-charge range. The probability that two peaks with randomized intensity values lie within two epsilon of each other is a constant. This constant is proportional to epsilon. So the additional term is the sum over all peaks of Spectrum 1 and Spectrum 2 of the products of their intensities multiplied with the constant. The details of the score can be found in: Signal Maps for Mass Spectrometry-based Comparative Proteomics Amol Prakash, Parag Mallick , Jeffrey Whiteaker, Heidi Zhang, Amanda Paulovich, Mark Flory, Hookeun Lee, Ruedi Aebersold, and Benno Schwikowski @htmlinclude OpenMS_SteinScottImproveScore.parameters @ingroup SpectraComparison */ class OPENMS_DLLAPI SteinScottImproveScore : public PeakSpectrumCompareFunctor { public: /// default constructor SteinScottImproveScore(); /// copy constructor SteinScottImproveScore(const SteinScottImproveScore & source); /// destructor ~SteinScottImproveScore() override; /// assignment operator SteinScottImproveScore & operator=(const SteinScottImproveScore & source); /** @brief Similarity pairwise score This function return the similarity score of two Spectra based on SteinScott. */ double operator()(const PeakSpectrum & spec1, const PeakSpectrum & spec2) const override; /** @brief Similarity pairwise score itself This function return the similarity score of itself based on SteinScott. */ double operator()(const PeakSpectrum & spec) const override; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/COMPARISON/SpectraSTSimilarityScore.h
.h
4,183
120
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: David Wojnar $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/COMPARISON/PeakSpectrumCompareFunctor.h> #include <OpenMS/KERNEL/BinnedSpectrum.h> namespace OpenMS { /** @brief Similarity score of SpectraST. Unlike the other similarity scores this score is used for matching a spectrum against a whole library, although the dot product seems to be an effective method for scoring on its own. For calculating the SpectraST score, first preprocess the spectra if not already done. Transform them and calculate the dot product and the dot bias. Afterwards get the best two hits and calculate delta_D. Now for every spectrum from the library you can calculate the final score. The details of the score can be found in: H. Lam et al., Development and validation of a spectral library searching method for peptide identification from MS/MS, Proteomics, 7 , 655-667, 2007 @ingroup SpectraComparison */ class OPENMS_DLLAPI SpectraSTSimilarityScore : public PeakSpectrumCompareFunctor { public: // @name Constructors and Destructors // @{ /// default constructor SpectraSTSimilarityScore(); /// copy constructor SpectraSTSimilarityScore(const SpectraSTSimilarityScore & source); /// destructor ~SpectraSTSimilarityScore() override; // @} /// assignment operator SpectraSTSimilarityScore & operator=(const SpectraSTSimilarityScore & source); /** @brief: calculates the dot product of the two spectra */ double operator()(const PeakSpectrum & spec1, const PeakSpectrum & spec2) const override; /** @brief: calculates the dot product of the two spectra */ double operator()(const BinnedSpectrum & bin1, const BinnedSpectrum & bin2) const; /** @brief: calculates the dot product of itself */ double operator()(const PeakSpectrum & spec) const override; /** @brief Preprocesses the spectrum The preprocessing removes peak below a intensity threshold, reject spectra that does not have enough peaks, and cuts peaks exceeding the max_peak_number most intense peaks. @return true if spectrum passes filtering */ bool preprocess(PeakSpectrum & spec, float remove_peak_intensity_threshold = 2.01, UInt cut_peaks_below = 1000, Size min_peak_number = 5, Size max_peak_number = 150); ///spectrum is transformed into a binned spectrum with bin size 1 and spread 1 and the intensities are normalized. BinnedSpectrum transform(const PeakSpectrum & spec); /** @brief Calculates how much of the dot product is dominated by a few peaks @param[in] dot_product if -1 this value will be calculated as well. @param[in] bin1 first spectrum in binned representation @param[in] bin2 second spectrum in binned representation */ double dot_bias(const BinnedSpectrum & bin1, const BinnedSpectrum & bin2, double dot_product = -1) const; /** @brief calculates the normalized distance between top_hit and runner_up. @param[in] top_hit is the best score for a given match. @param[in] runner_up a match with a worse score than top_hit, e.g. the second best score. @return normalized distance @throw DividedByZero exception if top_hit is 0. @note Range of the dot products is between 0 and 1. */ double delta_D(double top_hit, double runner_up); /** @brief computes the overall all score @param[in] dot_product of a match @param[in] delta_D should be calculated after all dot products for a unidentified spectrum are computed @param[in] dot_bias @return the SpectraST similarity score */ double compute_F(double dot_product, double delta_D, double dot_bias); protected: }; }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/COMPARISON/PeakSpectrumCompareFunctor.h
.h
1,456
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/DATASTRUCTURES/DefaultParamHandler.h> #include <OpenMS/KERNEL/StandardTypes.h> namespace OpenMS { /** @brief Base class for compare functors of spectra, that return a similarity value for two spectra. PeakSpectrumCompareFunctor classes return a similarity value for a pair of PeakSpectrum objects. The value should be greater equal 0. @ingroup SpectraComparison */ class OPENMS_DLLAPI PeakSpectrumCompareFunctor : public DefaultParamHandler { public: /// default constructor PeakSpectrumCompareFunctor(); /// copy constructor PeakSpectrumCompareFunctor(const PeakSpectrumCompareFunctor & source); /// destructor ~PeakSpectrumCompareFunctor() override; /// assignment operator PeakSpectrumCompareFunctor & operator=(const PeakSpectrumCompareFunctor & source); /// function call operator, calculates the similarity virtual double operator()(const PeakSpectrum & a, const PeakSpectrum & b) const = 0; /// calculates self similarity virtual double operator()(const PeakSpectrum & a) const = 0; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/COMPARISON/ZhangSimilarityScore.h
.h
1,666
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/COMPARISON/PeakSpectrumCompareFunctor.h> namespace OpenMS { /** @brief Similarity score of Zhang The details of the score can be found in: Z. Zhang, Prediction of Low-Energy Collision-Induced Dissociation Spectra of Peptides, Anal. Chem., 76 (14), 3908 - 3922, 2004 @htmlinclude OpenMS_ZhangSimilarityScore.parameters @ingroup SpectraComparison */ class OPENMS_DLLAPI ZhangSimilarityScore : public PeakSpectrumCompareFunctor { public: // @name Constructors and Destructors // @{ /// default constructor ZhangSimilarityScore(); /// copy constructor ZhangSimilarityScore(const ZhangSimilarityScore & source); /// destructor ~ZhangSimilarityScore() override; // @} // @name Operators // @{ /// assignment operator ZhangSimilarityScore & operator=(const ZhangSimilarityScore & source); /// double operator()(const PeakSpectrum & spec1, const PeakSpectrum & spec2) const override; double operator()(const PeakSpectrum & spec) const override; // @} protected: /// returns the factor associated with the m/z tolerance and m/z difference of the peaks double getFactor_(double mz_tolerance, double mz_difference, bool is_gaussian = false) const; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/COMPARISON/BinnedSpectralContrastAngle.h
.h
2,034
66
// 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/COMPARISON/BinnedSpectrumCompareFunctor.h> namespace OpenMS { /** @brief Compare functor scoring the spectral contrast angle for similarity measurement The details of the score can be found in: K. Wan, I. Vidavsky, and M. Gross. Comparing similar spectra: from similarity index to spectral contrast angle. Journal of the American Society for Mass Spectrometry, 13(1):85-88, January 2002. @htmlinclude OpenMS_BinnedSpectralContrastAngle.parameters @see BinnedSpectrumCompareFunctor @see BinnedSpectrum @ingroup SpectraComparison */ class OPENMS_DLLAPI BinnedSpectralContrastAngle : public BinnedSpectrumCompareFunctor { public: /// default constructor BinnedSpectralContrastAngle(); /// copy constructor BinnedSpectralContrastAngle(const BinnedSpectralContrastAngle& source); /// destructor ~BinnedSpectralContrastAngle() override; /// assignment operator BinnedSpectralContrastAngle& operator=(const BinnedSpectralContrastAngle& source); /** function call operator, calculates the similarity of the given arguments @param[in] spec1 First spectrum given in a binned representation @param[in] spec2 Second spectrum given in a binned representation @throw IncompatibleBinning is thrown if the bins of the spectra are not the same */ double operator()(const BinnedSpectrum& spec1, const BinnedSpectrum& spec2) const override; /// function call operator, calculates self similarity double operator()(const BinnedSpectrum& spec) const override; protected: void updateMembers_() override; double precursor_mass_tolerance_; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/COMPARISON/BinnedSharedPeakCount.h
.h
2,020
68
// 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/COMPARISON/BinnedSpectrumCompareFunctor.h> #include <cfloat> #include <cmath> namespace OpenMS { /** @brief Compare functor scoring the shared peaks for similarity measurement The details of the score can be found in: K. Wan, I. Vidavsky, and M. Gross. Comparing similar spectra: from similarity index to spectral contrast angle. Journal of the American Society for Mass Spectrometry, 13(1):85{88, January 2002. @htmlinclude OpenMS_BinnedSharedPeakCount.parameters @see BinnedSpectrumCompareFunctor @see BinnedSpectrum @ingroup SpectraComparison */ class OPENMS_DLLAPI BinnedSharedPeakCount : public BinnedSpectrumCompareFunctor { public: /// default constructor BinnedSharedPeakCount(); /// copy constructor BinnedSharedPeakCount(const BinnedSharedPeakCount& source); /// destructor ~BinnedSharedPeakCount() override; /// assignment operator BinnedSharedPeakCount& operator=(const BinnedSharedPeakCount& source); /** function call operator, calculates the similarity of the given arguments @param[in] spec1 First spectrum given as a binned representation @param[in] spec2 Second spectrum given as a binned representation @throw IncompatibleBinning is thrown if the binning of the two input spectra are not the same */ double operator()(const BinnedSpectrum& spec1, const BinnedSpectrum& spec2) const override; /// function call operator, calculates self similarity double operator()(const BinnedSpectrum& spec) const override; protected: void updateMembers_() override; double precursor_mass_tolerance_; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/COMPARISON/SpectrumCheapDPCorr.h
.h
2,674
99
// 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/COMPARISON/PeakSpectrumCompareFunctor.h> #include <OpenMS/KERNEL/MSSpectrum.h> #include <OpenMS/KERNEL/MSExperiment.h> #include <map> namespace OpenMS { /** @brief SpectrumCheapDPCorr calculates an optimal alignment on stick spectra to save computing time only Peak Pairs that could get a score > 0 are considered which Peak Pairs could get scores > 0 ? <br> Peaks get a score depending on the difference in position and the heights of the peaks <br> pairs with positions that differ more than some limit get score 0 @htmlinclude OpenMS_SpectrumCheapDPCorr.parameters @ingroup SpectraComparison */ class OPENMS_DLLAPI SpectrumCheapDPCorr : public PeakSpectrumCompareFunctor { public: // @name Constructors and Destructors // @{ /// default constructor SpectrumCheapDPCorr(); /// copy constructor SpectrumCheapDPCorr(const SpectrumCheapDPCorr & source); /// destructor ~SpectrumCheapDPCorr() override; // @} // @name Operators // @{ /// assignment operator SpectrumCheapDPCorr & operator=(const SpectrumCheapDPCorr & source); double operator()(const PeakSpectrum & a, const PeakSpectrum & b) const override; double operator()(const PeakSpectrum & a) const override; // @} // @name Accessors // @{ /// return consensus spectrum from last function call operator const PeakSpectrum & lastconsensus() const; /// std::map<UInt, UInt> getPeakMap() const; /// set weighting of the second spectrum for consensus from next function call operator void setFactor(double f); // @} private: /// O(n^2) dynamical programming double dynprog_(const PeakSpectrum &, const PeakSpectrum &, int, int, int, int) const; /// similarity of two peaks double comparepeaks_(double posa, double posb, double inta, double intb) const; static const String info_; /// consensus spectrum of the last comparison mutable PeakSpectrum lastconsensus_; /// should peaks with no alignment partner be kept in the consensus? bool keeppeaks_; /// weighting factor for the next consensus spectrum mutable double factor_; /// last peak map mutable std::map<UInt, UInt> peak_map_; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/COMPARISON/SpectrumAlignment.h
.h
8,846
292
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Andreas Bertsch $ // -------------------------------------------------------------------------- // #pragma once #include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h> #include <OpenMS/DATASTRUCTURES/MatchedIterator.h> #include <vector> #include <map> #include <utility> #include <algorithm> #define ALIGNMENT_DEBUG #undef ALIGNMENT_DEBUG namespace OpenMS { /** @brief Aligns the peaks of two sorted spectra Method 1: Using a banded (width via 'tolerance' parameter) alignment if absolute tolerances are given. Scoring function is the m/z distance between peaks. Intensity does not play a role! Method 2: If relative tolerance (ppm) is specified a simple matching of peaks is performed: Peaks from s1 (usually the theoretical spectrum) are assigned to the closest peak in s2 if it lies in the tolerance window @note: a peak in s2 can be matched to none, one or multiple peaks in s1. Peaks in s1 may be matched to none or one peak in s2. @note: intensity is ignored TODO: improve time complexity, currently O(|s1|*log(|s2|)) @htmlinclude OpenMS_SpectrumAlignment.parameters @ingroup SpectraComparison */ class OPENMS_DLLAPI SpectrumAlignment : public DefaultParamHandler { public: // @name Constructors and Destructors // @{ /// default constructor SpectrumAlignment(); /// copy constructor SpectrumAlignment(const SpectrumAlignment & source); /// destructor ~SpectrumAlignment() override; /// assignment operator SpectrumAlignment & operator=(const SpectrumAlignment & source); // @} template <typename SpectrumType1, typename SpectrumType2> void getSpectrumAlignment(std::vector<std::pair<Size, Size> >& alignment, const SpectrumType1& s1, const SpectrumType2& s2) const { if (!s1.isSorted() || !s2.isSorted()) { throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Input to SpectrumAlignment is not sorted!"); } // clear result alignment.clear(); double tolerance = (double)param_.getValue("tolerance"); if (!param_.getValue("is_relative_tolerance").toBool() ) { std::map<Size, std::map<Size, std::pair<Size, Size> > > traceback; std::map<Size, std::map<Size, double> > matrix; // init the matrix with "gap costs" tolerance matrix[0][0] = 0; for (Size i = 1; i <= s1.size(); ++i) { matrix[i][0] = i * tolerance; traceback[i][0] = std::make_pair(i - 1, 0); } for (Size j = 1; j <= s2.size(); ++j) { matrix[0][j] = j * tolerance; traceback[0][j] = std::make_pair(0, j - 1); } // fill in the matrix Size left_ptr(1); Size last_i(0), last_j(0); //Size off_band_counter(0); for (Size i = 1; i <= s1.size(); ++i) { double pos1(s1[i - 1].getMZ()); for (Size j = left_ptr; j <= s2.size(); ++j) { bool off_band(false); // find min of the three possible directions double pos2(s2[j - 1].getMZ()); double diff_align = fabs(pos1 - pos2); // running off the right border of the band? if (pos2 > pos1 && diff_align > tolerance) { if (i < s1.size() && j < s2.size() && s1[i].getMZ() < pos2) { off_band = true; } } // can we tighten the left border of the band? if (pos1 > pos2 && diff_align > tolerance && j > left_ptr + 1) { ++left_ptr; } double score_align = diff_align; if (matrix.find(i - 1) != matrix.end() && matrix[i - 1].find(j - 1) != matrix[i - 1].end()) { score_align += matrix[i - 1][j - 1]; } else { score_align += (i - 1 + j - 1) * tolerance; } double score_up = tolerance; if (matrix.find(i) != matrix.end() && matrix[i].find(j - 1) != matrix[i].end()) { score_up += matrix[i][j - 1]; } else { score_up += (i + j - 1) * tolerance; } double score_left = tolerance; if (matrix.find(i - 1) != matrix.end() && matrix[i - 1].find(j) != matrix[i - 1].end()) { score_left += matrix[i - 1][j]; } else { score_left += (i - 1 + j) * tolerance; } #ifdef ALIGNMENT_DEBUG cerr << i << " " << j << " " << left_ptr << " " << pos1 << " " << pos2 << " " << score_align << " " << score_left << " " << score_up << endl; #endif if (score_align <= score_up && score_align <= score_left && diff_align <= tolerance) { matrix[i][j] = score_align; traceback[i][j] = std::make_pair(i - 1, j - 1); last_i = i; last_j = j; } else { if (score_up <= score_left) { matrix[i][j] = score_up; traceback[i][j] = std::make_pair(i, j - 1); } else { matrix[i][j] = score_left; traceback[i][j] = std::make_pair(i - 1, j); } } if (off_band) { break; } } } //last_i = s1.size() + 1; //last_j = s2.size() + 1; //cerr << last_i << " " << last_j << endl; #ifdef ALIGNMENT_DEBUG #if 0 cerr << "TheMatrix: " << endl << " \t \t"; for (Size j = 0; j != s2.size(); ++j) { cerr << s2[j].getPosition()[0] << " \t"; } cerr << endl; for (Size i = 0; i <= s1.size(); ++i) { if (i != 0) { cerr << s1[i - 1].getPosition()[0] << " \t"; } else { cerr << " \t"; } for (Size j = 0; j <= s2.size(); ++j) { if (matrix.has(i) && matrix[i].has(j)) { if (traceback[i][j].first == i - 1 && traceback[i][j].second == j - 1) { cerr << "\\"; } else { if (traceback[i][j].first == i - 1 && traceback[i][j].second == j) { cerr << "|"; } else { cerr << "-"; } } cerr << matrix[i][j] << " \t"; } else { cerr << "-1 \t"; } } cerr << endl; } #endif #endif // do traceback Size i = last_i; Size j = last_j; while (i >= 1 && j >= 1) { if (traceback[i][j].first == i - 1 && traceback[i][j].second == j - 1) { alignment.push_back(std::make_pair(i - 1, j - 1)); } Size new_i = traceback[i][j].first; Size new_j = traceback[i][j].second; i = new_i; j = new_j; } std::reverse(alignment.begin(), alignment.end()); #ifdef ALIGNMENT_DEBUG #if 0 // print alignment cerr << "Alignment (size=" << alignment.size() << "): " << endl; Size i_s1(0), i_s2(0); for (vector<pair<Size, Size> >::const_reverse_iterator it = alignment.rbegin(); it != alignment.rend(); ++it, ++i_s1, ++i_s2) { while (i_s1 < it->first - 1) { cerr << i_s1 << " " << s1[i_s1].getPosition()[0] << " " << s1[i_s1].getIntensity() << endl; i_s1++; } while (i_s2 < it->second - 1) { cerr << " \t " << i_s2 << " " << s2[i_s2].getPosition()[0] << " " << s2[i_s2].getIntensity() << endl; i_s2++; } cerr << "(" << s1[it->first - 1].getPosition()[0] << " <-> " << s2[it->second - 1].getPosition()[0] << ") (" << it->first << "|" << it->second << ") (" << s1[it->first - 1].getIntensity() << "|" << s2[it->second - 1].getIntensity() << ")" << endl; } #endif #endif } else // relative alignment (ppm tolerance) { // find closest match of s1[i] in s2 for all i MatchedIterator<SpectrumType1, PpmTrait> it(s1, s2, tolerance); for (; it != it.end(); ++it) alignment.emplace_back(it.refIdx(), it.tgtIdx()); } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/COMPARISON/BinnedSpectrumCompareFunctor.h
.h
1,808
59
// 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/DefaultParamHandler.h> #include <OpenMS/CONCEPT/Exception.h> #include <OpenMS/KERNEL/BinnedSpectrum.h> #include <cmath> namespace OpenMS { /** @brief Base class for compare functors of BinnedSpectra BinnedSpectrumCompareFunctor classes return a value for a pair of BinnedSpectrum objects (or a single one with itself). Ideally the value should reflect the similarity of the pair. For methods of computing the similarity see the documentation of the concrete functors. Functors normalized in the range [0,1] are identifiable at the set "normalized" parameter of the ParameterHandler @ingroup SpectraComparison */ class OPENMS_DLLAPI BinnedSpectrumCompareFunctor : public DefaultParamHandler { private: public: /// default constructor BinnedSpectrumCompareFunctor(); /// copy constructor BinnedSpectrumCompareFunctor(const BinnedSpectrumCompareFunctor& source); /// destructor ~BinnedSpectrumCompareFunctor() override; /// assignment operator BinnedSpectrumCompareFunctor& operator=(const BinnedSpectrumCompareFunctor& source); /// function call operator, calculates the similarity of the given arguments virtual double operator()(const BinnedSpectrum& spec1, const BinnedSpectrum& spec2) const = 0; /// function call operator, calculates self similarity virtual double operator()(const BinnedSpectrum& spec) const = 0; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/COMPARISON/SpectrumPrecursorComparator.h
.h
1,349
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/COMPARISON/PeakSpectrumCompareFunctor.h> namespace OpenMS { /** @brief SpectrumPrecursorComparator compares just the parent mass of two spectra @htmlinclude OpenMS_SpectrumPrecursorComparator.parameters @ingroup SpectraComparison */ class OPENMS_DLLAPI SpectrumPrecursorComparator : public PeakSpectrumCompareFunctor { public: // @name Constructors and Destructors // @{ /// default constructor SpectrumPrecursorComparator(); /// copy constructor SpectrumPrecursorComparator(const SpectrumPrecursorComparator & source); /// destructor ~SpectrumPrecursorComparator() override; // @} // @name Operators // @{ /// assignment operator SpectrumPrecursorComparator & operator=(const SpectrumPrecursorComparator & source); double operator()(const PeakSpectrum & a, const PeakSpectrum & b) const override; double operator()(const PeakSpectrum & a) const override; // @} }; }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/MATH/MathFunctions.h
.h
16,975
587
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg$ // $Authors: Marc Sturm $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/CONCEPT/Exception.h> #include <OpenMS/CONCEPT/Macros.h> #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/KERNEL/RangeManager.h> #include <boost/random/mersenne_twister.hpp> // for mt19937_64 #include <boost/random/uniform_int.hpp> #include <cmath> #include <boost/math/special_functions/binomial.hpp> #include <boost/math/special_functions/gamma.hpp> #include <boost/math/special_functions/log1p.hpp> #include <boost/math/distributions/binomial.hpp> #include <boost/math/distributions/complement.hpp> #include <limits> #include <utility> // for std::pair #include <vector> namespace OpenMS { /** @brief %Math namespace. Contains mathematical auxiliary functions. @ingroup Concept */ namespace Math { /** @brief Given an interval/range and a new value, extend the range to include the new value if needed @param[in,out] min The current minimum of the range @param[in,out] max The current maximum of the range @param[in] value The new value which may extend the range @return true if the range was modified */ template<typename T> bool extendRange(T& min, T& max, const T& value) { if (value < min) { min = value; return true; } if (value > max) { max = value; return true; } return false; } /** * \brief Is a @p value contained in [min, max] ? * \tparam T Type, e.g. double * \return True if contained, false otherwise */ template<typename T> bool contains(T value, T min, T max) { return min <= value && value <= max; } /** * \brief Zoom into an interval [left, right], decreasing its width by @p factor (which must be in [0,inf]). * * To actually zoom in, the @p factor needs to be within [0,1]. Chosing a factor > 1 actually zooms out. * @p align (between [0,1]) determines where the zoom happens: * i.e. align = 0 leaves @p left the same and reduces @p right (or extends if factor>1) * whereas align = 0.5 zooms into the center of the range etc * * You can do round trips, i.e. undo a zoom in, by inverting the factor: * \code * [a2, b2] = zoomIn(a1, b1, 0.5, al); // zoom in * [a1, b1] === zoomIn(a2, b2, 2, al); // zoom out again (inverting) * \endcode * * \param left Start of interval * \param right End of interval * \param factor Number between [0,1] to shrink, or >1 to extend the span (=right-left) * \param align Where to position the smaller/shrunk interval (0 = left, 1 = right, 0.5=center etc) * \return [new_left, new_right] as pair */ inline std::pair<double, double> zoomIn(const double left, const double right, const float factor, const float align) { OPENMS_PRECONDITION(factor >= 0, "Factor must be >=0") OPENMS_PRECONDITION(align >= 0, "align must be >=0") OPENMS_PRECONDITION(align <= 1, "align must be <=1") std::pair<double, double> res; auto old_width = right - left; auto offset_left = (1.0f - factor) * old_width * align; res.first = left + offset_left; res.second = res.first + old_width * factor; return res; } using BinContainer = std::vector<RangeBase>; /** @brief Split a range [min,max] into @p number_of_bins (with optional overlap) and return the ranges of each bin. Optionally, bins can be made overlapping, by extending each bins' left and right margin by @p extend_margin. The overlap between neighboring bins will thus be `2 x extend_margin`. The borders of the original interval will @em not be extended. @param[in] min The minimum of the range; must be smaller than @p max @param[in] max The maximum of the range @param[in] number_of_bins How many bins should the range be divided into? Must be 1 or larger @param[in] extend_margin Overlap of neighboring bins (=0 for no overlap). Negative values will shrink the range (feature). @return Vector with @p number_of_bins elements, each representing the margins of one bin @throws OpenMS::Precondition if `min >= max` or `number_of_bins == 0` */ inline BinContainer createBins(double min, double max, uint32_t number_of_bins, double extend_margin = 0) { OPENMS_PRECONDITION(number_of_bins >= 1, "Number of bins must be >= 1") OPENMS_PRECONDITION(min < max, "Require min < max"); std::vector<RangeBase> res(number_of_bins); const double bin_width = (max - min) / number_of_bins; for (uint32_t i = 0; i < number_of_bins; ++i) { res[i] = RangeBase(min + i * bin_width, min + (i + 1) * bin_width); res[i].extendLeftRight(extend_margin); } res.front().setMin(min); // undo potential margin res.back().setMax(max); // undo potential margin return res; } /** @brief rounds @p x up to the next decimal power 10 ^ @p decPow @verbatim e.g.: (123.0 , 1) => 130 (123.0 , 2) => 200 (0.123 ,-2) => 0.13 ( 10^-2 = 0.01 ) @endverbatim @ingroup MathFunctionsMisc */ inline double ceilDecimal(double x, int decPow) { return (ceil(x / pow(10.0, decPow))) * pow(10.0, decPow); // decimal shift right, ceiling, decimal shift left } /** @brief rounds @p x to the next decimal power 10 ^ @p decPow @verbatim e.g.: (123.0 , 1) => 120 (123.0 , 2) => 100 @endverbatim @ingroup MathFunctionsMisc */ inline double roundDecimal(double x, int decPow) { if (x > 0) return (floor(0.5 + x / pow(10.0, decPow))) * pow(10.0, decPow); return -((floor(0.5 + fabs(x) / pow(10.0, decPow))) * pow(10.0, decPow)); } /** @brief transforms point @p x of interval [left1,right1] into interval [left2,right2] @ingroup MathFunctionsMisc */ inline double intervalTransformation(double x, double left1, double right1, double left2, double right2) { return left2 + (x - left1) * (right2 - left2) / (right1 - left1); } /** @brief Transforms a number from linear to log10 scale. Avoids negative logarithms by adding 1. @param[in] x The number to transform @ingroup MathFunctionsMisc */ inline double linear2log(double x) { return log10(x + 1); //+1 to avoid negative logarithms } /** @brief Transforms a number from log10 to to linear scale. Subtracts the 1 added by linear2log(double) @param[in] x The number to transform @ingroup MathFunctionsMisc */ inline double log2linear(double x) { return pow(10, x) - 1; } /** @brief Returns true if the given integer is odd @ingroup MathFunctionsMisc */ inline bool isOdd(UInt x) { return (x & 1) != 0; } /** @brief Rounds the value @ingroup MathFunctionsMisc */ template<typename T> T round(T x) { return std::round(x); } /** * Rounds to the i'th digit after the decimal point, also works for negative digits. e.g. \code round_to(3.14159265, 2) // 3.14 round_to(1234.9 , -2) // 1200 \endcode @param[in] value The value to round @param[in] digits The number of digits to round to (can be negative) @return The rounded value */ template<typename T> T roundTo(const T value, int digits) { T factor = 1.0; if (digits > 0) { for (int i = 0; i < digits; ++i) factor *= 10.0; } else if (digits < 0) { for (int i = 0; i < -digits; ++i) factor /= 10.0; } return std::round(value * factor) / factor; } /** Computes the percentage of @p value in relation to @p total, rounded to @p digits. @note If @p total is zero, the function returns 0.0 to avoid division by zero. @param[in] value The value to compute the percentage for @param[in] total The total value to compute the percentage against @param[in] digits The number of digits to round the result to @return The percentage of @p value in relation to @p total, rounded to @p digits @throw OpenMS::Exception::InvalidValue if @p value or @p total is negative. \code auto one_third = 1.0/3; percentOf(one_third, 1.0, 2) // returns 33.33 \endcode */ template<typename T> double percentOf(T value, T total, int digits) { if (value < 0) { throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Value must be non-negative", String(value)); } if (total < 0) { throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Total must be non-negative", String(total)); } if (total <= 0) // avoid float equality compare { return 0.0; // avoid division by zero } return roundTo(value * 100.0 / total, digits); } /** @brief Returns if @p a is approximately equal @p b , allowing a tolerance of @p tol @ingroup MathFunctionsMisc */ inline bool approximatelyEqual(double a, double b, double tol) { return std::fabs(a - b) <= tol; } /** @brief Returns the greatest common divisor (gcd) of two numbers by applying the Euclidean algorithm. @param[in] a A number. @param[in] b A number. @return The greatest common divisor. @see gcd(T a, T b, T& a1, T& b1) @ingroup MathFunctionsMisc */ template<typename T> T gcd(T a, T b) { T c; while (b != 0) { c = a % b; a = b; b = c; } return a; } /** @brief Returns the greatest common divisor by applying the extended Euclidean algorithm (Knuth TAoCP vol. 2, p342). Calculates u1, u2 and u3 (which is returned) so that a * u1 + b * u2 = u3 = gcd(a, b, u1, u2) @param[in] a A number. @param[in] b A number. @param[out] u1 A reference to the number to be returned (see the above formula). @param[out] u2 A reference to the number to be returned (see the above formula). @return The greatest common divisor. @see gcd(T, T) @ingroup MathFunctionsMisc */ template<typename T> T gcd(T a, T b, T& u1, T& u2) { u1 = 1; u2 = 0; T u3 = a; T v1 = 0; T v2 = 1; T v3 = b; while (v3 != 0) { T q = u3 / v3; T t1 = u1 - v1 * q; T t2 = u2 - v2 * q; T t3 = u3 - v3 * q; u1 = v1; u2 = v2; u3 = v3; v1 = t1; v2 = t2; v3 = t3; } return u3; } /** @brief Compute parts-per-million of two @em m/z values. The returned ppm value can be either positive (mz_obs > mz_ref) or negative (mz_obs < mz_ref)! @param[in] mz_obs Observed (experimental) m/z @param[in] mz_ref Reference (theoretical) m/z @return The ppm value */ template<typename T> T getPPM(T mz_obs, T mz_ref) { return (mz_obs - mz_ref) / mz_ref * 1e6; } /** @brief Compute absolute parts-per-million of two @em m/z values. The returned ppm value is always >= 0. @param[in] mz_obs Observed (experimental) m/z @param[in] mz_ref Reference (theoretical) m/z @return The absolute ppm value */ template<typename T> T getPPMAbs(T mz_obs, T mz_ref) { return std::fabs(getPPM(mz_obs, mz_ref)); } /** @brief Compute the mass diff in [Th], given a ppm value and a reference point. The returned mass diff can be either positive (ppm > 0) or negative (ppm < 0)! @param[in] ppm Parts-per-million error @param[in] mz_ref Reference m/z @return The mass diff in [Th] */ template<typename T> T ppmToMass(T ppm, T mz_ref) { return (ppm / T(1e6)) * mz_ref; } /* @brief Compute the absolute mass diff in [Th], given a ppm value and a reference point. The returned mass diff is always positive! @param[in] ppm Parts-per-million error @param[in] mz_ref Reference m/z @return The absolute mass diff in [Th] */ template<typename T> T ppmToMassAbs(T ppm, T mz_ref) { return std::fabs(ppmToMass(ppm, mz_ref)); } /** @brief Return tolerance window around @p val given tolerance @p tol Note that when ppm is used, the window is not symmetric. In this case, (right - @p val) > (@p val - left), i.e., the tolerance window also includes the largest value x which still has @p val in *its* tolerance window for the given ppms, so the compatibility relation is symmetric. @param[in] val Value @param[in] tol Tolerance @param[in] ppm Whether @p tol is in ppm or absolute @return Tolerance window boundaries */ inline std::pair<double, double> getTolWindow(double val, double tol, bool ppm) { double left, right; if (ppm) { left = val - val * tol * 1e-6; right = val / (1.0 - tol * 1e-6); } else { left = val - tol; right = val + tol; } return std::make_pair(left, right); } /** @brief Returns the value of the @p q th quantile (0-1) in a sorted non-empty vector @p x */ template<typename T1> typename T1::value_type quantile(const T1& x, double q) { if (x.empty()) throw Exception::InvalidParameter(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Quantile requested from empty container."); if (q < 0.0) q = 0.; if (q > 1.0) q = 1.; const auto n = x.size(); const auto id = std::max(0., n * q - 1); // -1 for c++ index starting at 0 const auto lo = floor(id); const auto hi = ceil(id); const auto qs = x[lo]; const auto h = (id - lo); return (1.0 - h) * qs + h * x[hi]; } // portable random shuffle class OPENMS_DLLAPI RandomShuffler { public: explicit RandomShuffler(int seed): rng_(boost::mt19937_64(seed)) { } explicit RandomShuffler(const boost::mt19937_64& mt_rng): rng_(mt_rng) { } RandomShuffler() = default; ~RandomShuffler() = default; boost::mt19937_64 rng_; template<class RandomAccessIterator> void portable_random_shuffle(RandomAccessIterator first, RandomAccessIterator last) { for (auto i = (last - first) - 1; i > 0; --i) // OMS_CODING_TEST_EXCLUDE { boost::uniform_int<decltype(i)> d(0, i); std::swap(first[i], first[d(rng_)]); } } void seed(uint64_t val) { rng_.seed(val); } }; /** * @brief Calculate logarithm of binomial coefficient C(n,k) using log-gamma function * * @param[in] n Total number of items * @param[in] k Number of items to choose * @return Natural logarithm of binomial coefficient C(n,k) * @throws std::invalid_argument if k > n */ inline double log_binomial_coef(unsigned n, unsigned k) { // Handle edge cases for improved numerical stability if (k > n) { throw std::invalid_argument("k cannot be greater than n in binomial coefficient"); } if (k == 0 || k == n) { return 0.0; // log(1) = 0 } // Use symmetry to minimize computation for large k if (k > n / 2) { k = n - k; } return boost::math::lgamma(n + 1.0) - boost::math::lgamma(k + 1.0) - boost::math::lgamma(n - k + 1.0); } /** * @brief Log-sum-exp operation for numerical stability * * @param[in] x First logarithmic value * @param[in] y Second logarithmic value * @return Natural logarithm of (exp(x) + exp(y)) */ inline double log_sum_exp(double x, double y) { // Handle infinite cases if (std::isinf(x) && x < 0) return y; if (std::isinf(y) && y < 0) return x; // Use the maximum value for numerical stability double max_val = std::max(x, y); return max_val + std::log(std::exp(x - max_val) + std::exp(y - max_val)); } /** * @brief Calculate binomial cumulative distribution function P(X ≥ n) * * Calculates P(X ≥ n) for a binomial distribution with parameters N and p, * using numerically stable algorithms in the log domain to handle large values. * * @param[in] N Total number of trials * @param[in] n Minimum number of successes * @param[in] p Probability of success in each trial * @return Probability P(X ≥ n) for binomial distribution B(N,p) * @throws std::invalid_argument if parameters are invalid */ inline double binomial_cdf_complement(unsigned N, unsigned n, double p) { if (p < 0.0 || p > 1.0) { throw std::invalid_argument("Probability p must be between 0 and 1"); } if (n > N) { throw std::invalid_argument("n cannot be greater than N"); } if (n == 0) return 1.0; // P(X ≥ 0) = 1 if (p == 0.0) return (n == 0) ? 1.0 : 0.0; if (p == 1.0) return 1.0; // all mass at N const boost::math::binomial_distribution<double> dist(N, p); return boost::math::cdf(boost::math::complement(dist, n - 1)); } } // namespace Math } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/MATH/StatisticFunctions.h
.h
32,887
960
// 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, Johannes Junker, Mathias Walzer, Chris Bielow $ // -------------------------------------------------------------------------- #pragma once #include <vector> #include <OpenMS/CONCEPT/Exception.h> #include <OpenMS/CONCEPT/Macros.h> #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/DATASTRUCTURES/String.h> #include <algorithm> #include <cmath> #include <iterator> #include <numeric> namespace OpenMS { namespace Math { /** @brief Result of adaptiveQuantile computation. Fields: - blended : the final blended (adaptive) quantile - half_raw : raw q-quantile of values - half_rob : q-quantile after IQR-winsorization - upper_fence : Tukey upper fence (Q3 + k*IQR), +inf if undefined - tail_fraction : fraction of values above upper_fence - weight : blend weight w in [0,1] (0=robust, 1=raw) */ struct AdaptiveQuantileResult { double blended{0.0}; double half_raw{0.0}; double half_rob{0.0}; double upper_fence{std::numeric_limits<double>::infinity()}; double tail_fraction{0.0}; double weight{0.0}; }; /** @brief Helper function checking if two iterators are not equal @exception Exception::InvalidRange is thrown if the range is NULL @ingroup MathFunctionsStatistics */ template <typename IteratorType> static void checkIteratorsNotNULL(IteratorType begin, IteratorType end) { if (begin == end) { throw Exception::InvalidRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION); } } /** @brief Helper function checking if two iterators are equal @exception Exception::InvalidRange is thrown if the iterators are not equal @ingroup MathFunctionsStatistics */ template <typename IteratorType> static void checkIteratorsEqual(IteratorType begin, IteratorType end) { if (begin != end) { throw Exception::InvalidRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION); } } /** @brief Helper function checking if an iterator and a co-iterator both have a next element @exception Exception::InvalidRange is thrown if the iterator do not end simultaneously @ingroup MathFunctionsStatistics */ template <typename IteratorType1, typename IteratorType2> static void checkIteratorsAreValid( IteratorType1 begin_b, IteratorType1 end_b, IteratorType2 begin_a, IteratorType2 end_a) { if ((begin_b == end_b) ^ (begin_a == end_a)) { throw Exception::InvalidRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION); } } /** @brief Calculates the sum of a range of values @ingroup MathFunctionsStatistics */ template <typename IteratorType> static double sum(IteratorType begin, IteratorType end) { return std::accumulate(begin, end, 0.0); } /** @brief Calculates the mean of a range of values @exception Exception::InvalidRange is thrown if the range is NULL @ingroup MathFunctionsStatistics */ template <typename IteratorType> static double mean(IteratorType begin, IteratorType end) { checkIteratorsNotNULL(begin, end); return sum(begin, end) / std::distance(begin, end); } /** @brief Calculates the median of a range of values @param[in] begin Start of range @param[in] end End of range (past-the-end iterator) @param[in] sorted Is the range already sorted? If not, it will be sorted. @return Median (as floating point, since we need to support average of middle values) @exception Exception::InvalidRange is thrown if the range is NULL @ingroup MathFunctionsStatistics */ template <typename IteratorType> static double median(IteratorType begin, IteratorType end, bool sorted = false) { checkIteratorsNotNULL(begin, end); if (!sorted) { std::sort(begin, end); } Size size = std::distance(begin, end); if (size % 2 == 0) // even size => average two middle values { IteratorType it1 = begin; std::advance(it1, size / 2 - 1); IteratorType it2 = it1; std::advance(it2, 1); return (*it1 + *it2) / 2.0; } else { IteratorType it = begin; std::advance(it, (size - 1) / 2); return *it; } } /** @brief median absolute deviation (MAD) Computes the MAD, defined as MAD = median( | x_i - median(x) | ) for a vector x with indices i in [1,n]. Sortedness of the input is not required (nor does it provide a speedup). For efficiency, you must provide the median separately, in order to avoid potentially duplicate efforts (usually one computes the median anyway externally). @param[in] begin Start of range @param[in] end End of range (past-the-end iterator) @param[in] median_of_numbers The precomputed median of range @p begin - @p end. @return the MAD @ingroup MathFunctionsStatistics */ template <typename IteratorType> double MAD(IteratorType begin, IteratorType end, double median_of_numbers) { std::vector<double> diffs; diffs.reserve(std::distance(begin, end)); for (IteratorType it = begin; it != end; ++it) { diffs.push_back(fabs(*it - median_of_numbers)); } return median(diffs.begin(), diffs.end(), false); } /** @brief mean absolute deviation (MeanAbsoluteDeviation) Computes the MeanAbsoluteDeviation, defined as MeanAbsoluteDeviation = mean( | x_i - mean(x) | ) for a vector x with indices i in [1,n]. For efficiency, you must provide the mean separately, in order to avoid potentially duplicate efforts (usually one computes the mean anyway externally). @param[in] begin Start of range @param[in] end End of range (past-the-end iterator) @param[in] mean_of_numbers The precomputed mean of range @p begin - @p end. @return the MeanAbsoluteDeviation @ingroup MathFunctionsStatistics */ template <typename IteratorType> double MeanAbsoluteDeviation(IteratorType begin, IteratorType end, double mean_of_numbers) { double mean_value {0}; for (IteratorType it = begin; it != end; ++it) { mean_value += fabs(*it - mean_of_numbers); } return mean_value / std::distance(begin, end); } /** @brief Calculates the first quantile of a range of values The range is divided into half and the median for the first half is returned. @param[in] begin Start of range @param[in] end End of range (past-the-end iterator) @param[in] sorted Is the range already sorted? If not, it will be sorted. @exception Exception::InvalidRange is thrown if the range is NULL @ingroup MathFunctionsStatistics */ template <typename IteratorType> static double quantile1st(IteratorType begin, IteratorType end, bool sorted = false) { checkIteratorsNotNULL(begin, end); if (!sorted) { std::sort(begin, end); } Size size = std::distance(begin, end); if (size % 2 == 0) { return median(begin, begin + (size/2)-1, true); //-1 to exclude median values } return median(begin, begin + (size/2), true); } /** @brief Calculates the third quantile of a range of values The range is divided into half and the median for the second half is returned. @param[in] begin Start of range @param[in] end End of range (past-the-end iterator) @param[in] sorted Is the range already sorted? If not, it will be sorted. @exception Exception::InvalidRange is thrown if the range is NULL @ingroup MathFunctionsStatistics */ template <typename IteratorType> static double quantile3rd( IteratorType begin, IteratorType end, bool sorted = false) { checkIteratorsNotNULL(begin, end); if (!sorted) { std::sort(begin, end); } Size size = std::distance(begin, end); return median(begin + (size/2)+1, end, true); //+1 to exclude median values } /** @brief Calculates the q-quantile (0 <= q <= 1) of a *sorted* range of values. Assumes the range [begin, end) is already sorted in non-decreasing order. Uses the common "Type 7" definition (linear interpolation): pos = q * (n - 1) idx = floor(pos), frac = pos - idx quantile = (1 - frac) * x[idx] + frac * x[idx + 1] Exact endpoints: - q == 0 returns the first (minimum) element - q == 1 returns the last (maximum) element @param[in] begin Start of range @param[in] end End of range (past-the-end iterator) @param[in] q Quantile in [0, 1] @pre Input range must be sorted ascending. @exception Exception::InvalidRange is thrown if the range is NULL or empty. @exception Exception::InvalidValue is thrown if q is outside [0, 1]. @ingroup MathFunctionsStatistics */ template <typename IteratorType> static double quantile(IteratorType begin, IteratorType end, double q) { OPENMS_PRECONDITION(std::is_sorted(begin, end), "Math::quantile expects a sorted range. Sort before calling."); checkIteratorsNotNULL(begin, end); const Size n = std::distance(begin, end); if (n == 0) { throw Exception::InvalidRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION); } if (q < 0.0 || q > 1.0) { throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "q must be in [0,1]", String(q)); } if (n == 1) return static_cast<double>(*begin); const double pos = q * static_cast<double>(n - 1); const Size i = static_cast<Size>(std::floor(pos)); const double frac = pos - static_cast<double>(i); const auto it_i = begin + static_cast<typename std::iterator_traits<IteratorType>::difference_type>(i); if (frac == 0.0) return static_cast<double>(*it_i); const auto it_ip1 = it_i + 1; return (1.0 - frac) * static_cast<double>(*it_i) + frac * static_cast<double>(*it_ip1); } /** @brief Tukey upper fence (UF) for outlier detection. Computes Q3 + k * IQR on the (finite) values in [begin,end). If there are too few values or IQR ≤ 0, returns +infinity. References: J. W. Tukey (1977). Exploratory Data Analysis. @tparam IteratorType input iterator over arithmetic values @param[in] begin start iterator @param[in] end past-the-end iterator @param[in] k Tukey factor (default 1.5) @return upper fence (Q3 + k*IQR) or +infinity if undefined */ template <typename IteratorType> double tukeyUpperFence(IteratorType begin, IteratorType end, double k = 1.5) { std::vector<double> v; v.reserve(std::distance(begin, end)); for (auto it = begin; it != end; ++it) { if (std::isfinite(*it)) v.push_back(static_cast<double>(*it)); } if (v.size() < 4) return std::numeric_limits<double>::infinity(); std::sort(v.begin(), v.end()); const double q1 = quantile(v.begin(), v.end(), 0.25); const double q3 = quantile(v.begin(), v.end(), 0.75); const double iqr = q3 - q1; if (!(iqr > 0.0)) return std::numeric_limits<double>::infinity(); return q3 + k * iqr; } /** @brief Fraction of values above a threshold. @tparam IteratorType input iterator over arithmetic values @param[in] begin start iterator @param[in] end past-the-end iterator @param[in] threshold threshold T @return (# { x > T } / N), ignoring non-finite x */ template <typename IteratorType> double tailFractionAbove(IteratorType begin, IteratorType end, double threshold) { size_t n = 0, n_tail = 0; for (auto it = begin; it != end; ++it) { const double x = static_cast<double>(*it); if (!std::isfinite(x)) continue; ++n; if (x > threshold) ++n_tail; } return (n == 0) ? 0.0 : static_cast<double>(n_tail) / static_cast<double>(n); } /** @brief Quantile after winsorizing at an upper fence. Copies the (finite) values in [begin,end), caps them at @p upper_fence (and at 0 on the lower side, which is convenient for absolute residuals), then returns the requested quantile. If @p upper_fence is not finite, this falls back to the raw quantile. References: J. W. Tukey (1962). The Future of Data Analysis. @tparam IteratorType input iterator over arithmetic values @param[in] begin start iterator @param[in] end past-the-end iterator @param[in] q quantile in [0,1] @param[in] upper_fence winsorization cap (Q3+k*IQR), or +inf to disable @return winsorized quantile */ template <typename IteratorType> double winsorizedQuantile(IteratorType begin, IteratorType end, double q, double upper_fence) { std::vector<double> v; v.reserve(std::distance(begin, end)); for (auto it = begin; it != end; ++it) { const double x = static_cast<double>(*it); if (!std::isfinite(x)) continue; v.push_back(x); } if (v.empty()) return 0.0; if (std::isfinite(upper_fence)) { for (double& x : v) { if (x > upper_fence) x = upper_fence; if (x < 0.0) x = 0.0; // defensive; useful when passing |residual| } } std::sort(v.begin(), v.end()); return quantile(v.begin(), v.end(), q); } /** @brief Adaptive quantile that blends RAW and IQR-winsorized quantiles based on tail density beyond the Tukey upper fence. Let UF = Q3 + k*IQR on the (finite) inputs. Compute: - half_raw = quantile(values, q) - half_rob = winsorizedQuantile(values, q, UF) - r = fraction(values > UF) Blend with weight w(r): r ≤ r_sparse -> w=0 (use robust) r ≥ r_dense -> w=1 (use raw) otherwise -> linear interpolation between 0 and 1 Returned value = (1-w)*half_rob + w*half_raw. This keeps windows stable when outliers are sparse, while respecting genuinely broad tails (dense outliers) by leaning toward the raw quantile. References: - J. W. Tukey (1962). The Future of Data Analysis. - J. W. Tukey (1977). Exploratory Data Analysis. - R. J. Hyndman, Y. Fan (1996). Sample Quantiles in Statistical Packages @tparam IteratorType input iterator over arithmetic values @param[in] begin start iterator @param[in] end past-the-end iterator @param[in] q target quantile in [0,1] (e.g., 0.99 for 99% half-width) @param[in] k Tukey factor (default 1.5) @param[in] r_sparse tail density below which robust wins (default 0.01 = 1%) @param[in] r_dense tail density above which raw wins (default 0.10 = 10%) @return AdaptiveQuantileResult */ template <typename IteratorType> AdaptiveQuantileResult adaptiveQuantile(IteratorType begin, IteratorType end, double q, double k = 1.5, double r_sparse = 0.01, double r_dense = 0.10) { AdaptiveQuantileResult res; // Copy finite values std::vector<double> v; v.reserve(std::distance(begin, end)); for (auto it = begin; it != end; ++it) { if (std::isfinite(*it)) v.push_back(static_cast<double>(*it)); } if (v.empty()) { return res; } std::sort(v.begin(), v.end()); const double half_raw = quantile(v.begin(), v.end(), q); // Robust path (winsorization at Tukey fence) const double uf = tukeyUpperFence(v.begin(), v.end(), k); const double r = std::isfinite(uf) ? tailFractionAbove(v.begin(), v.end(), uf) : 0.0; const double half_rob = winsorizedQuantile(v.begin(), v.end(), q, uf); // Blend weight w(r) double w = 0.0; if (r_dense <= r_sparse) { w = (r > r_sparse) ? 1.0 : 0.0; } else { const double t = (r - r_sparse) / (r_dense - r_sparse); w = std::max(0.0, std::min(1.0, t)); } res.half_raw = half_raw; res.half_rob = half_rob; res.upper_fence = uf; res.tail_fraction = r; res.weight = w; res.blended = (1.0 - w) * half_rob + w * half_raw; return res; } /** @brief Calculates the variance of a range of values The @p mean can be provided explicitly to save computation time. If left at default, it will be computed internally. @exception Exception::InvalidRange is thrown if the range is empty @ingroup MathFunctionsStatistics */ template <typename IteratorType> static double variance(IteratorType begin, IteratorType end, double mean = std::numeric_limits<double>::max()) { checkIteratorsNotNULL(begin, end); double sum_value = 0.0; if (mean == std::numeric_limits<double>::max()) { mean = Math::mean(begin, end); } for (IteratorType iter=begin; iter!=end; ++iter) { double diff = *iter - mean; sum_value += diff * diff; } return sum_value / (std::distance(begin, end)-1); } /** @brief Calculates the standard deviation of a range of values. The @p mean can be provided explicitly to save computation time. If left at default, it will be computed internally. @exception Exception::InvalidRange is thrown if the range is empty @ingroup MathFunctionsStatistics */ template <typename IteratorType> static double sd(IteratorType begin, IteratorType end, double mean = std::numeric_limits<double>::max()) { checkIteratorsNotNULL(begin, end); return std::sqrt( variance(begin, end, mean) ); } /** @brief Calculates the absolute deviation of a range of values @exception Exception::InvalidRange is thrown if the range is empty @ingroup MathFunctionsStatistics */ template <typename IteratorType> static double absdev(IteratorType begin, IteratorType end, double mean = std::numeric_limits<double>::max()) { checkIteratorsNotNULL(begin, end); double sum_value = 0.0; if (mean == std::numeric_limits<double>::max()) { mean = Math::mean(begin, end); } for (IteratorType iter=begin; iter!=end; ++iter) { sum_value += *iter - mean; } return sum_value / std::distance(begin, end); } /** @brief Calculates the covariance of two ranges of values. Note that the two ranges must be of equal size. @exception Exception::InvalidRange is thrown if the range is empty @ingroup MathFunctionsStatistics */ template <typename IteratorType1, typename IteratorType2> static double covariance(IteratorType1 begin_a, IteratorType1 end_a, IteratorType2 begin_b, IteratorType2 end_b) { //no data or different lengths checkIteratorsNotNULL(begin_a, end_a); double sum_value = 0.0; double mean_a = Math::mean(begin_a, end_a); double mean_b = Math::mean(begin_b, end_b); IteratorType1 iter_a = begin_a; IteratorType2 iter_b = begin_b; for (; iter_a != end_a; ++iter_a, ++iter_b) { /* assure both ranges have the same number of elements */ checkIteratorsAreValid(begin_b, end_b, begin_a, end_a); sum_value += (*iter_a - mean_a) * (*iter_b - mean_b); } /* assure both ranges have the same number of elements */ checkIteratorsEqual(iter_b, end_b); Size n = std::distance(begin_a, end_a); return sum_value / (n-1); } /** @brief Calculates the mean square error for the values in [begin_a, end_a) and [begin_b, end_b) Calculates the mean square error for the data given by the two iterator ranges. @exception Exception::InvalidRange is thrown if the iterator ranges are not of the same length or empty. @ingroup MathFunctionsStatistics */ template <typename IteratorType1, typename IteratorType2> static double meanSquareError(IteratorType1 begin_a, IteratorType1 end_a, IteratorType2 begin_b, IteratorType2 end_b) { //no data or different lengths checkIteratorsNotNULL(begin_a, end_a); SignedSize dist = std::distance(begin_a, end_a); double error = 0; IteratorType1 iter_a = begin_a; IteratorType2 iter_b = begin_b; for (; iter_a != end_a; ++iter_a, ++iter_b) { /* assure both ranges have the same number of elements */ checkIteratorsAreValid(iter_b, end_b, iter_a, end_a); double tmp(*iter_a - *iter_b); error += tmp * tmp; } /* assure both ranges have the same number of elements */ checkIteratorsEqual(iter_b, end_b); return error / dist; } /** @brief Calculates the root mean square error (RMSE) for the values in [begin_a, end_a) and [begin_b, end_b) Computes the square root of the mean of the squared differences between the two iterator ranges (i.e., RMSE = sqrt(MSE)). . @exception Exception::InvalidRange is thrown if the iterator ranges are not of the same length or are empty. @ingroup MathFunctionsStatistics */ template <typename IteratorType1, typename IteratorType2> static double rootMeanSquareError(IteratorType1 begin_a, IteratorType1 end_a, IteratorType2 begin_b, IteratorType2 end_b) { return std::sqrt(meanSquareError(begin_a, end_a, begin_b, end_b)); } /** @brief Calculates the classification rate for the values in [begin_a, end_a) and [begin_b, end_b) Calculates the classification rate for the data given by the two iterator ranges. @exception Exception::InvalidRange is thrown if the iterator ranges are not of the same length or empty. @ingroup MathFunctionsStatistics */ template <typename IteratorType1, typename IteratorType2> static double classificationRate(IteratorType1 begin_a, IteratorType1 end_a, IteratorType2 begin_b, IteratorType2 end_b) { //no data or different lengths checkIteratorsNotNULL(begin_a, end_a); SignedSize dist = std::distance(begin_a, end_a); SignedSize correct = dist; IteratorType1 iter_a = begin_a; IteratorType2 iter_b = begin_b; for (; iter_a != end_a; ++iter_a, ++iter_b) { /* assure both ranges have the same number of elements */ checkIteratorsAreValid(iter_b, end_b, iter_a, end_a); if ((*iter_a < 0 && *iter_b >= 0) || (*iter_a >= 0 && *iter_b < 0)) { --correct; } } /* assure both ranges have the same number of elements */ checkIteratorsEqual(iter_b, end_b); return double(correct) / dist; } /** @brief Calculates the Matthews correlation coefficient for the values in [begin_a, end_a) and [begin_b, end_b) Calculates the Matthews correlation coefficient for the data given by the two iterator ranges. The values in [begin_a, end_a) have to be the predicted labels and the values in [begin_b, end_b) have to be the real labels. @exception Exception::InvalidRange is thrown if the iterator ranges are not of the same length or empty. @ingroup MathFunctionsStatistics */ template <typename IteratorType1, typename IteratorType2> static double matthewsCorrelationCoefficient( IteratorType1 begin_a, IteratorType1 end_a, IteratorType2 begin_b, IteratorType2 end_b) { //no data or different lengths checkIteratorsNotNULL(begin_a, end_b); double tp = 0; double fp = 0; double tn = 0; double fn = 0; IteratorType1 iter_a = begin_a; IteratorType2 iter_b = begin_b; for (; iter_a != end_a; ++iter_a, ++iter_b) { /* assure both ranges have the same number of elements */ checkIteratorsAreValid(iter_b, end_b, iter_a, end_a); if (*iter_a < 0 && *iter_b >= 0) { ++fn; } else if (*iter_a < 0 && *iter_b < 0) { ++tn; } else if (*iter_a >= 0 && *iter_b >= 0) { ++tp; } else if (*iter_a >= 0 && *iter_b < 0) { ++fp; } } /* assure both ranges have the same number of elements */ checkIteratorsEqual(iter_b, end_b); return (tp * tn - fp * fn) / std::sqrt((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn)); } /** @brief Calculates the Pearson correlation coefficient for the values in [begin_a, end_a) and [begin_b, end_b) Calculates the linear correlation coefficient for the data given by the two iterator ranges. If one of the ranges contains only the same values 'nan' is returned. @exception Exception::InvalidRange is thrown if the iterator ranges are not of the same length or empty. @ingroup MathFunctionsStatistics */ template <typename IteratorType1, typename IteratorType2> static double pearsonCorrelationCoefficient( IteratorType1 begin_a, IteratorType1 end_a, IteratorType2 begin_b, IteratorType2 end_b) { //no data or different lengths checkIteratorsNotNULL(begin_a, end_a); //calculate average SignedSize dist = std::distance(begin_a, end_a); double avg_a = std::accumulate(begin_a, end_a, 0.0) / dist; double avg_b = std::accumulate(begin_b, end_b, 0.0) / dist; double numerator = 0; double denominator_a = 0; double denominator_b = 0; IteratorType1 iter_a = begin_a; IteratorType2 iter_b = begin_b; for (; iter_a != end_a; ++iter_a, ++iter_b) { /* assure both ranges have the same number of elements */ checkIteratorsAreValid(iter_b, end_b, iter_a, end_a); double temp_a = *iter_a - avg_a; double temp_b = *iter_b - avg_b; numerator += (temp_a * temp_b); denominator_a += (temp_a * temp_a); denominator_b += (temp_b * temp_b); } /* assure both ranges have the same number of elements */ checkIteratorsEqual(iter_b, end_b); return numerator / std::sqrt(denominator_a * denominator_b); } /// Replaces the elements in vector @p w by their ranks template <typename Value> static void computeRank(std::vector<Value> & w) { Size i = 0; // main index Size z = 0; // "secondary" index Value rank = 0; Size n = (w.size() - 1); //store original indices for later std::vector<std::pair<Size, Value> > w_idx; for (Size j = 0; j < w.size(); ++j) { w_idx.push_back(std::make_pair(j, w[j])); } //sort std::sort(w_idx.begin(), w_idx.end(), [](const auto& pair1, const auto& pair2) { return pair1.second < pair2.second; }); //replace pairs <orig_index, value> in w_idx by pairs <orig_index, rank> while (i < n) { // test for equality with tolerance: if (fabs(w_idx[i + 1].second - w_idx[i].second) > 0.0000001 * fabs(w_idx[i + 1].second)) // no tie { w_idx[i].second = Value(i + 1); ++i; } else // tie, replace by mean rank { // count number of ties for (z = i + 1; (z <= n) && fabs(w_idx[z].second - w_idx[i].second) <= 0.0000001 * fabs(w_idx[z].second); ++z) { } // compute mean rank of tie rank = 0.5 * (i + z + 1); // replace intensities by rank for (Size v = i; v <= z - 1; ++v) { w_idx[v].second = rank; } i = z; } } if (i == n) w_idx[n].second = Value(n + 1); //restore original order and replace elements of w with their ranks for (Size j = 0; j < w.size(); ++j) { w[w_idx[j].first] = w_idx[j].second; } } /** @brief calculates the rank correlation coefficient for the values in [begin_a, end_a) and [begin_b, end_b) Calculates the rank correlation coefficient for the data given by the two iterator ranges. If one of the ranges contains only the same values 'nan' is returned. @exception Exception::InvalidRange is thrown if the iterator ranges are not of the same length or empty. @ingroup MathFunctionsStatistics */ template <typename IteratorType1, typename IteratorType2> static double rankCorrelationCoefficient( IteratorType1 begin_a, IteratorType1 end_a, IteratorType2 begin_b, IteratorType2 end_b) { //no data or different lengths checkIteratorsNotNULL(begin_a, end_a); // store and sort intensities of model and data SignedSize dist = std::distance(begin_a, end_a); std::vector<double> ranks_data; ranks_data.reserve(dist); std::vector<double> ranks_model; ranks_model.reserve(dist); IteratorType1 iter_a = begin_a; IteratorType2 iter_b = begin_b; for (; iter_a != end_a; ++iter_a, ++iter_b) { /* assure both ranges have the same number of elements */ checkIteratorsAreValid(iter_b, end_b, iter_a, end_a); ranks_model.push_back(*iter_a); ranks_data.push_back(*iter_b); } /* assure both ranges have the same number of elements */ checkIteratorsEqual(iter_b, end_b); // replace entries by their ranks computeRank(ranks_data); computeRank(ranks_model); double mu = double(ranks_data.size() + 1) / 2.; // mean of ranks // Was the following, but I think the above is more correct ... (Clemens) // double mu = (ranks_data.size() + 1) / 2; double sum_model_data = 0; double sqsum_data = 0; double sqsum_model = 0; for (Int i = 0; i < dist; ++i) { sum_model_data += (ranks_data[i] - mu) * (ranks_model[i] - mu); sqsum_data += (ranks_data[i] - mu) * (ranks_data[i] - mu); sqsum_model += (ranks_model[i] - mu) * (ranks_model[i] - mu); } // check for division by zero if (!sqsum_data || !sqsum_model) { return 0; } return sum_model_data / (std::sqrt(sqsum_data) * std::sqrt(sqsum_model)); } /// Helper class to gather (and dump) some statistics from a e.g. vector<double>. template<typename T> struct SummaryStatistics { SummaryStatistics() = default; // Ctor with data SummaryStatistics(T& data) { count = data.size(); // Sanity check: avoid core dump if no data points present. if (data.empty()) { mean = variance = min = lowerq = median = upperq = max = 0.0; } else { sort(data.begin(), data.end()); mean = Math::mean(data.begin(), data.end()); variance = Math::variance(data.begin(), data.end(), mean); min = data.front(); lowerq = Math::quantile1st(data.begin(), data.end(), true); median = Math::median(data.begin(), data.end(), true); upperq = Math::quantile3rd(data.begin(), data.end(), true); max = data.back(); } } double mean = 0, variance = 0 , lowerq = 0, median = 0, upperq = 0; typename T::value_type min = 0, max = 0; size_t count = 0; }; } // namespace Math } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/MATH/MISC/CubicSpline2d.h
.h
2,620
94
// 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/OpenMSConfig.h> #include <vector> #include <map> namespace OpenMS { /** @brief cubic spline interpolation as described in R.L. Burden, J.D. Faires, Numerical Analysis, 4th ed. PWS-Kent, 1989, ISBN 0-53491-585-X, pp. 126-131. Construction of the spline takes by far the most time. Evaluating it is rather fast (one evaluation is about 50x faster than construction -- depending on number of points etc.). */ class OPENMS_DLLAPI CubicSpline2d { std::vector<double> a_; ///< constant spline coefficients std::vector<double> b_; ///< linear spline coefficients std::vector<double> c_; ///< quadratic spline coefficients std::vector<double> d_; ///< cubic spline coefficients std::vector<double> x_; ///< knots public: /** * @brief constructor of spline interpolation * * The coordinates must match by index. Both vectors must be * the same size and sorted in x. Sortedness in x is required * for @see SplinePackage. * * @param[in] x x-coordinates of input data points (knots) * @param[in] y y-coordinates of input data points */ CubicSpline2d(const std::vector<double>& x, const std::vector<double>& y); /** * @brief constructor of spline interpolation * * @param[in] m (x,y) coordinates of input data points */ CubicSpline2d(const std::map<double, double>& m); /** * @brief evaluates the spline at position x * * @param[in] x x-position */ double eval(double x) const; /** * @brief evaluates first derivative of spline at position x * * @param[in] x x-position */ double derivative(double x) const; /** * @brief evaluates derivative of spline at position x * * @param[in] x x-position * @param[in] order order of the derivative * Only order 1 or 2 make sense for cubic splines. */ double derivatives(double x, unsigned order) const; private: /** * @brief initialize the spline * * @param[in] x x-coordinates of input data points (knots) * @param[in] y y-coordinates of input data points */ void init_(const std::vector<double>& x, const std::vector<double>& y); }; }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/MATH/MISC/EmgGradientDescent.h
.h
17,393
536
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Douglas McCloskey, Pasquale Domenico Colaianni $ // $Authors: Douglas McCloskey, Pasquale Domenico Colaianni $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/config.h> // OPENMS_DLLAPI #include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h> #include <OpenMS/KERNEL/MSChromatogram.h> #include <OpenMS/KERNEL/MSSpectrum.h> namespace OpenMS { /** @brief Fit peaks to an Exponentially Modified Gaussian (EMG) model using gradient descent. The exponentially modified Gaussian (EMG) function is a peak model used to accurately fit chromatographic and spectral peaks, especially those showing tailing behavior. This class provides methods to fit EMG parameters using gradient descent and to compute peak areas based on the fitted model. @section EmgGradientDescent_model The EMG Model The EMG model combines a Gaussian distribution with exponential decay, characterized by four parameters: - \b h (amplitude): Peak height - \b mu (mean): Gaussian center position - \b sigma (standard deviation): Gaussian width - \b tau (exponential relaxation time): Controls the degree of tailing @section EmgGradientDescent_algorithm Algorithm The fitting is performed using the iRprop+ algorithm, a variant of resilient backpropagation that adapts step sizes based on gradient behavior: - If gradient sign is consistent: increase step size (accelerate) - If gradient sign changes: decrease step size and revert (avoid oscillation) - Independent step sizes for each parameter The algorithm automatically extracts a training set that avoids saturated points and handles three different z-value regimes to maintain numerical stability. @section EmgGradientDescent_usage Use Cases EMG fitting is particularly useful for: - **Saturated peaks**: Reconstruct true peak shape when detector saturates - **Cutoff peaks**: Estimate full area when acquisition window is incomplete - **Tailing peaks**: Model asymmetric peaks common in chromatography - **Quality assessment**: Compare measured vs. ideal peak shape @section EmgGradientDescent_reference Reference Yuri Kalambet, Yuri Kozmin, Ksenia Mikhailova, Igor Nagaev, Pavel Tikhonov, "Reconstruction of chromatographic peaks using the exponentially modified Gaussian function," Journal of Chemometrics, 2011, 25, 352-356. @see PeakIntegrator for integration using EMG fitting @ingroup TargetedQuantitation */ class OPENMS_DLLAPI EmgGradientDescent : public DefaultParamHandler { public: /// Constructor EmgGradientDescent(); /// Destructor ~EmgGradientDescent() override = default; void getDefaultParameters(Param& params); /// To test private and protected methods friend class EmgGradientDescent_friend; /** @brief Fit the given peak (either MSChromatogram or MSSpectrum) to the EMG peak model The method is able to recapitulate the actual peak area of saturated or cutoff peaks. In addition, the method is able to fine tune the peak area of well acquired peaks. The output is a reconstruction of the input peak. Additional points are often added to produce a peak with similar intensities on boundaries' points. Metadata will be added to the output peak, containing the optimal parameters for the EMG peak model. This information will be found in a `FloatDataArray` of name "emg_parameters", with the parameters being saved in the following order (from index 0 to 3): amplitude `h`, mean `mu`, standard deviation `sigma`, exponent relaxation time `tau`. If `left_pos` and `right_pos` are passed, then only that part of the peak is taken into consideration. @note All optimal gradient descent parameters are currently hard coded to allow for a simplified user interface @note Cutoff peak: The intensities of the left and right baselines are not equal @note Saturated peak: The maximum intensity of the peak is lower than expected due to saturation of the detector Inspired by the results found in: Yuri Kalambet, Yuri Kozmin, Ksenia Mikhailova, Igor Nagaev, Pavel Tikhonov Reconstruction of chromatographic peaks using the exponentially modified Gaussian function @tparam PeakContainerT Either a MSChromatogram or a MSSpectrum @param[in] input_peak Input peak @param[out] output_peak Output peak @param[in] left_pos RT or MZ value of the first point of interest @param[in] right_pos RT or MZ value of the last point of interest */ template <typename PeakContainerT> void fitEMGPeakModel( const PeakContainerT& input_peak, PeakContainerT& output_peak, const double left_pos = 0.0, const double right_pos = 0.0 ) const; /** @brief The implementation of the gradient descent algorithm for the EMG peak model @param[in] xs Positions @param[in] ys Intensities @param[out] best_h `h` (amplitude) parameter @param[out] best_mu `mu` (mean) parameter @param[out] best_sigma `sigma` (standard deviation) parameter @param[out] best_tau `tau` (exponent relaxation time) parameter @return The number of iterations necessary to reach the best values for the parameters */ UInt estimateEmgParameters( const std::vector<double>& xs, const std::vector<double>& ys, double& best_h, double& best_mu, double& best_sigma, double& best_tau ) const; /** @brief Compute the EMG function on a set of points If class parameter `compute_additional_points` is `"true"`, the algorithm will detect which side of the peak is cutoff and add points to it. @param[in] xs Positions @param[in] h Amplitude @param[in] mu Mean @param[in] sigma Standard deviation @param[in] tau Exponent relaxation time @param[out] out_xs The output positions @param[out] out_ys The output intensities */ void applyEstimatedParameters( const std::vector<double>& xs, const double h, const double mu, const double sigma, const double tau, std::vector<double>& out_xs, std::vector<double>& out_ys ) const; protected: void updateMembers_() override; /** @brief Given a peak, extract a training set to be used with the gradient descent algorithm The algorithm tries to select only those points that can help in finding the optimal parameters with gradient descent. The decision of which points to skip is based on the derivatives between consecutive points. It first selects all those points whose intensity is below a certain value (`intensity_threshold`). Then, the derivatives of all the remaining points are computed. Based on the results, the algorithm selects those points that present a high enough derivative. Once a low value is found, the algorithm stops taking points from that side. It then repeats the same procedure on the other side of the peak. The goal is to limit the inclusion of saturated or spurious points near the peak apex during training. @throw Exception::SizeUnderflow if the input has less than 2 elements @param[in] xs Positions @param[in] ys Intensities @param[out] TrX Extracted training set positions @param[out] TrY Extracted training set intensities */ void extractTrainingSet( const std::vector<double>& xs, const std::vector<double>& ys, std::vector<double>& TrX, std::vector<double>& TrY ) const; /** @brief Compute the boundary for the mean (`mu`) parameter in gradient descent Together with the value returned by computeInitialMean(), this method decides the minimum and maximum value that `mu` can assume during iterations of the gradient descent algorithm. The value is based on the width of the peak. @param[in] xs Positions @return The maximum distance from the precomputed initial mean in the gradient descent algorithm */ double computeMuMaxDistance(const std::vector<double>& xs) const; /** @brief Compute an estimation of the mean of a peak The method computes the middle point on different levels of intensity of the peak. The returned mean is the average of these middle points. @throw Exception::SizeUnderflow if the input is empty @param[in] xs Positions @param[in] ys Intensities @return The peak's estimated mean */ double computeInitialMean( const std::vector<double>& xs, const std::vector<double>& ys ) const; private: /** @brief Apply the iRprop+ algorithm for gradient descent Reference: Christian Igel and Michael Hüsken. Improving the Rprop Learning Algorithm. Second International Symposium on Neural Computation (NC 2000), pp. 115-121, ICSC Academic Press, 2000 @param[in] prev_diff_E_param The cost of the partial derivative of E with respect to the given parameter, at the previous iteration of gradient descent @param[in,out] diff_E_param The cost of the partial derivative of E with respect to the given parameter, at the current iteration @param[in,out] param_lr The learning rate for the given parameter @param[in,out] param_update The amount to add/remove to/from `param` @param[in,out] param The parameter for which the algorithm tries speeding the convergence to a minimum @param[in] current_E The current cost E @param[in] previous_E The previous cost E */ void iRpropPlus( const double prev_diff_E_param, double& diff_E_param, double& param_lr, double& param_update, double& param, const double current_E, const double previous_E ) const; /** @brief Compute the cost given by loss function E Needed by the gradient descent algorithm. The mean squared error is used as the loss function E. @param[in] xs Positions @param[in] ys Intensities @param[in] h Amplitude @param[in] mu Mean @param[in] sigma Standard deviation @param[in] tau Exponent relaxation time @return The computed cost */ double Loss_function( const std::vector<double>& xs, const std::vector<double>& ys, const double h, const double mu, const double sigma, const double tau ) const; /** @brief Compute the cost given by the partial derivative of the loss function E, with respect to `h` (the amplitude) Needed by the gradient descent algorithm. @param[in] xs Positions @param[in] ys Intensities @param[in] h Amplitude @param[in] mu Mean @param[in] sigma Standard deviation @param[in] tau Exponent relaxation time @return The computed cost */ double E_wrt_h( const std::vector<double>& xs, const std::vector<double>& ys, const double h, const double mu, const double sigma, const double tau ) const; /** @brief Compute the cost given by the partial derivative of the loss function E, with respect to `mu` (the mean) Needed by the gradient descent algorithm. @param[in] xs Positions @param[in] ys Intensities @param[in] h Amplitude @param[in] mu Mean @param[in] sigma Standard deviation @param[in] tau Exponent relaxation time @return The computed cost */ double E_wrt_mu( const std::vector<double>& xs, const std::vector<double>& ys, const double h, const double mu, const double sigma, const double tau ) const; /** @brief Compute the cost given by the partial derivative of the loss function E, with respect to `sigma` (the standard deviation) Needed by the gradient descent algorithm. @param[in] xs Positions @param[in] ys Intensities @param[in] h Amplitude @param[in] mu Mean @param[in] sigma Standard deviation @param[in] tau Exponent relaxation time @return The computed cost */ double E_wrt_sigma( const std::vector<double>& xs, const std::vector<double>& ys, const double h, const double mu, const double sigma, const double tau ) const; /** @brief Compute the cost given by the partial derivative of the loss function E, with respect to `tau` (the exponent relaxation time) Needed by the gradient descent algorithm. @param[in] xs Positions @param[in] ys Intensities @param[in] h Amplitude @param[in] mu Mean @param[in] sigma Standard deviation @param[in] tau Exponent relaxation time @return The computed cost */ double E_wrt_tau( const std::vector<double>& xs, const std::vector<double>& ys, const double h, const double mu, const double sigma, const double tau ) const; /** @brief Compute EMG's z parameter The value of z decides which formula is to be used during EMG function computation. Z values in the following ranges will each use a different EMG formula to avoid numerical instability and potential numerical overflow: (-inf, 0), [0, 6.71e7], (6.71e7, +inf) Reference: Kalambet, Y.; Kozmin, Y.; Mikhailova, K.; Nagaev, I.; Tikhonov, P. (2011). "Reconstruction of chromatographic peaks using the exponentially modified Gaussian function". Journal of Chemometrics. 25 (7): 352. @param[in] x Position @param[in] mu Mean @param[in] sigma Standard deviation @param[in] tau Exponent relaxation time @return The computed parameter z */ double compute_z( const double x, const double mu, const double sigma, const double tau ) const; /** @brief Compute the EMG function on a single point @param[in] x Position @param[in] h Amplitude @param[in] mu Mean @param[in] sigma Standard deviation @param[in] tau Exponent relaxation time @return The estimated intensity for the given input point */ double emg_point( const double x, const double h, const double mu, const double sigma, const double tau ) const; /// Alias for OpenMS::Constants:PI const double PI = OpenMS::Constants::PI; /** Level of debug information to print to the terminal Valid values are: 0, 1, 2 Higher values mean more information */ UInt print_debug_; /// Maximum number of gradient descent iterations in `fitEMGPeakModel()` UInt max_gd_iter_; /** Whether additional points should be added when fitting EMG peak model, particularly useful with cutoff peaks */ bool compute_additional_points_; }; class EmgGradientDescent_friend { public: EmgGradientDescent_friend() = default; ~EmgGradientDescent_friend() = default; double Loss_function( const std::vector<double>& xs, const std::vector<double>& ys, const double h, const double mu, const double sigma, const double tau ) const { return emg_gd_.Loss_function(xs, ys, h, mu, sigma, tau); } double computeMuMaxDistance(const std::vector<double>& xs) const { return emg_gd_.computeMuMaxDistance(xs); } void extractTrainingSet( const std::vector<double>& xs, const std::vector<double>& ys, std::vector<double>& TrX, std::vector<double>& TrY ) const { emg_gd_.extractTrainingSet(xs, ys, TrX, TrY); } double computeInitialMean( const std::vector<double>& xs, const std::vector<double>& ys ) const { return emg_gd_.computeInitialMean(xs, ys); } void iRpropPlus( const double prev_diff_E_param, double& diff_E_param, double& param_lr, double& param_update, double& param, const double current_E, const double previous_E ) const { emg_gd_.iRpropPlus( prev_diff_E_param, diff_E_param, param_lr, param_update, param, current_E, previous_E ); } double compute_z( const double x, const double mu, const double sigma, const double tau ) const { return emg_gd_.compute_z(x, mu, sigma, tau); } void applyEstimatedParameters( const std::vector<double>& xs, const double h, const double mu, const double sigma, const double tau, std::vector<double>& out_xs, std::vector<double>& out_ys ) const { emg_gd_.applyEstimatedParameters(xs, h, mu, sigma, tau, out_xs, out_ys); } double emg_point( const double x, const double h, const double mu, const double sigma, const double tau ) const { return emg_gd_.emg_point(x, h, mu, sigma, tau); } EmgGradientDescent emg_gd_; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/MATH/MISC/BSpline2d.h
.h
3,779
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, Timo Sachsenberg $ // -------------------------------------------------------------------------- #pragma once #include <vector> #include <OpenMS/config.h> #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/CONCEPT/Exception.h> #include <OpenMS/CONCEPT/Macros.h> // forward declaration of impl class BSpline namespace eol_bspline { template <class T> class BSpline; } namespace OpenMS { /** * @brief b spline interpolation */ class OPENMS_DLLAPI BSpline2d { public: // Note: Don't change boundary condition constants as these are passed through to the eol-bspline implementation. enum BoundaryCondition { /// Set the endpoints of the spline to zero. BC_ZERO_ENDPOINTS = 0, /// Set the first derivative of the spline to zero at the endpoints. BC_ZERO_FIRST = 1, /// Set the second derivative to zero. BC_ZERO_SECOND = 2 }; /** * Create a single spline with the parameters required to set up * the domain and subsequently smooth the given set of y values. * The y values must correspond to each of the x values. * If either the domain setup fails or the spline cannot be solved, * the state will be set to "not OK". * * @see ok(). * * @param[in] x The array of x values in the domain. * @param[in] y The array of y values corresponding to each of the * x values in the domain. * @param[in] wavelength The cutoff wavelength, in the same units as the * @p x values. A wavelength of zero disables * the derivative constraint. * @param[in] boundary_condition The boundary condition type. If * omitted it defaults to BC_ZERO_SECOND. * @param[in] num_nodes The number of nodes to use for the cubic b-spline. * If less than 2, a "reasonable" number will be * calculated automatically, taking into account * the given cutoff wavelength. * @pre x and y must be of the same dimensions. **/ BSpline2d(const std::vector<double>& x, const std::vector<double>& y, double wavelength = 0, BoundaryCondition boundary_condition = BC_ZERO_SECOND, Size num_nodes = 0); /** * Destructor */ virtual ~BSpline2d(); /** * Solve the spline curve for a new set of y values. Returns false * if the solution fails. * * @param[in] y The array of y values corresponding to each of the * x values in the domain. */ bool solve(const std::vector<double>& y); /** * Return the evaluation of the smoothed curve * at a particular @p x value. If current state is not ok(), returns zero. */ double eval(const double x) const; /** * Return the first derivative of the spline curve at the given @p x. * Returns zero if the current state is not ok(). */ double derivative(const double x) const; /** * Return whether the spline fit was successful. */ bool ok() const; /** * Enable or disable debug messages from the B-spline library. */ static void debug(bool enable); private: // Pointer to actual implementation. Note: This class follows the PIMPL idiom hiding the actual // B-spline implementation behind this pointer to avoid any dependency of the interface to the // implementation. Thus, the eol splines are only required during compilation of OpenMS and // not when linking against OpenMS. eol_bspline::BSpline<double>* spline_; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/MATH/MISC/SplineBisection.h
.h
1,834
74
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Hannes Roest $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/config.h> #include <limits> #include <cmath> namespace OpenMS { /** * @brief Uses bisection to find the maximum point of a spline * * Should work with BSpline2d and CubicSpline2d * */ namespace Math { template <class T> void spline_bisection(const T & peak_spline, double const left_neighbor_mz, double const right_neighbor_mz, double & max_peak_mz, double & max_peak_int, double const threshold = 1e-6) { // calculate maximum by evaluating the spline's 1st derivative // (bisection method) double lefthand = left_neighbor_mz; double righthand = right_neighbor_mz; bool lefthand_sign = true; double eps = std::numeric_limits<double>::epsilon(); // bisection do { double mid = (lefthand + righthand) / 2.0; double midpoint_deriv_val = peak_spline.derivative(mid); // if deriv nearly zero then maximum already found if (!(std::fabs(midpoint_deriv_val) > eps)) { break; } bool midpoint_sign = (midpoint_deriv_val < 0.0) ? false : true; if (lefthand_sign ^ midpoint_sign) { righthand = mid; } else { lefthand = mid; } } while (righthand - lefthand > threshold); max_peak_mz = (lefthand + righthand) / 2; max_peak_int = peak_spline.eval(max_peak_mz); } } }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/MATH/STATISTICS/GumbelMaxLikelihoodFitter.h
.h
2,527
87
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Julianus Pfeuffer $ // $Authors: Julianus Pfeuffer $ // -------------------------------------------------------------------------- // #pragma once #include <OpenMS/DATASTRUCTURES/String.h> #include <vector> namespace OpenMS { namespace Math { /** @brief Implements a fitter for the Gumbel distribution. This class fits a Gumbel distribution to a number of data points. The results as well as the initial guess are specified using the struct GumbelDistributionFitResult. The formula with the fitted parameters can be transformed into a gnuplot formula using getGnuplotFormula() after fitting. @ingroup Math */ class OPENMS_DLLAPI GumbelMaxLikelihoodFitter { public: /// struct to represent the parameters of a gumbel distribution struct GumbelDistributionFitResult { GumbelDistributionFitResult(double local_a, double local_b) : a(local_a), b(local_b) { } /// location parameter a double a; /// scale parameter b double b; double log_eval_no_normalize(double x) const; }; /// Default constructor GumbelMaxLikelihoodFitter(); /// Default constructor GumbelMaxLikelihoodFitter(GumbelDistributionFitResult init); /// Destructor virtual ~GumbelMaxLikelihoodFitter(); /// sets the gumbel distribution start parameters a and b for the fitting void setInitialParameters(const GumbelDistributionFitResult & result); /** @brief Fits a gumbel distribution to the given data x values. Fills a weighted histogram first and generates y values. @param[in] x Input x values @param[in] w Input weights @exception Exception::UnableToFit is thrown if fitting cannot be performed */ GumbelDistributionFitResult fitWeighted(const std::vector<double> & x, const std::vector<double> & w); protected: GumbelDistributionFitResult init_param_; private: /// Copy constructor (not implemented) GumbelMaxLikelihoodFitter(const GumbelMaxLikelihoodFitter & rhs); /// assignment operator (not implemented) GumbelMaxLikelihoodFitter & operator=(const GumbelMaxLikelihoodFitter & rhs); }; } }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/MATH/STATISTICS/PosteriorErrorProbabilityModel.h
.h
15,659
278
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: David Wojnar $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/DATASTRUCTURES/DPosition.h> #include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h> #include <OpenMS/DATASTRUCTURES/ListUtils.h> #include <OpenMS/MATH/STATISTICS/GumbelDistributionFitter.h> #include <OpenMS/MATH/STATISTICS/GumbelMaxLikelihoodFitter.h> #include <OpenMS/MATH/STATISTICS/GaussFitter.h> #include <OpenMS/METADATA/PeptideIdentificationList.h> #include <vector> #include <map> namespace OpenMS { class String; class TextFile; class PeptideIdentification; class ProteinIdentification; class PeptideHit; class PeptideIdentificationList; namespace Math { /** @brief Implements a mixture model of the inverse gumbel and the gauss distribution or a gaussian mixture. This class fits either a Gumbel distribution and a Gauss distribution to a set of data points or two Gaussian distributions using the EM algorithm. One can output the fit as a gnuplot formula using getGumbelGnuplotFormula() and getGaussGnuplotFormula() after fitting. @note All parameters are stored in GaussFitResult. In the case of the Gumbel distribution x0 and sigma represent the local parameter alpha and the scale parameter beta, respectively. @todo test performance and make fitGumbelGauss available via parameters. @todo allow charge state based fitting @todo allow semi-supervised by using decoy annotations @todo allow non-parametric via kernel density estimation @htmlinclude OpenMS_PosteriorErrorProbabilityModel.parameters @ingroup Math */ class OPENMS_DLLAPI PosteriorErrorProbabilityModel : public DefaultParamHandler { public: ///default constructor PosteriorErrorProbabilityModel(); ///Destructor ~PosteriorErrorProbabilityModel() override; /** * @brief extract and transform score types to a range and score orientation that the PEP model can handle * @param[in] protein_ids the protein identifications * @param[in] peptide_ids the peptide identifications * @param[in] split_charge whether different charge states should be treated separately * @param[in] top_hits_only only consider rank 1 * @param[in] target_decoy_available whether target decoy information is stored as meta value * @param[in] fdr_for_targets_smaller fdr threshold for targets * @return engine (and optional charge state) id -> vector of triplets (score, target, decoy) * @note supported engines are: XTandem,OMSSA,MASCOT,SpectraST,MyriMatch,SimTandem,MSGFPlus,MS-GF+,Comet,Sage */ static std::map<String, std::vector<std::vector<double>>> extractAndTransformScores( const std::vector<ProteinIdentification> & protein_ids, const PeptideIdentificationList & peptide_ids, const bool split_charge, const bool top_hits_only, const bool target_decoy_available, const double fdr_for_targets_smaller); /** * @brief update score entries with PEP (or 1-PEP) estimates * @param[in] PEP_model the PEP model used to update the scores * @param[in] search_engine the score of search_engine will be updated * @param[in] charge identifications with the given charge will be updated * @param[in] prob_correct report 1-PEP * @param[in] split_charge if charge states have been treated separately * @param[in,out] protein_ids the protein identifications * @param[in,out] peptide_ids the peptide identifications * @param[out] unable_to_fit_data there was a problem fitting the data (probabilities are all smaller 0 or larger 1) * @param[out] data_might_not_be_well_fit fit was successful but of bad quality (probabilities are all smaller 0.8 and larger 0.2) * @note supported engines are: XTandem,OMSSA,MASCOT,SpectraST,MyriMatch,SimTandem,MSGFPlus,MS-GF+,Comet */ static void updateScores( const PosteriorErrorProbabilityModel & PEP_model, const String & search_engine, const Int charge, const bool prob_correct, const bool split_charge, std::vector<ProteinIdentification> & protein_ids, PeptideIdentificationList & peptide_ids, bool & unable_to_fit_data, bool & data_might_not_be_well_fit); /** @brief fits the distributions to the data points(search_engine_scores). Estimated parameters for the distributions are saved in member variables. computeProbability can be used afterwards. Uses two Gaussians to fit. And Gauss+Gauss or Gumbel+Gauss to plot and calculate final probabilities. @param[in,out] search_engine_scores a vector which holds the data points @param[in] outlier_handling Valid values are in the Param 'outlier_handling' @return true if algorithm has run through. Else false will be returned. In that case no plot and no probabilities are calculated. @note the vector is sorted from smallest to biggest value! */ bool fit(std::vector<double>& search_engine_scores, const String& outlier_handling); /** @brief fits the distributions to the data points(search_engine_scores). Estimated parameters for the distributions are saved in member variables. computeProbability can be used afterwards. Uses Gumbel+Gauss for everything. Fits Gumbel by maximizing log likelihood. @param[in,out] search_engine_scores a vector which holds the data points @param[in] outlier_handling Valid values are in the Param 'outlier_handling' @return true if algorithm has run through. Else false will be returned. In that case no plot and no probabilities are calculated. @note the vector is sorted from smallest to biggest value! */ bool fitGumbelGauss(std::vector<double>& search_engine_scores, const String& outlier_handling); /** @brief fits the distributions to the data points(search_engine_scores) and writes the computed probabilities into the given vector (the second one). @param[in,out] search_engine_scores a vector which holds the data points @param[out] probabilities Probability for each data point after running this function. If it has some content it will be overwritten. @param[in] outlier_handling Valid values are in the Param 'outlier_handling' @return true if algorithm has run through. Else false will be returned. In that case no plot and no probabilities are calculated. @note the vectors are sorted from smallest to biggest value! */ bool fit(std::vector<double>& search_engine_scores, std::vector<double>& probabilities, const String& outlier_handling); ///Writes the distributions densities into the two vectors for a set of scores. Incorrect_densities represent the incorrectly assigned sequences. void fillDensities(const std::vector<double> & x_scores, std::vector<double> & incorrect_density, std::vector<double> & correct_density); ///Writes the log distributions densities into the two vectors for a set of scores. Incorrect_densities represent the incorrectly assigned sequences. void fillLogDensities(const std::vector<double> & x_scores, std::vector<double> & incorrect_density, std::vector<double> & correct_density); ///Writes the log distributions of gumbel and gauss densities into the two vectors for a set of scores. Incorrect_densities represent the incorrectly assigned sequences. void fillLogDensitiesGumbel(const std::vector<double> & x_scores, std::vector<double> & incorrect_density, std::vector<double> & correct_density); ///computes the Likelihood with a log-likelihood function. double computeLogLikelihood(const std::vector<double> & incorrect_density, const std::vector<double> & correct_density) const; /**computes the posteriors for the datapoints to belong to the incorrect distribution @param[in] incorrect_log_density ... @param[in] correct_log_density ... @param[out] incorrect_posterior resulting posteriors; same size as @p incorrect_log_density @return the log-likelihood of the model */ double computeLLAndIncorrectPosteriorsFromLogDensities( const std::vector<double>& incorrect_log_density, const std::vector<double>& correct_log_density, std::vector<double>& incorrect_posterior) const; /** * @param[in] x_scores Scores observed "on the x-axis" * @param[in] incorrect_posteriors Posteriors/responsibilities of belonging to the incorrect component * @return New estimate for the mean of the correct (pair.first) and incorrect (pair.second) component * @note only for Gaussian estimates */ std::pair<double, double> pos_neg_mean_weighted_posteriors(const std::vector<double> &x_scores, const std::vector<double> &incorrect_posteriors); /** * @param[in] x_scores Scores observed "on the x-axis" * @param[in] incorrect_posteriors Posteriors/responsibilities of belonging to the incorrect component * @param[in] pos_neg_mean Positive(correct) and negative(incorrect) means, respectively * @return New estimate for the std. deviation of the correct (pair.first) and incorrect (pair.second) component * @note only for Gaussian estimates */ std::pair<double, double> pos_neg_sigma_weighted_posteriors(const std::vector<double> &x_scores, const std::vector<double> &incorrect_posteriors, const std::pair<double, double>& pos_neg_mean); ///returns estimated parameters for correctly assigned sequences. Fit should be used before. GaussFitter::GaussFitResult getCorrectlyAssignedFitResult() const { return correctly_assigned_fit_param_; } ///returns estimated parameters for correctly assigned sequences. Fit should be used before. GaussFitter::GaussFitResult getIncorrectlyAssignedFitResult() const { return incorrectly_assigned_fit_param_; } ///returns estimated parameters for correctly assigned sequences. Fit should be used before. GumbelMaxLikelihoodFitter::GumbelDistributionFitResult getIncorrectlyAssignedGumbelFitResult() const { return incorrectly_assigned_fit_gumbel_param_; } ///returns the estimated negative prior probability. double getNegativePrior() const { return negative_prior_; } ///computes the gumbel density at position x with parameters params. static double getGumbel_(double x, const GaussFitter::GaussFitResult & params) { double z = exp((params.x0 - x) / params.sigma); return (z * exp(-1 * z)) / params.sigma; } /** Returns the computed posterior error probability for a given score. @note: fit has to be used before using this function. Otherwise this function will compute nonsense. */ double computeProbability(double score) const; /// initializes the plots TextFile initPlots(std::vector<double> & x_scores); /// returns the gnuplot formula of the fitted gumbel distribution. Only x0 and sigma are used as local parameter alpha and scale parameter beta, respectively. const String getGumbelGnuplotFormula(const GaussFitter::GaussFitResult & params) const; /// returns the gnuplot formula of the fitted gauss distribution. const String getGaussGnuplotFormula(const GaussFitter::GaussFitResult & params) const; /// returns the gnuplot formula of the fitted mixture distribution. const String getBothGnuplotFormula(const GaussFitter::GaussFitResult & incorrect, const GaussFitter::GaussFitResult & correct) const; ///plots the estimated distribution against target and decoy hits void plotTargetDecoyEstimation(std::vector<double> & target, std::vector<double> & decoy); /// returns the smallest score used in the last fit inline double getSmallestScore() const { return smallest_score_; } /// try to invoke 'gnuplot' on the file to create PDF automatically void tryGnuplot(const String& gp_file); private: /// transform different score types to a range and score orientation that the model can handle (engine string is assumed in upper-case) void processOutliers_(std::vector<double>& x_scores, const String& outlier_handling) const; /// transform different score types to a range and score orientation that the model can handle (engine string is assumed in upper-case) /// @param[in] engine the search engine name as in the SE param object /// @param[in] hit the PeptideHit to extract transformed scores from /// @param[in] current_score_type the current score type of the PeptideIdentification to take precedence static double transformScore_(const String& engine, const PeptideHit& hit, const String& current_score_type); /// gets a specific score (either main score [preferred] or metavalue) /// @param[in] requested_score_types the requested score_types in order of preference (will be tested with a "_score" suffix as well) /// @param[in] hit the PeptideHit to extract from /// @param[in] actual_score_type the current score type to take preference if matching static double getScore_(const std::vector<String>& requested_score_types, const PeptideHit & hit, const String& actual_score_type); /// assignment operator (not implemented) PosteriorErrorProbabilityModel & operator=(const PosteriorErrorProbabilityModel & rhs); ///Copy constructor (not implemented) PosteriorErrorProbabilityModel(const PosteriorErrorProbabilityModel & rhs); ///stores parameters for incorrectly assigned sequences. If gumbel fit was used, A can be ignored. Furthermore, in this case, x0 and sigma are the local parameter alpha and scale parameter beta, respectively. GaussFitter::GaussFitResult incorrectly_assigned_fit_param_; GumbelMaxLikelihoodFitter::GumbelDistributionFitResult incorrectly_assigned_fit_gumbel_param_; ///stores gauss parameters GaussFitter::GaussFitResult correctly_assigned_fit_param_; ///stores final prior probability for negative peptides double negative_prior_; ///peak of the incorrectly assigned sequences distribution double max_incorrectly_; ///peak of the gauss distribution (correctly assigned sequences) double max_correctly_; ///smallest score which was used for fitting the model double smallest_score_; ///points either to getGumbelGnuplotFormula or getGaussGnuplotFormula depending on whether one uses the gumbel or the gaussian distribution for incorrectly assigned sequences. const String (PosteriorErrorProbabilityModel::* getNegativeGnuplotFormula_)(const GaussFitter::GaussFitResult & params) const; ///points to getGumbelGnuplotFormula const String (PosteriorErrorProbabilityModel::* getPositiveGnuplotFormula_)(const GaussFitter::GaussFitResult & params) const; }; } }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/MATH/STATISTICS/Histogram.h
.h
12,218
438
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg$ // $Authors: Marc Sturm $ // -------------------------------------------------------------------------- #pragma once //OpenMS #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/CONCEPT/Exception.h> //STL #include <vector> #include <cmath> #include <limits> #include <iostream> #include <algorithm> namespace OpenMS { namespace Math { /** @brief Representation of a histogram The first template argument gives the Type of the values that are stored in the bins. The second argument gives the type for the bin size and range. @ingroup Math */ template <typename ValueType = UInt, typename BinSizeType = double> class Histogram { public: /// Non-mutable iterator of the bins typedef typename std::vector<ValueType>::const_iterator ConstIterator; /** @name Constructors and Destructors */ //@{ ///default constructor Histogram() : min_(0), max_(0), bin_size_(0) { } ///copy constructor Histogram(const Histogram & histogram) : min_(histogram.min_), max_(histogram.max_), bin_size_(histogram.bin_size_), bins_(histogram.bins_) { } /** @brief constructor with min, max (inclusive) and bin width @exception Exception::OutOfRange is thrown if @p bin_size negative or zero */ Histogram(BinSizeType min, BinSizeType max, BinSizeType bin_size) : min_(min), max_(max), bin_size_(bin_size) { this->initBins_(); } /** @brief constructor with data iterator and min, max, bin_size parameters @exception Exception::OutOfRange is thrown if @p bin_size negative or zero */ template <typename DataIterator> Histogram(DataIterator begin, DataIterator end, BinSizeType min, BinSizeType max, BinSizeType bin_size) : min_(min), max_(max), bin_size_(bin_size) { this->initBins_(); for (DataIterator it = begin; it != end; ++it) { this->inc((BinSizeType) *it); } } ///destructor virtual ~Histogram() { } //@} /// returns the lower bound (inclusive) BinSizeType minBound() const { return min_; } /// returns the upper bound (inclusive) BinSizeType maxBound() const { return max_; } /// returns the bin with the highest count ValueType maxValue() const { return *(std::max_element(bins_.begin(), bins_.end())); } /// returns the bin with lowest count ValueType minValue() const { return *(std::min_element(bins_.begin(), bins_.end())); } /// returns the bin size BinSizeType binSize() const { return bin_size_; } /// returns the number of bins Size size() const { return bins_.size(); } /** @brief returns the value of bin @p index @exception Exception::IndexOverflow is thrown for invalid indices */ ValueType operator[](Size index) const { if (index >= bins_.size()) { throw Exception::IndexOverflow(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION); } return bins_[index]; } /** @brief returns the center position of the bin with the index @p bin_index @exception Exception::IndexOverflow is thrown for invalid indices */ BinSizeType centerOfBin(Size bin_index) const { if (bin_index >= bins_.size()) { throw Exception::IndexOverflow(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION); } return (BinSizeType)(min_ + ((BinSizeType)bin_index + 0.5) * bin_size_); } /** @brief returns the first value to the right side of the bin with the index @p bin_index, which is not part of this bin, i.e. open right side of the interval. @exception Exception::IndexOverflow is thrown for invalid indices */ BinSizeType rightBorderOfBin(Size bin_index) const { if (bin_index >= bins_.size()) { throw Exception::IndexOverflow(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION); } if (bin_index + 1 == bins_.size()) { // rightmost bin is special. It contains the maximum value - see valueToBin(). return std::nextafter(maxBound(), maxBound() + 1); } return (BinSizeType)(min_ + ((BinSizeType) bin_index + 1) * bin_size_); } /** @brief returns the leftmost value of the bin with the index @p bin_index, which is part of this bin, i.e. closed left side of the interval. @exception Exception::IndexOverflow is thrown for invalid indices */ BinSizeType leftBorderOfBin(Size bin_index) const { if (bin_index >= bins_.size()) { throw Exception::IndexOverflow(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION); } return (BinSizeType)(min_ + (BinSizeType)bin_index * bin_size_); } /** @brief returns the value of bin corresponding to the value @p val @exception Exception::OutOfRange is thrown if the value is out of valid range */ ValueType binValue(BinSizeType val) const { return bins_[valueToBin(val)]; } /** @brief increases the bin corresponding to value @p val by @p increment @return The index of the increased bin. @exception Exception::OutOfRange is thrown if the value is out of valid range */ Size inc(BinSizeType val, ValueType increment = 1) { Size bin_index = this->valueToBin(val); this->bins_[bin_index] += increment; return bin_index; } /** * @brief Increment all bins from to lowest(=first) bin up to (and including?) the bin for @p val by a certain number of counts * @param[in] val The value which determines the highest bin * @param[in] inclusive Is the highest bin included? * @param[in] increment Increase each bin by this value * @return The index of the bin for @p value */ Size incUntil(BinSizeType val, bool inclusive, ValueType increment = 1) { Size bin_index = this->valueToBin(val); for (Size i = 0; i < bin_index; ++i) { this->bins_[i] += increment; } if (inclusive) { this->bins_[bin_index] += increment; } return bin_index; } /** * @brief Increment all bins from the bin of @p val to the highest(=last) bin by a certain number of counts * @param[in] val The value which determines the lowest bin * @param[in] inclusive Is the lowest bin included? * @param[in] increment Increase each bin by this value * @return The index of the bin for @p value */ Size incFrom(BinSizeType val, bool inclusive, ValueType increment = 1) { Size bin_index = this->valueToBin(val); for (Size i = bin_index + 1; i < this->bins_.size(); ++i) { this->bins_[i] += increment; } if (inclusive) { this->bins_[bin_index] += increment; } return bin_index; } template< typename DataIterator > static void getCumulativeHistogram(DataIterator begin, DataIterator end, bool complement, bool inclusive, Histogram< ValueType, BinSizeType > & histogram) { for (DataIterator it = begin; it != end; ++it) { if (complement) { histogram.incUntil(*it, inclusive); } else { histogram.incFrom(*it, inclusive); } } } /** @brief resets the histogram with the given range and bin size @exception Exception::OutOfRange is thrown if @p bin_size negative or zero */ void reset(BinSizeType min, BinSizeType max, BinSizeType bin_size) { min_ = min; max_ = max; bin_size_ = bin_size; bins_.clear(); if (bin_size_ <= 0) { throw Exception::OutOfRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION); } else { // if max_ == min_ there is only one bin if (max_ != min_) { bins_.resize(Size(ceil((max_ - min_) / bin_size_)), 0); } else { bins_.resize(1, 0); } } } /** @name Assignment and equality operators */ //@{ ///Equality operator bool operator==(const Histogram & histogram) const { return min_ == histogram.min_ && max_ == histogram.max_ && bin_size_ == histogram.bin_size_ && bins_ == histogram.bins_; } ///Inequality operator bool operator!=(const Histogram & histogram) const { return !operator==(histogram); } ///Assignment Histogram & operator=(const Histogram & histogram) { if (&histogram == this) return *this; min_ = histogram.min_; max_ = histogram.max_; bin_size_ = histogram.bin_size_; bins_ = histogram.bins_; return *this; } //@} /** @name Iterators */ //@{ /// Non-mutable iterator pointing to the first bin inline ConstIterator begin() const { return bins_.begin(); } /// Non-mutable iterator pointing after the last bin inline ConstIterator end() const { return bins_.end(); } //@} /// Transforms the bin values with f(x)=multiplier*log(x+1) void applyLogTransformation(BinSizeType multiplier) { for (typename std::vector<ValueType>::iterator it = bins_.begin(); it != bins_.end(); ++it) { *it = (ValueType)(multiplier * log((BinSizeType)(*it + 1.0f))); } } /** @brief Returns the bin index a given value belongs to @exception Exception::OutOfRange is thrown if the value is out of valid range [min, max] */ Size valueToBin(BinSizeType val) const { //std::cout << "val: " << val << " (min: " << min_ << " max: " << max_ << ")" << std::endl; if (val < min_ || val > max_) { throw Exception::OutOfRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION); } if (val == max_) { return Size(bins_.size() - 1); } else { return (Size) floor((val - min_) / bin_size_); } } protected: /// Lower bound BinSizeType min_; /// Upper bound BinSizeType max_; /// Bin size BinSizeType bin_size_; /// Vector of bins std::vector<ValueType> bins_; /// initialize the bins void initBins_() { if (this->bin_size_ <= 0) { throw Exception::OutOfRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION); } else { if (this->max_ != this->min_) { this->bins_ = std::vector<ValueType>(Size(ceil((max_ - min_) / bin_size_)), 0); } else { // if max_ == min_ there is only one bin this->bins_ = std::vector<ValueType>(1, 0); } } } }; ///Print the contents to a stream. template <typename ValueType, typename BinSizeType> std::ostream & operator<<(std::ostream & os, const Histogram<ValueType, BinSizeType> & hist) { for (Size i = 0; i < hist.size(); ++i) { os << hist.centerOfBin(i) << "\t"<< hist[i] << std::endl; } return os; } } // namespace Math } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/MATH/STATISTICS/BasicStatistics.h
.h
9,005
293
// 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 <vector> #include <ostream> #include <cmath> #include <numeric> namespace OpenMS { namespace Math { /** @brief Calculates some basic statistical parameters of a distribution: sum, mean, variance, and provides the normal approximation. The intended usage is as follows: - <i>create</i> an instance - <i>set</i> the basic statistical parameters by either - calling one of the update() member functions, or - using the set... methods . - <i>do</i> something with the basic statistical parameters, e.g. - using the get... methods, or - obtain samples from a normal approximation with these parameters - whatever member function you might want to add to this class ;-) . @ingroup Math */ template <typename RealT = double> class BasicStatistics { public: /// The real type specified as template argument. typedef RealT RealType; typedef std::vector<RealType> probability_container; typedef std::vector<RealType> coordinate_container; /// Default constructor. BasicStatistics() : mean_(0), variance_(0), sum_(0) {} /// Copy constructor. BasicStatistics(BasicStatistics const & arg) : mean_(arg.mean_), variance_(arg.variance_), sum_(arg.sum_) {} /// Assignment. BasicStatistics & operator=(BasicStatistics const & arg) { mean_ = arg.mean_; variance_ = arg.variance_; sum_ = arg.sum_; return *this; } /// Set sum, mean, and variance to zero. void clear() { mean_ = 0; variance_ = 0; sum_ = 0; } /// This does the actual calculation. /** You can call this as often as you like, using different input vectors. */ template <typename ProbabilityIterator> void update(ProbabilityIterator probability_begin, ProbabilityIterator const probability_end ) { clear(); unsigned pos = 0; ProbabilityIterator iter = probability_begin; for (; iter != probability_end; ++iter, ++pos) { sum_ += *iter; mean_ += *iter * pos; } mean_ /= sum_; for (iter = probability_begin, pos = 0; iter != probability_end; ++iter, ++pos) { RealType diff = RealType(pos) - mean_; diff *= diff; variance_ += *iter * diff; } variance_ /= sum_; if (sum_ == 0 && (std::isnan(mean_) || std::isinf(mean_)) ) { mean_ = 0; variance_ = 0; } } /// This does the actual calculation. /** You can call this as often as you like, using different input vectors. */ template <typename ProbabilityIterator, typename CoordinateIterator> void update(ProbabilityIterator const probability_begin, ProbabilityIterator const probability_end, CoordinateIterator const coordinate_begin ) { clear(); ProbabilityIterator prob_iter = probability_begin; CoordinateIterator coord_iter = coordinate_begin; for (; prob_iter != probability_end; ++prob_iter, ++coord_iter) { sum_ += *prob_iter; mean_ += *prob_iter * *coord_iter; } mean_ /= sum_; for (prob_iter = probability_begin, coord_iter = coordinate_begin; prob_iter != probability_end; ++prob_iter, ++coord_iter ) { RealType diff = *coord_iter - mean_; diff *= diff; variance_ += *prob_iter * diff; } variance_ /= sum_; return; } /// Returns the mean. RealType mean() const { return mean_; } void setMean(RealType const & mean) { mean_ = mean; } /// Returns the variance. RealType variance() const { return variance_; } void setVariance(RealType const & variance) { variance_ = variance; } /// Returns the sum. RealType sum() const { return sum_; } void setSum(RealType const & sum) { sum_ = sum; } /**@brief Returns the density of the normal approximation at point, multiplied by sqrt( 2 * pi ). This saves a division operation compared to normalDensity() */ RealType normalDensity_sqrt2pi(RealType coordinate) const { coordinate -= mean(); coordinate *= coordinate; return exp(-coordinate / RealType(2) / variance()); } /// Returns sqrt( 2 * pi ), which is useful to normalize the result of normalDensity_sqrt2pi(). static RealType sqrt2pi() { return 2.50662827463100050240; } /**@brief See normalDensity_sqrt2pi(). Returns the density of the normal distribution at point. */ inline RealType normalDensity(RealType const coordinate) const { return normalDensity_sqrt2pi(coordinate) / sqrt2pi(); } /**@brief The argument \c probability is filled with values according to the normal approximation. Its \c size() is not changed. The approximation takes place at coordinate positions 0, 1, ..., size()-1. */ void normalApproximation(probability_container & probability) { normalApproximationHelper_(probability, probability.size()); return; } /** The argument \c probability is filled with values according to the normal approximation. Its size() is set to \c size. The approximation takes place at coordinate positions 0, 1, ..., size-1. */ void normalApproximation(probability_container & probability, typename probability_container::size_type const size ) { probability.resize(size); normalApproximationHelper_(probability, size); return; } /**@brief The argument probability is filled with values according to the normal approximation. The second argument coordinate contains the positions where the approximation takes place. probability.size() is set to coordinate.size(). */ void normalApproximation(probability_container & probability, coordinate_container const & coordinate ) { probability.resize(coordinate.size()); normalApproximationHelper_(probability, coordinate); return; } /**@brief A convenient overload for debugging purposes. @relatesalso BasicStatistics */ friend std::ostream & operator<<(std::ostream & os, BasicStatistics & arg) { os << "BasicStatistics: mean=" << arg.mean() << " variance=" << arg.variance() << " sum=" << arg.sum(); return os; } protected: /// @name Protected Members //@{ RealType mean_; RealType variance_; RealType sum_; private: //@} /// @name Private Methods //@{ void normalApproximationHelper_(probability_container & probability, typename probability_container::size_type const size ) { RealType gaussSum = 0; typename coordinate_container::size_type i; // precondition size == probability.size() is guaranteed by wrappers. for (i = 0; i < size; ++i) { gaussSum += normalDensity_sqrt2pi(RealType(i)); } for (i = 0; i < size; ++i) { probability[i] = normalDensity_sqrt2pi(RealType(i)) / gaussSum * sum(); } return; } void normalApproximationHelper_(probability_container & probability, coordinate_container const & coordinate ) { RealType gaussSum = 0; typename coordinate_container::size_type i; typename coordinate_container::size_type const size = coordinate.size(); for (i = 0; i < size; ++i) { gaussSum += normalDensity_sqrt2pi(coordinate[i]); } for (i = 0; i < size; ++i) { probability[i] = normalDensity_sqrt2pi(coordinate[i]) / gaussSum * sum(); } return; } //@} }; } // namespace Math } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/MATH/STATISTICS/GumbelDistributionFitter.h
.h
2,861
96
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: $ // -------------------------------------------------------------------------- // #pragma once #include <OpenMS/DATASTRUCTURES/String.h> #include <OpenMS/DATASTRUCTURES/DPosition.h> #include <vector> namespace OpenMS { namespace Math { /** @brief Implements a fitter for the Gumbel distribution. This class fits a Gumbel distribution to a number of data points. The results as well as the initial guess are specified using the struct GumbelDistributionFitResult. The formula with the fitted parameters can be transformed into a gnuplot formula using getGnuplotFormula() after fitting. @ingroup Math */ class OPENMS_DLLAPI GumbelDistributionFitter { public: /// struct to represent the parameters of a gumbel distribution struct GumbelDistributionFitResult { GumbelDistributionFitResult(double local_a = 1.0, double local_b = 2.0) : a(local_a), b(local_b) { } /// location parameter a double a; /// scale parameter b double b; double eval(double x) const; double log_eval_no_normalize(double x) const ; }; /// Default constructor GumbelDistributionFitter(); /// Destructor virtual ~GumbelDistributionFitter(); /// sets the gumbel distribution start parameters a and b for the fitting void setInitialParameters(const GumbelDistributionFitResult & result); /** @brief Fits a gumbel distribution to the given data points @param[in,out] points Input parameter which represents the point used for the fitting @exception Exception::UnableToFit is thrown if fitting cannot be performed */ GumbelDistributionFitResult fit(std::vector<DPosition<2> > & points) const; /** @brief Fits a gumbel distribution to the given data x values. Fills a weighted histogram first and generates y values. @param[in] x Input x values @param[in] w Input weights @exception Exception::UnableToFit is thrown if fitting cannot be performed */ GumbelDistributionFitResult fitWeighted(const std::vector<double> & x, const std::vector<double> & w); protected: GumbelDistributionFitResult init_param_; private: /// Copy constructor (not implemented) GumbelDistributionFitter(const GumbelDistributionFitter & rhs); /// assignment operator (not implemented) GumbelDistributionFitter & operator=(const GumbelDistributionFitter & rhs); }; } }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/MATH/STATISTICS/GammaDistributionFitter.h
.h
2,474
86
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Andreas Bertsch $ // -------------------------------------------------------------------------- // #pragma once #include <OpenMS/DATASTRUCTURES/String.h> #include <OpenMS/DATASTRUCTURES/DPosition.h> #include <vector> namespace OpenMS { namespace Math { /** @brief Implements a fitter for the Gamma distribution. This class fits a Gamma distribution to a number of data points. The results as well as the initial guess are specified using the struct GammaDistributionFitResult. @note We actually fit a slightly customized version of the gamma distribution that is 0.0 if the parameters b or p are <= 0.0. With this modification we can still use an unconstrained optimization algorithm. @ingroup Math */ class OPENMS_DLLAPI GammaDistributionFitter { public: /// struct to represent the parameters of a gamma distribution struct GammaDistributionFitResult { public: GammaDistributionFitResult(double bIn, double pIn) : b(bIn), p(pIn) { } /// parameter b of the gamma distribution double b; /// parameter p of the gamma distribution double p; }; /// Default constructor GammaDistributionFitter(); /// Destructor virtual ~GammaDistributionFitter(); /// sets the gamma distribution start parameters b and p for the fitting void setInitialParameters(const GammaDistributionFitResult& result); /** @brief Fits a gamma distribution to the given data points @param[in] points Input parameter which represents the point used for the fitting @exception Exception::UnableToFit is thrown if fitting cannot be performed */ GammaDistributionFitResult fit(const std::vector<DPosition<2> >& points) const; protected: GammaDistributionFitResult init_param_; private: /// Copy constructor (not implemented to prevent usage) GammaDistributionFitter(const GammaDistributionFitter& rhs); /// assignment operator (not implemented to prevent usage) GammaDistributionFitter& operator=(const GammaDistributionFitter& rhs); }; } }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/MATH/STATISTICS/GaussFitter.h
.h
3,846
121
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow $ // $Authors: Andreas Bertsch, Chris Bielow $ // -------------------------------------------------------------------------- // #pragma once #include <OpenMS/DATASTRUCTURES/String.h> #include <OpenMS/DATASTRUCTURES/DPosition.h> #include <OpenMS/CONCEPT/Constants.h> #include <cmath> #include <vector> namespace OpenMS { namespace Math { /** @brief Implements a fitter for Gaussian functions This class fits a Gaussian distribution to a number of data points. The results as well as the initial guess are specified using the struct GaussFitResult. The complete Gaussian formula with the fitted parameters can be transformed into a gnuplot formula using getGnuplotFormula after fitting. @ingroup Math */ class OPENMS_DLLAPI GaussFitter { public: /// struct of parameters of a Gaussian distribution struct OPENMS_DLLAPI GaussFitResult { public: GaussFitResult() : A(-1.0), x0(-1.0), sigma(-1.0) {} GaussFitResult(double a, double x, double s) : A(a), x0(x), sigma(s) {} /// parameter A of Gaussian distribution (amplitude) double A; /// parameter x0 of Gaussian distribution (center position) double x0; /// parameter sigma of Gaussian distribution (width) double sigma; /** @brief Evaluate the current density Gaussian model at the specified point. Returns the intensities (i.e. probabilities scaled by the factor 'A') of the PDF at the given positions. This function can be called with any set of parameters, e.g. the initial parameters (to get a 'before-fit' status), or after fitting. */ double eval(double x) const; /** @brief Evaluate the current log density of the Gaussian model at the specified point. Returns the intensities (i.e. probabilities scaled by the factor 'A') of the PDF at the given positions. This function can be called with any set of parameters, e.g. the initial parameters (to get a 'before-fit' status), or after fitting. */ double log_eval_no_normalize(double x) const; private: double halflogtwopi = 0.5*log(2.0*Constants::PI); }; /// Constructor GaussFitter(); /// Destructor virtual ~GaussFitter(); /// sets the initial parameters used by the fit method as initial guess for the Gaussian void setInitialParameters(const GaussFitResult& result); /** @brief Fits a Gaussian distribution to the given data points @param[in,out] points the data points used for the Gaussian fitting @exception Exception::UnableToFit is thrown if fitting cannot be performed */ GaussFitResult fit(std::vector<DPosition<2> > & points) const; /** @brief Evaluate the current Gaussian model at the specified points. Returns the intensities (i.e. probabilities scaled by the factor 'A') of the PDF at the given positions. This function can be called with any set of parameters, e.g. the initial parameters (to get a 'before-fit' status), or after fitting. */ static std::vector<double> eval(const std::vector<double>& evaluation_points, const GaussFitResult& model); protected: GaussFitResult init_param_; private: /// Copy constructor (not implemented) GaussFitter(const GaussFitter & rhs); /// Assignment operator (not implemented) GaussFitter & operator=(const GaussFitter & rhs); }; } }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/DATASTRUCTURES/StringView.h
.h
2,497
103
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg$ // $Authors: Marc Sturm $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/OpenMSConfig.h> #include <OpenMS/DATASTRUCTURES/String.h> #include <algorithm> // for "min" #include <string> #include <cstring> #include <vector> class QString; namespace OpenMS { /** * Minimal replacement for boost::string_ref or std::experimental::string_view until we increase our min boost version * @brief StringView provides a non-owning view on an existing string. */ class OPENMS_DLLAPI StringView { public: // create view on string StringView() = default; // construct from other view StringView(const StringView&) = default; // copy assignment StringView& operator=(const StringView&) = default; // create view on string StringView(const std::string& s) : begin_(s.data()), size_(s.size()) { } /// less operator bool operator<(const StringView other) const { if (size_ < other.size_) return true; if (size_ > other.size_) return false; // same size // same sequence, if both Views point to the same start if (begin_ == other.begin_) return false; return strncmp(begin_, other.begin_, size_) < 0; } bool operator==(const StringView other) const { if (size_ != other.size_) return false; //same size // same sequence, if both Views point to the same start if (begin_ == other.begin_) return true; return strncmp(begin_, other.begin_, size_) == 0; } /// create view that references a substring of the original string inline StringView substr(Size start, Size length) const { if (!size_) return *this; StringView sv(*this); sv.begin_ = begin_ + start; sv.size_ = std::min(length, sv.size_ - start); return sv; } /// size of view inline Size size() const { return size_; } /// create String object from view inline String getString() const { if (!size_) return String(); return String(begin_, begin_ + size_); } private: const char* begin_; Size size_; }; } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/DATASTRUCTURES/ChargePair.h
.h
4,547
155
// 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/CONCEPT/HashUtils.h> #include <OpenMS/DATASTRUCTURES/Compomer.h> #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/OpenMSConfig.h> #include <functional> #include <iosfwd> #include <vector> namespace OpenMS { /** @brief Representation of a (putative) link between two Features, which stem from the same compound but have different charge (including different adduct ions (H+, Na+, ..) A ChargePair represents an edge between two Features and specifies their respective charge and adducts, so that when decharged they can be explained as stemming from the same compound. @ingroup Datastructures */ class OPENMS_DLLAPI ChargePair { public: ///@name Constructors and destructor //@{ /// Default constructor ChargePair(); /// Constructor from map index, element index and Feature ChargePair(const Size& index0, const Size& index1, const Int& charge0, const Int& charge1, const Compomer& compomer, const double& mass_diff, const bool active); /// Copy constructor ChargePair(const ChargePair& rhs); /// Assignment operator ChargePair& operator=(const ChargePair& rhs); /// Destructor virtual ~ChargePair() = default; //@} //@name Accessors //@{ /// Returns the charge (for element 0 or 1) Int getCharge(UInt pairID) const; /// Set the charge (for element 0 or 1) void setCharge(UInt pairID, Int e); /// Returns the element index (for element 0 or 1) Size getElementIndex(UInt pairID) const; /// Set the element index (for element 0 or 1) void setElementIndex(UInt pairID, Size e); /// Returns the Id of the compomer that explains the mass difference const Compomer& getCompomer() const; /// Set the compomer id void setCompomer(const Compomer& compomer); /// Returns the mass difference double getMassDiff() const; /// Sets the mass difference void setMassDiff(double mass_diff); /// Returns the ILP edge score double getEdgeScore() const; /// Sets the ILP edge score void setEdgeScore(double score); /// is this pair realized? bool isActive() const; void setActive(const bool active); //@} /// Equality operator virtual bool operator==(const ChargePair& i) const; /// Equality operator virtual bool operator!=(const ChargePair& i) const; protected: /// Int of the first element within the FeatureMap Size feature0_index_; /// Int of the second element within the FeatureMap Size feature1_index_; /// Assumed charge of the first feature Int feature0_charge_; /// Assumed charge of the second feature Int feature1_charge_; /// Compomer that explains the mass difference Compomer compomer_; /// mass difference (after explanation by compomer) double mass_diff_; /// Score of this edge used in ILP double score_; /// was this pair realized by ILP? bool is_active_; }; ///Print the contents of a ChargePair to a stream. OPENMS_DLLAPI std::ostream& operator<<(std::ostream& os, const ChargePair& cons); } // namespace OpenMS // Hash function specialization for ChargePair // Note: Only hash fields used in operator== (feature0_index_, feature1_index_, // feature0_charge_, feature1_charge_, compomer_, mass_diff_, is_active_) // Do NOT hash score_ as it is not compared in operator== namespace std { template<> struct hash<OpenMS::ChargePair> { std::size_t operator()(const OpenMS::ChargePair& cp) const noexcept { std::size_t seed = OpenMS::hash_int(cp.getElementIndex(0)); OpenMS::hash_combine(seed, OpenMS::hash_int(cp.getElementIndex(1))); OpenMS::hash_combine(seed, OpenMS::hash_int(cp.getCharge(0))); OpenMS::hash_combine(seed, OpenMS::hash_int(cp.getCharge(1))); OpenMS::hash_combine(seed, std::hash<OpenMS::Compomer>{}(cp.getCompomer())); OpenMS::hash_combine(seed, OpenMS::hash_float(cp.getMassDiff())); OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(cp.isActive()))); return seed; } }; } // namespace std
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/DATASTRUCTURES/DefaultParamHandler.h
.h
7,314
182
// 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/Param.h> #include <OpenMS/DATASTRUCTURES/String.h> #include <OpenMS/OpenMSConfig.h> #include <vector> namespace OpenMS { class MetaInfoInterface; /** @brief A base class for all classes handling default parameters. This class facilitates the handling of parameters: - it manages default parameter (defaults_) - it checks for valid parameters: - unknown/misspelled parameter names - correct parameter type - range restrictions of numeric parameters - valid values for string parameters (enum) - subsections that are passed to other classes can be excluded from the check (subsections_) - it keeps member variables in synchronicity with the parameters stored in param_ - it helps to automatically create a doxygen documentation page for the parameters Extra member variables are needed if getting the value from param_ would be too slow e.g. when they are used in methods that are called very often. No matter if you have extra variables or not, do the following: - Set defaults_ and subsections_ in the derived classes' default constructor. - Make sure to set the 'advanced' flag of the parameters right in order to hide certain parameters from inexperienced users. - Set the range restrictions for numeric defaults and valid strings for string defaults (if possible) - Call defaultsToParam_() at the end of derived classes' default constructor. It copies the defaults to param_ (and calls updateMembers_()). If you have extra member variables you need to synchronize with param_, do the following: - Implement the updateMembers_() method. It is used after each change of param_ in order to update the extra member variables. If the base class is a DefaultParamHandler as well make sure to call the updateMembers_() method of the base class in the updateMembers_() method. - Call updateMembers_() at the end of the derived classes' copy constructor and assignment operator. - If you need mutable access to the extra member variables, provide a set-method and make sure to set the corresponding value in param_ as well! @b Base @b classes: @n If you create a class @a A that is derived from DefaultParamHandler and derive another class @a B for @a A, you should set use the setName(String) method to set the name used for error messages to @a B. @b Parameter @b documentation: @n Each default parameter has to be documented in a comprehensive way. This is done using the Param::setValue methods and the Param::setDescription method. @b Flags: @n Flags (boolean parameters) are not supported directly. It's best to implement them as a string parameter with valid strings 'true' and 'false'. @ingroup Datastructures */ class OPENMS_DLLAPI DefaultParamHandler { public: /// Constructor with name that is displayed in error messages DefaultParamHandler(const String& name); /// Copy constructor DefaultParamHandler(const DefaultParamHandler& rhs); /// Destructor virtual ~DefaultParamHandler(); /// Assignment operator. DefaultParamHandler& operator=(const DefaultParamHandler& rhs); /// Equality operator virtual bool operator==(const DefaultParamHandler& rhs) const; /** @brief Sets the parameters. Before setting the parameters, missing parameters are filled up with default values. @n Then the parameters are checked for unknown parameters (warning) and violations of restrictions (exception) with the @ref Param::checkDefaults() method. @exception Exception::InvalidParameter is thrown if errors occur during the check. */ void setParameters(const Param& param); /// Non-mutable access to the parameters const Param& getParameters() const; /// Non-mutable access to the default parameters const Param& getDefaults() const; /// Non-mutable access to the name const String& getName() const; /// Mutable access to the name void setName(const String& name); /// Non-mutable access to the registered subsections const std::vector<String>& getSubsections() const; /** * @brief Writes all parameters to meta values * * Parameters are written with 'name' as key and 'value' as value * * @param[in] write_this Params to be written * @param[in,out] write_here a MetaInfoInterface object into which the meta values will be written * @param[in] key_prefix Will be added in front of the parameter name for the meta value key. * If the prefix isn't empty and doesn't end with a colon one will be added. */ static void writeParametersToMetaValues(const Param& write_this, MetaInfoInterface& write_here, const String& key_prefix = ""); protected: /** @brief This method is used to update extra member variables at the end of the setParameters() method. Also call it at the end of the derived classes' copy constructor and assignment operator. The default implementation is empty. */ virtual void updateMembers_(); /** @brief Updates the parameters after the defaults have been set in the constructor Also calls updateMembers_(). */ void defaultsToParam_(); /// Container for current parameters Param param_; /** @brief Container for default parameters. This member should be filled in the constructor of derived classes! @note call the defaultsToParam_() method at the end of the constructor in order to copy the defaults to param_. */ Param defaults_; /** @brief Container for registered subsections. This member should be filled in the constructor of derived classes! @note Do not add a ':' character at the end of subsections. */ std::vector<String> subsections_; /// Name that is displayed in error messages during the parameter checking String error_name_; /** @brief If this member is set to false no checking if parameters in done; The only reason to set this member to false is that the derived class has no parameters! However, if a grand-child has defaults and you are using a base class cast, checking will not be done when casting back to grand-child. To just omit the warning, use 'warn_empty_defaults_' */ bool check_defaults_; /** @brief If this member is set to false no warning is emitted when defaults are empty; The only reason to set this member to false is that the derived class has no parameters! @see check_defaults_ */ bool warn_empty_defaults_; private: /// Hidden default C'tor (class name parameter is required!) DefaultParamHandler(); }; // class } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/DATASTRUCTURES/MatrixEigen.h
.h
4,516
133
// 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 // NOTE: This is an INTERNAL header file and should NOT be included in public headers. // It provides Eigen-based utilities for internal OpenMS algorithms. // Users of the public API should use Matrix.h directly. #include <OpenMS/DATASTRUCTURES/Matrix.h> #include <Eigen/Core> namespace OpenMS { /// Type alias for Eigen dynamic matrix (internal use only) template <typename Value> using EigenMatrixType = Eigen::Matrix<Value, Eigen::Dynamic, Eigen::Dynamic>; /// Type alias for Eigen dynamic column vector (internal use only) template <typename Value> using EigenVectorType = Eigen::Matrix<Value, Eigen::Dynamic, 1>; /// Type alias for Eigen dynamic row vector (internal use only) template <typename Value> using EigenRowVectorType = Eigen::Matrix<Value, 1, Eigen::Dynamic>; /** * @brief Create a mutable Eigen::Map view of an OpenMS Matrix. * * Zero-copy: the returned Map operates directly on the Matrix's buffer. * The Matrix must outlive the returned Map. * * @param mat The matrix to view * @return Eigen::Map providing full Eigen matrix operations * * @note Internal use only. This function requires Eigen headers. */ template <typename Value> Eigen::Map<EigenMatrixType<Value>> eigenView(Matrix<Value>& mat) { return Eigen::Map<EigenMatrixType<Value>>(mat.data(), mat.rows(), mat.cols()); } /** * @brief Create a const Eigen::Map view of an OpenMS Matrix. * * Zero-copy: the returned Map operates directly on the Matrix's buffer. * The Matrix must outlive the returned Map. * * @param mat The matrix to view * @return Const Eigen::Map for read-only Eigen operations */ template <typename Value> Eigen::Map<const EigenMatrixType<Value>> eigenView(const Matrix<Value>& mat) { return Eigen::Map<const EigenMatrixType<Value>>(mat.data(), mat.rows(), mat.cols()); } /** * @brief Create an Eigen::Map view of a std::vector as a column vector. * * Zero-copy: the returned Map operates directly on the vector's buffer. * * @param vec The vector to view * @return Eigen::Map treating the vector as a column vector */ template <typename Value> Eigen::Map<EigenVectorType<Value>> eigenVectorView(std::vector<Value>& vec) { return Eigen::Map<EigenVectorType<Value>>(vec.data(), vec.size()); } /** * @brief Create a const Eigen::Map view of a std::vector as a column vector. */ template <typename Value> Eigen::Map<const EigenVectorType<Value>> eigenVectorView(const std::vector<Value>& vec) { return Eigen::Map<const EigenVectorType<Value>>(vec.data(), vec.size()); } /** * @brief Create an Eigen::Map view of a raw pointer + size as column vector. * * @param data Pointer to the first element * @param size Number of elements * @return Eigen::Map treating the data as a column vector */ template <typename Value> Eigen::Map<EigenVectorType<Value>> eigenVectorView(Value* data, size_t size) { return Eigen::Map<EigenVectorType<Value>>(data, size); } /** * @brief Create a const Eigen::Map view of a raw pointer + size as column vector. */ template <typename Value> Eigen::Map<const EigenVectorType<Value>> eigenVectorView(const Value* data, size_t size) { return Eigen::Map<const EigenVectorType<Value>>(data, size); } /** * @brief Create an Eigen::Map view of a raw pointer + dimensions as a matrix. * * @param data Pointer to the first element (column-major storage) * @param rows Number of rows * @param cols Number of columns * @return Eigen::Map treating the data as a matrix */ template <typename Value> Eigen::Map<EigenMatrixType<Value>> eigenMatrixView(Value* data, size_t rows, size_t cols) { return Eigen::Map<EigenMatrixType<Value>>(data, rows, cols); } /** * @brief Create a const Eigen::Map view of a raw pointer + dimensions as a matrix. */ template <typename Value> Eigen::Map<const EigenMatrixType<Value>> eigenMatrixView(const Value* data, size_t rows, size_t cols) { return Eigen::Map<const EigenMatrixType<Value>>(data, rows, cols); } } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/DATASTRUCTURES/MassExplainer.h
.h
7,603
224
// 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/Adduct.h> #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/DATASTRUCTURES/String.h> #include <OpenMS/OpenMSConfig.h> namespace OpenMS { class Compomer; /** @brief Computes empirical formulas for given mass differences using a set of allowed elements MassExplainer is used to explain observed mass differences between features by determining the most likely combination of adducts that could cause such differences. The class works by: 1. Taking a set of allowed adducts (elements, molecules, or ions) 2. Computing all possible combinations of these adducts that could explain observed mass differences 3. Providing a query interface to search for explanations for specific mass differences This is particularly useful in mass spectrometry data analysis for identifying related features that represent the same analyte but with different adducts or charge states. @ingroup Datastructures */ class OPENMS_DLLAPI MassExplainer { public: /// Type definition for a vector of Adduct objects typedef Adduct::AdductsType AdductsType; /// Type definition for an iterator over Compomer objects typedef std::vector<Compomer>::const_iterator CompomerIterator; ///@name Constructors and destructor //@{ /** @brief Default constructor Initializes with default parameters: - No adducts - Charge range from -2 to +4 - Maximum charge span of 4 - Log probability threshold of -5.0 - Maximum number of neutral adducts of 2 */ MassExplainer(); /** @brief Constructor with custom adduct base @param[in] adduct_base Set of allowed adducts to use for mass difference explanations */ MassExplainer(AdductsType adduct_base); /** @brief Constructor with custom charge parameters @param[in] q_min Minimum charge state to consider @param[in] q_max Maximum charge state to consider @param[in] max_span Maximum allowed charge span between related features @param[in] thresh_logp Minimum log probability threshold for accepting explanations */ MassExplainer(Int q_min, Int q_max, Int max_span, double thresh_logp); /** @brief Constructor with all custom parameters @param[in] adduct_base Set of allowed adducts to use for mass difference explanations @param[in] q_min Minimum charge state to consider @param[in] q_max Maximum charge state to consider @param[in] max_span Maximum allowed charge span between related features @param[in] thresh_logp Minimum log probability threshold for accepting explanations @param[in] max_neutrals Maximum number of neutral adducts allowed in an explanation */ MassExplainer(AdductsType adduct_base, Int q_min, Int q_max, Int max_span, double thresh_logp, Size max_neutrals); private: /** @brief Check consistency of input parameters and initialize internal data structures This method validates the input parameters and sets default values where needed. @param[in] init_thresh_p Whether to initialize the probability threshold with default value (set to "false" to keep current value) */ void init_(bool init_thresh_p); public: /** @brief Assignment operator @param[in] rhs Source object to assign from @return Reference to this object */ MassExplainer& operator=(const MassExplainer& rhs); /// Destructor virtual ~MassExplainer(); //@} /** @brief Compute all possible mass differences and their explanations This method generates all possible combinations of adducts from the adduct base and stores them internally for later querying. This must be called after changing any parameters and before performing queries. */ void compute(); //@name Accessors //@{ /** @brief Set the base set of allowed adducts @param[in] adduct_base Vector of adducts to use for explanations */ void setAdductBase(AdductsType adduct_base); /** @brief Get the current set of allowed adducts @return Vector of adducts currently used for explanations */ AdductsType getAdductBase() const; /** @brief Get a specific compomer by its ID This is typically used after a query() to retrieve detailed information about a specific explanation. @param[in] id ID of the compomer to retrieve @return Reference to the requested compomer */ const Compomer& getCompomerById(Size id) const; //@} /** @brief Search for explanations of a given mass difference This method searches the precomputed explanations for those that match the given mass difference within the specified tolerance and have the required net charge. @param[in] net_charge Net charge of the compomer being sought @param[in] mass_to_explain Mass difference in Da that needs explanation @param[in] mass_delta Allowed deviation from exact mass (tolerance) @param[in] thresh_log_p Minimum log probability required for explanations @param[out] firstExplanation Output iterator to the beginning of matching explanations @param[out] lastExplanation Output iterator to the end of matching explanations @return Number of explanations found, or negative value if no explanations found */ SignedSize query(const Int net_charge, const float mass_to_explain, const float mass_delta, const float thresh_log_p, std::vector<Compomer>::const_iterator& firstExplanation, std::vector<Compomer>::const_iterator& lastExplanation) const; protected: /** @brief Check if a generated compomer is valid based on its probability, charges, etc. @param[in] cmp The compomer to validate @return True if the compomer is valid, false otherwise */ bool compomerValid_(const Compomer& cmp) const; /** @brief Create a proper adduct from formula, charge, and probability @param[in] formula Chemical formula of the adduct @param[in] charge Charge of the adduct @param[in] p Probability of the adduct @return Adduct object with the specified properties */ Adduct createAdduct_(const String& formula, const Int charge, const double p) const; /// Vector storing all possible explanations for mass differences std::vector<Compomer> explanations_; /// Set of allowed adducts that can be combined to explain mass differences AdductsType adduct_base_; /// Minimum charge state to consider in explanations Int q_min_; /// Maximum charge state to consider in explanations Int q_max_; /// Maximum allowed charge span between related features (e.g., a cluster with q={3,6} has span=4) Int max_span_; /// Minimum required probability threshold for accepting explanations double thresh_p_; /// Maximum number of neutral (q=0) adducts allowed in an explanation Size max_neutrals_; }; } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/DATASTRUCTURES/KDTree.h
.h
64,453
2,209
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Johannes Veit $ // $Authors: Johannes Veit $ // -------------------------------------------------------------------------- /* Note: This file contains a concatenation of the 6 header files comprising * libkdtree++ (node.hpp, function.hpp, allocator.hpp, iterator.hpp, * region.hpp, kdtree.hpp). * * Johannes Veit (2016) */ /* COPYRIGHT -- * * This file is part of libkdtree++, a C++ template KD-Tree sorting container. * libkdtree++ is (c) 2004-2007 Martin F. Krafft <libkdtree@pobox.madduck.net> * and Sylvain Bougerel <sylvain.bougerel.devel@gmail.com> distributed under the * terms of the Artistic License 2.0. See the ./COPYING file in the source tree * root for more information. * * THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /** \file * Defines interfaces for nodes as used by the KDTree class. * * \author Martin F. Krafft <libkdtree@pobox.madduck.net> */ #ifndef OPENMS_DATASTRUCTURES_KDTREE_H #define OPENMS_DATASTRUCTURES_KDTREE_H #ifdef KDTREE_DEFINE_OSTREAM_OPERATORS # include <ostream> #endif #include <cstddef> #include <cmath> #include <memory> namespace KDTree { struct _Node_base { typedef _Node_base* _Base_ptr; typedef _Node_base const* _Base_const_ptr; _Base_ptr _M_parent; _Base_ptr _M_left; _Base_ptr _M_right; _Node_base(_Base_ptr const __PARENT = nullptr, _Base_ptr const __LEFT = nullptr, _Base_ptr const __RIGHT = nullptr) : _M_parent(__PARENT), _M_left(__LEFT), _M_right(__RIGHT) {} static _Base_ptr _S_minimum(_Base_ptr __x) { while (__x->_M_left) __x = __x->_M_left; return __x; } static _Base_ptr _S_maximum(_Base_ptr __x) { while (__x->_M_right) __x = __x->_M_right; return __x; } }; template <typename _Val> struct _Node : public _Node_base { using _Node_base::_Base_ptr; typedef _Node* _Link_type; _Val _M_value; _Node(_Val const& __VALUE = _Val(), _Base_ptr const __PARENT = nullptr, _Base_ptr const __LEFT = nullptr, _Base_ptr const __RIGHT = nullptr) : _Node_base(__PARENT, __LEFT, __RIGHT), _M_value(__VALUE) {} #ifdef KDTREE_DEFINE_OSTREAM_OPERATORS template <typename Char, typename Traits> friend std::basic_ostream<Char, Traits>& operator<<(typename std::basic_ostream<Char, Traits>& out, _Node_base const& node) { out << &node; out << " parent: " << node._M_parent; out << "; left: " << node._M_left; out << "; right: " << node._M_right; return out; } template <typename Char, typename Traits> friend std::basic_ostream<Char, Traits>& operator<<(typename std::basic_ostream<Char, Traits>& out, _Node<_Val> const& node) { out << &node; out << ' ' << node._M_value; out << "; parent: " << node._M_parent; out << "; left: " << node._M_left; out << "; right: " << node._M_right; return out; } #endif }; template <typename _Val, typename _Acc, typename _Cmp> class _Node_compare { public: _Node_compare(size_t const __DIM, _Acc const& acc, _Cmp const& cmp) : _M_DIM(__DIM), _M_acc(acc), _M_cmp(cmp) {} bool operator()(_Val const& __A, _Val const& __B) const { return _M_cmp(_M_acc(__A, _M_DIM), _M_acc(__B, _M_DIM)); } private: size_t _M_DIM; // don't make this const so that an assignment operator can be auto-generated _Acc _M_acc; _Cmp _M_cmp; }; /*! Compare two values on the same dimension using a comparison functor _Cmp and an accessor _Acc. The comparison functor and the accessor are references to the template parameters of the KDTree. */ template <typename _ValA, typename _ValB, typename _Cmp, typename _Acc> inline bool _S_node_compare (const size_t __dim, const _Cmp& __cmp, const _Acc& __acc, const _ValA& __a, const _ValB& __b) { return __cmp(__acc(__a, __dim), __acc(__b, __dim)); } /*! Compute the distance between two values for one dimension only. The distance functor and the accessor are references to the template parameters of the KDTree. */ template <typename _ValA, typename _ValB, typename _Dist, typename _Acc> inline typename _Dist::distance_type _S_node_distance (const size_t __dim, const _Dist& __dist, const _Acc& __acc, const _ValA& __a, const _ValB& __b) { return __dist(__acc(__a, __dim), __acc(__b, __dim)); } /*! Compute the distance between two values and accumulate the result for all dimensions. The distance functor and the accessor are references to the template parameters of the KDTree. */ template <typename _ValA, typename _ValB, typename _Dist, typename _Acc> inline typename _Dist::distance_type _S_accumulate_node_distance (const size_t __dim, const _Dist& __dist, const _Acc& __acc, const _ValA& __a, const _ValB& __b) { typename _Dist::distance_type d = 0; for (size_t i=0; i<__dim; ++i) d += __dist(__acc(__a, i), __acc(__b, i)); return d; } /*! Descend on the left or the right of the node according to the comparison between the node's value and the value. \note it's the caller responsibility to check if node is NULL. */ template <typename _Val, typename _Cmp, typename _Acc, typename NodeType> inline const NodeType* _S_node_descend (const size_t __dim, const _Cmp& __cmp, const _Acc& __acc, const _Val& __val, const NodeType* __node) { if (_S_node_compare(__dim, __cmp, __acc, __val, __node->_M_value)) return static_cast<const NodeType *>(__node->_M_left); return static_cast<const NodeType *>(__node->_M_right); } /*! Find the nearest node to __val from __node If many nodes are equidistant to __val, the node with the lowest memory address is returned. \return the nearest node of __end node if no nearest node was found for the given arguments. */ template <class SearchVal, typename NodeType, typename _Cmp, typename _Acc, typename _Dist, typename _Predicate> inline std::pair<const NodeType*, std::pair<size_t, typename _Dist::distance_type> > _S_node_nearest (const size_t __k, size_t __dim, SearchVal const& __val, const NodeType* __node, const _Node_base* __end, const NodeType* __best, typename _Dist::distance_type __max, const _Cmp& __cmp, const _Acc& __acc, const _Dist& __dist, _Predicate __p) { typedef const NodeType* NodePtr; NodePtr pcur = __node; NodePtr cur = _S_node_descend(__dim % __k, __cmp, __acc, __val, __node); size_t cur_dim = __dim+1; // find the smallest __max distance in direct descent while (cur) { if (__p(cur->_M_value)) { typename _Dist::distance_type d = 0; for (size_t i=0; i != __k; ++i) d += _S_node_distance(i, __dist, __acc, __val, cur->_M_value); d = std::sqrt(d); if (d <= __max) // ("bad candidate notes") // Changed: removed this test: || ( d == __max && cur < __best )) // Can't do this optimisation without checking that the current 'best' is not the root AND is not a valid candidate... // This is because find_nearest() etc will call this function with the best set to _M_root EVEN IF _M_root is not a valid answer (eg too far away or doesn't pass the predicate test) { __best = cur; __max = d; __dim = cur_dim; } } pcur = cur; cur = _S_node_descend(cur_dim % __k, __cmp, __acc, __val, cur); ++cur_dim; } // Swap cur to prev, only prev is a valid node. cur = pcur; --cur_dim; pcur = NULL; // Probe all node's children not visited yet (siblings of the visited nodes). NodePtr probe = cur; NodePtr pprobe = probe; NodePtr near_node; NodePtr far_node; size_t probe_dim = cur_dim; if (_S_node_compare(probe_dim % __k, __cmp, __acc, __val, probe->_M_value)) near_node = static_cast<NodePtr>(probe->_M_right); else near_node = static_cast<NodePtr>(probe->_M_left); if (near_node // only visit node's children if node's plane intersect hypersphere && (std::sqrt(_S_node_distance(probe_dim % __k, __dist, __acc, __val, probe->_M_value)) <= __max)) { probe = near_node; ++probe_dim; } while (cur != __end) { while (probe != cur) { if (_S_node_compare(probe_dim % __k, __cmp, __acc, __val, probe->_M_value)) { near_node = static_cast<NodePtr>(probe->_M_left); far_node = static_cast<NodePtr>(probe->_M_right); } else { near_node = static_cast<NodePtr>(probe->_M_right); far_node = static_cast<NodePtr>(probe->_M_left); } if (pprobe == probe->_M_parent) // going downward ... { if (__p(probe->_M_value)) { typename _Dist::distance_type d = 0; for (size_t i=0; i < __k; ++i) d += _S_node_distance(i, __dist, __acc, __val, probe->_M_value); d = std::sqrt(d); if (d <= __max) // CHANGED, see the above notes ("bad candidate notes") { __best = probe; __max = d; __dim = probe_dim; } } pprobe = probe; if (near_node) { probe = near_node; ++probe_dim; } else if (far_node && // only visit node's children if node's plane intersect hypersphere std::sqrt(_S_node_distance(probe_dim % __k, __dist, __acc, __val, probe->_M_value)) <= __max) { probe = far_node; ++probe_dim; } else { probe = static_cast<NodePtr>(probe->_M_parent); --probe_dim; } } else // ... and going upward. { if (pprobe == near_node && far_node // only visit node's children if node's plane intersect hypersphere && std::sqrt(_S_node_distance(probe_dim % __k, __dist, __acc, __val, probe->_M_value)) <= __max) { pprobe = probe; probe = far_node; ++probe_dim; } else { pprobe = probe; probe = static_cast<NodePtr>(probe->_M_parent); --probe_dim; } } } pcur = cur; cur = static_cast<NodePtr>(cur->_M_parent); --cur_dim; pprobe = cur; probe = cur; probe_dim = cur_dim; if (cur != __end) { if (pcur == cur->_M_left) near_node = static_cast<NodePtr>(cur->_M_right); else near_node = static_cast<NodePtr>(cur->_M_left); if (near_node // only visit node's children if node's plane intersect hypersphere && (std::sqrt(_S_node_distance(cur_dim % __k, __dist, __acc, __val, cur->_M_value)) <= __max)) { probe = near_node; ++probe_dim; } } } return std::pair<NodePtr, std::pair<size_t, typename _Dist::distance_type> > (__best, std::pair<size_t, typename _Dist::distance_type> (__dim, __max)); } } // namespace KDTree #endif // include guard /* COPYRIGHT -- * * This file is part of libkdtree++, a C++ template KD-Tree sorting container. * libkdtree++ is (c) 2004-2007 Martin F. Krafft <libkdtree@pobox.madduck.net> * and Sylvain Bougerel <sylvain.bougerel.devel@gmail.com> distributed under the * terms of the Artistic License 2.0. See the ./COPYING file in the source tree * root for more information. * * THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /** \file * Defines the various functors and interfaces used for KDTree. * * \author Martin F. Krafft <libkdtree@pobox.madduck.net> * \author Sylvain Bougerel <sylvain.bougerel.devel@gmail.com> */ #ifndef INCLUDE_KDTREE_ACCESSOR_HPP #define INCLUDE_KDTREE_ACCESSOR_HPP #include <cstddef> namespace KDTree { template <typename _Val> struct _Bracket_accessor { typedef typename _Val::value_type result_type; result_type operator()(_Val const& V, size_t const N) const { return V[N]; } }; template <typename _Tp> struct always_true { bool operator() (const _Tp& ) const { return true; } }; template <typename _Tp, typename _Dist> struct squared_difference { typedef _Dist distance_type; distance_type operator() (const _Tp& __a, const _Tp& __b) const { distance_type d=__a - __b; return d*d; } }; template <typename _Tp, typename _Dist> struct squared_difference_counted { typedef _Dist distance_type; squared_difference_counted() : _M_count(0) { } void reset () { _M_count = 0; } long& count () const { return _M_count; } distance_type operator() (const _Tp& __a, const _Tp& __b) const { distance_type d=__a - __b; ++_M_count; return d*d; } private: mutable long _M_count; }; } // namespace KDTree #endif // include guard /* COPYRIGHT -- * * This file is part of libkdtree++, a C++ template KD-Tree sorting container. * libkdtree++ is (c) 2004-2007 Martin F. Krafft <libkdtree@pobox.madduck.net> * and Sylvain Bougerel <sylvain.bougerel.devel@gmail.com> distributed under the * terms of the Artistic License 2.0. See the ./COPYING file in the source tree * root for more information. * * THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /** \file * Defines the allocator interface as used by the KDTree class. * * \author Martin F. Krafft <libkdtree@pobox.madduck.net> */ #ifndef INCLUDE_KDTREE_ALLOCATOR_HPP #define INCLUDE_KDTREE_ALLOCATOR_HPP #include <cstddef> namespace KDTree { template <typename _Tp, typename _Alloc> class _Alloc_base { public: typedef _Node<_Tp> _Node_; typedef typename _Node_::_Base_ptr _Base_ptr; typedef _Alloc allocator_type; _Alloc_base(allocator_type const& __A) : _M_node_allocator(__A) {} allocator_type get_allocator() const { return _M_node_allocator; } class NoLeakAlloc { _Alloc_base * base; _Node_ * new_node; public: NoLeakAlloc(_Alloc_base * b) : base(b), new_node(base->_M_allocate_node()) {} _Node_ * get() { return new_node; } void disconnect() { new_node = nullptr; } ~NoLeakAlloc() { if (new_node) base->_M_deallocate_node(new_node); } }; protected: allocator_type _M_node_allocator; _Node_* _M_allocate_node() { return _M_node_allocator.allocate(1); } void _M_deallocate_node(_Node_* const __P) { return _M_node_allocator.deallocate(__P, 1); } void _M_construct_node(_Node_* __p, _Tp const __V = _Tp(), _Base_ptr const __PARENT = NULL, _Base_ptr const __LEFT = NULL, _Base_ptr const __RIGHT = NULL) { new (__p) _Node_(__V, __PARENT, __LEFT, __RIGHT); } void _M_destroy_node(_Node_* __p) { std::allocator_traits<allocator_type>::destroy(_M_node_allocator, __p); } }; } // namespace KDTree #endif // include guard /* COPYRIGHT -- * * This file is part of libkdtree++, a C++ template KD-Tree sorting container. * libkdtree++ is (c) 2004-2007 Martin F. Krafft <libkdtree@pobox.madduck.net> * and Sylvain Bougerel <sylvain.bougerel.devel@gmail.com> distributed under the * terms of the Artistic License 2.0. See the ./COPYING file in the source tree * root for more information. * * THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /** \file * Defines interfaces for iterators as used by the KDTree class. * * \author Martin F. Krafft <libkdtree@pobox.madduck.net> */ #ifndef INCLUDE_KDTREE_ITERATOR_HPP #define INCLUDE_KDTREE_ITERATOR_HPP #include <iterator> namespace KDTree { template <typename _Val, typename _Ref, typename _Ptr> class _Iterator; template<typename _Val, typename _Ref, typename _Ptr> inline bool operator==(_Iterator<_Val, _Ref, _Ptr> const&, _Iterator<_Val, _Ref, _Ptr> const&); template<typename _Val> inline bool operator==(_Iterator<_Val, const _Val&, const _Val*> const&, _Iterator<_Val, _Val&, _Val*> const&); template<typename _Val> inline bool operator==(_Iterator<_Val, _Val&, _Val*> const&, _Iterator<_Val, const _Val&, const _Val*> const&); template<typename _Val, typename _Ref, typename _Ptr> inline bool operator!=(_Iterator<_Val, _Ref, _Ptr> const&, _Iterator<_Val, _Ref, _Ptr> const&); template<typename _Val> inline bool operator!=(_Iterator<_Val, const _Val&, const _Val*> const&, _Iterator<_Val, _Val&, _Val*> const&); template<typename _Val> inline bool operator!=(_Iterator<_Val, _Val&, _Val*> const&, _Iterator<_Val, const _Val&, const _Val*> const&); class _Base_iterator { protected: typedef _Node_base::_Base_const_ptr _Base_const_ptr; _Base_const_ptr _M_node; inline _Base_iterator(_Base_const_ptr const __N = nullptr) : _M_node(__N) {} inline _Base_iterator(_Base_iterator const& __THAT) : _M_node(__THAT._M_node) {} inline void _M_increment() { if (_M_node->_M_right) { _M_node = _M_node->_M_right; while (_M_node->_M_left) _M_node = _M_node->_M_left; } else { _Base_const_ptr __p = _M_node->_M_parent; while (__p && _M_node == __p->_M_right) { _M_node = __p; __p = _M_node->_M_parent; } if (__p) // (__p) provide undetermined behavior on end()++ rather // than a segfault, similar to standard iterator. _M_node = __p; } } inline void _M_decrement() { if (!_M_node->_M_parent) // clearly identify the header node { _M_node = _M_node->_M_right; } else if (_M_node->_M_left) { _Base_const_ptr x = _M_node->_M_left; while (x->_M_right) x = x->_M_right; _M_node = x; } else { _Base_const_ptr __p = _M_node->_M_parent; while (__p && _M_node == __p->_M_left) // see below { _M_node = __p; __p = _M_node->_M_parent; } if (__p) // (__p) provide undetermined behavior on rend()++ rather // than a segfault, similar to standard iterator. _M_node = __p; } } template <size_t const __K, typename _Val, typename _Acc, typename _Dist, typename _Cmp, typename _Alloc> friend class KDTree; }; template <typename _Val, typename _Ref, typename _Ptr> class _Iterator : protected _Base_iterator { public: typedef _Val value_type; typedef _Ref reference; typedef _Ptr pointer; typedef _Iterator<_Val, _Val&, _Val*> iterator; typedef _Iterator<_Val, _Val const&, _Val const*> const_iterator; typedef _Iterator<_Val, _Ref, _Ptr> _Self; typedef _Node<_Val> const* _Link_const_type; typedef std::bidirectional_iterator_tag iterator_category; typedef ptrdiff_t difference_type; inline _Iterator() : _Base_iterator() {} inline _Iterator(_Link_const_type const __N) : _Base_iterator(__N) {} inline _Iterator(iterator const& __THAT) : _Base_iterator(__THAT) {} _Link_const_type get_raw_node() const { return _Link_const_type(_M_node); } reference operator*() const { return _Link_const_type(_M_node)->_M_value; } pointer operator->() const { return &(operator*()); } _Self operator++() { _M_increment(); return *this; } _Self operator++(int) { _Self ret = *this; _M_increment(); return ret; } _Self& operator--() { _M_decrement(); return *this; } _Self operator--(int) { _Self ret = *this; _M_decrement(); return ret; } friend bool operator== <>(_Iterator<_Val, _Ref, _Ptr> const&, _Iterator<_Val, _Ref, _Ptr> const&); friend bool operator== <>(_Iterator<_Val, const _Val&, const _Val*> const&, _Iterator<_Val, _Val&, _Val*> const&); friend bool operator== <>(_Iterator<_Val, _Val&, _Val*> const&, _Iterator<_Val, const _Val&, const _Val*> const&); friend bool operator!= <>(_Iterator<_Val, _Ref, _Ptr> const&, _Iterator<_Val, _Ref, _Ptr> const&); friend bool operator!= <>(_Iterator<_Val, const _Val&, const _Val*> const&, _Iterator<_Val, _Val&, _Val*> const&); friend bool operator!= <>(_Iterator<_Val, _Val&, _Val*> const&, _Iterator<_Val, const _Val&, const _Val*> const&); }; template<typename _Val, typename _Ref, typename _Ptr> bool operator==(_Iterator<_Val, _Ref, _Ptr> const& __X, _Iterator<_Val, _Ref, _Ptr> const& __Y) { return __X._M_node == __Y._M_node; } template<typename _Val> bool operator==(_Iterator<_Val, const _Val&, const _Val*> const& __X, _Iterator<_Val, _Val&, _Val*> const& __Y) { return __X._M_node == __Y._M_node; } template<typename _Val> bool operator==(_Iterator<_Val, _Val&, _Val*> const& __X, _Iterator<_Val, const _Val&, const _Val*> const& __Y) { return __X._M_node == __Y._M_node; } template<typename _Val, typename _Ref, typename _Ptr> bool operator!=(_Iterator<_Val, _Ref, _Ptr> const& __X, _Iterator<_Val, _Ref, _Ptr> const& __Y) { return __X._M_node != __Y._M_node; } template<typename _Val> bool operator!=(_Iterator<_Val, const _Val&, const _Val*> const& __X, _Iterator<_Val, _Val&, _Val*> const& __Y) { return __X._M_node != __Y._M_node; } template<typename _Val> bool operator!=(_Iterator<_Val, _Val&, _Val*> const& __X, _Iterator<_Val, const _Val&, const _Val*> const& __Y) { return __X._M_node != __Y._M_node; } } // namespace KDTree #endif // include guard /* COPYRIGHT -- * * This file is part of libkdtree++, a C++ template KD-Tree sorting container. * libkdtree++ is (c) 2004-2007 Martin F. Krafft <libkdtree@pobox.madduck.net> * and Sylvain Bougerel <sylvain.bougerel.devel@gmail.com> distributed under the * terms of the Artistic License 2.0. See the ./COPYING file in the source tree * root for more information. * * THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /** \file * Defines the interface of the _Region class. * * \author Martin F. Krafft <libkdtree@pobox.madduck.net> */ #ifndef INCLUDE_KDTREE_REGION_HPP #define INCLUDE_KDTREE_REGION_HPP #include <cstddef> namespace KDTree { template <size_t const __K, typename _Val, typename _SubVal, typename _Acc, typename _Cmp> struct _Region { typedef _Val value_type; typedef _SubVal subvalue_type; // special typedef for checking against a fuzzy point (for find_nearest) // Note the region (first) component is not supposed to have an area, its // bounds should all be set to a specific point. typedef std::pair<_Region,_SubVal> _CenterPt; _Region(_Acc const& __acc=_Acc(), const _Cmp& __cmp=_Cmp()) : _M_acc(__acc), _M_cmp(__cmp) {} template <typename Val> _Region(Val const& __V, _Acc const& __acc=_Acc(), const _Cmp& __cmp=_Cmp()) : _M_acc(__acc), _M_cmp(__cmp) { for (size_t __i = 0; __i != __K; ++__i) { _M_low_bounds[__i] = _M_high_bounds[__i] = _M_acc(__V,__i); } } template <typename Val> _Region(Val const& __V, subvalue_type const& __R, _Acc const& __acc=_Acc(), const _Cmp& __cmp=_Cmp()) : _M_acc(__acc), _M_cmp(__cmp) { for (size_t __i = 0; __i != __K; ++__i) { _M_low_bounds[__i] = _M_acc(__V,__i) - __R; _M_high_bounds[__i] = _M_acc(__V,__i) + __R; } } bool intersects_with(_CenterPt const& __THAT) const { for (size_t __i = 0; __i != __K; ++__i) { // does it fall outside the bounds? // ! low-tolerance <= x <= high+tolerance // ! (low-tol <= x and x <= high+tol) // !low-tol<=x or !x<=high+tol // low-tol>x or x>high+tol // x<low-tol or high+tol<x if (_M_cmp(__THAT.first._M_low_bounds[__i], _M_low_bounds[__i] - __THAT.second) || _M_cmp(_M_high_bounds[__i] + __THAT.second, __THAT.first._M_low_bounds[__i])) return false; } return true; } bool intersects_with(_Region const& __THAT) const { for (size_t __i = 0; __i != __K; ++__i) { if (_M_cmp(__THAT._M_high_bounds[__i], _M_low_bounds[__i]) || _M_cmp(_M_high_bounds[__i], __THAT._M_low_bounds[__i])) return false; } return true; } bool encloses(value_type const& __V) const { for (size_t __i = 0; __i != __K; ++__i) { if (_M_cmp(_M_acc(__V, __i), _M_low_bounds[__i]) || _M_cmp(_M_high_bounds[__i], _M_acc(__V, __i))) return false; } return true; } _Region& set_high_bound(value_type const& __V, size_t const __L) { _M_high_bounds[__L % __K] = _M_acc(__V, __L % __K); return *this; } _Region& set_low_bound(value_type const& __V, size_t const __L) { _M_low_bounds[__L % __K] = _M_acc(__V, __L % __K); return *this; } subvalue_type _M_low_bounds[__K], _M_high_bounds[__K]; _Acc _M_acc; _Cmp _M_cmp; }; } // namespace KDTree #endif // include guard /* COPYRIGHT -- * * This file is part of libkdtree++, a C++ template KD-Tree sorting container. * libkdtree++ is (c) 2004-2007 Martin F. Krafft <libkdtree@pobox.madduck.net> * and Sylvain Bougerel <sylvain.bougerel.devel@gmail.com> distributed under the * terms of the Artistic License 2.0. See the ./COPYING file in the source tree * root for more information. * * THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ /** \file * Defines the interface for the KDTree class. * * \author Martin F. Krafft <libkdtree@pobox.madduck.net> * * Paul Harris figured this stuff out (below) * Notes: * This is similar to a binary tree, but its not the same. * There are a few important differences: * * * Each level is sorted by a different criteria (this is fundamental to the design). * * * It is possible to have children IDENTICAL to its parent in BOTH branches * This is different to a binary tree, where identical children are always to the right * So, KDTree has the relationships: * * The left branch is <= its parent (in binary tree, this relationship is a plain < ) * * The right branch is <= its parent (same as binary tree) * * This is done for mostly for performance. * Its a LOT easier to maintain a consistent tree if we use the <= relationship. * Note that this relationship only makes a difference when searching for an exact * item with find() or find_exact, other search, erase and insert functions don't notice * the difference. * * In the case of binary trees, you can safely assume that the next identical item * will be the child leaf, * but in the case of KDTree, the next identical item might * be a long way down a subtree, because of the various different sort criteria. * * So to erase() a node from a KDTree could require serious and complicated * tree rebalancing to maintain consistency... IF we required binary-tree-like relationships. * * This has no effect on insert()s, a < test is good enough to keep consistency. * * It has an effect on find() searches: * * Instead of using compare(child,node) for a < relationship and following 1 branch, * we must use !compare(node,child) for a <= relationship, and test BOTH branches, as * we could potentially go down both branches. * * It has no real effect on bounds-based searches (like find_nearest, find_within_range) * as it compares vs a boundary and would follow both branches if required. * * This has no real effect on erase()s, a < test is good enough to keep consistency. */ #ifndef INCLUDE_KDTREE_KDTREE_HPP #define INCLUDE_KDTREE_KDTREE_HPP // // This number is guaranteed to change with every release. // // KDTREE_VERSION % 100 is the patch level // KDTREE_VERSION / 100 % 1000 is the minor version // KDTREE_VERSION / 100000 is the major version #define KDTREE_VERSION 701 // // KDTREE_LIB_VERSION must be defined to be the same as KDTREE_VERSION // but as a *string* in the form "x_y[_z]" where x is the major version // number, y is the minor version number, and z is the patch level if not 0. #define KDTREE_LIB_VERSION "0_7_1" #include <vector> #ifdef KDTREE_CHECK_PERFORMANCE_COUNTERS # include <map> #endif #include <algorithm> #include <functional> #ifdef KDTREE_DEFINE_OSTREAM_OPERATORS # include <ostream> # include <stack> #endif #include <cmath> #include <cstddef> #include <cassert> namespace KDTree { #ifdef KDTREE_CHECK_PERFORMANCE unsigned long long num_dist_calcs = 0; #endif template <size_t const __K, typename _Val, typename _Acc = _Bracket_accessor<_Val>, typename _Dist = squared_difference<typename _Acc::result_type, typename _Acc::result_type>, typename _Cmp = std::less<typename _Acc::result_type>, typename _Alloc = std::allocator<_Node<_Val> > > class KDTree : protected _Alloc_base<_Val, _Alloc> { protected: typedef _Alloc_base<_Val, _Alloc> _Base; typedef typename _Base::allocator_type allocator_type; typedef _Node_base* _Base_ptr; typedef _Node_base const* _Base_const_ptr; typedef _Node<_Val>* _Link_type; typedef _Node<_Val> const* _Link_const_type; typedef _Node_compare<_Val, _Acc, _Cmp> _Node_compare_; public: typedef _Region<__K, _Val, typename _Acc::result_type, _Acc, _Cmp> _Region_; typedef _Val value_type; typedef value_type* pointer; typedef value_type const* const_pointer; typedef value_type& reference; typedef value_type const& const_reference; typedef typename _Acc::result_type subvalue_type; typedef typename _Dist::distance_type distance_type; typedef size_t size_type; typedef ptrdiff_t difference_type; KDTree(_Acc const& __acc = _Acc(), _Dist const& __dist = _Dist(), _Cmp const& __cmp = _Cmp(), const allocator_type& __a = allocator_type()) : _Base(__a), _M_header(), _M_count(0), _M_acc(__acc), _M_cmp(__cmp), _M_dist(__dist) { _M_empty_initialise(); } KDTree(const KDTree& __x) : _Base(__x.get_allocator()), _M_header(), _M_count(0), _M_acc(__x._M_acc), _M_cmp(__x._M_cmp), _M_dist(__x._M_dist) { _M_empty_initialise(); // this is slow: // this->insert(begin(), __x.begin(), __x.end()); // this->optimise(); // this is much faster, as it skips a lot of useless work // do the optimisation before inserting // Needs to be stored in a vector first as _M_optimise() // sorts the data in the passed iterators directly. std::vector<value_type> temp; temp.reserve(__x.size()); std::copy(__x.begin(),__x.end(),std::back_inserter(temp)); _M_optimise(temp.begin(), temp.end(), 0); } template<typename _InputIterator> KDTree(_InputIterator __first, _InputIterator __last, _Acc const& acc = _Acc(), _Dist const& __dist = _Dist(), _Cmp const& __cmp = _Cmp(), const allocator_type& __a = allocator_type()) : _Base(__a), _M_header(), _M_count(0), _M_acc(acc), _M_cmp(__cmp), _M_dist(__dist) { _M_empty_initialise(); // this is slow: // this->insert(begin(), __first, __last); // this->optimise(); // this is much faster, as it skips a lot of useless work // do the optimisation before inserting // Needs to be stored in a vector first as _M_optimise() // sorts the data in the passed iterators directly. std::vector<value_type> temp; temp.reserve(std::distance(__first,__last)); std::copy(__first,__last,std::back_inserter(temp)); _M_optimise(temp.begin(), temp.end(), 0); // NOTE: this will BREAK users that are passing in // read-once data via the iterator... // We increment __first all the way to __last once within // the distance() call, and again within the copy() call. // // This should end up using some funky C++ concepts or // type traits to check that the iterators can be used in this way... } // this will CLEAR the tree and fill it with the contents // of 'writable_vector'. it will use the passed vector directly, // and will basically resort the vector many times over while // optimising the tree. // // Paul: I use this when I have already built up a vector of data // that I want to add, and I don't mind if its contents get shuffled // by the kdtree optimise routine. void efficient_replace_and_optimise( std::vector<value_type> & writable_vector ) { this->clear(); _M_optimise(writable_vector.begin(), writable_vector.end(), 0); } KDTree& operator=(const KDTree& __x) { if (this != &__x) { _M_acc = __x._M_acc; _M_dist = __x._M_dist; _M_cmp = __x._M_cmp; // this is slow: // this->insert(begin(), __x.begin(), __x.end()); // this->optimise(); // this is much faster, as it skips a lot of useless work // do the optimisation before inserting // Needs to be stored in a vector first as _M_optimise() // sorts the data in the passed iterators directly. std::vector<value_type> temp; temp.reserve(__x.size()); std::copy(__x.begin(),__x.end(),std::back_inserter(temp)); efficient_replace_and_optimise(temp); } return *this; } ~KDTree() { this->clear(); } allocator_type get_allocator() const { return _Base::get_allocator(); } size_type size() const { return _M_count; } size_type max_size() const { return size_type(-1); } bool empty() const { return this->size() == 0; } void clear() { _M_erase_subtree(_M_get_root()); _M_set_leftmost(&_M_header); _M_set_rightmost(&_M_header); _M_set_root(nullptr); _M_count = 0; } /*! \brief Comparator for the values in the KDTree. The comparator shall not be modified, it could invalidate the tree. \return a copy of the comparator used by the KDTree. */ _Cmp value_comp() const { return _M_cmp; } /*! \brief Accessor to the value's elements. This accessor shall not be modified, it could invalidate the tree. \return a copy of the accessor used by the KDTree. */ _Acc value_acc() const { return _M_acc; } /*! \brief Distance calculator between 2 value's element. This functor can be modified. It's modification will only affect the behavior of the find and find_nearest functions. \return a reference to the distance calculator used by the KDTree. */ const _Dist& value_distance() const { return _M_dist; } _Dist& value_distance() { return _M_dist; } // typedef _Iterator<_Val, reference, pointer> iterator; typedef _Iterator<_Val, const_reference, const_pointer> const_iterator; // No mutable iterator at this stage typedef const_iterator iterator; typedef std::reverse_iterator<const_iterator> const_reverse_iterator; typedef std::reverse_iterator<iterator> reverse_iterator; // Note: the static_cast in end() is invalid (_M_header is not convertible to a _Link_type), but // that's ok as it just means undefined behaviour if the user dereferences the end() iterator. const_iterator begin() const { return const_iterator(_M_get_leftmost()); } const_iterator end() const { return const_iterator(static_cast<_Link_const_type>(&_M_header)); } const_reverse_iterator rbegin() const { return const_reverse_iterator(end()); } const_reverse_iterator rend() const { return const_reverse_iterator(begin()); } iterator insert(iterator /* ignored */, const_reference __V) { return this->insert(__V); } iterator insert(const_reference __V) { if (!_M_get_root()) { _Link_type __n = _M_new_node(__V, &_M_header); ++_M_count; _M_set_root(__n); _M_set_leftmost(__n); _M_set_rightmost(__n); return iterator(__n); } return _M_insert(_M_get_root(), __V, 0); } template <class _InputIterator> void insert(_InputIterator __first, _InputIterator __last) { for (; __first != __last; ++__first) this->insert(*__first); } void insert(iterator __pos, size_type __n, const value_type& __x) { for (; __n > 0; --__n) this->insert(__pos, __x); } template<typename _InputIterator> void insert(iterator __pos, _InputIterator __first, _InputIterator __last) { for (; __first != __last; ++__first) this->insert(__pos, *__first); } // Note: this uses the find() to location the item you want to erase. // find() compares by equivalence of location ONLY. See the comments // above find_exact() for why you may not want this. // // If you want to erase ANY item that has the same location as __V, // then use this function. // // If you want to erase a PARTICULAR item, and not any other item // that might happen to have the same location, then you should use // erase_exact(). void erase(const_reference __V) { const_iterator b = this->find(__V); this->erase(b); } void erase_exact(const_reference __V) { this->erase(this->find_exact(__V)); } // note: kept as const because its easier to const-cast it away void erase(const_iterator const& __IT) { assert(__IT != this->end()); _Link_const_type target = __IT.get_raw_node(); _Link_const_type n = target; size_type level = 0; while ((n = _S_parent(n)) != &_M_header) ++level; _M_erase( const_cast<_Link_type>(target), level ); _M_delete_node( const_cast<_Link_type>(target) ); --_M_count; } /* this does not work since erasure changes sort order void erase(const_iterator __A, const_iterator const& __B) { if (0 && __A == this->begin() && __B == this->end()) { this->clear(); } else { while (__A != __B) this->erase(__A++); } } */ // compares via equivalence // so if you are looking for any item with the same location, // according to the standard accessor comparisons, // then this is the function for you. template <class SearchVal> const_iterator find(SearchVal const& __V) const { if (!_M_get_root()) return this->end(); return _M_find(_M_get_root(), __V, 0); } // compares via equality // if you are looking for a particular item in the tree, // and (for example) it has an ID that is checked via an == comparison // e.g. // struct Item // { // size_type unique_id; // bool operator==(Item const& a, Item const& b) { return a.unique_id == b.unique_id; } // Location location; // }; // Two items may be equivalent in location. find() would return // either one of them. But no two items have the same ID, so // find_exact() would always return the item with the same location AND id. // template <class SearchVal> const_iterator find_exact(SearchVal const& __V) const { if (!_M_get_root()) return this->end(); return _M_find_exact(_M_get_root(), __V, 0); } // NOTE: see notes on find_within_range(). size_type count_within_range(const_reference __V, subvalue_type const __R) const { if (!_M_get_root()) return 0; _Region_ __region(__V, __R, _M_acc, _M_cmp); return this->count_within_range(__region); } size_type count_within_range(_Region_ const& __REGION) const { if (!_M_get_root()) return 0; _Region_ __bounds(__REGION); return _M_count_within_range(_M_get_root(), __REGION, __bounds, 0); } // NOTE: see notes on find_within_range(). template <typename SearchVal, class Visitor> Visitor visit_within_range(SearchVal const& V, subvalue_type const R, Visitor visitor) const { if (!_M_get_root()) return visitor; _Region_ region(V, R, _M_acc, _M_cmp); return this->visit_within_range(region, visitor); } template <class Visitor> Visitor visit_within_range(_Region_ const& REGION, Visitor visitor) const { if (_M_get_root()) { _Region_ bounds(REGION); return _M_visit_within_range(visitor, _M_get_root(), REGION, bounds, 0); } return visitor; } // NOTE: this will visit points based on 'Manhattan distance' aka city-block distance // aka taxicab metric. Meaning it will find all points within: // max(x_dist,max(y_dist,z_dist)); // AND NOT than what you would expect: sqrt(x_dist*x_dist + y_dist*y_dist + z_dist*z_dist) // // This is because it converts the distance into a bounding-box 'region' and compares // against that. // // If you want the sqrt() behaviour, ask on the mailing list for different options. // template <typename SearchVal, typename _OutputIterator> _OutputIterator find_within_range(SearchVal const& val, subvalue_type const range, _OutputIterator out) const { if (!_M_get_root()) return out; _Region_ region(val, range, _M_acc, _M_cmp); return this->find_within_range(region, out); } template <typename _OutputIterator> _OutputIterator find_within_range(_Region_ const& region, _OutputIterator out) const { if (_M_get_root()) { _Region_ bounds(region); out = _M_find_within_range(out, _M_get_root(), region, bounds, 0); } return out; } template <class SearchVal> std::pair<const_iterator, distance_type> find_nearest (SearchVal const& __val) const { if (_M_get_root()) { std::pair<const _Node<_Val>*, std::pair<size_type, typename _Acc::result_type> > best = _S_node_nearest (__K, 0, __val, _M_get_root(), &_M_header, _M_get_root(), std::sqrt(_S_accumulate_node_distance (__K, _M_dist, _M_acc, _M_get_root()->_M_value, __val)), _M_cmp, _M_acc, _M_dist, always_true<value_type>()); return std::pair<const_iterator, distance_type> (best.first, best.second.second); } return std::pair<const_iterator, distance_type>(end(), 0); } template <class SearchVal> std::pair<const_iterator, distance_type> find_nearest (SearchVal const& __val, distance_type __max) const { if (_M_get_root()) { bool root_is_candidate = false; const _Node<_Val>* node = _M_get_root(); { // scope to ensure we don't use 'root_dist' anywhere else distance_type root_dist = std::sqrt(_S_accumulate_node_distance (__K, _M_dist, _M_acc, _M_get_root()->_M_value, __val)); if (root_dist <= __max) { root_is_candidate = true; __max = root_dist; } } std::pair<const _Node<_Val>*, std::pair<size_type, typename _Acc::result_type> > best = _S_node_nearest (__K, 0, __val, _M_get_root(), &_M_header, node, __max, _M_cmp, _M_acc, _M_dist, always_true<value_type>()); // make sure we didn't just get stuck with the root node... if (root_is_candidate || best.first != _M_get_root()) return std::pair<const_iterator, distance_type> (best.first, best.second.second); } return std::pair<const_iterator, distance_type>(end(), __max); } template <class SearchVal, class _Predicate> std::pair<const_iterator, distance_type> find_nearest_if (SearchVal const& __val, distance_type __max, _Predicate __p) const { if (_M_get_root()) { bool root_is_candidate = false; const _Node<_Val>* node = _M_get_root(); if (__p(_M_get_root()->_M_value)) { { // scope to ensure we don't use root_dist anywhere else distance_type root_dist = std::sqrt(_S_accumulate_node_distance (__K, _M_dist, _M_acc, _M_get_root()->_M_value, __val)); if (root_dist <= __max) { root_is_candidate = true; root_dist = __max; } } } std::pair<const _Node<_Val>*, std::pair<size_type, typename _Acc::result_type> > best = _S_node_nearest (__K, 0, __val, _M_get_root(), &_M_header, node, __max, _M_cmp, _M_acc, _M_dist, __p); // make sure we didn't just get stuck with the root node... if (root_is_candidate || best.first != _M_get_root()) return std::pair<const_iterator, distance_type> (best.first, best.second.second); } return std::pair<const_iterator, distance_type>(end(), __max); } void optimise() { std::vector<value_type> __v(this->begin(),this->end()); this->clear(); _M_optimise(__v.begin(), __v.end(), 0); } void optimize() { // cater for people who cannot spell :) this->optimise(); } void check_tree() { _M_check_node(_M_get_root(),0); } protected: void _M_check_children( _Link_const_type child, _Link_const_type parent, size_type const level, bool to_the_left ) { assert(parent); if (child) { _Node_compare_ compare(level % __K, _M_acc, _M_cmp); // REMEMBER! its a <= relationship for BOTH branches // for left-case (true), child<=node --> !(node<child) // for right-case (false), node<=child --> !(child<node) assert(!to_the_left || !compare(parent->_M_value,child->_M_value)); // check the left assert(to_the_left || !compare(child->_M_value,parent->_M_value)); // check the right // and recurse down the tree, checking everything _M_check_children(_S_left(child),parent,level,to_the_left); _M_check_children(_S_right(child),parent,level,to_the_left); } } void _M_check_node( _Link_const_type node, size_type const level ) { if (node) { // (comparing on this level) // everything to the left of this node must be smaller than this _M_check_children( _S_left(node), node, level, true ); // everything to the right of this node must be larger than this _M_check_children( _S_right(node), node, level, false ); _M_check_node( _S_left(node), level+1 ); _M_check_node( _S_right(node), level+1 ); } } void _M_empty_initialise() { _M_set_leftmost(&_M_header); _M_set_rightmost(&_M_header); _M_header._M_parent = nullptr; _M_set_root(nullptr); } iterator _M_insert_left(_Link_type __N, const_reference __V) { _S_set_left(__N, _M_new_node(__V)); ++_M_count; _S_set_parent( _S_left(__N), __N ); if (__N == _M_get_leftmost()) _M_set_leftmost( _S_left(__N) ); return iterator(_S_left(__N)); } iterator _M_insert_right(_Link_type __N, const_reference __V) { _S_set_right(__N, _M_new_node(__V)); ++_M_count; _S_set_parent( _S_right(__N), __N ); if (__N == _M_get_rightmost()) _M_set_rightmost( _S_right(__N) ); return iterator(_S_right(__N)); } iterator _M_insert(_Link_type __N, const_reference __V, size_type const __L) { if (_Node_compare_(__L % __K, _M_acc, _M_cmp)(__V, __N->_M_value)) { if (!_S_left(__N)) return _M_insert_left(__N, __V); return _M_insert(_S_left(__N), __V, __L+1); } else { if (!_S_right(__N) || __N == _M_get_rightmost()) return _M_insert_right(__N, __V); return _M_insert(_S_right(__N), __V, __L+1); } } _Link_type _M_erase(_Link_type dead_dad, size_type const level) { // find a new step_dad, he will become a drop-in replacement. _Link_type step_dad = _M_get_erase_replacement(dead_dad, level); // tell dead_dad's parent that his new child is step_dad if (dead_dad == _M_get_root()) _M_set_root(step_dad); else if (_S_left(_S_parent(dead_dad)) == dead_dad) _S_set_left(_S_parent(dead_dad), step_dad); else _S_set_right(_S_parent(dead_dad), step_dad); // deal with the left and right edges of the tree... // if the dead_dad was at the edge, then substitute... // but if there IS no new dead, then left_most is the dead_dad's parent if (dead_dad == _M_get_leftmost()) _M_set_leftmost( (step_dad ? step_dad : _S_parent(dead_dad)) ); if (dead_dad == _M_get_rightmost()) _M_set_rightmost( (step_dad ? step_dad : _S_parent(dead_dad)) ); if (step_dad) { // step_dad gets dead_dad's parent _S_set_parent(step_dad, _S_parent(dead_dad)); // first tell the children that step_dad is their new dad if (_S_left(dead_dad)) _S_set_parent(_S_left(dead_dad), step_dad); if (_S_right(dead_dad)) _S_set_parent(_S_right(dead_dad), step_dad); // step_dad gets dead_dad's children _S_set_left(step_dad, _S_left(dead_dad)); _S_set_right(step_dad, _S_right(dead_dad)); } return step_dad; } _Link_type _M_get_erase_replacement(_Link_type node, size_type const level) { // if 'node' is null, then we can't do any better if (_S_is_leaf(node)) return NULL; std::pair<_Link_type,size_type> candidate; // if there is nothing to the left, find a candidate on the right tree if (!_S_left(node)) candidate = _M_get_j_min( std::pair<_Link_type,size_type>(_S_right(node),level), level+1); // ditto for the right else if ((!_S_right(node))) candidate = _M_get_j_max( std::pair<_Link_type,size_type>(_S_left(node),level), level+1); // we have both children ... else { // we need to do a little more work in order to find a good candidate // this is actually a technique used to choose a node from either the // left or right branch RANDOMLY, so that the tree has a greater change of // staying balanced. // If this were a true binary tree, we would always hunt down the right branch. // See top for notes. _Node_compare_ compare(level % __K, _M_acc, _M_cmp); // compare the children based on this level's criteria... // (this gives virtually random results) if (compare(_S_right(node)->_M_value, _S_left(node)->_M_value)) // the right is smaller, get our replacement from the SMALLEST on the right candidate = _M_get_j_min(std::pair<_Link_type,size_type>(_S_right(node),level), level+1); else candidate = _M_get_j_max( std::pair<_Link_type,size_type>(_S_left(node),level), level+1); } // we have a candidate replacement by now. // remove it from the tree, but don't delete it. // it must be disconnected before it can be reconnected. _Link_type parent = _S_parent(candidate.first); if (_S_left(parent) == candidate.first) _S_set_left(parent, _M_erase(candidate.first, candidate.second)); else _S_set_right(parent, _M_erase(candidate.first, candidate.second)); return candidate.first; } // TODO: why not pass node by const-ref? std::pair<_Link_type,size_type> _M_get_j_min( std::pair<_Link_type,size_type> const node, size_type const level) { typedef std::pair<_Link_type,size_type> Result; if (_S_is_leaf(node.first)) return Result(node.first,level); _Node_compare_ compare(node.second % __K, _M_acc, _M_cmp); Result candidate = node; if (_S_left(node.first)) { Result left = _M_get_j_min(Result(_S_left(node.first), node.second), level+1); if (compare(left.first->_M_value, candidate.first->_M_value)) candidate = left; } if (_S_right(node.first)) { Result right = _M_get_j_min( Result(_S_right(node.first),node.second), level+1); if (compare(right.first->_M_value, candidate.first->_M_value)) candidate = right; } if (candidate.first == node.first) return Result(candidate.first,level); return candidate; } // TODO: why not pass node by const-ref? std::pair<_Link_type,size_type> _M_get_j_max( std::pair<_Link_type,size_type> const node, size_type const level) { typedef std::pair<_Link_type,size_type> Result; if (_S_is_leaf(node.first)) return Result(node.first,level); _Node_compare_ compare(node.second % __K, _M_acc, _M_cmp); Result candidate = node; if (_S_left(node.first)) { Result left = _M_get_j_max( Result(_S_left(node.first),node.second), level+1); if (compare(candidate.first->_M_value, left.first->_M_value)) candidate = left; } if (_S_right(node.first)) { Result right = _M_get_j_max(Result(_S_right(node.first),node.second), level+1); if (compare(candidate.first->_M_value, right.first->_M_value)) candidate = right; } if (candidate.first == node.first) return Result(candidate.first,level); return candidate; } void _M_erase_subtree(_Link_type __n) { while (__n) { _M_erase_subtree(_S_right(__n)); _Link_type __t = _S_left(__n); _M_delete_node(__n); __n = __t; } } const_iterator _M_find(_Link_const_type node, const_reference value, size_type const level) const { // be aware! This is very different to normal binary searches, because of the <= // relationship used. See top for notes. // Basically we have to check ALL branches, as we may have an identical node // in different branches. const_iterator found = this->end(); _Node_compare_ compare(level % __K, _M_acc, _M_cmp); if (!compare(node->_M_value,value)) // note, this is a <= test { // this line is the only difference between _M_find_exact() and _M_find() if (_M_matches_node(node, value, level)) return const_iterator(node); // return right away if (_S_left(node)) found = _M_find(_S_left(node), value, level+1); } if ( _S_right(node) && found == this->end() && !compare(value,node->_M_value)) // note, this is a <= test found = _M_find(_S_right(node), value, level+1); return found; } const_iterator _M_find_exact(_Link_const_type node, const_reference value, size_type const level) const { // be aware! This is very different to normal binary searches, because of the <= // relationship used. See top for notes. // Basically we have to check ALL branches, as we may have an identical node // in different branches. const_iterator found = this->end(); _Node_compare_ compare(level % __K, _M_acc, _M_cmp); if (!compare(node->_M_value,value)) // note, this is a <= test { // this line is the only difference between _M_find_exact() and _M_find() if (value == *const_iterator(node)) return const_iterator(node); // return right away if (_S_left(node)) found = _M_find_exact(_S_left(node), value, level+1); } // note: no else! items that are identical can be down both branches if ( _S_right(node) && found == this->end() && !compare(value,node->_M_value)) // note, this is a <= test found = _M_find_exact(_S_right(node), value, level+1); return found; } bool _M_matches_node_in_d(_Link_const_type __N, const_reference __V, size_type const __L) const { _Node_compare_ compare(__L % __K, _M_acc, _M_cmp); return !(compare(__N->_M_value, __V) || compare(__V, __N->_M_value)); } bool _M_matches_node_in_other_ds(_Link_const_type __N, const_reference __V, size_type const __L = 0) const { size_type __i = __L; while ((__i = (__i + 1) % __K) != __L % __K) if (!_M_matches_node_in_d(__N, __V, __i)) return false; return true; } bool _M_matches_node(_Link_const_type __N, const_reference __V, size_type __L = 0) const { return _M_matches_node_in_d(__N, __V, __L) && _M_matches_node_in_other_ds(__N, __V, __L); } size_type _M_count_within_range(_Link_const_type __N, _Region_ const& __REGION, _Region_ const& __BOUNDS, size_type const __L) const { size_type count = 0; if (__REGION.encloses(_S_value(__N))) { ++count; } if (_S_left(__N)) { _Region_ __bounds(__BOUNDS); __bounds.set_high_bound(_S_value(__N), __L); if (__REGION.intersects_with(__bounds)) count += _M_count_within_range(_S_left(__N), __REGION, __bounds, __L+1); } if (_S_right(__N)) { _Region_ __bounds(__BOUNDS); __bounds.set_low_bound(_S_value(__N), __L); if (__REGION.intersects_with(__bounds)) count += _M_count_within_range(_S_right(__N), __REGION, __bounds, __L+1); } return count; } template <class Visitor> Visitor _M_visit_within_range(Visitor visitor, _Link_const_type N, _Region_ const& REGION, _Region_ const& BOUNDS, size_type const L) const { if (REGION.encloses(_S_value(N))) { visitor(_S_value(N)); } if (_S_left(N)) { _Region_ bounds(BOUNDS); bounds.set_high_bound(_S_value(N), L); if (REGION.intersects_with(bounds)) visitor = _M_visit_within_range(visitor, _S_left(N), REGION, bounds, L+1); } if (_S_right(N)) { _Region_ bounds(BOUNDS); bounds.set_low_bound(_S_value(N), L); if (REGION.intersects_with(bounds)) visitor = _M_visit_within_range(visitor, _S_right(N), REGION, bounds, L+1); } return visitor; } template <typename _OutputIterator> _OutputIterator _M_find_within_range(_OutputIterator out, _Link_const_type __N, _Region_ const& __REGION, _Region_ const& __BOUNDS, size_type const __L) const { if (__REGION.encloses(_S_value(__N))) { *out++ = _S_value(__N); } if (_S_left(__N)) { _Region_ __bounds(__BOUNDS); __bounds.set_high_bound(_S_value(__N), __L); if (__REGION.intersects_with(__bounds)) out = _M_find_within_range(out, _S_left(__N), __REGION, __bounds, __L+1); } if (_S_right(__N)) { _Region_ __bounds(__BOUNDS); __bounds.set_low_bound(_S_value(__N), __L); if (__REGION.intersects_with(__bounds)) out = _M_find_within_range(out, _S_right(__N), __REGION, __bounds, __L+1); } return out; } template <typename _Iter> void _M_optimise(_Iter const& __A, _Iter const& __B, size_type const __L) { if (__A == __B) return; _Node_compare_ compare(__L % __K, _M_acc, _M_cmp); _Iter __m = __A + (__B - __A) / 2; std::nth_element(__A, __m, __B, compare); this->insert(*__m); if (__m != __A) _M_optimise(__A, __m, __L+1); if (++__m != __B) _M_optimise(__m, __B, __L+1); } _Link_const_type _M_get_root() const { return const_cast<_Link_const_type>(_M_root); } _Link_type _M_get_root() { return _M_root; } void _M_set_root(_Link_type n) { _M_root = n; } _Link_const_type _M_get_leftmost() const { return static_cast<_Link_type>(_M_header._M_left); } void _M_set_leftmost( _Node_base * a ) { _M_header._M_left = a; } _Link_const_type _M_get_rightmost() const { return static_cast<_Link_type>( _M_header._M_right ); } void _M_set_rightmost( _Node_base * a ) { _M_header._M_right = a; } static _Link_type _S_parent(_Base_ptr N) { return static_cast<_Link_type>( N->_M_parent ); } static _Link_const_type _S_parent(_Base_const_ptr N) { return static_cast<_Link_const_type>( N->_M_parent ); } static void _S_set_parent(_Base_ptr N, _Base_ptr p) { N->_M_parent = p; } static void _S_set_left(_Base_ptr N, _Base_ptr l) { N->_M_left = l; } static _Link_type _S_left(_Base_ptr N) { return static_cast<_Link_type>( N->_M_left ); } static _Link_const_type _S_left(_Base_const_ptr N) { return static_cast<_Link_const_type>( N->_M_left ); } static void _S_set_right(_Base_ptr N, _Base_ptr r) { N->_M_right = r; } static _Link_type _S_right(_Base_ptr N) { return static_cast<_Link_type>( N->_M_right ); } static _Link_const_type _S_right(_Base_const_ptr N) { return static_cast<_Link_const_type>( N->_M_right ); } static bool _S_is_leaf(_Base_const_ptr N) { return !_S_left(N) && !_S_right(N); } static const_reference _S_value(_Link_const_type N) { return N->_M_value; } static const_reference _S_value(_Base_const_ptr N) { return static_cast<_Link_const_type>(N)->_M_value; } static _Link_const_type _S_minimum(_Link_const_type __X) { return static_cast<_Link_const_type> ( _Node_base::_S_minimum(__X) ); } static _Link_const_type _S_maximum(_Link_const_type __X) { return static_cast<_Link_const_type>( _Node_base::_S_maximum(__X) ); } _Link_type _M_new_node(const_reference __V, // = value_type(), _Base_ptr const __PARENT = nullptr, _Base_ptr const __LEFT = nullptr, _Base_ptr const __RIGHT = nullptr) { typename _Base::NoLeakAlloc noleak(this); _Link_type new_node = noleak.get(); _Base::_M_construct_node(new_node, __V, __PARENT, __LEFT, __RIGHT); noleak.disconnect(); return new_node; } /* WHAT was this for? _Link_type _M_clone_node(_Link_const_type __X) { _Link_type __ret = _M_allocate_node(__X->_M_value); // TODO return __ret; } */ void _M_delete_node(_Link_type __p) { _Base::_M_destroy_node(__p); _Base::_M_deallocate_node(__p); } _Link_type _M_root; _Node_base _M_header; size_type _M_count; _Acc _M_acc; _Cmp _M_cmp; _Dist _M_dist; #ifdef KDTREE_DEFINE_OSTREAM_OPERATORS friend std::ostream& operator<<(std::ostream& o, KDTree<__K, _Val, _Acc, _Dist, _Cmp, _Alloc> const& tree) { o << "meta node: " << tree._M_header << std::endl; o << "root node: " << tree._M_root << std::endl; if (tree.empty()) return o << "[empty " << __K << "d-tree " << &tree << "]"; o << "nodes total: " << tree.size() << std::endl; o << "dimensions: " << __K << std::endl; typedef KDTree<__K, _Val, _Acc, _Dist, _Cmp, _Alloc> _Tree; typedef typename _Tree::_Link_type _Link_type; std::stack<_Link_const_type> s; s.push(tree._M_get_root()); while (!s.empty()) { _Link_const_type n = s.top(); s.pop(); o << *n << std::endl; if (_Tree::_S_left(n)) s.push(_Tree::_S_left(n)); if (_Tree::_S_right(n)) s.push(_Tree::_S_right(n)); } return o; } #endif }; } // namespace KDTree #endif // include guard /* COPYRIGHT -- * * This file is part of libkdtree++, a C++ template KD-Tree sorting container. * libkdtree++ is (c) 2004-2007 Martin F. Krafft <libkdtree@pobox.madduck.net> * and Sylvain Bougerel <sylvain.bougerel.devel@gmail.com> distributed under the * terms of the Artistic License 2.0. See the ./COPYING file in the source tree * root for more information. * Parts of this file are (c) 2004-2007 Paul Harris <paulharris@computer.org>. * * THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/DATASTRUCTURES/CVReference.h
.h
1,657
79
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Andreas Bertsch $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/OpenMSConfig.h> #include <OpenMS/DATASTRUCTURES/String.h> #include <vector> namespace OpenMS { /** @brief Controlled Vocabulary Reference Reference to a controlled vocabulary, defined in the first section of a mapping file. @ingroup Datastructures */ class OPENMS_DLLAPI CVReference { public: /// Default constructor CVReference(); /// Copy constructor CVReference(const CVReference& rhs); /// Destructor virtual ~CVReference(); /// Assignment operator CVReference& operator=(const CVReference& rhs); /** @name Accessors */ //@{ /// sets the name of the CV reference void setName(const String& name); /// returns the name of the CV reference const String& getName() const; /// sets the CV identifier which is referenced void setIdentifier(const String& identifier); /// returns the CV identifier which is referenced const String& getIdentifier() const; //@} /** @name Predicates */ //@{ /// equality operator bool operator==(const CVReference& rhs) const; /// inequality operator bool operator!=(const CVReference& rhs) const; //@} protected: String name_; String identifier_; }; } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/DATASTRUCTURES/DRange.h
.h
10,691
402
// 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/DIntervalBase.h> #include <OpenMS/CONCEPT/HashUtils.h> #include <OpenMS/CONCEPT/Macros.h> #include <OpenMS/CONCEPT/Types.h> #include <functional> namespace OpenMS { /** @brief A D-dimensional half-open interval. This class describes a range in D-dimensional space delimited by two points (i.e. a D-dimensional hyper-rectangle). The two points define the lower left and the upper right corner in 2D and analogous points in higher dimensions. A range is a pair of positions in D-space represented by DPosition. The two limiting points are accessed as minPosition() and maxPosition(). A range denotes a semi-open interval. A lower coordinate of each dimension is part of the range, the higher coordinate is not. @ingroup Datastructures */ template <UInt D> class DRange : public Internal::DIntervalBase<D> { public: /** @name Type definitions */ //@{ /// Dimensions enum {DIMENSION = D}; /// Base class type typedef Internal::DIntervalBase<D> Base; /// Position type typedef typename Base::PositionType PositionType; /// Coordinate type of the positions typedef typename Base::CoordinateType CoordinateType; /// Types that describe the kind of intersection between two ranges enum DRangeIntersection { Disjoint, ///< No intersection Intersects, ///< Intersection Inside ///< One contains the other }; //@} using Base::min_; using Base::max_; /**@name Constructors and Destructor */ //@{ /** @brief Default constructor. Creates a range with all coordinates zero. */ DRange() : Base() { } /// Constructor that takes two Points and constructs a range. DRange(const PositionType& lower, const PositionType& upper) : Base(lower, upper) { } /// Copy constructor DRange(const DRange& range) : Base(range) { } /// Move constructor DRange(DRange&&) noexcept = default; /// Copy constructor for the base class DRange(const Base& range) : Base(range) { } /// Convenient constructor for DRange<2> DRange(CoordinateType minx, CoordinateType miny, CoordinateType maxx, CoordinateType maxy) { static_assert(D == 2); min_[0] = minx; min_[1] = miny; max_[0] = maxx; max_[1] = maxy; Base::normalize_(); } /// Assignment operator DRange& operator=(const DRange& rhs) { Base::operator=(rhs); return *this; } /// Assignment operator for the base class DRange& operator=(const Base& rhs) { Base::operator=(rhs); return *this; } /// Destructor ~DRange() { } //@} /**@name Predicates */ //@{ ///Equality operator bool operator==(const DRange& rhs) const { return Base::operator==(rhs); } /// Equality operator bool operator==(const Base& rhs) const { return Base::operator==(rhs); } /** @brief Checks whether this range (half open interval!) contains a certain point. @param[in] position The point's position. @returns true if point lies inside this area. */ bool encloses(const PositionType& position) const { for (UInt i = 0; i != D; i++) { if (position[i] < min_[i]) return false; if (position[i] >= max_[i]) return false; } return true; } ///@brief 2D-version of encloses for convenience only bool encloses(CoordinateType x, CoordinateType y) const { if (x < min_[0]) return false; if (x >= max_[0]) return false; if (y < min_[1]) return false; if (y >= max_[1]) return false; return true; } /// Returns the smallest range containing this range and @p other_range DRange united(const DRange<D>& other_range) const { PositionType united_min; PositionType united_max; DRange<D> united_range = DRange<D>::empty; PositionType other_min = other_range.minPosition(); PositionType other_max = other_range.maxPosition(); for (Size i = 0; i != D; ++i) { united_min[i] = min_[i] < other_min[i] ? min_[i] : other_min[i]; united_max[i] = max_[i] > other_max[i] ? max_[i] : other_max[i]; } united_range.setMinMax(united_min, united_max); return united_range; } /** @brief Checks how this range intersects with another @p range. @param[in] range The max_ range. */ DRangeIntersection intersects(const DRange& range) const { //check if r.min_ is in this area if (encloses(range.min_)) { //check if r.max_ in this area => Inside / Intersects for (Size i = 0; i != D; i++) { if (range.max_[i] > max_[i]) { return Intersects; } } return Inside; } // => r.min_ is not inside this area //check if any r.min_ >= max_ => Disjoint for (Size i = 0; i != D; i++) { if (range.min_[i] >= max_[i]) { return Disjoint; } } // => some coordinate of r.min_ has to be smaller than the one of min_ //check if all coords of r are smaller than the those of the range for (Size i = 0; i != D; i++) { if (range.max_[i] <= min_[i]) { return Disjoint; } } return Intersects; } /** @brief Checks whether this range intersects with another @p range. @param[in] range The max_ range. @returns True if the areas intersect (i.e. they intersect or one contains the other). */ bool isIntersected(const DRange& range) const { //check if r.min_ is in this area if (encloses(range.min_)) { return true; } // => r.min_ is not inside this area //check if any r.min_ >= max_ => Disjoint for (Size i = 0; i != D; i++) { if (range.min_[i] >= max_[i]) { return false; } } // => some coordinate of r.min_ has to be smaller than the one of min_ //check if all coords of r are smaller than the those of the range for (Size i = 0; i != D; i++) { if (range.max_[i] <= min_[i]) { return false; } } return true; } /** @brief Extends the range in all dimensions by a certain multiplier. Extends the range, while maintaining the original center position. Examples (for D=1): factor = 1.01 extends the range by 1% in total, i.e. 0.5% left and right. factor = 2.00 doubles the total range, e.g. from [0,100] to [-50,150] @param[in] factor Multiplier (allowed is [0, inf)). @return A reference to self */ DRange<D>& extend(double factor) { if (factor < 0) { throw Exception::InvalidParameter(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "DRange::extend(): factor must not be negative!"); } for (UInt i = 0; i != D; ++i) { Internal::DIntervalBase<1>::CoordinateType extra = (max_[i] - min_[i]) / 2.0 * (factor - 1); min_[i] -= extra; max_[i] += extra; } return *this; } /** @brief Extends the range in all dimensions by a certain amount. Extends the range, while maintaining the original center position. If a negative @p addition is given, the range shrinks and may result in min==max (but never min>max). Examples (for D=1): addition = 0.5 extends the range by 1 in total, i.e. 0.5 left and right. @param[in] addition Additive for each dimension (can be negative). Resulting invalid min/max are not fixed automatically! @return A reference to self */ DRange<D>& extend(typename Base::PositionType addition) { addition /= 2; min_ -= addition; max_ += addition; for (UInt i = 0; i != D; ++i) { // invalid range --> reduce to single center point if (min_[i] > max_[i]) min_[i] = max_[i] = (min_[i] + max_[i]) / 2; } return *this; } DRange<D>& ensureMinSpan(typename Base::PositionType min_span) { typename Base::PositionType extend_by {}; for (UInt i = 0; i != D; ++i) { // invalid range --> reduce to single center point if (max_[i] - min_[i] < min_span[i]) { extend_by[i] = min_span[i] - (max_[i] - min_[i]); // add whatever is missing to get to min_span } } extend(extend_by); return *this; } /// swaps dimensions for 2D data (i.e. x and y coordinates) DRange<D>& swapDimensions() { static_assert(D==2); std::swap(min_[0], min_[1]); std::swap(max_[0], max_[1]); return *this; } /** * @brief Make sure @p point is inside the current area * @param[in,out] point A point potentially outside the current range, which will be pulled into the current range. */ void pullIn(DPosition<D>& point) const { for (UInt i = 0; i != D; ++i) { point[i] = std::max(min_[i], std::min(point[i], max_[i])); } } //@} }; ///Print the contents to a stream. template <UInt D> std::ostream& operator<<(std::ostream& os, const DRange<D>& area) { os << "--DRANGE BEGIN--\n"; os << "MIN --> " << area.min_ << '\n'; os << "MAX --> " << area.max_ << '\n'; os << "--DRANGE END--\n"; return os; } } // namespace OpenMS // Hash function specialization for DRange namespace std { template<OpenMS::UInt D> struct hash<OpenMS::DRange<D>> { std::size_t operator()(const OpenMS::DRange<D>& range) const noexcept { std::size_t seed = 0; // Hash min_ position (all D coordinates) for (OpenMS::UInt i = 0; i < D; ++i) { OpenMS::hash_combine(seed, OpenMS::hash_float(range.minPosition()[i])); } // Hash max_ position (all D coordinates) for (OpenMS::UInt i = 0; i < D; ++i) { OpenMS::hash_combine(seed, OpenMS::hash_float(range.maxPosition()[i])); } return seed; } }; } // namespace std
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/DATASTRUCTURES/DPosition.h
.h
10,926
442
// 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/Macros.h> #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/CONCEPT/PrecisionWrapper.h> #include <OpenMS/CONCEPT/HashUtils.h> #include <algorithm> #include <array> #include <cmath> // for std::abs on integrals and floats #include <functional> #include <limits> #include <ostream> namespace OpenMS { /** @brief Representation of a coordinate in D-dimensional space. @ingroup Datastructures */ template <UInt D, typename TCoordinateType = double> class DPosition { public: /// Coordinate type using CoordinateType = TCoordinateType; using DataType = std::array<CoordinateType, D>; /// Dimensions enum { DIMENSION = D }; /** @name STL compatibility type definitions */ //@{ typedef CoordinateType value_type; typedef CoordinateType& reference; typedef CoordinateType* pointer; typedef CoordinateType* iterator; typedef const CoordinateType* const_iterator; //@} /** @name Constructors and Destructor */ //@{ /** @brief Default constructor. Creates a position with all coordinates zero. */ DPosition() = default; /// Constructor that fills all dimensions with the value @p x DPosition(CoordinateType x) { std::fill(coordinate_.begin(), coordinate_.end(), x); } /// Constructor only for DPosition<2> that takes two Coordinates. DPosition(CoordinateType x, CoordinateType y) { static_assert(D == 2, "DPosition<D, TCoordinateType>:DPosition(x,y): index overflow!"); coordinate_[0] = x; coordinate_[1] = y; } /// Constructor only for DPosition<3> that takes three Coordinates. DPosition(CoordinateType x, CoordinateType y, CoordinateType z) { static_assert(D == 3, "DPosition<D, TCoordinateType>:DPosition(x,y,z): index overflow!"); coordinate_[0] = x; coordinate_[1] = y; coordinate_[2] = z; } /// Copy constructor DPosition(const DPosition& pos) = default; /// Move constructor DPosition(DPosition&& rhs) noexcept = default; /// Assignment operator DPosition& operator=(const DPosition& source) = default; /// Move Assignment operator DPosition& operator=(DPosition&& source) noexcept = default; /// Destructor (not-virtual as this will save a lot of space!) ~DPosition() noexcept = default; //@} /// Swap the two objects void swap(DPosition& rhs) noexcept { std::swap(coordinate_, rhs.coordinate_); } /// Make all dimension values positive DPosition& abs() noexcept { for (Size i = 0; i < D; ++i) { coordinate_[i] = std::abs(coordinate_[i]); } return *this; } /**@name Accessors */ //@{ /// Const accessor for the dimensions CoordinateType operator[](Size index) const { OPENMS_PRECONDITION(index < D, "DPosition<D,TCoordinateType>:operator [] (Position): index overflow!"); return coordinate_[index]; } /// Accessor for the dimensions CoordinateType& operator[](Size index) { OPENMS_PRECONDITION(index < D, "DPosition<D,TCoordinateType>:operator [] (Position): index overflow!"); return coordinate_[index]; } /// Name accessor for the first dimension. Only for DPosition<2>, for visualization. CoordinateType getX() const { OPENMS_PRECONDITION(D == 2, "DPosition<D,TCoordinateType>:getX(): index overflow!"); return coordinate_[0]; } /// Name accessor for the second dimension. Only for DPosition<2>, for visualization. CoordinateType getY() const { OPENMS_PRECONDITION(D == 2, "DPosition<D,TCoordinateType>:getY(): index overflow!"); return coordinate_[1]; } /// Name mutator for the first dimension. Only for DPosition<2>, for visualization. void setX(CoordinateType c) { OPENMS_PRECONDITION(D == 2, "DPosition<D,TCoordinateType>:setX(): index overflow!"); coordinate_[0] = c; } /// Name mutator for the second dimension. Only for DPosition<2>, for visualization. void setY(CoordinateType c) { OPENMS_PRECONDITION(D == 2, "DPosition<D,TCoordinateType>:setY(): index overflow!"); coordinate_[1] = c; } /// Equality operator bool operator==(const DPosition& point) const = default; /// Equality operator bool operator!=(const DPosition& point) const = default; /** @brief Lexicographical less than operator. Lexicographical comparison from dimension 0 to dimension D-1 is done. */ bool operator<(const DPosition& point) const { return coordinate_ < point.coordinate_; } /// Lexicographical greater less or equal operator. bool operator<=(const DPosition& point) const { return coordinate_ <= point.coordinate_; } /// Spatially (geometrically) less or equal operator. All coordinates must be "<=". bool spatiallyLessEqual(const DPosition& point) const { for (Size i = 0; i < D; i++) { if (coordinate_[i] > point.coordinate_[i]) return false; } return true; } /// Spatially (geometrically) greater or equal operator. All coordinates must be ">=". bool spatiallyGreaterEqual(const DPosition& point) const { for (Size i = 0; i < D; i++) { if (coordinate_[i] < point.coordinate_[i]) return false; } return true; } /// Lexicographical greater than operator. bool operator>(const DPosition& point) const { return coordinate_ > point.coordinate_; } /// Lexicographical greater or equal operator. bool operator>=(const DPosition& point) const { return coordinate_ >= point.coordinate_; } /// Addition (a bit inefficient) DPosition operator+(const DPosition& point) const { DPosition result(*this); for (Size i = 0; i < D; ++i) { result.coordinate_[i] += point.coordinate_[i]; } return result; } /// Addition DPosition& operator+=(const DPosition& point) { for (Size i = 0; i < D; ++i) { coordinate_[i] += point.coordinate_[i]; } return *this; } /// Subtraction (a bit inefficient) DPosition operator-(const DPosition& point) const { DPosition result(*this); for (Size i = 0; i < D; ++i) { result.coordinate_[i] -= point.coordinate_[i]; } return result; } /// Subtraction DPosition& operator-=(const DPosition& point) { for (Size i = 0; i < D; ++i) { coordinate_[i] -= point.coordinate_[i]; } return *this; } /// Negation (a bit inefficient) DPosition operator-() const { DPosition<D, CoordinateType> result(*this); for (Size i = 0; i < D; ++i) { result.coordinate_[i] = -result.coordinate_[i]; } return result; } /// Inner product CoordinateType operator*(const DPosition& point) const { CoordinateType prod(0); for (Size i = 0; i < D; ++i) { prod += (point.coordinate_[i] * coordinate_[i]); } return prod; } /// Scalar multiplication DPosition& operator*=(CoordinateType scalar) { for (Size i = 0; i < D; ++i) { coordinate_[i] *= scalar; } return *this; } /// Scalar division DPosition& operator/=(CoordinateType scalar) { for (Size i = 0; i < D; ++i) { coordinate_[i] /= scalar; } return *this; } /// Returns the number of dimensions constexpr static Size size() { return D; } /// Set all dimensions to zero void clear() { coordinate_.fill(0); } //@} /** @name Static values */ //@{ /// all zero inline static constexpr DPosition zero() { return DPosition(0); } /// smallest positive inline static constexpr DPosition minPositive() { return DPosition((std::numeric_limits<typename DPosition::CoordinateType>::min)()); } /// smallest negative inline static constexpr DPosition minNegative() { return DPosition(std::numeric_limits<typename DPosition::CoordinateType>::lowest()); } /// largest positive inline static constexpr DPosition maxPositive() { return DPosition((std::numeric_limits<typename DPosition::CoordinateType>::max)()); } //@} /** @name Iteration */ //@{ /// Non-mutable begin iterator const_iterator begin() const { return &coordinate_[0]; } /// Non-mutable end iterator const_iterator end() const { return &coordinate_[0] + D; } /// Mutable begin iterator iterator begin() { return &coordinate_[0]; } /// Mutable end iterator iterator end() { return &coordinate_[0] + D; } //@} protected: DataType coordinate_{}; }; // DPosition /// Scalar multiplication (a bit inefficient) template <UInt D, typename TCoordinateType> DPosition<D, TCoordinateType> operator*(DPosition<D, TCoordinateType> position, typename DPosition<D, TCoordinateType>::CoordinateType scalar) { for (Size i = 0; i < D; ++i) { position[i] *= scalar; } return position; } /// Scalar multiplication (a bit inefficient) template <UInt D, typename TCoordinateType> DPosition<D, TCoordinateType> operator*(typename DPosition<D, TCoordinateType>::CoordinateType scalar, DPosition<D, TCoordinateType> position) { for (Size i = 0; i < D; ++i) { position[i] *= scalar; } return position; } /// Scalar multiplication (a bit inefficient) template <UInt D, typename TCoordinateType> DPosition<D, TCoordinateType> operator/(DPosition<D, TCoordinateType> position, typename DPosition<D, TCoordinateType>::CoordinateType scalar) { for (Size i = 0; i < D; ++i) { position[i] /= scalar; } return position; } /// Print the contents to a stream. template <UInt D, typename TCoordinateType> std::ostream& operator<<(std::ostream& os, const DPosition<D, TCoordinateType>& pos) { os << precisionWrapper(pos[0]); for (UInt i = 1; i < D; ++i) { os << ' ' << precisionWrapper(pos[i]); } return os; } } // namespace OpenMS // Hash function specialization for DPosition namespace std { template<OpenMS::UInt D, typename TCoordinateType> struct hash<OpenMS::DPosition<D, TCoordinateType>> { std::size_t operator()(const OpenMS::DPosition<D, TCoordinateType>& pos) const noexcept { std::size_t seed = 0; for (OpenMS::UInt i = 0; i < D; ++i) { OpenMS::hash_combine(seed, OpenMS::hash_float(pos[i])); } return seed; } }; } // namespace std
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/DATASTRUCTURES/CalibrationData.h
.h
5,832
184
// 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/KERNEL/RichPeak2D.h> #include <vector> #include <set> namespace OpenMS { /** @brief A helper class, holding all calibration points. Calibration points can be filled from Peptide IDs (using FeatureMaps or vector<PeptideIds>) or from lock masses in Raw data (MSExperiment). The m/z error can be queried using getError(). The unit of error is either ppm or Th, depending on usePPM(). Each calibration point can be assigned to a peak group. This should be done for calibration points derived from lock masses, to enable querying for a medianized representation of a lock mass trace in a certain RT range (see median()). For calibration points derived from peptide IDs, this does not make sense. From this data, a calibration function can be computed (see MZTrafoModel class). */ class OPENMS_DLLAPI CalibrationData { public: typedef RichPeak2D CalDataType; typedef std::vector<CalDataType>::const_iterator const_iterator; typedef std::vector<CalDataType>::value_type value_type; /** @brief Default constructor */ CalibrationData(); /** @brief Retrieve the observed m/z of the i'th calibration point */ CalDataType::CoordinateType getMZ(Size i) const; /** @brief Retrieve the observed RT of the i'th calibration point */ CalDataType::CoordinateType getRT(Size i) const; /** @brief Retrieve the intensity of the i'th calibration point */ CalDataType::CoordinateType getIntensity(Size i) const; /** @brief Begin iterator for calibration points */ const_iterator begin() const; /** @brief Past-the-end iterator for calibration points */ const_iterator end() const; /** @brief Number of calibration points */ Size size() const; /** @brief Do we have any calibration points */ bool empty() const; /** @brief Remove all calibration points */ void clear(); /** @brief When calling getError(), should ppm error or m/z error be returned? */ void setUsePPM(bool usePPM); /** @brief Current error unit (ppm or Th) */ bool usePPM() const; /** @brief Add a new calibration point @param[in] rt Retention time @param[in] mz_obs Observed m/z @param[in] intensity Intensity (useful for weighted model fitting) @param[in] mz_ref Theoretical m/z @param[in] weight Weight of calibration point (useful for weighted model fitting) @param[in] group Peak group of this calibration point. Using -1 will not assign any peak group. See also: median() */ void insertCalibrationPoint(CalDataType::CoordinateType rt, CalDataType::CoordinateType mz_obs, CalDataType::IntensityType intensity, CalDataType::CoordinateType mz_ref, double weight, int group = -1); /** @brief Number of peak groups (can be 0). */ Size getNrOfGroups() const; /** @brief Retrieve the error for i'th calibrant in either ppm or Th (depending on usePPM()) */ CalDataType::CoordinateType getError(Size i) const; /** @brief Retrieve the theoretical m/z of the i'th calibration point */ CalDataType::CoordinateType getRefMZ(Size i) const; /** @brief Retrieve the weight of the i'th calibration point */ CalDataType::CoordinateType getWeight(Size i) const; /** @brief Retrieve the group of the i'th calibration point. @param[in] i Index @return Group; returns -1 if peak has no group. */ int getGroup(Size i) const; /** @brief List of meta-values which are used internally (for conversion to PeakMap). */ static StringList getMetaValues(); /** @brief Compute the median in the given RT range for every peak group This is usually applied on calibration data obtained from lock masses, where each lock mass has its own peak group. Median() then computes an 'medianized' observed(!) lock mass within a certain RT range and returns calibration data with one calibration point per group. Also intensity is 'medianized'. The theoretical m/z is expected to be identical for all calibration points in a peak group. Groups must be specified during insertCalibrationPoint(). If no groups are present, the result is empty. The container must be sorted by RT (see sortByRT())! @param[in] rt_left Left border of RT range to medianize @param[in] rt_right Right border of RT range to medianize @return New container, containing median representation for each peak group */ CalibrationData median(double rt_left, double rt_right) const; /** @brief Sort calibration points by RT, to allow for valid RT chunking */ void sortByRT(); private: std::vector<RichPeak2D> data_; ///< calibration points bool use_ppm_; ///< return ppm values as y-values for the model instead of absolute delta in [Th] std::set<int> groups_; ///< peak groups present in this data }; } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/DATASTRUCTURES/CVMappingTerm.h
.h
2,908
115
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Andreas Bertsch $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/DATASTRUCTURES/String.h> #include <OpenMS/OpenMSConfig.h> namespace OpenMS { /** @brief Representation of controlled vocabulary term This class simply stores CV terms read from e.g. an OBO-file @ingroup Datastructures */ ///Representation of a CV term used by CVMappings class OPENMS_DLLAPI CVMappingTerm { public: /// Defaults constructor CVMappingTerm(); /// Copy constructor CVMappingTerm(const CVMappingTerm& rhs); /// Destructor virtual ~CVMappingTerm(); /// Assignment operator CVMappingTerm& operator=(const CVMappingTerm& rhs); /** @name Accessors */ //@{ /// sets the accession string of the term void setAccession(const String& accession); /// returns the accession string of the term const String& getAccession() const; /// sets whether the term name should be used, instead of the accession void setUseTermName(bool use_term_name); /// returns whether the term name should be used, instead of the accession bool getUseTermName() const; /// sets whether the term itself can be used (or only its children) void setUseTerm(bool use_term); /// returns true if the term can be used, false if only children are allowed bool getUseTerm() const; /// sets the name of the term void setTermName(const String& term_name); /// returns the name of the term const String& getTermName() const; /// sets whether this term can be repeated void setIsRepeatable(bool is_repeatable); /// returns true if this term can be repeated, false otherwise bool getIsRepeatable() const; /// sets whether children of this term are allowed void setAllowChildren(bool allow_children); /// returns true if the children of this term are allowed to be used bool getAllowChildren() const; /// sets the cv identifier reference string, e.g. UO for unit obo void setCVIdentifierRef(const String& cv_identifier_ref); /// returns the cv identifier reference string const String& getCVIdentifierRef() const; //@} /** @name Predicates */ //@{ /// equality operator bool operator==(const CVMappingTerm& rhs) const; /// inequality operator bool operator!=(const CVMappingTerm& rhs) const; //} protected: String accession_; bool use_term_name_; bool use_term_; String term_name_; bool is_repeatable_; bool allow_children_; String cv_identifier_ref_; }; } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/DATASTRUCTURES/Matrix.h
.h
8,667
314
// 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/Macros.h> #include <OpenMS/CONCEPT/Types.h> #include <vector> #include <algorithm> #include <iostream> #include <iomanip> #include <stdexcept> namespace OpenMS { /** * @brief A 2D matrix class with efficient buffer access for NumPy interoperability. * * Data is stored in column-major order (Fortran style) for compatibility with * Eigen and most numerical libraries. Internal OpenMS code can obtain zero-copy * Eigen views via the eigenView() function in MatrixEigen.h (internal header). * * @tparam Value The element type (typically double or float) * * @ingroup Datastructures */ template <typename Value> class Matrix { public: ///@name Type definitions ///@{ using value_type = Value; using iterator = typename std::vector<Value>::iterator; using const_iterator = typename std::vector<Value>::const_iterator; ///@} ///@name Constructors and assignment ///@{ /// Default constructor creates empty matrix Matrix() : rows_(0), cols_(0) {} /** * @brief Constructor to create a matrix with specified dimensions and fill value. * * @param rows Number of rows in the matrix. * @param cols Number of columns in the matrix. * @param value Initial value to fill the matrix. */ Matrix(Size rows, Size cols, Value value = Value()) : data_(rows * cols, value), rows_(rows), cols_(cols) {} /// Copy constructor Matrix(const Matrix&) = default; /// Move constructor Matrix(Matrix&&) noexcept = default; /// Copy assignment operator Matrix& operator=(const Matrix&) = default; /// Move assignment operator Matrix& operator=(Matrix&&) noexcept = default; /// Destructor ~Matrix() = default; ///@} ///@name Dimension accessors ///@{ /// Number of rows Size rows() const { return rows_; } /// Number of columns Size cols() const { return cols_; } /// Total number of elements Size size() const { return data_.size(); } /// Check if matrix is empty bool empty() const { return data_.empty(); } ///@} ///@name Element access ///@{ /** * @brief Get element at (row, col) * * Note: pyOpenMS can't easily wrap operator() so we provide additional getter. * * @param[in] row Zero-based row index. * @param[in] col Zero-based column index. * @return Const reference to the value at the given position. */ const Value& getValue(size_t const row, size_t const col) const { return data_[col * rows_ + row]; // Column-major } /** * @brief Get mutable element at (row, col) * * Note: pyOpenMS can't easily wrap operator() so we provide additional getter. * * @param[in] row Zero-based row index. * @param[in] col Zero-based column index. * @return Mutable reference to the value at the given position. */ Value& getValue(size_t const row, size_t const col) { return data_[col * rows_ + row]; // Column-major } /** * @brief Set element at (row, col) * * Note: pyOpenMS can't easily wrap operator() so we provide additional setter. * * @param[in] row Zero-based row index. * @param[in] col Zero-based column index. * @param[in] value Value to set at the given position. */ void setValue(size_t const row, size_t const col, const Value& value) { data_[col * rows_ + row] = value; // Column-major } /// Unchecked element access (row, col) Value& operator()(size_t row, size_t col) { return data_[col * rows_ + row]; } /// Unchecked const element access (row, col) const Value& operator()(size_t row, size_t col) const { return data_[col * rows_ + row]; } ///@} ///@name Buffer access (for NumPy/Cython interoperability) ///@{ /// Pointer to raw data buffer (column-major storage) Value* data() { return data_.data(); } /// Const pointer to raw data buffer const Value* data() const { return data_.data(); } /// Stride between consecutive elements in same column (always 1 for column-major) int innerStride() const { return 1; } /// Stride between consecutive columns int outerStride() const { return static_cast<int>(rows_); } /// Returns false (column-major storage, not row-major) static constexpr bool rowMajor() { return false; } ///@} ///@name Modifiers ///@{ /// Resize matrix (contents become undefined after resize) void resize(size_t rows, size_t cols) { rows_ = rows; cols_ = cols; data_.resize(rows * cols); } /// Fill all elements with value void fill(Value value) { std::fill(data_.begin(), data_.end(), value); } /// Clear matrix (set to 0x0) void clear() { data_.clear(); rows_ = 0; cols_ = 0; } /** * @brief Sets the matrix values using a 2D array. * * This function resizes the matrix to the specified number of rows and columns, * and then assigns the values from the 2D array to the corresponding elements * in the matrix. * * @tparam T The type of the matrix elements. * @tparam ROWS The number of rows in the matrix. * @tparam COLS The number of columns in the matrix. * @param[in] array The 2D array containing the values to be assigned to the matrix. */ template <typename T, long int ROWS, long int COLS> void setMatrix(T const (&array)[ROWS][COLS]) { resize(ROWS, COLS); for (long int i = 0; i < ROWS; ++i) { for (long int j = 0; j < COLS; ++j) { (*this)(i, j) = array[i][j]; } } } ///@} ///@name Iterators ///@{ iterator begin() { return data_.begin(); } iterator end() { return data_.end(); } const_iterator begin() const { return data_.begin(); } const_iterator end() const { return data_.end(); } const_iterator cbegin() const { return data_.cbegin(); } const_iterator cend() const { return data_.cend(); } ///@} ///@name Reduction operations ///@{ /** * @brief Returns the maximum value in the matrix. * * @return The maximum value. For empty matrices, returns Value() (default-constructed value). */ Value maxValue() const { if (data_.empty()) return Value(); return *std::max_element(data_.begin(), data_.end()); } /** * @brief Returns the minimum value in the matrix. * * @return The minimum value. For empty matrices, returns Value() (default-constructed value). */ Value minValue() const { if (data_.empty()) return Value(); return *std::min_element(data_.begin(), data_.end()); } ///@} ///@name Comparison ///@{ /** * @brief Equality operator. Compares two matrices for equality. * * @param[in] rhs The matrix to be compared. * @return True if matrices are equal, false otherwise. * * @throw Exception::Precondition if matrices have different dimensions (Debug mode only) */ bool operator==(const Matrix& rhs) const { OPENMS_PRECONDITION(rows_ == rhs.rows_ && cols_ == rhs.cols_, "Matrices must have the same dimensions for comparison."); return data_ == rhs.data_; } bool operator!=(const Matrix& rhs) const { return !(*this == rhs); } ///@} /** * @brief Friend function to output the matrix to an output stream. * * @param[in,out] os Output stream. * @param[in] matrix Matrix to be output. * @return Reference to the output stream. */ friend std::ostream& operator<<(std::ostream& os, const Matrix<Value>& matrix) { for (Size i = 0; i < matrix.rows(); ++i) { for (Size j = 0; j < matrix.cols(); ++j) { os << std::setprecision(6) << std::setw(6) << matrix(i, j) << ' '; } os << '\n'; } return os; } private: std::vector<Value> data_; ///< Column-major storage Size rows_; ///< Number of rows Size cols_; ///< Number of columns }; } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/DATASTRUCTURES/StringUtilsSimple.h
.h
19,471
653
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg, Chris Bielow $ // $Authors: Marc Sturm, Stephan Aiche, Chris Bielow $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/DATASTRUCTURES/String.h> #include <OpenMS/CONCEPT/Exception.h> #include <algorithm> #include <cmath> #include <sstream> #include <string_view> #include <string> #include <vector> namespace OpenMS { class String; namespace StringUtils { // /// Functions // static inline String numberLength(double d, UInt n) { std::stringstream s; //reserve one space for the minus sign Int sign = 0; if (d < 0) sign = 1; d = fabs(d); if (d < pow(10.0, Int(n - sign - 2))) { s.precision(writtenDigits(d)); if (sign == 1) s << "-"; s << d; } else { UInt exp = 0; while (d > pow(10.0, Int(n - sign - 4))) { d /= 10; ++exp; } d = Int(d) / 10.0; exp += 1; if (sign == 1) s << "-"; s << d << "e"; if (exp < 10) s << "0"; s << exp; } return s.str().substr(0, n); } static inline String& fillLeft(String & this_s, char c, UInt size) { if (this_s.size() < size) { this_s.std::string::operator=(String(size - this_s.size(), c) + this_s); } return this_s; } static inline String& fillRight(String & this_s, char c, UInt size) { if (this_s.size() < size) { this_s.std::string::operator=(this_s + String(size - this_s.size(), c)); } return this_s; } static inline bool hasPrefix(const String & this_s, const String & string) { if (string.size() > this_s.size()) { return false; } if (string.empty()) { return true; } return this_s.compare(0, string.size(), string) == 0; } static inline bool hasSuffix(const String & this_s, const String& string) { if (string.size() > this_s.size()) { return false; } if (string.empty()) { return true; } return this_s.compare(this_s.size() - string.size(), string.size(), string) == 0; } static inline bool hasSubstring(const String & this_s, const String& string) { return this_s.find(string) != std::string::npos; } static inline bool has(const String & this_s, Byte byte) { return this_s.find(char(byte)) != std::string::npos; } static inline String prefix(const String & this_s, size_t length) { if (length > this_s.size()) { throw Exception::IndexOverflow(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, length, this_s.size()); } return this_s.substr(0, length); } static inline String suffix(const String & this_s, size_t length) { if (length > this_s.size()) { throw Exception::IndexOverflow(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, length, this_s.size()); } return this_s.substr(this_s.size() - length, length); } static inline String prefix(const String & this_s, Int length) { if (length < 0) { throw Exception::IndexUnderflow(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, length, 0); } if (length > Int(this_s.size())) { throw Exception::IndexOverflow(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, length, this_s.size()); } return this_s.substr(0, length); } static inline String suffix(const String & this_s, Int length) { if (length < 0) { throw Exception::IndexUnderflow(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, length, 0); } if (length > Int(this_s.size())) { throw Exception::IndexOverflow(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, length, this_s.size()); } return this_s.substr(this_s.size() - length, length); } static inline String prefix(const String & this_s, char delim) { Size pos = this_s.find(delim); if (pos == std::string::npos) //char not found { throw Exception::ElementNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String(delim)); } return this_s.substr(0, pos); } static inline String suffix(const String & this_s, char delim) { Size pos = this_s.rfind(delim); if (pos == std::string::npos) //char not found { throw Exception::ElementNotFound(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String(delim)); } return this_s.substr(++pos); } static inline String substr(const String & this_s, size_t pos, size_t n) { Size begin = std::min(pos, this_s.size()); return static_cast<String>(this_s.std::string::substr(begin, n)); } static inline String chop(const String & this_s, Size n) { Size end = 0; if (n < this_s.size()) { end = this_s.size() - n; } return String(this_s.begin(), this_s.begin() + end); } static inline String& trim(String & this_s) { //search for the begin of truncated string std::string::iterator begin = this_s.begin(); while (begin != this_s.end() && (*begin == ' ' || *begin == '\t' || *begin == '\n' || *begin == '\r')) { ++begin; } //all characters are whitespaces if (begin == this_s.end()) { this_s.clear(); return this_s; } //search for the end of truncated string std::string::iterator end = this_s.end(); end--; while (end != begin && (*end == ' ' || *end == '\n' || *end == '\t' || *end == '\r')) { --end; } ++end; //no characters are whitespaces if (begin == this_s.begin() && end == this_s.end()) { return this_s; } // TODO: // string::operator=(std::string(begin, end)); this_s.std::string::operator=(std::string(begin, end)); return this_s; } static inline bool isQuoted(const String & this_s, char q) { return (this_s.size() < 2) || (this_s[0] != q) || (this_s[this_s.size() - 1] != q); } static inline String& quote(String & this_s, char q, String::QuotingMethod method) { if (method == String::ESCAPE) { this_s.substitute(String(R"(\)"), String(R"(\\)")); this_s.substitute(String(q), R"(\)" + String(q)); } else if (method == String::DOUBLE) this_s.substitute(String(q), String(q) + String(q)); this_s.std::string::operator=(q + this_s + q); return this_s; } static inline String& unquote(String & this_s, char q, String::QuotingMethod method) { // check if input string matches output format of the "quote" method: if (isQuoted(this_s, q)) { throw Exception::ConversionError( __FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "'" + this_s + "' does not have the expected format of a quoted string"); } this_s.std::string::operator=(this_s.substr(1, this_s.size() - 2)); // remove quotation marks if (method == String::ESCAPE) { this_s.substitute(R"(\)" + String(q), String(q)); this_s.substitute(String(R"(\\)"), String(R"(\)")); } else if (method == String::DOUBLE) this_s.substitute(String(q) + String(q), String(q)); return this_s; } static inline String& simplify(String & this_s) { String simple; bool last_was_whitespace = false; for (std::string::iterator it = this_s.begin(); it != this_s.end(); ++it) { if (*it == ' ' || *it == '\n' || *it == '\t' || *it == '\r') { if (!last_was_whitespace) { simple += ' '; } last_was_whitespace = true; } else { simple += *it; last_was_whitespace = false; } } this_s.swap(simple); return this_s; } static inline String random(UInt length) { srand(time(nullptr)); String tmp(length, '.'); size_t random; for (Size i = 0; i < length; ++i) { random = static_cast<size_t>(floor((static_cast<double>(rand()) / (double(RAND_MAX) + 1)) * 62.0)); if (random < 10) { tmp[i] = static_cast<char>(random + 48); } else if (random < 36) { tmp[i] = static_cast<char>(random + 55); } else { tmp[i] = static_cast<char>(random + 61); } } return tmp; } static inline String& reverse(String & this_s) { String tmp = this_s; for (Size i = 0; i != this_s.size(); ++i) { this_s[i] = tmp[this_s.size() - 1 - i]; } return this_s; } static inline bool split(const String & this_s, const char splitter, std::vector<String>& substrings, bool quote_protect) { substrings.clear(); if (this_s.empty()) return false; Size nsplits = count(this_s.begin(), this_s.end(), splitter); if (!quote_protect && (nsplits == 0)) { substrings.push_back(this_s); return false; } // splitter(s) found substrings.reserve(nsplits + 1); // why is "this_s." needed here? std::string::const_iterator begin = this_s.begin(); std::string::const_iterator end = this_s.begin(); if (quote_protect) { Int quote_count(0); for (; end != this_s.end(); ++end) { if (*end == '"') { ++quote_count; } if ((quote_count % 2 == 0) && (*end == splitter)) { String block = String(begin, end); block.trim(); if ((block.size() >= 2) && ((block.prefix(1) == String("\"")) ^ (block.suffix(1) == String("\"")))) { // block has start or end quote, but not both // (one quote is somewhere in the middle) throw Exception::ConversionError( __FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Could not dequote string '") + block + "' due to wrongly placed '\"'."); } else if ((block.size() >= 2) && (block.prefix(1) == String("\"")) && (block.suffix(1) == String("\""))) { // block has start and end quotes --> remove them block = block.substr(1, block.size() - 2); } substrings.push_back(block); begin = end + 1; } } // no valid splitter found - return empty list if (substrings.empty()) { substrings.push_back(this_s); return false; } String block = String(begin, end); block.trim(); if ((block.size() >= 2) && ((block.prefix(1) == String("\"")) ^ (block.suffix(1) == String("\"")))) { // block has start or end quote but not both // (one quote is somewhere in the middle) throw Exception::ConversionError( __FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Could not dequote string '") + block + "' due to wrongly placed '\"'."); } else if ((block.size() >= 2) && (block.prefix(1) == String("\"")) && (block.suffix(1) == String("\""))) { // block has start and end quotes --> remove them block = block.substr(1, block.size() - 2); } substrings.push_back(block); } else // do not honor quotes { for (; end != this_s.end(); ++end) { if (*end == splitter) { substrings.push_back(String(begin, end)); begin = end + 1; } } substrings.push_back(String(begin, end)); } // at this point we are sure that there are at least two components return true; } static inline bool split(const String & this_s, const String& splitter, std::vector<String>& substrings) { substrings.clear(); if (this_s.empty()) return false; if (splitter.empty()) // split after every character: { substrings.resize(this_s.size()); for (Size i = 0; i < this_s.size(); ++i) substrings[i] = this_s[i]; return true; } Size len = splitter.size(), start = 0, pos = this_s.find(splitter); if (len == 0) len = 1; while (pos != std::string::npos) { substrings.push_back(this_s.substr(start, pos - start)); start = pos + len; pos = this_s.find(splitter, start); } substrings.push_back(this_s.substr(start, this_s.size() - start)); return substrings.size() > 1; } static inline bool split_quoted(const String & this_s, const String& splitter, std::vector<String>& substrings, char q, String::QuotingMethod method) { substrings.clear(); if (this_s.empty() || splitter.empty()) return false; bool in_quote = false; char targets[2] = {q, splitter[0]}; // targets for "find_first_of" std::string rest = splitter.substr(1, splitter.size() - 1); Size start = 0; for (Size i = 0; i < this_s.size(); ++i) { if (in_quote) // skip to closing quotation mark { bool embedded = false; if (method == String::ESCAPE) { for (; i < this_s.size(); ++i) { if (this_s[i] == '\\') embedded = !embedded; else if ((this_s[i] == q) && !embedded) break; else embedded = false; } } else // method: NONE or DOUBLE { for (; i < this_s.size(); ++i) { if (this_s[i] == q) { if (method == String::NONE) break; // found // next character is also closing quotation mark: if ((i < this_s.size() - 1) && (this_s[i + 1] == q)) embedded = !embedded; // even number of subsequent quotes (doubled) => found else if (!embedded) break; // odd number of subsequent quotes => belongs to a pair else embedded = false; } } } in_quote = false; // end of quote reached } else { i = this_s.find_first_of(targets, i, 2); if (i == std::string::npos) break; // nothing found if (this_s[i] == q) in_quote = true; else if (this_s.compare(i + 1, rest.size(), rest) == 0) // splitter found { substrings.push_back(this_s.substr(start, i - start)); start = i + splitter.size(); i = start - 1; // increased by loop } } } if (in_quote) // reached end without finding closing quotation mark { throw Exception::ConversionError( __FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "unbalanced quotation marks in string '" + this_s + "'"); } substrings.push_back(this_s.substr(start, this_s.size() - start)); return substrings.size() > 1; } static inline String& toUpper(String & this_s) { std::transform(this_s.begin(), this_s.end(), this_s.begin(), (int (*)(int))toupper); return this_s; } static inline String& firstToUpper(String & this_s) { if (!this_s.empty()) { this_s[0] = toupper(this_s[0]); } return this_s; } static inline String& toLower(String & this_s) { std::transform(this_s.begin(), this_s.end(), this_s.begin(), (int (*)(int))tolower); return this_s; } static inline String& substitute(String & this_s, char from, char to) { std::replace(this_s.begin(), this_s.end(), from, to); return this_s; } static inline String& substitute(String & this_s, const String& from, const String& to) { if (!from.empty()) { std::vector<String> parts; this_s.split(from, parts); this_s.concatenate(parts.begin(), parts.end(), to); } return this_s; } static inline String& remove(String & this_s, char what) { this_s.erase(std::remove(this_s.begin(), this_s.end(), what), this_s.end()); return this_s; } static inline String& ensureLastChar(String & this_s, char end) { if (!this_s.hasSuffix(end)) this_s.append(1, end); return this_s; } /** @brief Get the first non-whitespace character (anything but \\n, \\t, \\r, ' ') in the string pointed to by @p p (where @p p_end is past the end of the string). If only whitespaces are contained, then @p p_end is returned. */ OPENMS_DLLAPI const char* skipWhitespace(const char* p, const char* p_end); /** @brief Get the number of whitespace characters (\\n, \\t, \\r, ' ') in the prefix of @p data */ inline int skipWhitespace(const std::string_view& data) { auto pos = skipWhitespace(data.data(), data.data() + data.size()); return pos - data.data(); } /** @brief Get the first whitespace character (\\n, \\t, \\r, ' ') in the string pointed to by @p p (where @p p_end is past the end of the string). If only non-whitespaces are contained, then @p p_end is returned. */ OPENMS_DLLAPI const char* skipNonWhitespace(const char* p, const char* p_end); /** @brief return the number of non-whitespace characters (anything but \\n, \\t, \\r, ' ') in the prefix of @p data */ inline int skipNonWhitespace(const std::string_view& data) { auto pos = skipNonWhitespace(data.data(), data.data() + data.size()); return pos - data.data(); } static inline String& removeWhitespaces(String& this_s) { auto start = skipNonWhitespace(std::string_view(this_s.data())); std::string::const_iterator it = this_s.begin() + start; std::string::iterator dest = this_s.begin() + start; std::string::const_iterator it_end = this_s.end(); bool has_spaces(false); while (it != it_end) { const char c = *it; if (c == ' ' || c == '\t' || c == '\n' || c == '\r') { ++it; has_spaces = true; continue; // no need to copy a whitespace } // copy to the left, if we had a whitespace before if (has_spaces) *dest = *it; // advance both ++dest; ++it; } // shorten result if (has_spaces) this_s.resize(dest - this_s.begin()); return this_s; } } } // namespace OPENMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/DATASTRUCTURES/ConvexHull2D.h
.h
7,047
178
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg$ // $Authors: Marc Sturm, Chris Bielow $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/CONCEPT/HashUtils.h> #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/DATASTRUCTURES/DBoundingBox.h> #include <OpenMS/DATASTRUCTURES/DPosition.h> #include <OpenMS/OpenMSConfig.h> #include <functional> #include <map> #include <vector> namespace OpenMS { /** @brief A 2-dimensional hull representation in [counter]clockwise direction - depending on axis labelling. The current implementation does not guarantee to produce convex hulls. It can still store 'old' convex hulls from featureXML without problems, but does not support the enclose() query in this case, and you will get an exception. As an alternative, you can use my_hull.getBoundingBox().encloses(), which yields similar results, and will always work. If you are creating new hull from peaks (e.g. during FeatureFinding), the generated hulls of a feature are defined as a range in m/z dimension for each RT scan (thus might be non-convex). This has the advantage that one can clearly see where points range within each scan (although missing points within this range are still not shown). When hulls are created like this, the encloses() function is supported, and works as expected, i.e. for the shape defined by this hull (view it in TOPPView) it answers whether the point is inside the shape. However, once you store the hull in featureXML and load it again, the encloses() function is not supported any longer, because the old convex hulls did not save min&max for each scan. (to support encloses() at least for the new hulls, one would need to check if there exists a min&max value for each scan --> then the query would be valid and the inner representation can be filled. Old featureXML's are not supported in any case.) The outer hullpoints can be queried by getHullPoints(). @improvement For chromatograms we could postprocess the input and remove points in intermediate RT scans, which are currently reported but make the number of points rather large. @ingroup Datastructures */ class OPENMS_DLLAPI ConvexHull2D { public: typedef DPosition<2> PointType; typedef std::vector<PointType> PointArrayType; typedef PointArrayType::size_type SizeType; typedef PointArrayType::const_iterator PointArrayTypeConstIterator; typedef std::map<PointType::CoordinateType, DBoundingBox<1> > HullPointType; /// default constructor ConvexHull2D(); /// Copy constructor ConvexHull2D(const ConvexHull2D&) = default; /// Move constructor ConvexHull2D(ConvexHull2D&&) = default; /// assignment operator ConvexHull2D& operator=(const ConvexHull2D& rhs); /// move assignment operator ConvexHull2D& operator=(ConvexHull2D&&) & = default; /// equality operator bool operator==(const ConvexHull2D& rhs) const; /// removes all points void clear(); /// accessor for the outer points const PointArrayType& getHullPoints() const; /// @brief Accessor for the internal map representation (RT -> m/z bounding box) const HullPointType& getMapPoints() const { return map_points_; } /// accessor for the outer(!) points (no checking is performed if this is actually a convex hull) void setHullPoints(const PointArrayType& points); /// returns the bounding box of the feature hull points DBoundingBox<2> getBoundingBox() const; /// adds a point to the hull if it is not already contained. Returns if the point was added. /// this will trigger recomputation of the outer hull points (thus points set with setHullPoints() will be lost) bool addPoint(const PointType& point); /// adds points to the hull if it is not already contained. /// this will trigger recomputation of the outer hull points (thus points set with setHullPoints() will be lost) void addPoints(const PointArrayType& points); /** @brief Allows to reduce the disk/memory footprint of a hull Removes points from the hull which lie on a straight line and do not contribute to the hulls shape. Should be called before saving to disk. Example: Consider a series of 3 scans with the same dimension in m/z. After calling compress, the points from the second scan will be removed, since they do not contribute to the convex hull. @returns Number of removed scans **/ Size compress(); /** @brief Expand a convex hull to its bounding box. This reduces the size of a convex hull to four points, its bounding box, thus reducing size when storing the information. Note that this leads to an enclosed area that can be significantly larger than the original convex hull. **/ void expandToBoundingBox(); /** @brief returns if the @p point lies in the feature hull This function is only supported if the hull is created using addPoint() or addPoints(), but not when using setHullPoints(). If you require the latter functionality, then augment this function. @throws Exception::NotImplemented if only hull points (outer_points_), but no internal structure (map_points_) is given **/ bool encloses(const PointType& point) const; protected: /// internal structure maintaining the hull and enabling queries to encloses() HullPointType map_points_; /// just the list of points of the outer hull (derived from map_points_ or given by user) mutable PointArrayType outer_points_; }; } // namespace OpenMS // Hash function specialization for ConvexHull2D namespace std { template<> struct hash<OpenMS::ConvexHull2D> { std::size_t operator()(const OpenMS::ConvexHull2D& hull) const noexcept { std::size_t seed = 0; // Hash map_points_ (map of RT -> m/z bounding box) // std::map iteration order is deterministic (sorted by key) const auto& map_points = hull.getMapPoints(); OpenMS::hash_combine(seed, OpenMS::hash_int(map_points.size())); for (const auto& entry : map_points) { OpenMS::hash_combine(seed, OpenMS::hash_float(entry.first)); OpenMS::hash_combine(seed, std::hash<OpenMS::DBoundingBox<1>>{}(entry.second)); } // Hash outer_points_ (vector of DPosition<2>) const auto& outer_points = hull.getHullPoints(); OpenMS::hash_combine(seed, OpenMS::hash_int(outer_points.size())); for (const auto& point : outer_points) { OpenMS::hash_combine(seed, std::hash<OpenMS::DPosition<2>>{}(point)); } return seed; } }; } // namespace std
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/DATASTRUCTURES/StringUtils.h
.h
10,303
247
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg, Chris Bielow $ // $Authors: Marc Sturm, Stephan Aiche, Chris Bielow $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/DATASTRUCTURES/String.h> #include <OpenMS/DATASTRUCTURES/StringUtilsSimple.h> #include <OpenMS/CONCEPT/Exception.h> #include <OpenMS/DATASTRUCTURES/DataValue.h> #include <OpenMS/CONCEPT/PrecisionWrapper.h> #include <QtCore/QString> #include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/karma.hpp> #include <boost/type_traits.hpp> #include <string> #include <vector> namespace OpenMS { class String; class OPENMS_DLLAPI StringUtilsHelper { public: // /// Functions // static Int toInt32(const String& this_s) { Int ret; // boost::spirit::qi was found to be vastly superior to boost::lexical_cast or stringstream extraction (especially for VisualStudio), // so don't change this unless you have benchmarks for all platforms! String::ConstIterator it = this_s.begin(); if (!boost::spirit::qi::phrase_parse(it, this_s.end(), boost::spirit::qi::int_, boost::spirit::ascii::space, ret)) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Could not convert string '") + this_s + "' to an integer value"); } // was the string parsed (white spaces are skipped automatically!) completely? If not, we have a problem because a previous split might have used the wrong split char if (it != this_s.end()) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Prefix of string '") + this_s + "' successfully converted to an int32 value. Additional characters found at position " + (int)(distance(this_s.begin(), it) + 1)); } return ret; } static Int64 toInt64(const String& this_s) { Int64 ret; // boost::spirit::qi was found to be vastly superior to boost::lexical_cast or stringstream extraction (especially for VisualStudio), // so don't change this unless you have benchmarks for all platforms! String::ConstIterator it = this_s.begin(); if (!boost::spirit::qi::phrase_parse(it, this_s.end(), boost::spirit::qi::long_long, boost::spirit::ascii::space, ret)) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Could not convert string '") + this_s + "' to an int64 value"); } // was the string parsed (white spaces are skipped automatically!) completely? If not, we have a problem because a previous split might have used the wrong split char if (it != this_s.end()) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Prefix of string '") + this_s + "' successfully converted to an integer value. Additional characters found at position " + (int)(distance(this_s.begin(), it) + 1)); } return ret; } static float toFloat(const String& this_s) { float ret; // boost::spirit::qi was found to be vastly superior to boost::lexical_cast or stringstream extraction (especially for VisualStudio), // so don't change this unless you have benchmarks for all platforms! String::ConstIterator it = this_s.begin(); if (!boost::spirit::qi::phrase_parse(it, this_s.end(), parse_float_, boost::spirit::ascii::space, ret)) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Could not convert string '") + this_s + "' to a float value"); } // was the string parsed (white spaces are skipped automatically!) completely? If not, we have a problem because a previous split might have used the wrong split char if (it != this_s.end()) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Prefix of string '") + this_s + "' successfully converted to a float value. Additional characters found at position " + (int)(distance(this_s.begin(), it) + 1)); } return ret; } /** @brief convert String (leading and trailing whitespace allowed) to double @p s Input string which represents a double, e.g. " 12.3 " @return A double representation of @p s @throws Exception::ConversionError if the string is not completely explained by the double (whitespaces are allowed) */ static double toDouble(const String& s) { double ret; // boost::spirit::qi was found to be vastly superior to boost::lexical_cast or stringstream extraction (especially for VisualStudio), // so don't change this unless you have benchmarks for all platforms! String::ConstIterator it = s.begin(); if (!boost::spirit::qi::phrase_parse(it, s.end(), parse_double_, boost::spirit::ascii::space, ret)) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Could not convert string '") + s + "' to a double value"); } // was the string parsed (white spaces are skipped automatically!) completely? If not, we have a problem because a previous split might have used the wrong split char if (it != s.end()) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Prefix of string '") + s + "' successfully converted to a double value. Additional characters found at position " + (int)(distance(s.begin(), it) + 1)); } return ret; } /// Reads a double from an iterator position. /// The begin iterator is modified (advanced) if parsing was successful. /// The @p target only contains a valid result if the functions returns true (i.e. parsing succeeded). /// Whitespaces before and after the double are NOT consumed! template <typename IteratorT> static bool extractDouble(IteratorT& begin, const IteratorT& end, double& target) { // boost::spirit::qi was found to be vastly superior to boost::lexical_cast or stringstream extraction (especially for VisualStudio), // so don't change this unless you have benchmarks for all platforms! // qi::parse() does not consume whitespace before or after the double (qi::parse_phrase() would). return boost::spirit::qi::parse(begin, end, parse_double_, target); } /// Reads an int from an iterator position. /// The begin iterator is modified (advanced) if parsing was successful. /// The @p target only contains a valid result if the functions returns true (i.e. parsing succeeded). /// Whitespaces before and after the double are NOT consumed! template <typename IteratorT> static bool extractInt(IteratorT& begin, const IteratorT& end, int& target) { // qi::parse() does not consume whitespace before or after the int (qi::parse_phrase() would). return boost::spirit::qi::parse(begin, end, parse_int_, target); } private: /* @brief A fixed Boost:pi real parser policy, capable of dealing with 'nan' without crashing The original Boost implementation has a bug, see https://svn.boost.org/trac/boost/ticket/6955. Can be removed if Boost 1.60 or above is required */ template <typename T> struct real_policies_NANfixed_ : boost::spirit::qi::real_policies<T> { template <typename Iterator, typename Attribute> static bool parse_nan(Iterator& first, Iterator const& last, Attribute& attr_) { if (first == last) return false; // end of input reached if (*first != 'n' && *first != 'N') return false; // not "nan" // nan[(...)] ? if (boost::spirit::qi::detail::string_parse("nan", "NAN", first, last, boost::spirit::qi::unused)) { if (first != last && *first == '(') /* this check is broken in boost 1.49 - (at least) 1.54; fixed in 1.60 */ { // skip trailing (...) part Iterator i = first; while (++i != last && *i != ')') ; if (i == last) return false; // no trailing ')' found, give up first = ++i; } attr_ = std::numeric_limits<T>::quiet_NaN(); return true; } return false; } }; // Qi parsers using the 'real_policies_NANfixed_' template which allows for 'nan' // (the original Boost implementation has a bug, see https://svn.boost.org/trac/boost/ticket/6955) static boost::spirit::qi::real_parser<double, real_policies_NANfixed_<double> > parse_double_; static boost::spirit::qi::real_parser<float, real_policies_NANfixed_<float> > parse_float_; static boost::spirit::qi::int_parser<> parse_int_; }; namespace StringUtils { [[maybe_unused]] static String number(double d, UInt n) { return QString::number(d, 'f', n); } [[maybe_unused]] static QString toQString(const String & this_s) { return QString(this_s.c_str()); } [[maybe_unused]] static Int32 toInt32(const String & this_s) { return StringUtilsHelper::toInt32(this_s); } [[maybe_unused]] static Int64 toInt64(const String& this_s) { return StringUtilsHelper::toInt64(this_s); } [[maybe_unused]] static float toFloat(const String & this_s) { return StringUtilsHelper::toFloat(this_s); } [[maybe_unused]] static double toDouble(const String & this_s) { return StringUtilsHelper::toDouble(this_s); } template <typename IteratorT> static bool extractDouble(IteratorT& begin, const IteratorT& end, double& target) { return StringUtilsHelper::extractDouble(begin, end, target); } template <typename IteratorT> static bool extractInt(IteratorT& begin, const IteratorT& end, int& target) { return StringUtilsHelper::extractInt(begin, end, target); } } } // namespace OPENMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/DATASTRUCTURES/StringListUtils.h
.h
8,402
230
// 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/DATASTRUCTURES/ListUtils.h> #include <OpenMS/OpenMSConfig.h> #include <QtCore/qcontainerfwd.h> // for QStringList namespace OpenMS { /** @brief Utilities operating on lists of Strings @ingroup Datastructures */ class OPENMS_DLLAPI StringListUtils { public: /** @name Type definitions */ //@{ /// Mutable iterator typedef std::vector<String>::iterator Iterator; /// Non-mutable iterator typedef std::vector<String>::const_iterator ConstIterator; /// Mutable reverse iterator typedef std::vector<String>::reverse_iterator ReverseIterator; /// Non-mutable reverse iterator typedef std::vector<String>::const_reverse_iterator ConstReverseIterator; //@} /// Creates a StringList from a QStringList static StringList fromQStringList(const QStringList& rhs); ///@name Search methods //@{ /** @brief Searches for the first line that starts with @p text beginning at line @p start @param[in] start Iterator pointing to the initial position to search. (note: that this does not need to correspond to the beginning of the container. @param[in] end Iterator pointing to the end final position of the sequence to search. @param[in] text The text to find @param[in] trim Whether the line is trimmed before @return Returns an iterator to the matching entry. If no line matches end is returned. */ static Iterator searchPrefix(const Iterator& start, const Iterator& end, const String& text, bool trim = false); /** @brief Searches for the first line that starts with @p text beginning at line @p start @param[in] start Iterator pointing to the initial position to search. (note: that this does not need to correspond to the beginning of the container. @param[in] end Iterator pointing to the end final position of the sequence to search. @param[in] text The text to find @param[in] trim Whether the line is trimmed before @return Returns an iterator to the matching entry. If no line matches end is returned. */ static ConstIterator searchPrefix(const ConstIterator& start, const ConstIterator& end, const String& text, bool trim = false); /** @brief Searches for the first line that starts with @p text in the StringList @p container. @param[in] container The StringList that should be searched. @param[in] text The text to find @param[in] trim Whether the line is trimmed before @return Returns an iterator to the matching entry. If no line matches end is returned. */ static ConstIterator searchPrefix(const StringList& container, const String& text, bool trim = false); /** @brief Searches for the first line that starts with @p text in the StringList @p container. @param[in] container The StringList that should be searched. @param[in] text The text to find @param[in] trim Whether the line is trimmed before @return Returns an iterator to the matching entry. If no line matches end is returned. */ static Iterator searchPrefix(StringList& container, const String& text, bool trim = false); /** @brief Searches for the first line that ends with @p text beginning at line @p start @param[in] start Iterator pointing to the initial position to search. (note: that this does not need to correspond to the beginning of the container. @param[in] end Iterator pointing to the end final position of the sequence to search. @param[in] text The text to find @param[in] trim Whether the line is trimmed before @return Returns an iterator to the matching entry. If no line matches end is returned. */ static Iterator searchSuffix(const Iterator& start, const Iterator& end, const String& text, bool trim = false); /** @brief Searches for the first line that ends with @p text beginning at line @p start @param[in] start Iterator pointing to the initial position to search. (note: that this does not need to correspond to the beginning of the container. @param[in] end Iterator pointing to the end final position of the sequence to search. @param[in] text The text to find @param[in] trim Whether the line is trimmed before @return Returns an iterator to the matching entry. If no line matches end is returned. */ static ConstIterator searchSuffix(const ConstIterator& start, const ConstIterator& end, const String& text, bool trim = false); /** @brief Searches for the first line that ends with @p text in the StringList @p container. @param[in] container The StringList that should be searched. @param[in] text The text to find @param[in] trim Whether the line is trimmed before @return Returns an iterator to the matching entry. If no line matches end is returned. */ static ConstIterator searchSuffix(const StringList& container, const String& text, bool trim = false); /** @brief Searches for the first line that ends with @p text in the StringList @p container. @param[in] container The StringList that should be searched. @param[in] text The text to find @param[in] trim Whether the line is trimmed before @return Returns an iterator to the matching entry. If no line matches end is returned. */ static Iterator searchSuffix(StringList& container, const String& text, bool trim = false); //@} /** @brief Transforms all strings contained in the passed StringList to upper case. @param[in] sl The StringList to convert to upper case. */ static void toUpper(StringList& sl); /** @brief Transforms all strings contained in the passed StringList to lower case. @param[in] sl The StringList to convert to lower case. */ static void toLower(StringList& sl); private: /// @cond INTERNAL struct TrimmableStringPredicate_ { TrimmableStringPredicate_(const String& target, const bool trim) : trim_(trim), target_(target) { if (trim_) target_.trim(); } inline String getValue(const String& value) const { if (trim_) { // trim is not a const function so we need to create a copy first String cp = value; return cp.trim(); } else { return value; } } protected: /// Should the strings be trimmed. bool trim_; /// The target value that should be found. String target_; }; /// Predicate to search in a StringList for a specific prefix. struct PrefixPredicate_ : TrimmableStringPredicate_ { PrefixPredicate_(const String& target, const bool trim) : TrimmableStringPredicate_(target, trim) {} /** @brief Returns true if the (trimmed) value has the prefix @p target_. @param[in] value The value to test. @return true if value has prefix target, false otherwise. */ inline bool operator()(const String& value) { return getValue(value).hasPrefix(target_); } }; /// Predicate to search in a StringList for a specific suffix. struct SuffixPredicate_ : TrimmableStringPredicate_ { SuffixPredicate_(const String& target, const bool trim) : TrimmableStringPredicate_(target, trim) {} /** @brief Returns true if the (trimmed) value has the suffix @p target_. @param[in] value The value to test. @return true if value has suffix target, false otherwise. */ inline bool operator()(const String& value) { return getValue(value).hasSuffix(target_); } }; /// @endcond INTERNAL /// hide c'tors to avoid instantiation of utils class StringListUtils() {} StringListUtils(const StringListUtils&){} StringListUtils& operator=(StringListUtils&){return *this; } }; } // namespace OPENMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/DATASTRUCTURES/StringConversions.h
.h
9,835
282
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg, Chris Bielow $ // $Authors: Marc Sturm, Stephan Aiche, Chris Bielow $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/DATASTRUCTURES/String.h> #include <OpenMS/CONCEPT/Exception.h> #include <OpenMS/DATASTRUCTURES/DataValue.h> #include <OpenMS/CONCEPT/PrecisionWrapper.h> #include <boost/spirit/include/qi.hpp> #include <boost/spirit/include/karma.hpp> #include <boost/type_traits.hpp> #include <boost/spirit/home/karma/numeric/detail/real_utils.hpp> #include <string> #include <vector> namespace OpenMS { class String; namespace StringConversions { namespace Detail { // Karma full precision float policy template<typename T> class BK_PrecPolicyFull : public boost::spirit::karma::real_policies<T> { typedef boost::spirit::karma::real_policies<T> base_policy_type; public: static unsigned precision(T /*n*/) { /* The following would be the only way for a lossless double-string-double * roundtrip but: * a) We only care about speed * b) Many tests have to be changed * c) In the end boost::karma is bugged and hard limits the fractional digits * even though you have leading zeros (basically forcing scientific notation) * for full precision https://github.com/boostorg/spirit/issues/585 if (BK_PrecPolicyFull::floatfield(n)) { T abs_n = boost::spirit::traits::get_absolute_value(n); if (abs_n >= 1) { return std::numeric_limits<T>::max_digits10 - (floor(log10(abs_n)) + 1); } else { return std::numeric_limits<T>::max_digits10 - (floor(log10(abs_n))); } } else { return std::numeric_limits<T>::max_digits10 - 1; } */ return writtenDigits<T>(); } // we want the numbers always to be in scientific format static unsigned floatfield(T n) { if (boost::spirit::traits::test_zero(n)) return base_policy_type::fmtflags::fixed; T abs_n = boost::spirit::traits::get_absolute_value(n); // this is due to a bug in downstream thirdparty tools that only can read // up to 19 digits. https://github.com/OpenMS/OpenMS/issues/4627 return (abs_n >= 1e4 || abs_n < 1e-2) ? base_policy_type::fmtflags::scientific : base_policy_type::fmtflags::fixed; } // we need this special 'NaN' since the default 'nan' is not recognized by downstream tools such as any Java-based tool (e.g. KNIME) trying to // parse our output files template<typename CharEncoding, typename Tag, typename OutputIterator> static bool nan(OutputIterator& sink, T n, bool force_sign) { return boost::spirit::karma::sign_inserter::call(sink, false, boost::spirit::traits::test_negative(n), force_sign) && boost::spirit::karma::string_inserter<CharEncoding, Tag>::call(sink, "NaN"); } }; // Karma default (3-digits) precision float policy template<typename T> class BK_PrecPolicyShort : public boost::spirit::karma::real_policies<T> { typedef boost::spirit::karma::real_policies<T> base_policy_type; public: // we need this special 'NaN' since the default 'nan' is not recognized by downstream tools such as any Java-based tool (e.g. KNIME) trying to // parse our output files template<typename CharEncoding, typename Tag, typename OutputIterator> static bool nan(OutputIterator& sink, T n, bool force_sign) { return boost::spirit::karma::sign_inserter::call(sink, false, boost::spirit::traits::test_negative(n), force_sign) && boost::spirit::karma::string_inserter<CharEncoding, Tag>::call(sink, "NaN"); } }; using BK_PrecPolicyFloatFull_type = boost::spirit::karma::real_generator<float, BK_PrecPolicyFull<float>>; const BK_PrecPolicyFloatFull_type BK_PrecPolicyFloatFull; using BK_PrecPolicyDoubleFull_type = boost::spirit::karma::real_generator<double, BK_PrecPolicyFull<double>>; const BK_PrecPolicyDoubleFull_type BK_PrecPolicyDoubleFull; using BK_PrecPolicyLongDoubleFull_type = boost::spirit::karma::real_generator<long double, BK_PrecPolicyFull<long double>>; const BK_PrecPolicyLongDoubleFull_type BK_PrecPolicyLongDoubleFull; using BK_PrecPolicyFloatShort_type = boost::spirit::karma::real_generator<float, BK_PrecPolicyShort<float>>; const BK_PrecPolicyFloatShort_type BK_PrecPolicyFloatShort; using BK_PrecPolicyDoubleShort_type = boost::spirit::karma::real_generator<double, BK_PrecPolicyShort<double>>; const BK_PrecPolicyDoubleShort_type BK_PrecPolicyDoubleShort; using BK_PrecPolicyLongDoubleShort_type = boost::spirit::karma::real_generator<long double, BK_PrecPolicyShort<long double>>; const BK_PrecPolicyLongDoubleShort_type BK_PrecPolicyLongDoubleShort; } // namespace Detail // toString functions (single argument) /// fallback template for general purpose using Boost::Karma; more specializations below /// does NOT clear the input string @p target, so appending is as efficient as possible template <typename T> inline void append(const T& i, String& target) { std::back_insert_iterator<std::string> sink(target); boost::spirit::karma::generate(sink, i); } /// fallback template for general purpose using Boost::Karma; more specializations below template <typename T> inline String toString(const T& i) { //std::stringstream s; //s << i; //return s.str(); String str; append(i, str); return str; } /// low precision (3 fractional digits) conversion to string (Karma default) /// does NOT clear the input string @p target, so appending is as efficient as possible inline void appendLowP(float f, String& target) { std::back_insert_iterator<std::string> sink(target); boost::spirit::karma::generate(sink, Detail::BK_PrecPolicyFloatShort, f); } /// low precision (3 fractional digits) conversion to string (Karma default) inline String toStringLowP(float f) { String str; appendLowP(f, str); return str; } /// low precision (3 fractional digits) conversion to string (Karma default) /// does NOT clear the input string @p target, so appending is as efficient as possible inline void appendLowP(double d, String& target) { std::back_insert_iterator<std::string> sink(target); boost::spirit::karma::generate(sink, Detail::BK_PrecPolicyDoubleShort, d); } /// low precision (3 fractional digits) conversion to string (Karma default) inline String toStringLowP(double d) { String str; appendLowP(d, str); return str; } /// low precision (3 fractional digits) conversion to string (Karma default) inline void appendLowP(long double ld, String& target) { std::back_insert_iterator<std::string> sink(target); boost::spirit::karma::generate(sink, Detail::BK_PrecPolicyLongDoubleShort, ld); } /// low precision (3 fractional digits) conversion to string (Karma default) inline String toStringLowP(long double ld) { String str; appendLowP(ld, str); return str; } /// high precision (6 fractional digits) conversion to String inline void append(float f, String& target) { std::back_insert_iterator<std::string> sink(target); boost::spirit::karma::generate(sink, Detail::BK_PrecPolicyFloatFull, f); } /// high precision (6 fractional digits) conversion to String inline String toString(float f) { String str; append(f, str); return str; } /// high precision (15 fractional digits) conversion to String inline void append(double d, String& target) { std::back_insert_iterator<std::string> sink(target); boost::spirit::karma::generate(sink, Detail::BK_PrecPolicyDoubleFull, d); } /// high precision (15 fractional digits) conversion to String inline String toString(double d) { String str; append(d, str); return str; } /// high precision (15 fractional digits) conversion to String inline void append(long double ld, String& target) { std::back_insert_iterator<std::string> sink(target); boost::spirit::karma::generate(sink, Detail::BK_PrecPolicyLongDoubleFull, ld); } /// high precision (15 fractional digits) conversion to String inline String toString(long double ld) { String str; append(ld, str); return str; } inline void append(const DataValue& d, bool full_precision, String& target) { target += d.toString(full_precision); } inline String toString(const DataValue& d, bool full_precision) { return d.toString(full_precision); } inline String toString(const char c) { return std::string(1, c); } inline String toString(const std::string& s) { return s; } inline String toString(const char* s) { return std::string(s); } /// Other toString functions (different number of arguments) inline String toString() { return String(); } } } // namespace OPENMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/DATASTRUCTURES/DBoundingBox.h
.h
5,174
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/DATASTRUCTURES/DIntervalBase.h> #include <OpenMS/CONCEPT/HashUtils.h> #include <OpenMS/CONCEPT/Types.h> #include <functional> namespace OpenMS { /** @brief A D-dimensional bounding box. A DBoundingBox denotes a closed interval. Upper and lower margins are both contained. @ingroup Datastructures */ template <UInt D> class DBoundingBox : public Internal::DIntervalBase<D> { public: /** @name Type definitions */ //@{ /// Dimensions enum {DIMENSION = D}; /// Base class type typedef Internal::DIntervalBase<D> Base; /// Position type typedef typename Base::PositionType PositionType; /// Coordinate type of the positions typedef typename Base::CoordinateType CoordinateType; //@} // for convenience using Base::min_; using Base::max_; /**@name Constructors and Destructor */ //@{ ///Default constructor. DBoundingBox() : Base() { } /// Copy constructor DBoundingBox(const DBoundingBox& rhs) : Base(rhs) { } /// Assignment operator DBoundingBox& operator=(const DBoundingBox& rhs) { Base::operator=(rhs); return *this; } /// Assignment operator for the base class DBoundingBox& operator=(const Base& rhs) { Base::operator=(rhs); return *this; } /// Destructor ~DBoundingBox() { } ///Constructor from two positions DBoundingBox(const PositionType& minimum, const PositionType& maximum) : Base(minimum, maximum) { } //@} /**@name Accessors */ //@{ /// Enlarges the bounding box such that it contains a position. void enlarge(const PositionType& p) { for (UInt i = 0; i < DIMENSION; ++i) { if (p[i] < min_[i]) min_[i] = p[i]; if (p[i] > max_[i]) max_[i] = p[i]; } } ///Enlarges the bounding box such that it contains a position specified by two coordinates void enlarge(CoordinateType x, CoordinateType y) { enlarge(PositionType(x, y)); } //}@ /**@name Predicates */ //@{ /// Equality operator bool operator==(const DBoundingBox& rhs) const { return Base::operator==(rhs); } /// Equality operator bool operator==(const Base& rhs) const { return Base::operator==(rhs); } /** @brief Checks whether this range contains a certain point. @param[in] position The point's position. @returns true if point lies inside this area. */ bool encloses(const PositionType& position) const { for (UInt i = 0; i < DIMENSION; ++i) { if (position[i] < min_[i] || position[i] > max_[i]) { return false; } } return true; } ///2D-version encloses(x,y) is for convenience only bool encloses(CoordinateType x, CoordinateType y) const { return encloses(PositionType(x, y)); } /** Checks whether this bounding box intersects with another bounding box */ bool intersects(const DBoundingBox& bounding_box) const { for (UInt i = 0; i < DIMENSION; ++i) { if (bounding_box.min_[i] > max_[i]) return false; if (bounding_box.max_[i] < min_[i]) return false; } return true; } /// Test if bounding box is empty bool isEmpty() const { for (UInt i = 0; i != D; i++) { if (max_[i] <= min_[i]) { return true; } } return false; } //@} }; /**@brief Print the contents to a stream. @relatesalso DBoundingBox */ template <UInt D> std::ostream& operator<<(std::ostream& os, const DBoundingBox<D>& bounding_box) { os << "--DBOUNDINGBOX BEGIN--" << std::endl; os << "MIN --> " << bounding_box.minPosition() << std::endl; os << "MAX --> " << bounding_box.maxPosition() << std::endl; os << "--DBOUNDINGBOX END--" << std::endl; return os; } } // namespace OpenMS // Hash function specialization for DBoundingBox namespace std { template<OpenMS::UInt D> struct hash<OpenMS::DBoundingBox<D>> { std::size_t operator()(const OpenMS::DBoundingBox<D>& bb) const noexcept { // Hash both min_ and max_ positions (fields used in operator==) std::size_t seed = 0; // Hash minPosition const auto& min_pos = bb.minPosition(); for (OpenMS::UInt i = 0; i < D; ++i) { OpenMS::hash_combine(seed, OpenMS::hash_float(min_pos[i])); } // Hash maxPosition const auto& max_pos = bb.maxPosition(); for (OpenMS::UInt i = 0; i < D; ++i) { OpenMS::hash_combine(seed, OpenMS::hash_float(max_pos[i])); } return seed; } }; } // namespace std
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/DATASTRUCTURES/ExposedVector.h
.h
10,218
372
// 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 <cstddef> // for size_t #include <vector> #include <algorithm> #include <concepts> namespace OpenMS { template<typename T> concept LessThanComparable = requires(const T& a, const T& b) { // less and greater { a < b } -> std::convertible_to<bool>; }; /// Macro to expose common dependent types, such as @p iterator in the derived class #define EXPOSED_VECTOR_INTERFACE(InnerElement) \ using ExpVec = ExposedVector< InnerElement >; \ using ExpVec::ExposedVector; \ using value_type = typename ExpVec::value_type; \ using iterator = typename ExpVec::iterator; \ using const_iterator = typename ExpVec::const_iterator; \ using reverse_iterator = typename ExpVec::reverse_iterator; \ using const_reverse_iterator = typename ExpVec::const_reverse_iterator; \ using size_type = typename ExpVec::size_type; \ using pointer = typename ExpVec::pointer; \ using reference = typename ExpVec::reference; \ using const_reference = typename ExpVec::const_reference; \ using difference_type = typename ExpVec::difference_type; \ /** @brief Makes a vector<VectorElement> available in the derived class and exposed commonly used vector member functions at class level. This saves writing repetitive code which forwards commonly used functions of a data member, e.g. 'data_.begin()' as a member function of the class. Also it makes private inheritance from vector<VectorElement> obsolete. The latter is problematic for many reasons (read up on 'prefer composition over inheritance'). In our case, even linking can be problematic with private inheritance once you require RTTI (which some tools do, e.g. softwipe). To fully utilize this class (i.e. access the 'iterator' type), insert \code EXPOSED_VECTOR_INTERFACE(VectorElement) \endcode in your derived class, where @p VectorElement is identical to the template argument of ExposedVector, e.g. 'Feature' for FeatureMap. @ingroup Datastructures */ template<class VectorElement> class ExposedVector { public: using VecMember = std::vector<VectorElement>; // types using value_type = typename VecMember::value_type; using iterator = typename VecMember::iterator; using const_iterator = typename VecMember::const_iterator; using reverse_iterator = typename VecMember::reverse_iterator; using const_reverse_iterator = typename VecMember::const_reverse_iterator; using size_type = typename VecMember::size_type; using pointer = typename VecMember::pointer; using reference = typename VecMember::reference; using const_reference = typename VecMember::const_reference; using difference_type = typename VecMember::difference_type; protected: VecMember data_; ///< the container which holds all the data public: ExposedVector() = default; explicit ExposedVector(const size_t n) : data_(n) { } ExposedVector(const size_t n, const VectorElement& val) : data_(n, val) { } template <class Iter> ExposedVector(Iter begin, Iter end) : data_(begin, end) { } /// Copy C'tor ExposedVector(const ExposedVector& rhs) = default; /// Move C'tor ExposedVector(ExposedVector&& rhs) noexcept = default; /// Assignment ExposedVector& operator=(const ExposedVector& rhs) = default; /// Move Assignment ExposedVector& operator=(ExposedVector&& rhs) noexcept = default; iterator begin() noexcept { return data_.begin(); } iterator end() noexcept { return data_.end(); } const_iterator begin() const noexcept { return data_.begin(); } const_iterator end() const noexcept { return data_.end(); } const_iterator cbegin() const noexcept { return data_.cbegin(); } const_iterator cend() const noexcept { return data_.cend(); } size_t size() const noexcept { return data_.size(); } void resize(const size_t new_size) { data_.resize(new_size); } void reserve(const size_t new_size) { data_.reserve(new_size); } bool empty() const noexcept { return data_.empty(); } VectorElement& operator[](size_t i) noexcept { return data_[i]; } const VectorElement& operator[](size_t i) const noexcept { return data_[i]; } VectorElement& at(size_t i) { return data_.at(i); } const VectorElement& at(size_t i) const { return data_.at(i); } VectorElement& back() noexcept { return data_.back(); } const VectorElement& back() const noexcept { return data_.back(); } void push_back(const VectorElement& f) { data_.push_back(f); } void push_back(VectorElement&& f) { data_.push_back(std::move(f)); } template<typename... Args> decltype(auto) emplace_back(Args&&... args) { return data_.emplace_back(std::forward<Args>(args)...); } void pop_back() noexcept { data_.pop_back(); } iterator erase(const_iterator where) noexcept { return data_.erase(where); } iterator erase(const_iterator from, const_iterator to) noexcept { return data_.erase(from, to); } template<typename T> iterator insert(const_iterator where, T from, T to) { return data_.insert(where, from, to); } /// Clear all elements void clear() noexcept { data_.clear(); } /// Get reverse iterator to beginning reverse_iterator rbegin() noexcept { return data_.rbegin(); } /// Get const reverse iterator to beginning const_reverse_iterator rbegin() const noexcept { return data_.rbegin(); } /// Get reverse iterator to end reverse_iterator rend() noexcept { return data_.rend(); } /// Get const reverse iterator to end const_reverse_iterator rend() const noexcept { return data_.rend(); } /// Get const reverse iterator to beginning const_reverse_iterator crbegin() const noexcept { return data_.crbegin(); } /// Get const reverse iterator to end const_reverse_iterator crend() const noexcept { return data_.crend(); } /// Swap contents with another ExposedVector void swap(ExposedVector& other) noexcept { data_.swap(other.data_); } /// Assign values from iterators template<typename InputIt> void assign(InputIt first, InputIt last) { data_.assign(first, last); } /// Assign n copies of value void assign(size_type count, const VectorElement& value) { data_.assign(count, value); } /// Assign from initializer list void assign(std::initializer_list<VectorElement> init) { data_.assign(init); } /// Get first element VectorElement& front() noexcept { return data_.front(); } /// Get first element (const) const VectorElement& front() const noexcept { return data_.front(); } /// Get maximum possible size size_type max_size() const noexcept { return data_.max_size(); } /// Get current capacity size_type capacity() const noexcept { return data_.capacity(); } /// Shrink capacity to fit size void shrink_to_fit() { data_.shrink_to_fit(); } /// Insert single element iterator insert(const_iterator pos, const VectorElement& value) { return data_.insert(pos, value); } /// Insert single element (move) iterator insert(const_iterator pos, VectorElement&& value) { return data_.insert(pos, std::move(value)); } /// Insert n copies of value iterator insert(const_iterator pos, size_type count, const VectorElement& value) { return data_.insert(pos, count, value); } /// Insert from initializer list iterator insert(const_iterator pos, std::initializer_list<VectorElement> init) { return data_.insert(pos, init); } /// Emplace element at position template<typename... Args> iterator emplace(const_iterator pos, Args&&... args) { return data_.emplace(pos, std::forward<Args>(args)...); } /// read-only access to the underlying data const VecMember& getData() const { return data_; } /// read access to the underlying data VecMember& getData() { return data_; } /// Equality comparison bool operator==(const ExposedVector& other) const { return data_ == other.data_; } /// Inequality comparison bool operator!=(const ExposedVector& other) const { return data_ != other.data_; } // Define operators only if underlying vector supports them bool operator<(const ExposedVector& other) const requires LessThanComparable<VectorElement> { return data_ < other.data_; } bool operator<=(const ExposedVector& other) const requires LessThanComparable<VectorElement> { return data_ <= other.data_; } bool operator>(const ExposedVector& other) const requires LessThanComparable<VectorElement> { return data_ > other.data_; } bool operator>=(const ExposedVector& other) const requires LessThanComparable<VectorElement> { return data_ >= other.data_; } }; } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/DATASTRUCTURES/CVMappings.h
.h
2,301
91
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Andreas Bertsch $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/OpenMSConfig.h> #include <OpenMS/DATASTRUCTURES/String.h> #include <map> #include <vector> namespace OpenMS { class CVMappingRule; class CVReference; /** @brief Representation of controlled vocabulary mapping rules (for PSI formats) This file serves as object for the controlled vocabulary term usage definitions used in CV-Mapping files. All the supported attributes supported in the mapping file are supported by this class. @ingroup Format */ class OPENMS_DLLAPI CVMappings { public: /// Default constructor CVMappings(); /// Copy constructor CVMappings(const CVMappings& rhs); /// Destructor virtual ~CVMappings(); /// Assignment operator CVMappings& operator=(const CVMappings& rhs); /** @name Accessors */ //@{ /// sets the mapping rules of the mapping file void setMappingRules(const std::vector<CVMappingRule>& cv_mapping_rules); /// returns the mapping rules const std::vector<CVMappingRule>& getMappingRules() const; /// adds a mapping rule void addMappingRule(const CVMappingRule& cv_mapping_rule); /// sets the CV references void setCVReferences(const std::vector<CVReference>& cv_references); /// returns the CV references const std::vector<CVReference>& getCVReferences() const; /// adds a CV reference void addCVReference(const CVReference& cv_reference); //@} /** @name Predicates */ //@{ /// returns true if a CV reference is given bool hasCVReference(const String& identifier); /// equality operator bool operator==(const CVMappings& rhs) const; /// inequality operator bool operator!=(const CVMappings& rhs) const; //@} protected: std::vector<CVMappingRule> mapping_rules_; std::map<String, CVReference> cv_references_; std::vector<CVReference> cv_references_vector_; }; } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/DATASTRUCTURES/FlagSet.h
.h
4,738
212
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow $ // $Authors: Chris Bielow $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/CONCEPT/Macros.h> // for OPENMS_PRECONDITION namespace OpenMS { /** @brief Stores and handles combinations of enum values, e.g. a set of flags as bits flipped in an UInt64 Conversion from the enum is computed as `pow(2, r)`. Thus make sure that 0 <= 'r' <=63 for all enum values. Multiple enum values can be computed by bitwise 'or' (operator|=) This class allows assignment and bit operations with itself and an object of type ENUM, i.e. not with any numeric types. **/ template<class ENUM> class FlagSet { public: /// Constructors FlagSet() : value_(0) {} /// C'tor from Enum explicit FlagSet(const ENUM& en) : value_(getPow_(en)) { } FlagSet(const FlagSet& stat) = default; /// Assignment FlagSet& operator=(const FlagSet& stat) = default; /// no Assignment from Enum (would allow implicit conversion) FlagSet& operator=(const ENUM& en) = delete; /// Destructor (default) ~FlagSet() = default; /// Equality bool operator==(const FlagSet& stat) const { return (value_ == stat.value_); } /// bitwise AND FlagSet operator&(const ENUM& en) const { FlagSet s(*this) ; s &= en; return s; } /// bitwise AND FlagSet operator&(const FlagSet& rhs) const { FlagSet s(*this); s &= rhs; return s; } /// bitwise AND= FlagSet& operator&=(const ENUM& en) { value_ &= getPow_(en); return *this; } /// bitwise AND= FlagSet& operator&=(const FlagSet& rhs) { value_ &= rhs.value_; return *this; } /// bitwise OR FlagSet operator|(const ENUM& en) const { FlagSet s(*this); s.value_ |= getPow_(en); return s; } /// bitwise OR FlagSet operator|(const FlagSet& rhs) const { FlagSet s(*this); s.value_ |= rhs.value_; return s; } ///bitwise OR= FlagSet& operator|=(const ENUM& en) { value_ |= getPow_(en); return *this; } /// bitwise OR= FlagSet& operator|=(const FlagSet& rhs) { value_ |= rhs.value_; return *this; } /// bitwise OR (same as |) FlagSet operator+(const ENUM& en) const { return *this | en; } /// bitwise OR (same as |) FlagSet operator+(const FlagSet& en) const { return *this | en; } ///bitwise OR= (same as |=) FlagSet& operator+=(const ENUM& rhs) { return *this |= rhs; } /// bitwise OR= (same as |=) FlagSet& operator+=(const FlagSet& rhs) { return *this |= rhs; } /// remove all flags set in @p rhs from this FlagSet operator-(const FlagSet& rhs) { FlagSet r(*this); r -= rhs; return r; } /// remove all flags set in @p rhs from this FlagSet& operator-=(const FlagSet& rhs) { auto overlap = value_ & rhs.value_; value_ ^= overlap; // disable bits which overlap with rhs using XOR return *this; } /// remove flag in @p rhs from this FlagSet operator-(const ENUM& rhs) { FlagSet r(*this); r -= rhs; return r; } /// remove flag in @p rhs from this FlagSet& operator-=(const ENUM& rhs) { auto overlap = value_ & FlagSet(rhs).value_; value_ ^= overlap; // disable bits which overlap with rhs using XOR return *this; } /** * @brief Check if this FlagSet has at least the active bits of another @p required FlagSet */ bool isSuperSetOf(const FlagSet& required) const { return ((*this | required) == *this); } /** * @brief Check if this FlagSet has the bit for @p required */ bool isSuperSetOf(const ENUM& required) const { return ((*this | required) == *this); } /// checks if any bit is set bool empty() const { return value_ == 0; } /// internal representation (mostly for illustrative purposes) UInt64 value() const { return value_; } private: /// computes pow(2, r) UInt64 getPow_(const ENUM& en) const { OPENMS_PRECONDITION((int)en >= 0, "Enum value is too small!") OPENMS_PRECONDITION((int)en <= 63, "Enum value is too large!") return UInt64(1) << UInt64(en); } UInt64 value_; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/DATASTRUCTURES/BinaryTreeNode.h
.h
1,222
47
// 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/CONCEPT/Types.h> #include <OpenMS/OpenMSConfig.h> namespace OpenMS { /** @brief Elements of a binary tree used to represent a hierarchical clustering process strict indexing/topology is assumed, i.e. node no. x represents clusteringstep no. x left_child and right_child are each the lowest indices to elements of the merged clusters, distance is the distance of the two children */ class OPENMS_DLLAPI BinaryTreeNode { public: /// constructor BinaryTreeNode(const Size i, const Size j, const float x); /// destructor ~BinaryTreeNode(); /// copy constructor BinaryTreeNode(const BinaryTreeNode& source); /// assignment operator BinaryTreeNode& operator=(const BinaryTreeNode& source); Size left_child; Size right_child; float distance; private: BinaryTreeNode(); }; }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/DATASTRUCTURES/DistanceMatrix.h
.h
14,176
476
// 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/CONCEPT/Colorizer.h> #include <OpenMS/CONCEPT/Exception.h> #include <OpenMS/CONCEPT/Macros.h> #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/config.h> #include <algorithm> #include <cmath> #include <iomanip> #include <iostream> namespace OpenMS { /** @brief A two-dimensional distance matrix, similar to OpenMS::Matrix Similar to OpenMS::Matrix, but contains only elements above the main diagonal, hence translating access with operator(,) for elements of above the main diagonal to corresponding elements below the main diagonal and returning 0 for requested elements in the main diagonal, since self-distance is assumed to be 0. Keeps track of the minimal element in the Matrix with OpenMS::DistanceMatrix::min_element_ if only for setting a value OpenMS::DistanceMatrix::setValue is used. Other OpenMS::DistanceMatrix altering methods may require a manual update by call of OpenMS::DistanceMatrix::updateMinElement, see the respective methods documentation. @ingroup Datastructures */ template<typename Value> class DistanceMatrix { public: ///@name STL compliance type definitions //@{ typedef Value value_type; //@} ///@name OpenMS compliance type definitions //@{ typedef Size SizeType; typedef value_type ValueType; //@} /** @brief default constructor */ DistanceMatrix(): matrix_(nullptr), init_size_(0), dimensionsize_(0), min_element_(0, 0) { } /** @brief detailed constructor @param[in] dimensionsize the number of rows (and therewith cols) @param[in] value DistanceMatrix will be filled with this element (main diagonal will still "hold" only zeros) @throw Exception::OutOfMemory if requested dimensionsize is to big to fit into memory */ DistanceMatrix(SizeType dimensionsize, Value value = Value()): matrix_(new ValueType*[dimensionsize]), init_size_(dimensionsize), dimensionsize_(dimensionsize), min_element_(0, 0) { matrix_[0] = NULL; SizeType i = 1; for (i = 1; i < dimensionsize; ++i) { matrix_[i] = new ValueType[i]; if (matrix_[i] == NULL) { SizeType j = i; for (i = 1; i < j; i++) { delete[] matrix_[i]; } delete[] matrix_; matrix_ = NULL; dimensionsize_ = 0; init_size_ = 0; throw Exception::OutOfMemory(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, (UInt)((((dimensionsize - 2) * (dimensionsize - 1)) / 2) * sizeof(ValueType))); } } if (matrix_ != NULL) { for (i = 1; i < dimensionsize; ++i) { for (SizeType j = 0; j < i; ++j) { matrix_[i][j] = value; } } min_element_ = std::make_pair(1, 0); } } /** @brief copy constructor @param[in] source this DistanceMatrix will be copied @throw Exception::OutOfMemory if requested dimensionsize is to big to fit into memory */ DistanceMatrix(const DistanceMatrix& source): matrix_(new ValueType*[source.dimensionsize_]), init_size_(source.dimensionsize_), dimensionsize_(source.dimensionsize_), min_element_(source.min_element_) { matrix_[0] = NULL; SizeType i = 1; for (i = 1; i < dimensionsize_; ++i) { matrix_[i] = new ValueType[i]; if (matrix_[i] == NULL) { SizeType j = i; for (i = 1; i < j; i++) { delete[] matrix_[i]; } delete[] matrix_; matrix_ = NULL; dimensionsize_ = 0; init_size_ = 0; min_element_ = std::make_pair(0, 0); throw Exception::OutOfMemory(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, (UInt)((((dimensionsize_ - 2) * (dimensionsize_ - 1)) / 2) * sizeof(ValueType))); } } if (matrix_ != NULL) { for (i = 1; i < dimensionsize_; ++i) { std::copy(source.matrix_[i], source.matrix_[i] + i, matrix_[i]); } } } /// destructor ~DistanceMatrix() { for (SizeType i = 1; i < init_size_; i++) { delete[] matrix_[i]; } delete[] matrix_; } /** @brief gets a value at a given position (read only): @param[in] i the i-th row @param[in] j the j-th col */ const ValueType operator()(SizeType i, SizeType j) const { return getValue(i, j); } /** @brief gets a value at a given position (read only): @param[in] i the i-th row @param[in] j the j-th col */ ValueType operator()(SizeType i, SizeType j) { return getValue(i, j); } /** @brief gets a value at a given position: @param[in] i the i-th row @param[in] j the j-th col @throw Exception::OutOfRange if given coordinates are out of range */ const ValueType getValue(SizeType i, SizeType j) const { if (i >= dimensionsize_ || j >= dimensionsize_) { throw Exception::OutOfRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION); } // elements on main diagonal are not stored and assumed to be 0 if (i == j) { return 0; } if (i < j) { std::swap(i, j); } return (const ValueType)(matrix_[i][j]); } /** @brief gets a value at a given position: @param[in] i the i-th row @param[in] j the j-th col @throw Exception::OutOfRange if given coordinates are out of range */ ValueType getValue(SizeType i, SizeType j) { if (i >= dimensionsize_ || j >= dimensionsize_) { throw Exception::OutOfRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION); } // elements on main diagonal are not stored and assumed to be 0 if (i == j) { return 0; } if (i < j) { std::swap(i, j); } return matrix_[i][j]; } /** @brief sets a value at a given position: @param[in] i the i-th row @param[in] j the j-th col @param[in] value the set-value @throw Exception::OutOfRange if given coordinates are out of range */ void setValue(SizeType i, SizeType j, ValueType value) { if (i >= dimensionsize_ || j >= dimensionsize_) { throw Exception::OutOfRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION); } // elements on main diagonal are not stored and assumed to be 0 if (i != j) { if (i < j) { std::swap(i, j); } if (i != min_element_.first && j != min_element_.second) { matrix_[i][j] = value; if (value < matrix_[min_element_.first][min_element_.second]) // keep min_element_ up-to-date { min_element_ = std::make_pair(i, j); } } else { if (value <= matrix_[min_element_.first][min_element_.second]) { matrix_[i][j] = value; } else { matrix_[i][j] = value; updateMinElement(); } } } } /** @brief sets a value at a given position: @param[in] i the i-th row @param[in] j the j-th col @param[in] value the set-value @throw Exception::OutOfRange if given coordinates are out of range possible invalidation of min_element_ - make sure to update before further usage of matrix */ void setValueQuick(SizeType i, SizeType j, ValueType value) { if (i >= dimensionsize_ || j >= dimensionsize_) { throw Exception::OutOfRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION); } // elements on main diagonal are not stored and assumed to be 0 if (i != j) { if (i < j) { std::swap(i, j); } matrix_[i][j] = value; } } /// reset all void clear() { for (SizeType i = 1; i < init_size_; i++) { delete[] matrix_[i]; } delete[] matrix_; matrix_ = nullptr; min_element_ = std::make_pair(0, 0); dimensionsize_ = 0; init_size_ = 0; } /** @brief resizing the container @param[in] dimensionsize the desired number of rows (and therewith cols) @param[in] value which the matrix will be filled with @throw Exception::OutOfMemory thrown if size of DistanceMatrix requested does not fit into memory invalidates all content */ void resize(SizeType dimensionsize, Value value = Value()) { for (SizeType j = 1; j < init_size_; j++) { delete[] matrix_[j]; } delete[] matrix_; dimensionsize_ = dimensionsize; init_size_ = dimensionsize; min_element_ = std::make_pair(0, 0); matrix_ = new ValueType*[dimensionsize_]; for (SizeType j = 1; j < dimensionsize_; ++j) { matrix_[j] = new ValueType[j]; if (matrix_[j] == nullptr) { for (SizeType k = 1; k < j; ++k) { delete[] matrix_[k]; } delete[] matrix_; matrix_ = nullptr; dimensionsize_ = 0; init_size_ = 0; throw Exception::OutOfMemory(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, (UInt)((((dimensionsize_ - 2) * (dimensionsize_ - 1)) / 2) * sizeof(Value))); } } if (matrix_ != nullptr) { for (SizeType j = 0; j < dimensionsize; ++j) { for (SizeType k = 0; k < j; ++k) { matrix_[j][k] = value; } } min_element_ = std::make_pair(1, 0); } } /** @brief reduces DistanceMatrix by one dimension. first the jth row, then jth column @param[in] j the jth row (and therewith also jth col) to be removed @throw Exception::OutOfRange if @p j is grater than the greatest row number May invalidates min_element_, make sure to update min_element_ if necessary before used */ void reduce(SizeType j) { if (j >= dimensionsize_) { throw Exception::OutOfRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION); } // delete row j and therefor overwrite with row j+1 and iterate like this to last row SizeType i = j + 1; while (i < dimensionsize_ && matrix_[i] != nullptr) { // left out in the copy is each rows jth element, pointer working here as iterators just fine std::copy(matrix_[i] + j + 1, matrix_[i] + i, std::copy(matrix_[i], matrix_[i] + j, matrix_[i - 1])); ++i; } // last row is freed and the pointer set to NULL (outer array's size is not changed) delete[] matrix_[i - 1]; matrix_[i - 1] = nullptr; --dimensionsize_; } /// gives the number of rows (i.e. number of columns) SizeType dimensionsize() const { return dimensionsize_; } /** @brief keep track of the actual minimum element after altering the matrix @throw Exception::OutOfRange thrown if there is no element to access */ void updateMinElement() { min_element_ = std::make_pair(1, 0); // error if dimensionsize_<1, return if dimensionsize_ == 1, else if (dimensionsize_ < 1) { throw Exception::OutOfRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION); } if (dimensionsize_ != 1) // else matrix has one element: (1,0) { ValueType* row_min_; for (SizeType r = 2; r < dimensionsize_ && matrix_[r] != nullptr; ++r) { row_min_ = std::min_element(matrix_[r], matrix_[r] + r); if (*row_min_ < matrix_[min_element_.first][min_element_.second]) { min_element_ = std::make_pair(r, row_min_ - matrix_[r]); } } } } /** @brief Equality comparator. @throw Exception::Precondition thrown if given DistanceMatrix is not compatible in size */ bool operator==(DistanceMatrix<ValueType> const& rhs) const { OPENMS_PRECONDITION(dimensionsize_ == rhs.dimensionsize_, "DistanceMatrices have different sizes."); for (Size i = 1; i < rhs.dimensionsize(); ++i) { for (Size j = 0; j < i; ++j) { if (matrix_[i][j] != rhs.matrix_[i][j]) { return false; } } } return true; } /** @brief Indexpair of minimal element @throw Exception::OutOfRange thrown if there is no element to access */ std::pair<SizeType, SizeType> getMinElementCoordinates() const { if (dimensionsize_ == 0) { throw Exception::OutOfRange(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION); } return min_element_; } protected: /// sparse element not to be included in base container ValueType** matrix_; /// number of actually stored rows SizeType init_size_; // actual size of outer array /// number of accessibly stored rows (i.e. number of columns) SizeType dimensionsize_; // number of virtual elements: ((dimensionsize-1)*(dimensionsize))/2 /// index of minimal element(i.e. number in underlying SparseVector) std::pair<SizeType, SizeType> min_element_; private: /// assignment operator (unsafe) DistanceMatrix& operator=(const DistanceMatrix& rhs) { matrix_ = rhs.matrix_; init_size_ = rhs.init_size_; dimensionsize_ = rhs.dimensionsize_; min_element_ = rhs.min_element_; return *this; } }; // class DistanceMatrix /** @brief Print the contents to a stream (and colors the diagonal, if the stream is cout/cerr) @relatesalso DistanceMatrix */ template<typename Value> std::ostream& operator<<(std::ostream& os, const DistanceMatrix<Value>& matrix) { using SizeType = typename DistanceMatrix<Value>::SizeType; // we need to print a square matrix. So we set the width //std::ios_base::fmtflags flag_backup = os.setf(std::ios::scientific); // 'scientific' messes with the width; don't do it std::streamsize precision_backup = os.precision(6); // we could go with `writtenDigits<Value>(Value())`, but it becomes unreadable... auto width_backup = os.width(8); for (SizeType i = 0; i < matrix.dimensionsize(); ++i) { for (SizeType j = 0; j < matrix.dimensionsize(); ++j) { if (i == j) { // color the diagonal in red (conditional, see Colorizer) os << red(matrix(i, j)) << '\t'; } else { os << matrix(i, j) << '\t'; } } os << '\n'; } //os.flags(flag_backup); os.precision(precision_backup); os.width(width_backup); return os; } } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/DATASTRUCTURES/DateTime.h
.h
5,802
218
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Nico Pfeifer $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/CONCEPT/HashUtils.h> #include <OpenMS/DATASTRUCTURES/String.h> #include <OpenMS/OpenMSConfig.h> #include <functional> #include <memory> // unique_ptr #include <string> // foward declarations class QDateTime; namespace OpenMS { /** @brief DateTime Class. This class implements date handling. Import and export to/from both string and integers is possible. @ingroup Datastructures */ class OPENMS_DLLAPI DateTime { public: /** @brief Default constructor Fills the object with an undefined date: 00/00/0000 */ DateTime(); /// Copy constructor DateTime(const DateTime& date); /// Move constructor DateTime(DateTime&&) noexcept; /// Assignment operator DateTime& operator=(const DateTime& source); /// Move assignment operator DateTime& operator=(DateTime&&) & noexcept; /// Destructor ~DateTime(); /// equal operator bool operator==(const DateTime& rhs) const; /// not-equal operator bool operator!=(const DateTime& rhs) const; /// less operator bool operator<(const DateTime& rhs) const; /** @brief sets date from a string Reads both English, German and iso/ansi date formats: 'MM/dd/yyyy', 'dd.MM.yyyy' or 'yyyy-MM-dd' @exception Exception::ParseError */ void setDate(const String& date); /** @brief sets time from a string Reads time format: 'hh:mm:ss' @exception Exception::ParseError */ void setTime(const String& date); /** @brief sets data from three integers Give the numbers in the following order: month, day and year. @exception Exception::ParseError */ void setDate(UInt month, UInt day, UInt year); /** @brief sets time from three integers Give the numbers in the following order: hour, minute and second. @exception Exception::ParseError */ void setTime(UInt hour, UInt minute, UInt second); /** @brief sets data from six integers Give the numbers in the following order: month, day, year, hour, minute, second. @exception Exception::ParseError */ void set(UInt month, UInt day, UInt year, UInt hour, UInt minute, UInt second); /** @brief Fills the arguments with the date and the time Give the numbers in the following order: month, day and year, hour minute, second. */ void get(UInt& month, UInt& day, UInt& year, UInt& hour, UInt& minute, UInt& second) const; /** @brief Fills the arguments with the date Give the numbers in the following order: month, day and year. */ void getDate(UInt& month, UInt& day, UInt& year) const; /** @brief Returns the date as string The format of the string is yyyy-MM-dd */ String getDate() const; /** @brief Fills the arguments with the time The arguments are all UInts and the order is hour minute second */ void getTime(UInt& hour, UInt& minute, UInt& second) const; // add @param[in] s seconds to date time DateTime& addSecs(int s); /** @brief Returns the time as string The format of the string is hh:mm:ss */ String getTime() const; /// Returns the current date and time static DateTime now(); /// Returns true if the date time is valid bool isValid() const; /// return true if the date and time is null bool isNull() const; /// Sets the undefined date: 00/00/0000 00:00:00 void clear(); /* @brief Returns a string representation of the DateTime object. @param[in] format "yyyy-MM-ddThh:mm:ss" corresponds to ISO 8601 and should be preferred. */ String toString(const std::string& format = "yyyy-MM-ddThh:mm:ss") const; /* @brief Creates a DateTime object from string representation. @param[in] format "yyyy-MM-ddThh:mm:ss" corresponds to ISO 8601 and should be preferred. */ static DateTime fromString(const std::string& date, const std::string& format = "yyyy-MM-ddThh:mm:ss"); /** @brief Returns a string representation of the date and time The format of the string will be yyyy-MM-dd hh:mm:ss */ String get() const; /** @brief Sets date and time The following formats are supported: - MM/dd/yyyy hh:mm:ss - dd.MM.yyyy hh:mm:ss - yyyy-MM-dd hh:mm:ss - yyyy-MM-ddThh:mm:ss (ISO 8601 format) - yyyy-MM-ddZ (ISO 8601 format) - yyyy-MM-dd+hh:mm (ISO 8601 format) @exception Exception::ParseError */ void set(const String& date); private: std::unique_ptr<QDateTime> dt_; // use PImpl, to avoid costly #include }; } // namespace OpenMS // Hash function specialization for DateTime namespace std { template<> struct hash<OpenMS::DateTime> { std::size_t operator()(const OpenMS::DateTime& dt) const noexcept { // Hash the date/time components including milliseconds to match operator== // (which compares the underlying QDateTime including milliseconds) // Use toString with millisecond format and convert to std::string for hashing std::string datetime_str = dt.toString("yyyy-MM-ddThh:mm:ss.zzz"); return OpenMS::fnv1a_hash_string(datetime_str); } }; } // namespace std
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/DATASTRUCTURES/ListUtils.h
.h
8,710
285
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Stephan Aiche, Chris Bielow $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/DATASTRUCTURES/String.h> #include <OpenMS/CONCEPT/Exception.h> #include <OpenMS/OpenMSConfig.h> #include <OpenMS/config.h> #include <cmath> #include <iterator> #include <vector> #include <algorithm> namespace OpenMS { /** @brief Vector of signed integers. @ingroup Datastructures */ typedef std::vector<Int> IntList; /** @brief Vector of double precision real types. @ingroup Datastructures */ typedef std::vector<double> DoubleList; /** @brief Vector of String. @ingroup Datastructures */ typedef std::vector<String> StringList; /** @brief Collection of utility functions for management of vectors. @ingroup Datastructures */ class OPENMS_DLLAPI ListUtils { private: /** @brief Predicate to check double equality with a given tolerance. */ struct DoubleTolerancePredicate_ { DoubleTolerancePredicate_(const double& target, const double& tolerance) : tolerance_(tolerance), target_(target) {} /** @brief Returns true if \| @p value - @p target \| \< @p tolerance. @param[in] value The value to test. @return true if \| @p value - @p target \| \< @p tolerance, false otherwise. */ inline bool operator()(const double& value) const { return std::fabs(value - target_) < tolerance_; } private: /// The allowed tolerance. double tolerance_; /// The target value that should be found. double target_; }; public: /** @brief Returns a list that is created by splitting the given comma-separated string. @note If converted to vector<String> the strings are not trimmed. @note The values get converted by boost::lexical_cast so a valid conversion from String to T needs to be available. @param[in] str The string that should be split and converted to a list. @param[in] splitter The separator to look for in @p str @return A vector containing the elements of the string converted into type T. */ template <typename T> static std::vector<T> create(const String& str, const char splitter = ',') { // temporary storage for the individual elements of the string std::vector<String> temp_string_vec; str.split(splitter, temp_string_vec); return create<T>(temp_string_vec); } /** @brief Converts a vector of strings to a vector of the target type T. @note The strings are trimmed before conversion. @note The values get converted by boost::lexical_cast so a valid conversion from String to T needs to be available. @param[in] s The vector of strings that should be converted. @return A vector containing the elements of input vector converted into type T. */ template <typename T> static std::vector<T> create(const std::vector<String>& s); /** @brief Converts a vector of T's to a vector of Strings. @param[in] s The vector of T's that should be converted. @return A vector containing the elements of input vector converted into Strings. */ template <typename T> static std::vector<String> toStringList(const std::vector<T>& s) { StringList out; out.reserve(s.size()); for (const auto& elem : s) out.push_back(elem); return out; } /** @brief Checks whether the element @p elem is contained in the given container. @param[in] container The container to check. @param[in] elem The element to check whether it is in the container or not. @return True if @p elem is contained in @p container, false otherwise. */ template <typename T, typename E> static bool contains(const std::vector<T>& container, const E& elem) { return find(container.begin(), container.end(), elem) != container.end(); } /** @brief Checks whether the element @p elem is contained in the given container of floating point numbers. @param[in] container The container of doubles to check. @param[in] elem The element to check whether it is in the container or not. @param[in] tolerance The allowed tolerance for the double. @return True if @p elem is contained in @p container, false otherwise. */ static bool contains(const std::vector<double>& container, const double& elem, double tolerance = 0.00001) { return find_if(container.begin(), container.end(), DoubleTolerancePredicate_(elem, tolerance)) != container.end(); } enum class CASE { SENSITIVE, INSENSITIVE}; /** @brief Checks whether the String @p elem is contained in the given container (potentially case insensitive) @param[in] container The container of String to check. @param[in] elem The element to check whether it is in the container or not. @param[in] case_sensitive Do the comparison case sensitive or insensitive @return True if @p elem is contained in @p container, false otherwise. */ static bool contains(const std::vector<String>& container, String elem, const CASE case_sensitive) { if (case_sensitive == CASE::SENSITIVE) return contains(container, elem); // case insensitive ... elem.toLower(); return find_if(container.begin(), container.end(), [&elem](String ce) { return elem == ce.toLower(); }) != container.end(); } /** @brief Concatenates all elements of the @p container and puts the @p glue string between elements. @param[in] container The container to concatenate; @param[in] glue The string to add in between elements. */ template <typename T> static String concatenate(const std::vector<T>& container, const String& glue = "") { return concatenate< std::vector<T> >(container, glue); } /** @brief Concatenates all elements of the @p container and puts the @p glue string between elements. @param[in] container The container to concatenate; must have begin() and end() iterator. @param[in] glue The string to add in between elements. */ template <typename T> static String concatenate(const T& container, const String& glue = "") { // handle empty containers if (container.empty()) return ""; typename T::const_iterator it = container.begin(); String ret = String(*it); // we have handled the first element ++it; // add the rest for (; it != container.end(); ++it) { ret += (glue + String(*it)); } return ret; } /** @brief Get the index of the first occurrence of an element in the vector (or -1 if not found) */ template <typename T, typename E> static Int getIndex(const std::vector<T>& container, const E& elem) { typename std::vector<T>::const_iterator pos = std::find(container.begin(), container.end(), elem); if (pos == container.end()) return -1; return static_cast<Int>(std::distance(container.begin(), pos)); } }; namespace detail { template <typename T> T convert(const String& s); template<> inline Int32 convert(const String& s) { return s.toInt32(); } template<> inline double convert(const String& s) { return s.toDouble(); } template<> inline float convert(const String& s) { return s.toFloat(); } template<> inline std::string convert(const String& s) { return static_cast<std::string>(s); } } template <typename T> inline std::vector<T> ListUtils::create(const std::vector<String>& s) { std::vector<T> c; c.reserve(s.size()); for (std::vector<String>::const_iterator it = s.begin(); it != s.end(); ++it) { try { c.push_back(detail::convert<T>(String(*it).trim())); // succeeds only if the whole output can be explained, i.e. "1.3 3" will fail (which is good) } catch (...) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Could not convert string '") + *it + "'"); } } return c; } /// create specialization for String since we do not need to cast here template <> inline std::vector<String> ListUtils::create(const std::vector<String>& s) { return s; } } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/DATASTRUCTURES/ParamValue.h
.h
14,831
445
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Authors: Ruben Grünberg $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/OpenMSConfig.h> #include <OpenMS/CONCEPT/HashUtils.h> #include <cstddef> // for ptrdiff_t #include <functional> #include <string> #include <vector> namespace OpenMS { /** @brief Class to hold strings, numeric values, vectors of strings and vectors of numeric values using the stl types. - To choose one of these types, just use the appropriate constructor. - Automatic conversion is supported and throws Exceptions in case of invalid conversions. - An empty object is created with the default constructor. @ingroup Datastructures */ class OPENMS_DLLAPI ParamValue { public: /// Empty data value for comparisons static const ParamValue EMPTY; /// Supported types for ParamValue enum ValueType : unsigned char { STRING_VALUE, ///< string value INT_VALUE, ///< integer value DOUBLE_VALUE, ///< double value STRING_LIST, ///< string vector INT_LIST, ///< integer vector DOUBLE_LIST, ///< double vector EMPTY_VALUE ///< empty value }; /// @name Constructors and destructors //@{ /// Default constructor ParamValue(); /// Copy constructor ParamValue(const ParamValue&); /// Move constructor ParamValue(ParamValue&&) noexcept; /// specific constructor for char* (converted to string) ParamValue(const char*); /// specific constructor for std::string values ParamValue(const std::string&); /// specific constructor for string vectors ParamValue(const std::vector<std::string>&); /// specific constructor for integer vectors ParamValue(const std::vector<int>&); /// specific constructor for double vectors ParamValue(const std::vector<double>&); /// specific constructor for long double values (note: the implementation uses double) ParamValue(long double); /// specific constructor for double values (note: the implementation uses double) ParamValue(double); /// specific constructor for float values (note: the implementation uses double) ParamValue(float); /// specific constructor for short int values (note: the implementation uses ptrdiff_t) ParamValue(short int); /// specific constructor for unsigned short int values (note: the implementation uses ptrdiff_t) ParamValue(unsigned short int); /// specific constructor for int values (note: the implementation uses ptrdiff_t) ParamValue(int); /// specific constructor for unsigned int values (note: the implementation uses ptrdiff_t) ParamValue(unsigned); /// specific constructor for long int values (note: the implementation uses ptrdiff_t) ParamValue(long int); /// specific constructor for unsigned long int values (note: the implementation uses ptrdiff_t) ParamValue(unsigned long); /// specific constructor for long long int values (note: the implementation uses ptrdiff_t) ParamValue(long long); /// specific constructor for unsigned long long int values (note: the implementation uses ptrdiff_t) ParamValue(unsigned long long); /// Destructor ~ParamValue(); //@} ///@name Cast operators ///These methods are used when the DataType is known. ///If they are applied to a ParamValue with the wrong DataType, an exception (Exception::ConversionError) is thrown. In particular, none of these operators will work for an empty ParamValue (DataType EMPTY_VALUE) - except toChar(), which will return 0. //@{ /** @brief conversion operator to string @exception Exception::ConversionError is thrown if a cast from the the wrong type is requested */ operator std::string() const; /** @brief conversion operator to string vector @exception Exception::ConversionError is thrown if a cast from the the wrong type is requested */ operator std::vector<std::string>() const; /** @brief conversion operator to integer vector @exception Exception::ConversionError is thrown if a cast from the the wrong type is requested */ operator std::vector<int>() const; /** @brief conversion operator to double vector @exception Exception::ConversionError is thrown if a cast from the the wrong type is requested */ operator std::vector<double>() const; /** @brief conversion operator to long double Note: The implementation uses typedef double (as opposed to float, double, long double.) @exception Exception::ConversionError is thrown if a cast from the the wrong type is requested */ operator long double() const; /** @brief conversion operator to double Note: The implementation uses typedef double (as opposed to float, double, long double.) @exception Exception::ConversionError is thrown if a cast from the the wrong type is requested */ operator double() const; /** @brief conversion operator to float Note: The implementation uses typedef double (as opposed to float, double, long double.) @exception Exception::ConversionError is thrown if a cast from the the wrong type is requested */ operator float() const; /** @brief conversion operator to short int Note: The implementation uses typedef ptrdiff_t. @exception Exception::ConversionError is thrown if a cast from the the wrong type is requested */ operator short int() const; /** @brief conversion operator to unsigned short int Note: The implementation uses typedef ptrdiff_t. @exception Exception::ConversionError is thrown if a cast from the the wrong type is requested */ operator unsigned short int() const; /** @brief conversion operator to int Note: The implementation uses typedef ptrdiff_t. @exception Exception::ConversionError is thrown if a cast from the the wrong type is requested */ operator int() const; /** @brief conversion operator to unsigned int Note: The implementation uses typedef ptrdiff_t. @exception Exception::ConversionError is thrown if a cast from the the wrong type is requested */ operator unsigned int() const; /** @brief conversion operator to long int Note: The implementation uses typedef ptrdiff_t. @exception Exception::ConversionError is thrown if a cast from the the wrong type is requested */ operator long int() const; /** @brief conversion operator to unsigned long int Note: The implementation uses typedef ptrdiff_t. @exception Exception::ConversionError is thrown if a cast from the the wrong type is requested */ operator unsigned long int() const; /** @brief conversion operator to long long Note: The implementation uses typedef ptrdiff_t. @exception Exception::ConversionError is thrown if a cast from the the wrong type is requested */ operator long long() const; /** @brief conversion operator to unsigned long long Note: The implementation uses typedef ptrdiff_t. @exception Exception::ConversionError is thrown if a cast from the the wrong type is requested */ operator unsigned long long() const; /** @brief Conversion to bool Converts the strings 'true' and 'false' to a bool. @exception Exception::ConversionError is thrown for non-string parameters and string parameters with values other than 'true' and 'false'. */ bool toBool() const; /** @brief Convert ParamValues to char* If the ParamValue contains a string, a pointer to it's char* is returned. If the ParamValue is empty, nullptr is returned. */ const char* toChar() const; /** * @brief Convert ParamValue to string * * @exception Exception::ConversionError is thrown for ParamValue::EMPTY and */ std::string toString(bool full_precision = true) const; /** @brief Explicitly convert ParamValue to string vector @exception Exception::ConversionError is thrown if a cast from the the wrong type is requested */ std::vector<std::string> toStringVector() const; /** @brief Explicitly convert ParamValue to IntList @exception Exception::ConversionError is thrown if a cast from the the wrong type is requested */ std::vector<int> toIntVector() const; /** @brief Explicitly convert ParamValue to DoubleList @exception Exception::ConversionError is thrown if a cast from the the wrong type is requested */ std::vector<double> toDoubleVector() const; //@} ///@name Assignment operators ///These methods are used to assign supported types directly to a ParamValue object. //@{ /// Assignment operator ParamValue& operator=(const ParamValue&); /// Move assignment operator ParamValue& operator=(ParamValue&&) noexcept; /// specific assignment for char* (converted to string) ParamValue& operator=(const char*); /// specific assignment for std::string values ParamValue& operator=(const std::string&); /// specific assignment for string vectors ParamValue& operator=(const std::vector<std::string>&); /// specific assignment for integer vectors ParamValue& operator=(const std::vector<int>&); /// specific assignment for double vectors ParamValue& operator=(const std::vector<double>&); /// specific assignment for long double values (note: the implementation uses double) ParamValue& operator=(const long double); /// specific assignment for double values (note: the implementation uses double) ParamValue& operator=(const double); /// specific assignment for float values (note: the implementation uses double) ParamValue& operator=(const float); /// specific assignment for short int values (note: the implementation uses ptrdiff_t) ParamValue& operator=(const short int); /// specific assignment for unsigned short int values (note: the implementation uses ptrdiff_t) ParamValue& operator=(const unsigned short int); /// specific assignment for int values (note: the implementation uses ptrdiff_t) ParamValue& operator=(const int); /// specific assignment for unsigned int values (note: the implementation uses ptrdiff_t) ParamValue& operator=(const unsigned); /// specific assignment for long int values (note: the implementation uses ptrdiff_t) ParamValue& operator=(const long int); /// specific assignment for unsigned long int values (note: the implementation uses ptrdiff_t) ParamValue& operator=(const unsigned long); /// specific assignment for long long int values (note: the implementation uses ptrdiff_t) ParamValue& operator=(const long long); /// specific assignment for unsigned long long int values (note: the implementation uses ptrdiff_t) ParamValue& operator=(const unsigned long long); //@} /// returns the type of value stored inline ValueType valueType() const { return value_type_; } /** @brief Test if the value is empty @note A ParamValue containing an empty string ("") does not count as empty! */ inline bool isEmpty() const { return value_type_ == EMPTY_VALUE; } /// output stream operator friend OPENMS_DLLAPI std::ostream& operator<<(std::ostream&, const ParamValue&); /// Equality comparator friend OPENMS_DLLAPI bool operator==(const ParamValue&, const ParamValue&); /// Smaller than comparator (for vectors we use the size) friend OPENMS_DLLAPI bool operator<(const ParamValue&, const ParamValue&); /// Greater than comparator (for vectors we use the size) friend OPENMS_DLLAPI bool operator>(const ParamValue&, const ParamValue&); /// Equality comparator friend OPENMS_DLLAPI bool operator!=(const ParamValue&, const ParamValue&); protected: /// Type of the currently stored value ValueType value_type_; /// Space to store the data union { std::ptrdiff_t ssize_; double dou_; std::string* str_; std::vector<std::string>* str_list_; std::vector<int>* int_list_; std::vector<double>* dou_list_; } data_; private: /// Clears the current state of the ParamValue and release every used memory. void clear_() noexcept; /// Convert a double to std::string /// with full precision 15 decimal places are given, otherwise 3 /// numbers above 10000 or below 0.0001 are given in scientific notation (i.e. 1.0e04) static std::string doubleToString(double value, bool full_precision = true); }; } // namespace OpenMS // std::hash specialization for ParamValue - must be in std namespace namespace std { template<> struct hash<OpenMS::ParamValue> { std::size_t operator()(const OpenMS::ParamValue& pv) const noexcept { using namespace OpenMS; std::size_t seed = hash_int(static_cast<unsigned char>(pv.valueType())); switch (pv.valueType()) { case ParamValue::EMPTY_VALUE: // No additional data to hash break; case ParamValue::STRING_VALUE: { std::string s = pv; hash_combine(seed, fnv1a_hash_string(s)); break; } case ParamValue::INT_VALUE: { std::ptrdiff_t i = static_cast<long long>(pv); hash_combine(seed, hash_int(i)); break; } case ParamValue::DOUBLE_VALUE: { double d = pv; hash_combine(seed, hash_float(d)); break; } case ParamValue::STRING_LIST: { std::vector<std::string> sl = pv.toStringVector(); hash_combine(seed, hash_int(sl.size())); for (const auto& s : sl) { hash_combine(seed, fnv1a_hash_string(s)); } break; } case ParamValue::INT_LIST: { std::vector<int> il = pv.toIntVector(); hash_combine(seed, hash_int(il.size())); for (int i : il) { hash_combine(seed, hash_int(i)); } break; } case ParamValue::DOUBLE_LIST: { std::vector<double> dl = pv.toDoubleVector(); hash_combine(seed, hash_int(dl.size())); for (double d : dl) { hash_combine(seed, hash_float(d)); } break; } } return seed; } }; } // namespace std
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/DATASTRUCTURES/ConstRefVector.h
.h
19,686
749
// 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 <algorithm> #include <typeinfo> #include <vector> namespace OpenMS { /** @brief This vector holds pointer to the elements of another container. If you for example want to sort the elements of a constant container, you would have to copy the whole container. @n To avoid copy actions this class only holds pointer to the constant elements of a container. @n You can insert new elements, but it is not possible to change existing ones. The following code demonstrates the use of this class: @code FeatureMap<> map; map.resize(10); //...fill map with data //Create pointer vector to the map ConstRefVector<FeatureMap<> > ref_vector(map); //Sort the pointer vector without changing the original data ref_vector.sortByIntensity(); @endcode @improvement Check if we can omit the iterator template arguments (Clemens) @ingroup Datastructures */ template <typename ContainerT> class ConstRefVector { public: ///ConstIterator for the ConstRefVector template <class ValueT> class ConstRefVectorConstIterator { friend class ConstRefVector; public: typedef ValueT ValueType; typedef ValueType value_type; typedef typename std::vector<ValueType*>::difference_type difference_type; typedef const value_type& reference; typedef const value_type* pointer; typedef std::random_access_iterator_tag iterator_category; ConstRefVectorConstIterator() = default; ConstRefVectorConstIterator(const ConstRefVectorConstIterator&) = default; ConstRefVectorConstIterator& operator=(const ConstRefVectorConstIterator&) = default; ~ConstRefVectorConstIterator() = default; ConstRefVectorConstIterator(const typename std::vector<ValueType*>* vec, unsigned int position) { vector_ = (typename std::vector<ValueType*>*)vec; position_ = position; } ConstRefVectorConstIterator(typename std::vector<ValueType*>* vec, unsigned int position) { vector_ = vec; position_ = position; } bool operator<(const ConstRefVectorConstIterator& it) const { return position_ < it.position_; } bool operator>(const ConstRefVectorConstIterator& it) const { return position_ > it.position_; } bool operator<=(const ConstRefVectorConstIterator& it) const { return position_ < it.position_ || position_ == it.position_; } bool operator>=(const ConstRefVectorConstIterator& it) const { return position_ > it.position_ || position_ == it.position_; } bool operator==(const ConstRefVectorConstIterator& it) const { return position_ == it.position_ && vector_ == it.vector_; } bool operator!=(const ConstRefVectorConstIterator& it) const { return position_ != it.position_ || vector_ != it.vector_; } ConstRefVectorConstIterator& operator++() { position_ += 1; return *this; } ConstRefVectorConstIterator operator++(int) { ConstRefVectorConstIterator tmp(*this); ++(*this); return tmp; } ConstRefVectorConstIterator& operator--() { position_ -= 1; return *this; } ConstRefVectorConstIterator operator--(int) { ConstRefVectorConstIterator tmp(*this); --(*this); return tmp; } ConstRefVectorConstIterator operator-(difference_type n) const { ConstRefVectorConstIterator tmp(*this); tmp.position_ -= n; return tmp; } ConstRefVectorConstIterator operator+(difference_type n) const { ConstRefVectorConstIterator tmp(*this); tmp.position_ += n; return tmp; } ConstRefVectorConstIterator& operator+=(difference_type n) { position_ += n; return *this; } ConstRefVectorConstIterator& operator-=(difference_type n) { position_ -= n; return *this; } friend difference_type operator-(const ConstRefVectorConstIterator& i1, const ConstRefVectorConstIterator& i2) { return i1.position_ - i2.position_; } friend ConstRefVectorConstIterator operator+(difference_type n, const ConstRefVectorConstIterator& i) { ConstRefVectorConstIterator tmp(i); tmp.position_ += n; return tmp; } reference operator*() const { return *((*vector_)[position_]); } pointer operator->() const { return (*vector_)[position_]; } protected: typename std::vector<ValueType*>* vector_; unsigned int position_; }; /// Mutable iterator for the ConstRefVector template <class ValueT> class ConstRefVectorIterator : public ConstRefVectorConstIterator<ValueT> { friend class ConstRefVector; public: typedef ValueT ValueType; typedef typename ConstRefVectorConstIterator<ValueType>::value_type& reference; typedef typename ConstRefVectorConstIterator<ValueType>::value_type* pointer; using ConstRefVectorConstIterator<ValueType>::vector_; using ConstRefVectorConstIterator<ValueType>::position_; ConstRefVectorIterator() = default; ConstRefVectorIterator(const ConstRefVectorIterator&) = default; ConstRefVectorIterator(typename std::vector<ValueType*>* vec, unsigned int position) : ConstRefVectorConstIterator<ValueType>(vec, position) { } ~ConstRefVectorIterator() = default; ConstRefVectorIterator& operator=(const ConstRefVectorIterator& rhs) = default; reference operator*() const { return *((*vector_)[position_]); } pointer operator->() const { return (*vector_)[position_]; } ConstRefVectorIterator& operator++() { ConstRefVectorConstIterator<ValueType>::position_ += 1; return *this; } ConstRefVectorIterator operator++(int) { ConstRefVectorIterator tmp(*this); ++(*this); return tmp; } ConstRefVectorIterator& operator--() { ConstRefVectorConstIterator<ValueType>::position_ -= 1; return *this; } ConstRefVectorIterator operator--(int) { ConstRefVectorIterator tmp(*this); --(*this); return tmp; } ConstRefVectorIterator operator-(typename ConstRefVectorIterator::difference_type n) const { ConstRefVectorIterator tmp(*this); tmp.position_ -= n; return tmp; } ConstRefVectorIterator operator+(typename ConstRefVectorIterator::difference_type n) const { ConstRefVectorIterator tmp(*this); tmp.position_ += n; return tmp; } friend ConstRefVectorIterator operator+(typename ConstRefVectorIterator::difference_type n, const ConstRefVectorIterator& i) { ConstRefVectorIterator tmp(i); tmp.position_ += n; return tmp; } ConstRefVectorIterator& operator+=(typename ConstRefVectorIterator::difference_type n) { ConstRefVectorConstIterator<ValueType>::position_ += n; return *this; } ConstRefVectorIterator& operator-=(typename ConstRefVectorIterator::difference_type n) { ConstRefVectorConstIterator<ValueType>::position_ -= n; return *this; } friend void swap(ConstRefVectorIterator& i1, ConstRefVectorIterator& i2) { unsigned int tmp = i1.position_; i1.position_ = i2.position_; i2.position_ = tmp; } }; ///Type definitions //@{ /// Wrapped container type typedef ContainerT ContainerType; /// typedef typename ContainerType::value_type ValueType; typedef ConstRefVectorIterator<const ValueType> Iterator; typedef ConstRefVectorConstIterator<const ValueType> ConstIterator; typedef std::reverse_iterator<Iterator> ReverseIterator; typedef std::reverse_iterator<ConstIterator> ConstReverseIterator; //@} ///STL-compliance type definitions //@{ typedef ValueType value_type; typedef typename ContainerType::size_type size_type; typedef typename ContainerType::difference_type difference_type; typedef typename ContainerType::reference reference; typedef typename ContainerType::const_reference const_reference; typedef typename ContainerType::pointer pointer; typedef Iterator iterator; typedef ConstIterator const_iterator; typedef ReverseIterator reverse_iterator; typedef ConstReverseIterator const_reverse_iterator; //@} /// See std::vector documentation. void push_back(const ValueType& x) { const ValueType* element = &x; vector_.push_back(element); } /// See std::vector documentation. void pop_back() { vector_.pop_back(); } /// See std::vector documentation. size_type size() const { return vector_.size(); } /// See std::vector documentation. size_type capacity() const { return std::max(vector_.size(), capacity_); } /// See std::vector documentation. void reserve(size_type n) { size_type cap = capacity(); if (n > cap) { vector_.reserve(n); capacity_ = n; } } /// See std::vector documentation. size_type max_size() const { return vector_.max_size(); } /// See std::vector documentation. Iterator begin() { return Iterator((std::vector<const ValueType*>*) & vector_, (unsigned int)0); } /// See std::vector documentation. Iterator end() { return Iterator((std::vector<const ValueType*>*) & vector_, (unsigned int)(vector_.size())); } /// See std::vector documentation. ConstIterator begin() const { return ConstIterator((const std::vector<const ValueType*>*) & vector_, (unsigned int)0); } /// See std::vector documentation. ConstIterator end() const { return ConstIterator((const std::vector<const ValueType*>*) & vector_, (unsigned int)(vector_.size())); } /// See std::vector documentation. ReverseIterator rbegin() { return ReverseIterator(end()); } /// See std::vector documentation. ReverseIterator rend() { return ReverseIterator(begin()); } /// See std::vector documentation. ConstReverseIterator rbegin() const { return ConstReverseIterator(end()); } /// See std::vector documentation. ConstReverseIterator rend() const { return ConstReverseIterator(begin()); } /// See std::vector documentation. void resize(size_type new_size) { vector_.resize(new_size); capacity_ = vector_.capacity(); } /// See std::vector documentation. void resize(size_type new_size, const ValueType& t) { vector_.resize(new_size, &t); capacity_ = vector_.capacity(); } /// See std::vector documentation. const_reference front() const { return *(begin()); } /// See std::vector documentation. const_reference back() const { return *(end() - 1); } /// See std::vector documentation. void clear() { vector_.clear(); } /// See std::vector documentation. bool empty() const { return vector_.empty(); } /// See std::vector documentation. const_reference operator[](size_type n) const { return *(vector_[n]); } /// See std::vector documentation. bool operator==(const ConstRefVector& array) const { if (base_container_ptr_ != array.base_container_ptr_) { return false; } if (size() != array.size()) { return false; } for (Size i = 0; i < size(); i++) { if (typeid(*(vector_[i])) != typeid(*(array.vector_[i]))) { return false; } if (vector_[i]->operator!=(* array.vector_[i])) { return false; } } return true; } /// See std::vector documentation. bool operator!=(const ConstRefVector& array) const { return !(operator==(array)); } /// Comparison of container sizes bool operator<(const ConstRefVector& array) const { return size() < array.size(); } /// Comparison of container sizes bool operator>(const ConstRefVector& array) const { return size() > array.size(); } /// Comparison of container sizes bool operator<=(const ConstRefVector& array) const { return operator<(array) || operator==(array); } /// Comparison of container sizes bool operator>=(const ConstRefVector& array) const { return operator>(array) || operator==(array); } /// See std::vector documentation. void swap(ConstRefVector& array) { vector_.swap(array.vector_); } /// See std::vector documentation. friend void swap(ConstRefVector& a1, ConstRefVector& a2) { a1.vector_.swap(a2.vector_); } /// See std::vector documentation. Iterator insert(Iterator pos, const ValueType& element) { const ValueType* pointer = &element; vector_.insert(vector_.begin() + pos.position_, pointer); return pos; } /// See std::vector documentation. void insert(Iterator pos, size_type n, const ValueType& element) { const ValueType* pointer; std::vector<const ValueType*> tmp; for (size_type i = 0; i < n; i++) { pointer = &element; tmp.push_back(pointer); } vector_.insert(vector_.begin() + pos.position_, tmp.begin(), tmp.end()); } /// See std::vector documentation. template <class InputIterator> void insert(Iterator pos, InputIterator f, InputIterator l) { const ValueType* pointer; std::vector<const ValueType*> tmp; for (InputIterator it = f; it != l; ++it) { pointer = &(*it); tmp.push_back(pointer); } vector_.insert(vector_.begin() + pos.position_, tmp.begin(), tmp.end()); } /// See std::vector documentation. Iterator erase(Iterator pos) { vector_.erase(vector_.begin() + pos.position_); return pos; } /// See std::vector documentation. Iterator erase(Iterator first, Iterator last) { vector_.erase(vector_.begin() + first.position_, vector_.begin() + last.position_); return first; } ///@name Constructors and Destructor //@{ /// See std::vector documentation. ConstRefVector() : capacity_(0), base_container_ptr_(nullptr) { } /// See std::vector documentation. ConstRefVector(size_type n) : capacity_(0), base_container_ptr_(0) { vector_ = std::vector<const ValueType*>(n); } /// See std::vector documentation. ConstRefVector(size_type n, const ValueType& element) : capacity_(0), base_container_ptr_(0) { vector_ = std::vector<const ValueType*>(n, &element); } /// See std::vector documentation. ConstRefVector(const ConstRefVector& p) : capacity_(0), base_container_ptr_(p.base_container_ptr_) { const ValueType* element; for (ConstIterator it = p.begin(); it != p.end(); ++it) { element = &(*it); vector_.push_back(element); } } /// See std::vector documentation. template <class InputIterator> ConstRefVector(InputIterator f, InputIterator l) : capacity_(0), base_container_ptr_(nullptr) { const ValueType* pointer; for (InputIterator it = f; it != l; ++it) { pointer = &(*it); vector_.push_back(pointer); } } /// See std::vector documentation. ConstRefVector(ContainerType& p) : capacity_(0), base_container_ptr_(&p) { const ValueType* element; for (typename ContainerType::iterator it = p.begin(); it != p.end(); ++it) { element = &(*it); vector_.push_back(element); } } /// See std::vector documentation. ~ConstRefVector() { } //@} /// See std::vector documentation. ConstRefVector& operator=(const ConstRefVector& rhs) { if (this == &rhs) return *this; base_container_ptr_ = rhs.base_container_ptr_; clear(); reserve(rhs.size()); const ValueType* element; for (ConstIterator it = rhs.begin(); it != rhs.end(); ++it) { element = &(*it); vector_.push_back(element); } return *this; } /// See std::vector documentation. template <class InputIterator> void assign(InputIterator f, InputIterator l) { clear(); insert(end(), f, l); } /// See std::vector documentation. void assign(size_type n, const ValueType& x) { clear(); insert(end(), n, x); } /** @brief Sorting. These simplified sorting methods are supported for convenience. @note To use these methods, the ValueType must provide an interface similar to Peak1D or Peak2D. */ //@{ /// Sorts the elements by intensity void sortByIntensity(bool reverse = false) { if (reverse) { auto pointerCmp = [](auto& left, auto& right){typename ValueType::IntensityLess cmp; return cmp(*left, *right);}; std::sort(vector_.begin(), vector_.end(), [&](auto &left, auto &right) {return pointerCmp(right, left);}); } else { std::sort(vector_.begin(), vector_.end(), [](auto& left, auto& right){typename ValueType::IntensityLess cmp; return cmp(*left, *right);}); } } /// Lexicographically sorts the elements by their position. void sortByPosition() { std::sort(vector_.begin(), vector_.end(), [](auto& left, auto& right){typename ValueType::PositionLess cmp; return cmp(*left, *right);}); } //@} /** @name Generic sorting function templates. Any element comparator can be given as template argument. You can also give the comparator as an argument to the function template (this is useful if the comparator is not default constructed, but keep in mind that STL copies comparators a lot). <p> Thus your can e.g. write <code>elements.sortByComparator < DFeature<1>::IntensityLess > ()</code>, if elements have type <code>ConstRefVector < 1, DFeature <1> ></code>. */ //@{ template <typename ComparatorType> void sortByComparator(ComparatorType const& comparator = ComparatorType()) { std::sort(vector_.begin(), vector_.end(), [&](auto& left, auto& right){return comparator(*left, *right);}); } //@} //---------------------------------------------------------------------- protected: ///the internal vector of ValueType pointers std::vector<const ValueType*> vector_; ///the current capacity size_type capacity_; /// Pointer to the base container const ContainerType* base_container_ptr_; }; } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/DATASTRUCTURES/LPWrapper.h
.h
17,138
526
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Alexandra Zerck $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/DATASTRUCTURES/String.h> // for String #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/OpenMSConfig.h> #include <OpenMS/config.h> #include <limits> // do NOT include glpk and CoinOr headers here, as they define bad stuff, which ripples through OpenMS then... // include them in LPWrapper.cpp where they do not harm // only declare them here class CoinModel; // if GLPK was found: #ifndef OPENMS_HAS_COINOR #ifndef GLP_PROB_DEFINED #define GLP_PROB_DEFINED // depending on the glpk version // define glp_prob as forward or struct #if OPENMS_GLPK_VERSION_MAJOR == 4 && OPENMS_GLPK_VERSION_MINOR < 48 typedef struct { double _opaque_prob[100]; } glp_prob; #else class glp_prob; #endif #endif #endif namespace OpenMS { /** @brief A wrapper class for linear programming (LP) solvers This class provides a unified interface to different linear programming solvers, including GLPK (GNU Linear Programming Kit) and COIN-OR (if available). Linear programming is a method to find the best outcome in a mathematical model whose requirements are represented by linear relationships. It is used for optimization problems where the objective function and constraints are linear. LPWrapper allows you to: - Create and manipulate LP problems (add rows, columns, set bounds) - Set objective functions and constraints - Solve the LP problem using different solvers - Access the solution and status information The class supports both continuous and integer variables, allowing for mixed-integer linear programming (MILP) problems. @ingroup Datastructures */ class OPENMS_DLLAPI LPWrapper { public: /** @brief Struct that holds the parameters of the LP solver This structure contains various parameters that control the behavior of the LP solver, including algorithm selection, cut generation, heuristics, and output control. Most parameters have reasonable defaults and don't need to be modified for basic use cases. Advanced users can tune these parameters to improve performance for specific problem types. */ struct SolverParam { /** @brief Default constructor that initializes all parameters with reasonable defaults */ SolverParam() : message_level(3), branching_tech(4), backtrack_tech(3), preprocessing_tech(2), enable_feas_pump_heuristic(true), enable_gmi_cuts(true), enable_mir_cuts(true), enable_cov_cuts(true), enable_clq_cuts(true), mip_gap(0.0), time_limit((std::numeric_limits<Int>::max)()), output_freq(5000), output_delay(10000), enable_presolve(true), enable_binarization(true) { } Int message_level; ///< Controls verbosity of solver output (0-3) Int branching_tech; ///< Branching technique for MIP problems Int backtrack_tech; ///< Backtracking technique for MIP problems Int preprocessing_tech; ///< Preprocessing technique bool enable_feas_pump_heuristic; ///< Enable feasibility pump heuristic bool enable_gmi_cuts; ///< Enable Gomory mixed-integer cuts bool enable_mir_cuts; ///< Enable mixed-integer rounding cuts bool enable_cov_cuts; ///< Enable cover cuts bool enable_clq_cuts; ///< Enable clique cuts double mip_gap; ///< Relative gap tolerance for MIP problems Int time_limit; ///< Time limit in milliseconds Int output_freq; ///< Output frequency in milliseconds Int output_delay; ///< Output delay in milliseconds bool enable_presolve; ///< Enable presolve techniques bool enable_binarization; ///< Enable binarization (only with presolve) }; /** @brief Enumeration for variable/constraint bound types Defines the type of bounds applied to variables or constraints in the LP problem. */ enum Type { UNBOUNDED = 1, ///< No bounds (free variable) LOWER_BOUND_ONLY, ///< Only lower bound is specified UPPER_BOUND_ONLY, ///< Only upper bound is specified DOUBLE_BOUNDED, ///< Both lower and upper bounds are specified FIXED ///< Lower bound equals upper bound (fixed value) }; /** @brief Enumeration for variable types in the LP problem Defines whether variables are continuous or discrete (integer/binary). */ enum VariableType { CONTINUOUS = 1, ///< Continuous variable (can take any real value within bounds) INTEGER, ///< Integer variable (can only take integer values within bounds) BINARY ///< Binary variable (can only take values 0 or 1) }; /** @brief Enumeration for optimization direction Defines whether the objective function should be minimized or maximized. */ enum Sense { MIN = 1, ///< Minimize the objective function MAX ///< Maximize the objective function }; /** @brief Enumeration for LP problem file formats Defines the file format used when writing LP problems to disk. */ enum WriteFormat { FORMAT_LP = 0, ///< LP format (human-readable) FORMAT_MPS, ///< MPS format (industry standard) FORMAT_GLPK ///< GLPK's native format }; /** @brief Enumeration for available LP solvers Defines which solver backend to use for solving LP problems. */ enum SOLVER { SOLVER_GLPK = 0 ///< GNU Linear Programming Kit solver #ifdef OPENMS_HAS_COINOR , SOLVER_COINOR ///< COIN-OR solver (if available) #endif }; /** @brief Enumeration for solver status after solving an LP problem Defines the possible outcomes after attempting to solve an LP problem. */ enum SolverStatus { UNDEFINED = 1, ///< Status is undefined (e.g., solver not run yet) OPTIMAL = 5, ///< Optimal solution found FEASIBLE = 2, ///< Feasible solution found (but not necessarily optimal) NO_FEASIBLE_SOL = 4 ///< No feasible solution exists for the problem }; /** @brief Default constructor Initializes a new LP problem with the default solver (GLPK or COIN-OR if available). */ LPWrapper(); /** @brief Virtual destructor Frees all resources associated with the LP problem. */ virtual ~LPWrapper(); // problem creation/manipulation /** @brief Adds a row to the LP matrix @param[in] row_indices Indices of the columns that have non-zero coefficients in this row @param[in] row_values Values of the non-zero coefficients in this row @param[in] name Name of the row (for identification purposes) @return Index of the newly added row */ Int addRow(const std::vector<Int>& row_indices, const std::vector<double>& row_values, const String& name); /** @brief Adds an empty column to the LP matrix @return Index of the newly added column */ Int addColumn(); /** @brief Adds a column to the LP matrix @param[in] column_indices Indices of the rows that have non-zero coefficients in this column @param[in] column_values Values of the non-zero coefficients in this column @param[in] name Name of the column (for identification purposes) @return Index of the newly added column */ Int addColumn(const std::vector<Int>& column_indices, const std::vector<double>& column_values, const String& name); /** @brief Adds a row with boundaries to the LP matrix, returns index If you have a fixed variable, GLPK requires to use the "fixed" type, instead of "double-bounded" with equal bounds. @param[in] row_indices @param[in] row_values @param[in] name @param[in] lower_bound @param[in] upper_bound @param[in] type Type of the row 1 - unbounded, 2 - only lower bound, 3 - only upper bound, 4 - double-bounded variable, 5 - fixed variable */ Int addRow(const std::vector<Int>& row_indices, const std::vector<double>& row_values, const String& name, double lower_bound, double upper_bound, Type type); /** @brief Adds a column with boundaries to the LP matrix, returns index @param[in] column_indices @param[in] column_values @param[in] name @param[in] lower_bound @param[in] upper_bound @param[in] type 1 - unbounded, 2 - only lower bound, 3 - only upper bound, 4 - double-bounded variable, 5 - fixed variable */ Int addColumn(const std::vector<Int>& column_indices, const std::vector<double>& column_values, const String& name, double lower_bound, double upper_bound, Type type); /** @brief Delete the row at the specified index @param[in] index Index of the row to delete */ void deleteRow(Int index); /** @brief Set the name of a column @param[in] index Index of the column to rename @param[in] name New name for the column */ void setColumnName(Int index, const String& name); /** @brief Get the name of a column @param[in] index Index of the column @return Name of the column */ String getColumnName(Int index); /** @brief Get the name of a row @param[in] index Index of the row @return Name of the row */ String getRowName(Int index); /** @brief Find the index of a row by its name @param[in] name Name of the row to find @return Index of the row with the given name */ Int getRowIndex(const String& name); /** @brief Find the index of a column by its name @param[in] name Name of the column to find @return Index of the column with the given name */ Int getColumnIndex(const String& name); /** @brief Get the upper bound of a column @param[in] index Index of the column @return Upper bound value of the column */ double getColumnUpperBound(Int index); /** @brief Get the lower bound of a column @param[in] index Index of the column @return Lower bound value of the column */ double getColumnLowerBound(Int index); /** @brief Get the upper bound of a row @param[in] index Index of the row @return Upper bound value of the row */ double getRowUpperBound(Int index); /** @brief Get the lower bound of a row @param[in] index Index of the row @return Lower bound value of the row */ double getRowLowerBound(Int index); /** @brief Set the name of a row @param[in] index Index of the row to rename @param[in] name New name for the row */ void setRowName(Int index, const String& name); /** @brief Set column bounds. @param[in] index @param[in] lower_bound @param[in] upper_bound @param[in] type 1 - unbounded, 2 - only lower bound, 3 - only upper bound, 4 - double-bounded variable, 5 - fixed variable */ void setColumnBounds(Int index, double lower_bound, double upper_bound, Type type); /** @brief Set row bounds. @param[in] index @param[in] lower_bound @param[in] upper_bound @param[in] type 1 - unbounded, 2 - only lower bound, 3 - only upper bound, 4 - double-bounded variable, 5 - fixed constraint */ void setRowBounds(Int index, double lower_bound, double upper_bound, Type type); /** @brief Set column/variable type. @param[in] index @param[in] type 1- continuous, 2- integer, 3- binary variable */ void setColumnType(Int index, VariableType type); /** @brief Get column/variable type. @param[in] index @return 1- continuous, 2- integer, 3- binary variable */ VariableType getColumnType(Int index); /** @brief Set the objective coefficient for a column/variable @param[in] index Index of the column/variable @param[in] obj_value Coefficient value in the objective function */ void setObjective(Int index, double obj_value); /** @brief Get the objective coefficient for a column/variable @param[in] index Index of the column/variable @return Coefficient value in the objective function */ double getObjective(Int index); /** @brief Set objective direction. @param[in] sense 1- minimize, 2- maximize */ void setObjectiveSense(Sense sense); /** @brief Get the current objective direction @return Current optimization direction (MIN or MAX) */ Sense getObjectiveSense(); /** @brief Get the number of columns/variables in the LP problem @return Number of columns in the LP matrix */ Int getNumberOfColumns(); /** @brief Get the number of rows/constraints in the LP problem @return Number of rows in the LP matrix */ Int getNumberOfRows(); /** @brief Set the value of a matrix element at the specified position @param[in] row_index Index of the row @param[in] column_index Index of the column @param[in] value Value to set at the specified position */ void setElement(Int row_index, Int column_index, double value); /** @brief Get the value of a matrix element at the specified position @param[in] row_index Index of the row @param[in] column_index Index of the column @return Value at the specified position */ double getElement(Int row_index, Int column_index); // problem reading/writing /** @brief Read LP from file @param[out] filename Filename where to store the LP problem. @param[in] format LP, MPS or GLPK. */ void readProblem(const String& filename, const String& format); /** @brief Write LP formulation to a file. @param[out] filename output filename, if the filename ends with '.gz' it will be compressed @param[in] format MPS-format is supported by GLPK and COIN-OR; LP and GLPK-formats only by GLPK */ void writeProblem(const String& filename, const WriteFormat format) const; /** @brief solve problems, parameters like enabled heuristics can be given via solver_param The verbose level (0,1,2) determines if the solver prints status messages and internals. @param[in] solver_param @param[in] verbose_level @return solver dependent (todo: fix) */ Int solve(SolverParam& solver_param, const Size verbose_level = 0); /** @brief Get solution status. @return status: 1 - undefined, 2 - integer optimal, 3- integer feasible (no optimality proven), 4- no integer feasible solution */ SolverStatus getStatus(); // solution access /** @brief Get the objective function value of the solution @return Value of the objective function at the optimal solution */ double getObjectiveValue(); /** @brief Get the value of a variable in the solution @param[in] index Index of the column/variable @return Value of the variable in the optimal solution */ double getColumnValue(Int index); /** @brief Get the number of non-zero entries in a specific row @param[in] idx Index of the row @return Number of non-zero coefficients in the row */ Int getNumberOfNonZeroEntriesInRow(Int idx); /** @brief Get the indices of non-zero entries in a specific row @param[in] idx Index of the row @param[out] indexes Vector to store the column indices of non-zero entries */ void getMatrixRow(Int idx, std::vector<Int>& indexes); /** @brief Get the currently active solver backend @return Currently active solver (GLPK or COIN-OR) */ SOLVER getSolver() const; protected: #ifdef OPENMS_HAS_COINOR CoinModel * model_ = nullptr; ///< COIN-OR model object for the LP problem std::vector<double> solution_; ///< Solution vector when using COIN-OR #else glp_prob * lp_problem_ = nullptr; ///< GLPK problem object for the LP problem #endif SOLVER solver_; ///< Currently active solver backend }; // class } // namespace
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/DATASTRUCTURES/QTCluster.h
.h
12,376
347
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hendrik Weisser $ // $Authors: Steffen Sass, Hendrik Weisser $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/CHEMISTRY/AASequence.h> #include <OpenMS/OpenMSConfig.h> #include <OpenMS/config.h> #include <unordered_map> #include <map> // for multimap<> #include <vector> // for vector<> #include <set> // for set<> #include <utility> // for pair<> namespace OpenMS { class GridFeature; /** @brief A representation of a QT cluster used for feature grouping. Ultimately, a cluster represents a group of corresponding features (or consensus features) from different input maps (feature maps or consensus maps). Clusters are defined by their center points (one feature each). A cluster also stores a number of potential cluster elements (other features) from different input maps, together with their distances to the cluster center. Every feature that satisfies certain constraints with respect to the cluster center is a @e potential cluster element. However, since a feature group can only contain one feature from each input map, only the "best" (i.e. closest to the cluster center) such feature is considered a true cluster element. To save memory, only the "best" element for each map is stored inside a cluster. The QT clustering algorithm has the characteristic of initially producing all possible, overlapping clusters. Iteratively, the best cluster is then extracted and the clustering is recomputed for the remaining points. In our implementation, multiple rounds of clustering are not necessary. Instead, the clustering is updated in each iteration. This is the reason for temporarily storing all potential cluster elements: When a certain cluster is finalized, its elements have to be removed from the remaining clusters, and affected clusters change their composition. (Note that clusters can also be invalidated by this, if the cluster center is being removed.) The quality of a cluster is the normalized average distance to the cluster center for present and missing cluster elements. The distance value for missing elements (if the cluster contains no feature from a certain input map) is the user-defined threshold that marks the maximum allowed radius of a cluster. When adding elements to the cluster, the client needs to call initializeCluster first and the client needs to call finalizeCluster after adding the last element. After finalizeCluster, the client may not add any more elements through the add function (the client must call initializeCluster again before adding new elements). If use_id_ is set, clusters are extended only with elements that have at least one matching ID. Quality is then computed as the best quality of all possible IDs and this ID is then used as the only (representative) ID of the cluster. The left-out alternative IDs might be added back later based on the original features though. @todo This implementation may benefit from two separate implementations (one considering IDs/annotations one without). The current implementation most likely hinders speed/memory of both by trying to do both in one. The ID-based implementation could additionally benefit from ID scores and make use of ConsensusID functions. @see QTClusterFinder @ingroup Datastructures */ class OPENMS_DLLAPI QTCluster { public: // need to store more than one typedef std::multimap<double, const GridFeature*> NeighborList; typedef std::unordered_map<Size, NeighborList> NeighborMapMulti; struct Neighbor { double distance; const GridFeature* feature; }; typedef std::unordered_map<Size, Neighbor> NeighborMap; struct Element { Size map_index; const GridFeature* feature; }; typedef std::vector<Element> Elements; /** * @brief Class to store the bulk internal data (neighbors, annotations, etc.) * * Has no functionality without a QTCluster pointing to it. * Create object of this class before calling constructor of QTCluster */ class OPENMS_DLLAPI BulkData { friend class QTCluster; public: /** * @brief Detailed constructor of the cluster body * @param[in] center_point Pointer to the center point * @param[in] num_maps Number of input maps * @param[in] max_distance Maximum allowed distance of two points * @param[in] x_coord The x-coordinate in the grid cell * @param[in] y_coord The y-coordinate in the grid cell * @param[in] id Unique ID of this cluster */ BulkData(const OpenMS::GridFeature* const center_point, Size num_maps, double max_distance, Int x_coord, Int y_coord, Size id); private: /// Pointer to the cluster center const GridFeature* const center_point_; /// unique id of this cluster Size id_; /** * @brief Map that keeps track of the best current feature for each map * */ NeighborMap neighbors_; /** * @brief Temporary map tracking *all* neighbors * * For each input run, a multimap which contains pointers to all * neighboring elements and the respective distance. * */ NeighborMapMulti tmp_neighbors_; /// Maximum distance of a point that can still belong to the cluster double max_distance_; /// Number of input maps Size num_maps_; /// x coordinate in the grid cell Int x_coord_; /// y coordinate in the grid cell Int y_coord_; /** * @brief Set of annotations of the cluster * * The set of peptide sequences that is compatible to the cluster center * and results in the best cluster quality. */ std::set<AASequence> annotations_; }; /** * @brief Detailed constructor of the cluster head * @param[in] data Pointer to internal data * @param[in] use_IDs Use peptide annotations? */ QTCluster(BulkData* const data, bool use_IDs); /** * @brief Default constructor not accessible * Objects of this class should only exist with a valid BulkData* given. * Otherwise most of the member functions are undefined behavior or produce segfaults */ QTCluster() = delete; /** * @brief Cheap copy ctor because most of the data lies outside of this class (BulkData*) * Be very careful with this copy constructor. The copy will point to the same * BulkData object as the given QTCluster. The latter one shouldn't be used anymore. * This operation is only allowed because the boost::heap interface needs it. */ QTCluster(const QTCluster& rhs) = default; /// Cheap copy assignment, see copy ctor for details QTCluster& operator=(const QTCluster& rhs) = default; /// cheap move ctor because most of the data lies outside of this class (BulkData*) QTCluster(QTCluster&& rhs) = default; /// cheap move assignment because most of the data lies outside of this class (BulkData*) QTCluster& operator=(QTCluster&& rhs) = default; ~QTCluster() = default; /// Returns the cluster center const GridFeature* getCenterPoint() const; /// returns the clusters id Size getId() const; /// Returns the RT value of the cluster double getCenterRT() const; /// Returns the m/z value of the cluster center double getCenterMZ() const; /// Returns the x coordinate in the grid Int getXCoord() const; /// Returns the y coordinate in the grid Int getYCoord() const; /// Returns the size of the cluster (number of elements, incl. center) Size size() const; /// Compare by quality bool operator<(const QTCluster& cluster) const; /** * @brief Adds a new element/neighbor to the cluster * @note There is no check whether the element/neighbor already exists in the cluster! * @param[in] element The element to be added * @param[in] distance Distance of the element to the center point */ void add(const GridFeature* const element, double distance); /// Gets the clustered elements meaning neighbors + cluster center Elements getElements() const; /** * @brief Updates the cluster after the indicated data points are removed * * @param[in] removed The datapoints to be removed from the cluster * * @return Whether the cluster composition has changed due to the update */ bool update(const Elements& removed); /// Returns the cluster quality and recomputes if necessary double getQuality(); /// Returns the cluster quality without recomputing double getCurrentQuality() const; /// Return the set of peptide sequences annotated to the cluster center const std::set<AASequence>& getAnnotations(); /** * @brief Sets current cluster as invalid (also frees some memory) * * @note Do not attempt to use the cluster again once it is invalid, some * internal data structures have now been cleared * */ void setInvalid(); /// Whether current cluster is invalid inline bool isInvalid() const { return !valid_; } /// Has to be called before adding elements (calling QTCluster::add) void initializeCluster(); /// Has to be called after adding elements (after calling QTCluster::add one or multiple times) void finalizeCluster(); /// Get all current neighbors Elements getAllNeighbors() const; private: /// Computes the quality of the cluster void computeQuality_(); /** * @brief Finds the optimal annotation (peptide sequences) for the cluster * * The optimal annotation is the one that results in the best quality. It * is stored in @p annotations_; * * This function is only needed when peptide ids are used and the current * center point does not have any peptide id associated with it. In this * case, it is not clear which peptide id the current cluster should use. * The function thus iterates through all possible peptide ids and selects * the one producing the best cluster. * * This function needs access to all possible neighbors for this cluster * and thus can only be run when tmp_neighbors_ is filled (which is during * the filling of a cluster). The function thus cannot be called after * finalizing the cluster. * * @returns The total distance between cluster elements and the center. */ double optimizeAnnotations_(); /// compute seq table, mapping: peptides -> best distance per input map void makeSeqTable_(std::map<AASequence, std::map<Size,double>>& seq_table) const; /// report elements that are compatible with the optimal annotation void recomputeNeighbors_(); /// Quality of the cluster double quality_; /// Pointer to data members BulkData* data_; /// Whether current cluster is valid bool valid_; /// Has the cluster changed (if yes, quality needs to be recomputed)? bool changed_; /// Keep track of peptide IDs and use them for matching? bool use_IDs_; /** * @brief Whether initial collection of all neighbors is needed * * This variable stores whether we need to collect all annotations first * before we can decide upon the best set of cluster points. This is * usually only necessary if the center point does not have an annotation * but we want to use ids. * */ bool collect_annotations_; /// Whether current cluster is accepting new elements or not (if true, no more new elements allowed) bool finalized_; }; } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/DATASTRUCTURES/IsotopeCluster.h
.h
2,710
91
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg$ // $Authors: Marc Sturm $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/CONCEPT/Types.h> #include <vector> #include <set> namespace OpenMS { /** @brief Stores information about an isotopic cluster (i.e. potential peptide charge variants) An isotopic cluster represents a group of related peaks that likely originate from the same peptide but with different isotopic compositions. This structure stores the indices of these peaks and the scans they appear in, along with charge state information when available. The structure is typically used in mass spectrometry data analysis to group related peaks and track their charge states for further processing. @ingroup Datastructures */ struct OPENMS_DLLAPI IsotopeCluster { /** @brief An index pair typically representing (scan_index, peak_index) in an MSExperiment The first value usually refers to the scan/spectrum index, while the second value refers to the peak index within that scan/spectrum. */ typedef std::pair<Size, Size> IndexPair; /** @brief A set of index pairs, usually referring to peaks in an MSExperiment This collection stores unique pairs of indices that point to specific peaks in specific scans of a mass spectrometry experiment. */ typedef std::set<IndexPair> IndexSet; /** @brief Index set with associated charge estimate Extends the basic IndexSet with charge state information for the peaks. This allows tracking which peaks belong to the same isotopic pattern and what charge state they represent. */ struct ChargedIndexSet : public IndexSet { /** @brief Default constructor Initializes the charge to 0, which by convention means "no charge estimate" */ ChargedIndexSet() : charge(0) { } /// Charge estimate (convention: zero means "no charge estimate") Int charge; }; /** @brief Default constructor Initializes an empty isotope cluster with no peaks and no scans */ IsotopeCluster() : peaks(), scans() { } /// Peaks in this cluster, with their charge state information ChargedIndexSet peaks; /// The scan indices where this cluster appears std::vector<Size> scans; }; } // namespace OPENMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/DATASTRUCTURES/String.h
.h
18,092
501
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg$ // $Authors: Marc Sturm $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/OpenMSConfig.h> #include <string> #include <cstring> #include <vector> class QString; namespace OpenMS { class DataValue; template <typename FloatingPointType> struct PrecisionWrapper; /** @brief A more convenient string class. It is based on std::string but adds a lot of methods for convenience. @ingroup Datastructures */ class String : public std::string { public: /// Empty string for comparisons OPENMS_DLLAPI static const String EMPTY; /** @name Type definitions */ //@{ /// Iterator typedef iterator Iterator; /// Const Iterator typedef const_iterator ConstIterator; /// Reverse Iterator typedef reverse_iterator ReverseIterator; /// Const reverse Iterator typedef const_reverse_iterator ConstReverseIterator; /// UInt type typedef size_type SizeType; /// How to handle embedded quotes when quoting strings enum QuotingMethod {NONE, ESCAPE, DOUBLE}; //@} /** @name Constructors */ //@{ /// Default constructor OPENMS_DLLAPI String(); /// Copy constructor OPENMS_DLLAPI String(const String&) = default; /// Move constructor OPENMS_DLLAPI String(String&&) = default; /// Constructor from std::string OPENMS_DLLAPI String(const std::string& s); /// Constructor from std::string_view OPENMS_DLLAPI String(const std::string_view& sv); /// Constructor from Qt QString OPENMS_DLLAPI String(const QString& s); /// Constructor from char* OPENMS_DLLAPI String(const char* s); /// Constructor from a char OPENMS_DLLAPI String(const char c); /// Constructor from char* (only @p length characters) OPENMS_DLLAPI String(const char* s, SizeType length); /// Constructor from char (repeats the char @p len times) OPENMS_DLLAPI String(size_t len, char c); /// Constructor from a char range template <class InputIterator> String(InputIterator first, InputIterator last) : std::string(first, last) { } /// Constructor from an integer OPENMS_DLLAPI String(int i); /// Constructor from an unsigned integer OPENMS_DLLAPI String(unsigned int i); /// Constructor from an integer OPENMS_DLLAPI String(short int i); /// Constructor from an unsigned integer OPENMS_DLLAPI String(short unsigned int i); /// Constructor from an integer OPENMS_DLLAPI String(long int i); /// Constructor from an unsigned integer OPENMS_DLLAPI String(long unsigned int i); /// Constructor from an unsigned integer OPENMS_DLLAPI String(long long unsigned int i); /// Constructor from an unsigned integer OPENMS_DLLAPI String(long long signed int i); /// Constructor from float (@p full_precision controls number of fractional digits, 3 digits when false, and 6 when true) OPENMS_DLLAPI String(float f, bool full_precision = true); /// Constructor from double (@p full_precision controls number of fractional digits, 3 digits when false, and 15 when true) OPENMS_DLLAPI String(double d, bool full_precision = true); /// Constructor from long double (@p full_precision controls number of fractional digits, 3 digits when false, and 15 when true) OPENMS_DLLAPI String(long double ld, bool full_precision = true); /// Constructor from DataValue (@p full_precision controls number of fractional digits for all double types or lists of double, 3 digits when false, and 15 when true) OPENMS_DLLAPI String(const DataValue& d, bool full_precision = true); //@} /** @name Predicates */ //@{ /// true if String begins with @p string, false otherwise OPENMS_DLLAPI bool hasPrefix(const String& string) const; /// true if String ends with @p string, false otherwise OPENMS_DLLAPI bool hasSuffix(const String& string) const; /// true if String contains the @p string, false otherwise OPENMS_DLLAPI bool hasSubstring(const String& string) const; /// true if String contains the @p byte, false otherwise OPENMS_DLLAPI bool has(Byte byte) const; //@} /// Assignment operator OPENMS_DLLAPI String& operator=(const String&) = default; /// Move assignment operator OPENMS_DLLAPI String& operator=(String&&) & = default; /** @name Accessors */ //@{ /** @brief returns the prefix of length @p length @exception Exception::IndexOverflow is thrown if @p length is bigger than the size */ OPENMS_DLLAPI String prefix(SizeType length) const; /** @brief returns the suffix of length @p length @exception Exception::IndexOverflow is thrown if @p length is bigger than the size */ OPENMS_DLLAPI String suffix(SizeType length) const; /** @brief returns the prefix of length @p length @exception Exception::IndexUnderflow is thrown if @p length is smaller than zero @exception Exception::IndexOverflow is thrown if @p length is bigger than the size */ OPENMS_DLLAPI String prefix(Int length) const; /** @brief returns the suffix of length @p length @exception Exception::IndexUnderflow is thrown if @p length is smaller than zero @exception Exception::IndexOverflow is thrown if @p length is bigger than the size */ OPENMS_DLLAPI String suffix(Int length) const; /** @brief returns the prefix up to the first occurrence of char @p delim (excluding it) @exception Exception::ElementNotFound is thrown if @p delim is not found */ OPENMS_DLLAPI String prefix(char delim) const; /** @brief returns the suffix up to the last occurrence of char @p delim (excluding it) @exception Exception::ElementNotFound is thrown if @p delim is not found */ OPENMS_DLLAPI String suffix(char delim) const; /** @brief Wrapper for the STL substr() method. Returns a String object with its contents initialized to a substring of the current object. @param[in] pos Position of a character in the current string object to be used as starting character for the substring. If the @p pos is past the end of the string, it is set to the end of the string. @param[in] n Length of the substring. If this value would make the substring to span past the end of the current string content, only those characters until the end of the string are used. npos is a static member constant value with the greatest possible value for an element of type size_t, therefore, when this value is used, all the characters between pos and the end of the string are used as the initialization substring. */ OPENMS_DLLAPI String substr(size_t pos = 0, size_t n = npos) const; /** @brief Returns a substring where @p n characters were removed from the end of the string. If @p n is greater than size(), the result is an empty string. @param[in] n Number of characters that will be removed from the end of the string. */ OPENMS_DLLAPI String chop(Size n) const; //@} /** @name Mutators All these methods return a reference to the string in order to make them chainable */ //@{ /// inverts the direction of the string OPENMS_DLLAPI String& reverse(); /// removes whitespaces (space, tab, line feed, carriage return) at the beginning and the end of the string OPENMS_DLLAPI String& trim(); /** @brief Checks if the string is wrapped in quotation marks The quotation mark can be specified by parameter @p q (typically single or double quote). @see unquote() */ OPENMS_DLLAPI bool isQuoted(char q = '"'); /** @brief Wraps the string in quotation marks The quotation mark can be specified by parameter @p q (typically single or double quote); embedded quotation marks are handled according to @p method by backslash-escaping, doubling, or not at all. @see unquote() */ OPENMS_DLLAPI String& quote(char q = '"', QuotingMethod method = ESCAPE); /** @brief Reverses changes made by the @p quote method Removes surrounding quotation marks (given by parameter @p q); handles embedded quotes according to @p method. @exception Exception::ConversionError is thrown if the string does not have the format produced by @p quote @see quote() */ OPENMS_DLLAPI String& unquote(char q = '"', QuotingMethod method = ESCAPE); /// merges subsequent whitespaces to one blank character OPENMS_DLLAPI String& simplify(); ///Adds @p c on the left side until the size of the string is @p size OPENMS_DLLAPI String& fillLeft(char c, UInt size); ///Adds @p c on the right side until the size of the string is @p size OPENMS_DLLAPI String& fillRight(char c, UInt size); ///Converts the string to uppercase OPENMS_DLLAPI String& toUpper(); ///Converts the string to lowercase OPENMS_DLLAPI String& toLower(); ///Converts the first letter of the string to uppercase OPENMS_DLLAPI String& firstToUpper(); ///Replaces all occurrences of the character @p from by the character @p to. OPENMS_DLLAPI String& substitute(char from, char to); ///Replaces all occurrences of the string @p from by the string @p to. OPENMS_DLLAPI String& substitute(const String& from, const String& to); ///Remove all occurrences of the character @p what. OPENMS_DLLAPI String& remove(char what); ///Makes sure the string ends with the character @p end OPENMS_DLLAPI String& ensureLastChar(char end); ///removes whitespaces (space, tab, line feed, carriage return) OPENMS_DLLAPI String& removeWhitespaces(); //@} /** @name Converters */ //@{ /** @brief Conversion to Int This method extracts only the integral part of the string. If you want the result rounded, use toFloat() and round the result. @exception Exception::ConversionError is thrown if the string could not be converted to Int */ OPENMS_DLLAPI Int toInt() const; /** @brief Conversion to Int32 This method extracts only the integral part of the string. If you want the result rounded, use toFloat() and round the result. @exception Exception::ConversionError is thrown if the string could not be converted to Int32 */ OPENMS_DLLAPI Int32 toInt32() const; /** @brief Conversion to Int64 This method extracts only the integral part of the string. If you want the result rounded, use toFloat() and round the result. @exception Exception::ConversionError is thrown if the string could not be converted to Int64 */ OPENMS_DLLAPI Int64 toInt64() const; /** @brief Conversion to float @exception Exception::ConversionError is thrown if the string could not be converted to float */ OPENMS_DLLAPI float toFloat() const; /** @brief Conversion to double @exception Exception::ConversionError is thrown if the string could not be converted to double */ OPENMS_DLLAPI double toDouble() const; /// Conversion to Qt QString OPENMS_DLLAPI QString toQString() const; //@} /** @name Sum operator overloads */ //@{ /// Sum operator for an integer OPENMS_DLLAPI String operator+(int i) const; /// Sum operator for an unsigned integer OPENMS_DLLAPI String operator+(unsigned int i) const; /// Sum operator for an integer OPENMS_DLLAPI String operator+(short int i) const; /// Sum operator for an unsigned integer OPENMS_DLLAPI String operator+(short unsigned int i) const; /// Sum operator for an integer OPENMS_DLLAPI String operator+(long int i) const; /// Sum operator for an unsigned integer OPENMS_DLLAPI String operator+(long unsigned int i) const; /// Sum operator for an unsigned integer OPENMS_DLLAPI String operator+(long long unsigned int i) const; /// Sum operator for float OPENMS_DLLAPI String operator+(float f) const; /// Sum operator for double OPENMS_DLLAPI String operator+(double d) const; /// Sum operator for long double OPENMS_DLLAPI String operator+(long double ld) const; /// Sum operator for char OPENMS_DLLAPI String operator+(char c) const; /// Sum operator for char* OPENMS_DLLAPI String operator+(const char* s) const; /// Sum operator for String OPENMS_DLLAPI String operator+(const String& s) const; /// Sum operator for std::string OPENMS_DLLAPI String operator+(const std::string& s) const; //@} /** @name Append operator overloads */ //@{ /// Sum operator for an integer OPENMS_DLLAPI String& operator+=(int i); /// Sum operator for an unsigned integer OPENMS_DLLAPI String& operator+=(unsigned int i); /// Sum operator for an integer OPENMS_DLLAPI String& operator+=(short int i); /// Sum operator for an unsigned integer OPENMS_DLLAPI String& operator+=(short unsigned int i); /// Sum operator for an integer OPENMS_DLLAPI String& operator+=(long int i); /// Sum operator for an unsigned integer OPENMS_DLLAPI String& operator+=(long unsigned int i); /// Sum operator for an unsigned integer OPENMS_DLLAPI String& operator+=(long long unsigned int i); /// Sum operator for float OPENMS_DLLAPI String& operator+=(float f); /// Sum operator for double OPENMS_DLLAPI String& operator+=(double d); /// Sum operator for long double OPENMS_DLLAPI String& operator+=(long double d); /// Sum operator for char OPENMS_DLLAPI String& operator+=(char c); /// Sum operator for char* OPENMS_DLLAPI String& operator+=(const char* s); /// Sum operator for String OPENMS_DLLAPI String& operator+=(const String& s); /// Sum operator for std::string OPENMS_DLLAPI String& operator+=(const std::string& s); //@} ///returns a random string of the given length. It consists of [0-9a-zA-Z] OPENMS_DLLAPI static String random(UInt length); ///returns a string for @p d with exactly @p n decimal places OPENMS_DLLAPI static String number(double d, UInt n); /** @brief Returns a string with at maximum @p n characters for @p d If @p d is larger, scientific notation is used. */ OPENMS_DLLAPI static String numberLength(double d, UInt n); /** @brief Splits a string into @p substrings using @p splitter as delimiter If @p splitter is not found, the whole string is put into @p substrings. If @p splitter is empty, the string is split into individual characters. If the invoking string is empty, @p substrings will also be empty. @p quote_protect (default: false) can be used to split only between quoted blocks e.g. ' "a string" , "another string with , in it" ' results in only two substrings (with double quotation marks @em removed). Every returned substring is trimmed and then (if present) has surrounding quotation marks removed. @return @e true if one or more splits occurred, @e false otherwise @see concatenate(). */ OPENMS_DLLAPI bool split(const char splitter, std::vector<String>& substrings, bool quote_protect = false) const; /** @brief Splits a string into @p substrings using @p splitter (the whole string) as delimiter If @p splitter is not found, the whole string is put into @p substrings. If @p splitter is empty, the string is split into individual characters. If the invoking string is empty, @p substrings will also be empty. @return @e true if one or more splits occurred, @e false otherwise @see concatenate(). */ OPENMS_DLLAPI bool split(const String& splitter, std::vector<String>& substrings) const; /** @brief Splits a string into @p substrings using @p splitter (the whole string) as delimiter, but does not split within quoted substrings A "quoted substring" has the format as produced by @p quote(q, method), where @p q is the quoting character and @p method defines the handling of embedded quotes. Substrings will not be "unquoted" or otherwise processed. If @p splitter is not found, the whole string is put into @p substrings. If @p splitter or the invoking string is empty, @p substrings will also be empty. @return @e true if one or more splits occurred, @e false otherwise @exception Exception::ConversionError is thrown if quotation marks are not balanced @see concatenate(), quote(). */ OPENMS_DLLAPI bool split_quoted(const String& splitter, std::vector<String>& substrings, char q = '"', QuotingMethod method = ESCAPE) const; /** @brief Concatenates all elements from @p first to @p last-1 and inserts @p glue between the elements @see split(). */ template <class StringIterator> void concatenate(StringIterator first, StringIterator last, const String& glue = "") { //empty container if (first == last) { std::string::clear(); return; } std::string::operator=(*first); for (StringIterator it = ++first; it != last; ++it) { std::string::operator+=(glue + (*it)); } } }; OPENMS_DLLAPI ::size_t hash_value(OpenMS::String const& s); } // namespace OpenMS namespace std { template <> struct hash<OpenMS::String> //hash for String { std::size_t operator()( OpenMS::String const& s) const { return std::hash<string>()(static_cast<string>(s)); } }; } // namespace std
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/DATASTRUCTURES/MatchedIterator.h
.h
11,585
316
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow $ // $Authors: Chris Bielow $ // -------------------------------------------------------------------------- // #pragma once #include <OpenMS/CONCEPT/Macros.h> #include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h> #include <OpenMS/MATH/MathFunctions.h> #include <iterator> #include <type_traits> namespace OpenMS { /** @brief For each element in the reference container the closest peak in the target will be searched. If no match is found within the tolerance window, the peak will be skipped over. This class can be used for example to iterate through the matching peaks in two spectra (e.g. experimental spectrum and reference spectrum) that are within a given tolerance (in m/z, RT, or something user-defined). The iterator always chooses the closest matching peak in the target container, if more than one candidate is found in the match-window. If two peaks have equal distance, the smaller value is preferred. If no peak is found within the given tolerance (distance), the reference peak does not yield a result and the next reference peak is tested. This means the operator++ can be called at most(!) ref.size()-1 times before it == is.end(). The TRAIT template argument (e.g., ValueTrait, DaTrait or PpmTrait) encodes the distance metric (on the value directly, or a member of the value_type, e.g. ppm or Da for m/z, or RT or any other metric you like). The simplest use case would be a vector<float> or similar. The TRAIT struct just defines two functions which return some distance metrics and accept elements of the container CONT_T as arguments. Both containers must be sorted with respect to the comparator used in TRAIT. The CONST_T template argument switches between a 'const_iterator' and an 'iterator'. This iterator is much more efficient than iterating over the reference container and calling findNearest(), i.e. binary search on the target container, i.e. O(n+m) vs. O(n*log(m)). Since this container is much more cache-friendly, the actual speedups are even larger. */ template <typename CONT_T, typename TRAIT, bool CONST_T = true > class MatchedIterator { public: // define the 5 types required for an iterator. Deriving from std::iterator is deprecated in C++17. using iterator_category = std::forward_iterator_tag; using value_type = typename CONT_T::value_type; //< dereferences to an element in the target container using difference_type = std::ptrdiff_t; using pointer = typename std::conditional<CONST_T, typename CONT_T::value_type const*, typename CONT_T::value_type*>::type; using reference = typename std::conditional<CONST_T, typename CONT_T::value_type const&, typename CONT_T::value_type&>::type; using CONT_IT = typename std::conditional<CONST_T, typename CONT_T::const_iterator, typename CONT_T::iterator>::type; // for dereferencing etc using CONST_CONT_IT = typename CONT_T::const_iterator; // for input containers /** @brief Constructs a MatchedIterator on two containers. The way a match is found, depends on the TRAIT type (ppm or Da tolerance) For each element in the reference container the closest peak in the target will be searched. If no match is found within the tolerance window, the peak will be skipped over. @param[in] ref For each element in this reference container the closest peak in the target will be searched @param[in] target Target container @param[in] tolerance Maximal distance between a valid matching pair in reference and target (unit is according to TRAIT::getDiffAbsolute(), i.e. could be ppm, Da, seconds, ...) */ explicit MatchedIterator(const CONT_T& ref, const CONT_T& target, float tolerance) : MatchedIterator(ref.begin(), ref.end(), target.begin(), target.end(), tolerance) { } /** @brief Constructs a MatchedIterator on two containers. The way a match is found, depends on the TRAIT type (ppm or Da tolerance) For each element in the reference container the closest peak in the target will be searched. If no match is found within the tolerance window, the peak will be skipped over. @param[in] ref_begin Begin range of reference container @param[in] ref_end End range of reference container @param[in] tgt_begin Begin range of reference container @param[in] tgt_end End range of reference container @param[in] tolerance Maximal distance between a valid matching pair in reference and target (unit is according to TRAIT::getDiffAbsolute(), i.e. could be ppm, Da, seconds, ...) */ explicit MatchedIterator(const CONST_CONT_IT ref_begin, const CONST_CONT_IT ref_end, const CONST_CONT_IT tgt_begin, const CONST_CONT_IT tgt_end, float tolerance) : ref_begin_(ref_begin), ref_end_(ref_end), tgt_begin_(tgt_begin), tgt_end_(tgt_end), it_ref_(ref_begin), it_tgt_(tgt_begin), tol_(tolerance), is_end_(false) { if (tgt_begin_ == tgt_end_) { // nothing to iterate over in target (if ref_ were empty, isEnd_() is automatically true) setToEnd_(); return; } advanceTarget_(); } /** @brief Default CTor; do not use this for anything other than assigning to it; */ explicit MatchedIterator() : ref_begin_(), ref_end_(), tgt_begin_(), tgt_end_(), it_ref_(), it_tgt_(), tol_(), is_end_(false) { } /// Copy CTor (default) MatchedIterator(const MatchedIterator& rhs) = default; /// Assignment operator (default) MatchedIterator& operator=(const MatchedIterator& rhs) = default; bool operator==(const MatchedIterator& rhs) const { if (this == &rhs) return true; if (isEnd_() || rhs.isEnd_()) { return isEnd_() == rhs.isEnd_(); } return (it_ref_ == rhs.it_ref_ && it_tgt_ == rhs.it_tgt_ && ref_begin_ == rhs.ref_begin_ && ref_end_ == rhs.ref_end_ && tgt_begin_ == rhs.tgt_begin_ && tgt_end_ == rhs.tgt_end_); } bool operator!=(const MatchedIterator& rhs) const { return !(*this == rhs); } /// dereference current target element template< bool _CONST = CONST_T > typename std::enable_if< _CONST, reference >::type operator*() const { return *it_tgt_; } template< bool _CONST = CONST_T > typename std::enable_if< !_CONST, reference >::type operator*() { return *it_tgt_; } /// pointer to current target element template< bool _CONST = CONST_T > typename std::enable_if< _CONST, pointer >::type operator->() const { return &(*it_tgt_); } template< bool _CONST = CONST_T > typename std::enable_if< !_CONST, pointer >::type operator->() { return &(*it_tgt_); } /// current element in reference container const value_type& ref() const { return *it_ref_; } /// index into reference container size_t refIdx() const { return it_ref_ - ref_begin_; } /// index into target container size_t tgtIdx() const { return it_tgt_ - tgt_begin_; } /** @brief Advances to the next valid pair @exception Exception::InvalidIterator If iterator is already at end */ MatchedIterator& operator++() { // are we at end already? --> wrong usage OPENMS_PRECONDITION(!isEnd_(), "Tried to advance beyond end iterator!"); ++it_ref_; advanceTarget_(); return *this; } /// post-increment MatchedIterator operator++(int) { MatchedIterator n(*this); ++(*this); return n; } /// the end iterator static MatchedIterator end() { return MatchedIterator(true); } protected: /// protected Ctor which creates and end() iterator /// the bool argument is only used to call the correct target (its value is ignored) MatchedIterator(bool /*is_end*/) : ref_begin_(), ref_end_(), tgt_begin_(), tgt_end_(), it_ref_(), it_tgt_(), tol_(), is_end_(true) { } void setToEnd_() { is_end_ = true; } bool isEnd_() const { return is_end_; } void advanceTarget_() { while (it_ref_ != ref_end_) { // note: it_tgt_ always points to a valid element (unless the whole container was empty -- see CTor) double max_dist = TRAIT::allowedTol(tol_, *it_ref_); // forward iterate over elements in target data until distance gets worse float diff = std::numeric_limits<float>::max(); do { auto d = TRAIT::getDiffAbsolute(*it_ref_, *it_tgt_); if (diff > d) // getting better { diff = d; } else // getting worse (overshot) { --it_tgt_; break; } ++it_tgt_; } while (it_tgt_ != tgt_end_); if (it_tgt_ == tgt_end_) { // reset to last valid entry --it_tgt_; } if (diff <= max_dist) return; // ok, found match // try next ref peak ++it_ref_; } // reached end of ref container setToEnd_(); // i.e. isEnd() is true now } CONST_CONT_IT ref_begin_, ref_end_; CONST_CONT_IT tgt_begin_, tgt_end_; CONT_IT it_ref_, it_tgt_; float tol_; bool is_end_ = false; }; /// Trait for MatchedIterator to find pairs with a certain distance, which is computed directly on the value_type of the container struct ValueTrait { template <typename T> static float allowedTol(float tol, const T& /*mz_ref*/) { return tol; } /// just use fabs on the value directly template <typename T> static T getDiffAbsolute(const T& elem_ref, const T& elem_tgt) { return fabs(elem_ref - elem_tgt); } }; /// Trait for MatchedIterator to find pairs with a certain ppm distance in m/z. /// Requires container elements to support .getMZ() as member function struct PpmTrait { template <typename T> static float allowedTol(float tol, const T& elem_ref) { return Math::ppmToMass(tol, (float)elem_ref.getMZ()); } /// for Peak1D & Co template <typename T> static float getDiffAbsolute(const T& elem_ref, const T& elem_tgt) { return fabs(elem_ref.getMZ() - elem_tgt.getMZ()); } }; /// Trait for MatchedIterator to find pairs with a certain Th/Da distance in m/z. /// Requires container elements to support .getMZ() as member function struct DaTrait { template <typename T> static float allowedTol(float tol, const T& /*mz_ref*/) { return tol; } /// for Peak1D & Co template <typename T> static float getDiffAbsolute(const T& elem_ref, const T& elem_tgt) { return fabs(elem_ref.getMZ() - elem_tgt.getMZ()); } }; } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/DATASTRUCTURES/Adduct.h
.h
3,505
110
// 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/OpenMSConfig.h> #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/CONCEPT/HashUtils.h> #include <OpenMS/DATASTRUCTURES/String.h> #include <functional> namespace OpenMS { class OPENMS_DLLAPI Adduct { public: typedef std::vector<Adduct> AdductsType; /// Default C'tor Adduct(); /// C'tor with initial charge Adduct(Int charge); /// C'tor for all members Adduct(Int charge, Int amount, double singleMass, const String& formula, double log_prob, double rt_shift, const String& label = ""); /// Increase amount of this adduct by factor @param[in] m Adduct operator*(const Int m) const; /// Add two adducts amount if they are equal (defined by equal formula) Adduct operator+(const Adduct& rhs); /// Add other adducts amount to *this (equal formula required!) void operator+=(const Adduct& rhs); /// Print the contents of an Adduct to a stream. friend OPENMS_DLLAPI std::ostream& operator<<(std::ostream& os, const Adduct& a); /// Comparator friend OPENMS_DLLAPI bool operator==(const Adduct& a, const Adduct& b); //@{ Accessors const Int& getCharge() const; void setCharge(const Int& charge); const Int& getAmount() const; void setAmount(const Int& amount); const double& getSingleMass() const; void setSingleMass(const double& singleMass); const double& getLogProb() const; void setLogProb(const double& log_prob); const String& getFormula() const; void setFormula(const String& formula); const double& getRTShift() const; const String& getLabel() const; // convert a ion string to adduct string with charge information (eg. ion_string = "Na1", charge = "1" --> "[M+Na]+") String toAdductString(const String& ion_string, const Int& charge); //} private: Int charge_; ///< usually +1 Int amount_; ///< number of entities double singleMass_; ///< mass of a single entity double log_prob_; ///< log probability of observing a single entity of this adduct String formula_; ///< chemical formula (parsable by EmpiricalFormula) double rt_shift_; ///< RT shift induced by a single entity of this adduct (this is for adducts attached prior to ESI, e.g. labeling) String label_; ///< Label for this adduct (can be used to indicate heavy labels) String checkFormula_(const String& formula); }; } // namespace OpenMS // Hash function specialization for Adduct // Note: Only hash fields used in operator== (charge, amount, singleMass, log_prob, formula) // Do NOT hash rt_shift_ and label_ as they are not compared in operator== namespace std { template<> struct hash<OpenMS::Adduct> { std::size_t operator()(const OpenMS::Adduct& a) const noexcept { std::size_t seed = OpenMS::hash_int(a.getCharge()); OpenMS::hash_combine(seed, OpenMS::hash_int(a.getAmount())); OpenMS::hash_combine(seed, OpenMS::hash_float(a.getSingleMass())); OpenMS::hash_combine(seed, OpenMS::hash_float(a.getLogProb())); OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(a.getFormula())); return seed; } }; } // namespace std
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/DATASTRUCTURES/CVMappingRule.h
.h
3,057
129
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Andreas Bertsch $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/OpenMSConfig.h> #include <OpenMS/DATASTRUCTURES/String.h> #include <vector> namespace OpenMS { class CVMappingTerm; /** @brief Representation of a CV Mapping rule used by CVMappings Representation of a controlled vocabulary mapping rule. @ingroup Datastructures */ class OPENMS_DLLAPI CVMappingRule { public: /// enum to specify the requirement level enum RequirementLevel { MUST = 0, SHOULD = 1, MAY = 2 }; /// enum to specify the combination operator enum CombinationsLogic { OR = 0, AND = 1, XOR = 2 }; /// Default constructor CVMappingRule(); /// Copy constructor CVMappingRule(const CVMappingRule& rhs); /// Destructor virtual ~CVMappingRule(); /// Assignment operator CVMappingRule& operator=(const CVMappingRule& rhs); /** @name Accessors */ //@{ /// sets the identifier of the rule void setIdentifier(const String& identifier); /// returns the identifier of the rule const String& getIdentifier() const; /// sets the path of the element, where this rule is allowed void setElementPath(const String& element_path); /// returns the path of the element, where this rule is allowed const String& getElementPath() const; /// sets the requirement level of this rule void setRequirementLevel(RequirementLevel level); /// returns the requirement level of this rule RequirementLevel getRequirementLevel() const; /// sets the combination operator of the rule void setCombinationsLogic(CombinationsLogic combinations_logic); /// returns the combinations operator of the rule CombinationsLogic getCombinationsLogic() const; /// sets the scope path of the rule void setScopePath(const String& path); /// returns the scope path of the rule const String& getScopePath() const; /// sets the terms which are allowed void setCVTerms(const std::vector<CVMappingTerm>& cv_terms); /// returns the allowed terms const std::vector<CVMappingTerm>& getCVTerms() const; /// adds a term to the allowed terms void addCVTerm(const CVMappingTerm& cv_terms); //@} /** @name Predicates */ //@{ /// equality operator bool operator==(const CVMappingRule& rhs) const; /// inequality operator bool operator!=(const CVMappingRule& rhs) const; //@} protected: String identifier_; String element_path_; RequirementLevel requirement_level_; String scope_path_; CombinationsLogic combinations_logic_; std::vector<CVMappingTerm> cv_terms_; }; } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/DATASTRUCTURES/OSWData.h
.h
14,081
397
// 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 <map> #include <vector> namespace OpenMS { class MSExperiment; /// hierarchy levels of the OSWData tree struct OPENMS_DLLAPI OSWHierarchy { /// the actual levels enum Level { PROTEIN, PEPTIDE, FEATURE, TRANSITION, SIZE_OF_VALUES }; /// strings matching 'Level' static const char* LevelName[SIZE_OF_VALUES]; }; /// Describes a node in the OSWData model tree. /// If a lower level, e.g. feature, is set, the upper levels need to be set as well. /// The lowest level which is set, must be indicated by setting @p lowest. struct OPENMS_DLLAPI OSWIndexTrace { int idx_prot = -1; int idx_pep = -1; int idx_feat = -1; int idx_trans = -1; OSWHierarchy::Level lowest = OSWHierarchy::Level::SIZE_OF_VALUES; /// is the trace default constructed (=false), or does it point somewhere (=true)? bool isSet() const { return lowest != OSWHierarchy::Level::SIZE_OF_VALUES; } }; /// high-level meta data of a transition struct OPENMS_DLLAPI OSWTransition { public: /// default c'tor OSWTransition() = default; /// custom c'tor which fills all the members with data; all members are read-only OSWTransition(const String& annotation, const UInt32 id, const float product_mz, const char type, const bool is_decoy); OSWTransition(const OSWTransition& rhs) = default; OSWTransition& operator=(const OSWTransition& rhs) = default; OSWTransition(OSWTransition&& rhs) = default; OSWTransition& operator=(OSWTransition&& rhs) = default; ~OSWTransition() = default; /// e.g. y5/-0.002 const String& getAnnotation() const { return annotation_; } /// ID as used in OSWPeakGroup::transition_ids UInt32 getID() const { return id_; } /// observed product m/z value float getProductMZ() const { return product_mz_; } /// b, y char getType() const { return type_; } /// is this a decoy transition (from a decoy protein/peptide) bool isDecoy() const { return is_decoy_; } private: String annotation_; ///< e.g. y5/-0.002 UInt32 id_; ///< ID as used in OSWPeakGroup::transition_ids float product_mz_; ///< observed product m/z value char type_; ///< b, y, bool is_decoy_; ///< is this a decoy transition (from a decoy protein/peptide) }; /** A peak group (also called feature) is defined on a small RT range (leftWidth to rightWidth) in a group of extracted transitions (chromatograms). The same transitions can be used to defined multiple (usually non-overlapping in RT) peak groups, of which usually only one is correct (lowest q-value). */ class OPENMS_DLLAPI OSWPeakGroup { public: /// fallback value of getQValue() if .osw file did not undergo pyProphet static constexpr float QVALUE_MISSING = -1; /// just a dummy feature to allow for acceptor output values etc OSWPeakGroup() = default; /// custom c'tor which fills all the members with data; all members are read-only OSWPeakGroup(const float rt_experimental, const float rt_left_width, const float rt_right_width, const float rt_delta, std::vector<UInt32>&& transition_ids, const float q_value = -1); /// Copy c'tor OSWPeakGroup(const OSWPeakGroup& rhs) = default; /// copy assignment OSWPeakGroup& operator=(const OSWPeakGroup& rhs) = default; /// move c'tor OSWPeakGroup(OSWPeakGroup&& rhs) = default; /// move assignment OSWPeakGroup& operator=(OSWPeakGroup&& rhs) = default; /// observed RT apex position in seconds of the feature float getRTExperimental() const { return rt_experimental_; } /// RT position in seconds of the left border float getRTLeftWidth() const { return rt_left_width_; } /// RT position in seconds of the right border float getRTRightWidth() const { return rt_right_width_; } /// RT difference in seconds to the expected RT float getRTDelta() const { return rt_delta_; } /// this might return QVALUE_MISSING if q-value is not annotated in the OSW file float getQValue() const { return q_value_; } /// get the transition ids (can be mapped to the chromatogram XICs in sqMass data) const std::vector<UInt32>& getTransitionIDs() const { return transition_ids_; } private: float rt_experimental_{ 0 }; ///< rt apex of this feature in seconds (averaged across all transitions) float rt_left_width_{ 0 }; ///< rt start in seconds float rt_right_width_{ 0 }; ///< rt end in seconds float rt_delta_{ 0 }; ///< rt offset from expected distance float q_value_{ -1 }; ///< optional Q-value from pyProphet; equals -1 if not set; std::vector<UInt32> transition_ids_; /// many features will point to the same transition (but at different RT); }; /** @brief A peptide with a charge state An OSWProtein has one or more OSWPeptidePrecursors. The OSWPeptidePrecursor contains multiple candidate features (peak groups) of type OSWPeakGroup, only one of which is usually true. */ class OPENMS_DLLAPI OSWPeptidePrecursor { public: /// just a dummy feature to allow for acceptor output values etc OSWPeptidePrecursor() = default; /// custom c'tor which fills all the members with data; all members are read-only OSWPeptidePrecursor(const String& seq, const short charge, const bool decoy, const float precursor_mz, std::vector<OSWPeakGroup>&& features); /// Copy c'tor OSWPeptidePrecursor(const OSWPeptidePrecursor& rhs) = default; /// assignment operator OSWPeptidePrecursor& operator=(const OSWPeptidePrecursor& rhs) = default; /// move c'tor OSWPeptidePrecursor(OSWPeptidePrecursor&& rhs) = default; /// move assignment operator OSWPeptidePrecursor& operator=(OSWPeptidePrecursor&& rhs) = default; /// the peptide sequence (incl. mods) const String& getSequence() const { return seq_; } /// precursor charge short getCharge() const { return charge_; } /// is this a decoy feature (from a decoy protein) bool isDecoy() const { return decoy_; } /// m/z of this charged peptide float getPCMz() const { return precursor_mz_; } /// candidate explanations const std::vector<OSWPeakGroup>& getFeatures() const { return features_; } private: String seq_; short charge_{0}; bool decoy_{false}; float precursor_mz_{0}; std::vector<OSWPeakGroup> features_; }; /** @brief A Protein is the highest entity and contains one or more peptides which were found/traced. */ class OPENMS_DLLAPI OSWProtein { public: /// just a dummy feature to allow for acceptor output values etc OSWProtein() = default; /// custom c'tor which fills all the members with data; all members are read-only OSWProtein(const String& accession, const Size id, std::vector<OSWPeptidePrecursor>&& peptides); /// Copy c'tor OSWProtein(const OSWProtein& rhs) = default; /// assignment operator OSWProtein& operator=(const OSWProtein& rhs) = default; /// move c'tor OSWProtein(OSWProtein&& rhs) = default; /// move assignment operator OSWProtein& operator=(OSWProtein&& rhs) = default; const String& getAccession() const { return accession_; } Size getID() const { return id_; } const std::vector<OSWPeptidePrecursor>& getPeptidePrecursors() const { return peptides_; } private: String accession_; Size id_; std::vector<OSWPeptidePrecursor> peptides_; }; /** @brief Holds all or partial information from an OSW file First, fill in all transitions and only then add proteins (which reference transitions via their transition-ids deep down). References will be checked and enforced (exception otherwise -- see addProtein()). */ class OPENMS_DLLAPI OSWData { public: /// Adds a transition; do this before adding Proteins void addTransition(const OSWTransition& tr) { transitions_.emplace(tr.getID(), tr); } void addTransition(OSWTransition&& tr) { UInt32 id = tr.getID(); transitions_.emplace(id, std::move(tr)); } /// Adds a protein, which has all its subcomponents already populated /// All transition references internally are checked to make sure /// they are valid. /// You can add stub proteins, by omitting their peptide references. /// @throws Exception::Precondition() if transition IDs within protein are unknown void addProtein(OSWProtein&& prot); /// constant accessor to proteins. /// There is no mutable access to prevent accidental violation of invariants (i.e. no matching transitions) const std::vector<OSWProtein>& getProteins() const { return proteins_; } /// Replace existing protein at position @p index /// Note: this is NOT the protein ID, but the index into the internal protein vector. See getProteins() /// /// @param[in] index A valid index into the getProteins() vector /// @param[in] protein The protein to replace the existing one /// @throws Exception::Precondition() if transition IDs within protein are unknown void setProtein(const Size index, OSWProtein&& protein) { checkTransitions_(protein); proteins_[index] = std::move(protein); } /// get the total number of transitions (chromatograms) Size transitionCount() const { return transitions_.size(); } /// obtain a certain transition meta information with @p id (this matches the ID of a chromatogram in an sqMass file). const OSWTransition& getTransition(const UInt32 id) const { return transitions_.at(id); } /// get all transitions mapped by their ID (UInt32) const std::map<UInt32, OSWTransition>& getTransitions() const { return transitions_; } void setSqlSourceFile(const String& filename) { source_file_ = filename; } const String& getSqlSourceFile() const { return source_file_; } void setRunID(const UInt64 run_id) { run_id_ = run_id; } UInt64 getRunID() const { return run_id_; } /// forget all data void clear(); /// only forget protein data void clearProteins(); /** @brief Create an internal mapping from the nativeIDs of all chromatograms (extracted by OpenSwathWorkflow (e.g. as sqMass file)) to their index (.getChromatograms[index]) The mapping is stored internally and can be used to translate transition.ids (which are native_ids) to a chromatogram index of the external sqMass file. The mapping can be queried using fromNativeID(int transition.id). Make sure that the other OSW data is loaded (at least via OSWFile::readMinimal()) before building this mapping here. @param[in] chrom_traces The external sqMass file, which we build the mapping on @throws Exception::MissingInformation if any nativeID is not known internally @throws Exception::Precondition if the run_ids do not match */ void buildNativeIDResolver(const MSExperiment& chrom_traces); /// resolve a transition.id (=nativeID) to a simple chromatogram index (.getChromatograms[index]) of the corresponding sqMass file /// Requires prior call to buildNativeIDResolver(), throws Exception::InvalidValue otherwise (or when nativeID is not known) UInt fromNativeID(int transition_id) const; protected: /// All transition references are checked against transitions_ to make sure /// they are valid. /// @throws Exception::Precondition() if transition IDs within protein are unknown void checkTransitions_(const OSWProtein& prot) const; private: std::map<UInt32, OSWTransition> transitions_; std::vector<OSWProtein> proteins_; String source_file_; ///< remember from which sql OSW file this data is loaded (to lazy load more data) UInt64 run_id_; ///< the ID of this run from the SQL RUN table std::map<UInt32, UInt32> transID_to_index_; ///< map a Transition.ID (==native_id) to a chromatogram index in the sqMass experiment which contains the raw data }; } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/DATASTRUCTURES/ToolDescription.h
.h
3,753
134
// 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, Mathias Walzer $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/DATASTRUCTURES/Param.h> #include <OpenMS/DATASTRUCTURES/String.h> #include <OpenMS/DATASTRUCTURES/ListUtils.h> #include <OpenMS/OpenMSConfig.h> #include <map> namespace OpenMS { namespace Internal { /** @brief Maps input/output files to filenames for the external program */ struct FileMapping { String location; ///< a regex/macro mix; to be expanded by tool; String target; ///< TOPP parameter that determines the desired name // thus: move location -> target /// Default constructor FileMapping() = default; /// Copy constructor FileMapping(const FileMapping& other) = default; /// Copy assignment FileMapping& operator=(const FileMapping& rhs) = default; }; /** @brief Filename mappings for all input/output files */ struct MappingParam { std::map<Int, String> mapping; std::vector<FileMapping> pre_moves; std::vector<FileMapping> post_moves; /// Default constructor MappingParam() = default; /// Copy constructor MappingParam(const MappingParam& other) = default; /// Copy assignment MappingParam& operator=(const MappingParam& other) = default; }; /** @brief ToolDescription Class. This class represents a ToolDescription. @ingroup Datastructures */ struct OPENMS_DLLAPI ToolDescriptionInternal { bool is_internal = false; String name; String category; StringList types; ///< -types of the tool /// default C'Tor ToolDescriptionInternal() = default; /// C'Tor with arguments ToolDescriptionInternal(const bool p_is_internal, const String& p_name, const String& p_category, const StringList& p_types); /// short C'Tor ToolDescriptionInternal(const String& p_name, const StringList& p_types); /// Copy assignment ToolDescriptionInternal& operator=(const ToolDescriptionInternal& rhs) = default; bool operator==(const ToolDescriptionInternal& rhs) const; bool operator<(const ToolDescriptionInternal& rhs) const; }; struct OPENMS_DLLAPI ToolExternalDetails { String text_startup; String text_fail; String text_finish; String category; String commandline; String path; ///< filename to external tool String working_directory; ///< folder where the command will be executed from MappingParam tr_table; Param param; }; /** Used for internal and external tools */ struct OPENMS_DLLAPI ToolDescription : ToolDescriptionInternal { /// additional details for external tools (one entry for each 'type') std::vector<ToolExternalDetails> external_details; /// default CTor ToolDescription() = default; /// Copy C'Tor ToolDescription(const ToolDescription& other) = default; /// C'Tor for internal TOPP tools ToolDescription(const String& p_name, const String& p_category, const StringList& p_types = StringList()); /// Copy assignment ToolDescription& operator=(const ToolDescription& rhs) = default; void addExternalType(const String& type, const ToolExternalDetails& details); void append(const ToolDescription& other); }; } // namespace Internal } // namespace OPENMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/DATASTRUCTURES/DIntervalBase.h
.h
9,730
386
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Clemens Groepl, Marc Sturm $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/DATASTRUCTURES/DPosition.h> #include <OpenMS/CONCEPT/Types.h> #include <utility> namespace OpenMS { namespace Internal { /** @brief A base class for D-dimensional interval. See DIntervalBase for a closed interval and DRange for a half-open interval class. @invariant All methods maintain the invariant that minPosition() is geometrically less or equal maxPosition() i.e. minPosition()[x] <= maxPosition()[x]. */ template <UInt D> class DIntervalBase { public: /** @name Type definitions */ //@{ /// Dimensions enum {DIMENSION = D}; /// Position type typedef DPosition<D> PositionType; /// Coordinate type of the positions typedef typename PositionType::CoordinateType CoordinateType; //@} /**@name Constructors and Destructor */ //@{ /** @brief Default constructor. Creates an empty interval with corners at infinity. */ DIntervalBase() : min_(PositionType::maxPositive()), max_(PositionType::minNegative()) { } /// Copy constructor DIntervalBase(const DIntervalBase& rhs) : min_(rhs.min_), max_(rhs.max_) { } /// Move constructor DIntervalBase(DIntervalBase&&) noexcept = default; /// Assignment operator DIntervalBase& operator=(const DIntervalBase& rhs) { min_ = rhs.min_; max_ = rhs.max_; return *this; } /// Destructor ~DIntervalBase() { } /** @brief This constructor sets min_ and max_ directly. */ DIntervalBase(PositionType const& minimum, PositionType const& maximum) : min_(minimum), max_(maximum) { normalize_(); } //@} /**@name Accessors */ //@{ /// Accessor to minimum position inline PositionType const& minPosition() const { return min_; } /// Accessor to maximum position inline PositionType const& maxPosition() const { return max_; } /** @brief Mutator for minimum position @note The minimum position given here will be returned my minPosition() after the method. If necessary the value returned by maxPosition() will be adjusted. */ void setMin(PositionType const& position) { min_ = position; for (UInt i = 0; i < DIMENSION; ++i) { if (min_[i] > max_[i]) max_[i] = min_[i]; } } /** @brief Mutator for maximum position @note The maximum position given here will be returned my maxPosition() after the method. If necessary the value returned by minPosition() will be adjusted. */ void setMax(PositionType const& position) { max_ = position; for (UInt i = 0; i < DIMENSION; ++i) { if (min_[i] > max_[i]) min_[i] = max_[i]; } } /** @brief Mutator for minimum and maximum position */ void setMinMax(PositionType const& min, PositionType const& max) { min_ = min; max_ = max; normalize_(); } /** @brief Assignment from a DIntervalBase of different dimensions. Only the dimensions 0 up to min(D,D2)-1 are copied. */ template <UInt D2> void assign(const DIntervalBase<D2> rhs) { for (UInt i = 0; i < std::min(D, D2); ++i) { min_[i] = rhs.minPosition()[i]; max_[i] = rhs.maxPosition()[i]; } } //}@ /**@name Predicates */ //@{ /// Equality operator bool operator==(const DIntervalBase& rhs) const { return (min_ == rhs.min_) && (max_ == rhs.max_); } /// Equality operator bool operator!=(const DIntervalBase& rhs) const { return !(operator==(rhs)); } DIntervalBase operator+(const PositionType& point) const { DIntervalBase result(*this); result += point; return result; } DIntervalBase& operator+=(const PositionType& point) { this->min_ += point; this->max_ += point; return *this; } DIntervalBase operator-(const PositionType& point) const { DIntervalBase result(*this); result -= point; return result; } DIntervalBase& operator-=(const PositionType& point) { this->min_ -= point; this->max_ -= point; return *this; } /// Make the interval empty inline void clear() { *this = empty; } /// Is the interval completely empty? i.e. clear()'d or default constructed /// If min==max, the interval is NOT empty! bool isEmpty() const { return *this == empty; } /// Is the dimension @p dim empty? If min==max, the interval is NOT empty! bool isEmpty(UInt dim) const { return DIntervalBase<1>(std::make_pair(min_[dim], max_[dim])) == DIntervalBase<1>::empty; } /// only set interval for a single dimension void setDimMinMax(UInt dim, const DIntervalBase<1>& min_max) { min_[dim] = min_max.min_[0]; max_[dim] = min_max.max_[0]; } // make all other templates friends to allow accessing min_ and max_ in setDimMinMax template<UInt> friend class DIntervalBase; //@} /**@name Misc */ //@{ ///Returns the center of the interval PositionType center() const { PositionType center(min_); center += max_; center /= 2; return center; } /// Returns the diagonal of the area, i.e. max_ - min_. PositionType diagonal() const { return max_ - min_; } /// empty instance static DIntervalBase const empty; /// instance with all positions zero static DIntervalBase const zero; //}@ /**@name Accessors for 2D-intervals (for convenience) */ //@{ /// Accessor for min_ coordinate minimum inline CoordinateType minX() const { return min_[0]; } /// Accessor for max_ coordinate minimum inline CoordinateType minY() const { return min_[1]; } /// Accessor for min_ coordinate maximum inline CoordinateType maxX() const { return max_[0]; } /// Accessor for max_ coordinate maximum inline CoordinateType maxY() const { return max_[1]; } /// Mutator for min_ coordinate of the smaller point void setMinX(CoordinateType const c) { min_[0] = c; if (min_[0] > max_[0]) max_[0] = min_[0]; } /// Mutator for max_ coordinate of the smaller point void setMinY(CoordinateType const c) { min_[1] = c; if (min_[1] > max_[1]) max_[1] = min_[1]; } /// Mutator for min_ coordinate of the larger point. void setMaxX(CoordinateType const c) { max_[0] = c; if (min_[0] > max_[0]) min_[0] = max_[0]; } /// Mutator for max_ coordinate of the larger point. void setMaxY(CoordinateType const c) { max_[1] = c; if (min_[1] > max_[1]) min_[1] = max_[1]; } /// Returns the width of the area i.e. the difference of dimension zero (X). inline CoordinateType width() const { return max_[0] - min_[0]; } /// Returns the height of the area i.e. the difference of dimension one (Y). inline CoordinateType height() const { return max_[1] - min_[1]; } //@} protected: /// lower left point PositionType min_; /// upper right point PositionType max_; /// normalization to keep all dimensions in the right geometrical order (min_[X] < max_[X]) void normalize_() { for (UInt i = 0; i < DIMENSION; ++i) { if (min_[i] > max_[i]) { std::swap(min_[i], max_[i]); } } } ///Protected constructor for the construction of static instances DIntervalBase(const std::pair<PositionType, PositionType>& pair) : min_(pair.first), max_(pair.second) { } }; template <UInt D> DIntervalBase<D> const DIntervalBase<D>::zero = DIntervalBase<D>(DIntervalBase<D>::PositionType::zero(), DIntervalBase<D>::PositionType::zero()); template <UInt D> DIntervalBase<D> const DIntervalBase<D>::empty = DIntervalBase<D>(std::make_pair(DIntervalBase<D>::PositionType::maxPositive(), DIntervalBase<D>::PositionType::minNegative())); ///Print the contents to a stream. template <UInt D> std::ostream& operator<<(std::ostream& os, const DIntervalBase<D>& rhs) { os << "--DIntervalBase BEGIN--" << std::endl; os << "MIN --> " << rhs.minPosition() << std::endl; os << "MAX --> " << rhs.maxPosition() << std::endl; os << "--DIntervalBase END--" << std::endl; return os; } } // namespace Internal } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/DATASTRUCTURES/DataValue.h
.h
16,338
483
// 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/DATASTRUCTURES/ListUtils.h> #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/CONCEPT/HashUtils.h> #include <OpenMS/OpenMSConfig.h> class QString; namespace OpenMS { class ParamValue; /** @brief Class to hold strings, numeric values, lists of strings and lists of numeric values. - To choose one of these types, just use the appropriate constructor. - Automatic conversion is supported and throws Exceptions in case of invalid conversions. - An empty object is created with the default constructor. @ingroup Datastructures */ class OPENMS_DLLAPI DataValue { public: /// Empty data value for comparisons static const DataValue EMPTY; /// Supported types for DataValue enum DataType : unsigned char { STRING_VALUE, ///< string value INT_VALUE, ///< integer value DOUBLE_VALUE, ///< double value STRING_LIST, ///< string list INT_LIST, ///< integer list DOUBLE_LIST, ///< double list EMPTY_VALUE, ///< empty SIZE_OF_DATATYPE }; /// Names of data types for DataValue static const std::string NamesOfDataType[SIZE_OF_DATATYPE]; /// Supported types for DataValue enum UnitType : unsigned char { UNIT_ONTOLOGY, ///< unit.ontology UO MS_ONTOLOGY, ///< ms.ontology MS OTHER ///< undefined ontology }; /// @name Constructors and destructors //@{ /// Default constructor DataValue(); /// Copy constructor DataValue(const DataValue&); /// Move constructor DataValue(DataValue&&) noexcept; /// specific constructor for char* (converted to string) DataValue(const char*); /// specific constructor for std::string values DataValue(const std::string&); /// specific constructor for string values DataValue(const String&); /// specific constructor for QString values DataValue(const QString&); /// specific constructor for string lists DataValue(const StringList&); /// specific constructor for integer lists DataValue(const IntList&); /// specific constructor for double lists DataValue(const DoubleList&); /// specific constructor for long double values (note: the implementation uses double) DataValue(long double); /// specific constructor for double values (note: the implementation uses double) DataValue(double); /// specific constructor for float values (note: the implementation uses double) DataValue(float); /// specific constructor for short int values (note: the implementation uses SignedSize) DataValue(short int); /// specific constructor for unsigned short int values (note: the implementation uses SignedSize) DataValue(unsigned short int); /// specific constructor for int values (note: the implementation uses SignedSize) DataValue(int); /// specific constructor for unsigned int values (note: the implementation uses SignedSize) DataValue(unsigned); /// specific constructor for long int values (note: the implementation uses SignedSize) DataValue(long int); /// specific constructor for unsigned long int values (note: the implementation uses SignedSize) DataValue(unsigned long); /// specific constructor for long long int values (note: the implementation uses SignedSize) DataValue(long long); /// specific constructor for unsigned long long int values (note: the implementation uses SignedSize) DataValue(unsigned long long); /// specific constructor for ParamValue DataValue(const ParamValue&); /// Destructor ~DataValue(); //@} ///@name Cast operators ///These methods are used when the DataType is known. ///If they are applied to a DataValue with the wrong DataType, an exception (Exception::ConversionError) is thrown. In particular, none of these operators will work for an empty DataValue (DataType EMPTY_VALUE) - except toChar(), which will return 0. //@{ /** @brief conversion operator to ParamValue based on DataType */ operator ParamValue() const; /** @brief conversion operator to string @exception Exception::ConversionError is thrown if a cast from the the wrong type is requested */ operator std::string() const; /** @brief conversion operator to string list @exception Exception::ConversionError is thrown if a cast from the the wrong type is requested */ operator StringList() const; /** @brief conversion operator to integer list @exception Exception::ConversionError is thrown if a cast from the the wrong type is requested */ operator IntList() const; /** @brief conversion operator to double list @exception Exception::ConversionError is thrown if a cast from the the wrong type is requested */ operator DoubleList() const; /** @brief conversion operator to long double Note: The implementation uses typedef double (as opposed to float, double, long double.) @exception Exception::ConversionError is thrown if a cast from the the wrong type is requested */ operator long double() const; /** @brief conversion operator to double Note: The implementation uses typedef double (as opposed to float, double, long double.) @exception Exception::ConversionError is thrown if a cast from the the wrong type is requested */ operator double() const; /** @brief conversion operator to float Note: The implementation uses typedef double (as opposed to float, double, long double.) @exception Exception::ConversionError is thrown if a cast from the the wrong type is requested */ operator float() const; /** @brief conversion operator to short int Note: The implementation uses typedef SignedSize. @exception Exception::ConversionError is thrown if a cast from the the wrong type is requested */ operator short int() const; /** @brief conversion operator to unsigned short int Note: The implementation uses typedef SignedSize. @exception Exception::ConversionError is thrown if a cast from the the wrong type is requested */ operator unsigned short int() const; /** @brief conversion operator to int Note: The implementation uses typedef SignedSize. @exception Exception::ConversionError is thrown if a cast from the the wrong type is requested */ operator int() const; /** @brief conversion operator to unsigned int Note: The implementation uses typedef SignedSize. @exception Exception::ConversionError is thrown if a cast from the the wrong type is requested */ operator unsigned int() const; /** @brief conversion operator to long int Note: The implementation uses typedef SignedSize. @exception Exception::ConversionError is thrown if a cast from the the wrong type is requested */ operator long int() const; /** @brief conversion operator to unsigned long int Note: The implementation uses typedef SignedSize. @exception Exception::ConversionError is thrown if a cast from the the wrong type is requested */ operator unsigned long int() const; /** @brief conversion operator to long long Note: The implementation uses typedef SignedSize. @exception Exception::ConversionError is thrown if a cast from the the wrong type is requested */ operator long long() const; /** @brief conversion operator to unsigned long long Note: The implementation uses typedef SignedSize. @exception Exception::ConversionError is thrown if a cast from the the wrong type is requested */ operator unsigned long long() const; /** @brief Conversion to bool Converts the strings 'true' and 'false' to a bool. @exception Exception::ConversionError is thrown for non-string parameters and string parameters with values other than 'true' and 'false'. */ bool toBool() const; /** @brief Convert DataValues to char* If the DataValue contains a string, a pointer to it's char* is returned. If the DataValue is empty, NULL is returned. */ const char* toChar() const; /** @brief Explicitly convert DataValue to StringList @exception Exception::ConversionError is thrown if a cast from the the wrong type is requested */ StringList toStringList() const; /** @brief Explicitly convert DataValue to IntList @exception Exception::ConversionError is thrown if a cast from the the wrong type is requested */ IntList toIntList() const; /** @brief Explicitly convert DataValue to DoubleList @exception Exception::ConversionError is thrown if a cast from the the wrong type is requested */ DoubleList toDoubleList() const; //@} ///@name Assignment operators ///These methods are used to assign supported types directly to a DataValue object. //@{ /// Assignment operator DataValue& operator=(const DataValue&); /// Move assignment operator DataValue& operator=(DataValue&&) noexcept; /// specific assignment for char* (converted to string) DataValue& operator=(const char*); /// specific assignment for std::string values DataValue& operator=(const std::string&); /// specific assignment for string values DataValue& operator=(const String&); /// specific assignment for QString values DataValue& operator=(const QString&); /// specific assignment for string lists DataValue& operator=(const StringList&); /// specific assignment for integer lists DataValue& operator=(const IntList&); /// specific assignment for double lists DataValue& operator=(const DoubleList&); /// specific assignment for long double values (note: the implementation uses double) DataValue& operator=(const long double); /// specific assignment for double values (note: the implementation uses double) DataValue& operator=(const double); /// specific assignment for float values (note: the implementation uses double) DataValue& operator=(const float); /// specific assignment for short int values (note: the implementation uses SignedSize) DataValue& operator=(const short int); /// specific assignment for unsigned short int values (note: the implementation uses SignedSize) DataValue& operator=(const unsigned short int); /// specific assignment for int values (note: the implementation uses SignedSize) DataValue& operator=(const int); /// specific assignment for unsigned int values (note: the implementation uses SignedSize) DataValue& operator=(const unsigned); /// specific assignment for long int values (note: the implementation uses SignedSize) DataValue& operator=(const long int); /// specific assignment for unsigned long int values (note: the implementation uses SignedSize) DataValue& operator=(const unsigned long); /// specific assignment for long long int values (note: the implementation uses SignedSize) DataValue& operator=(const long long); /// specific assignment for unsigned long long int values (note: the implementation uses SignedSize) DataValue& operator=(const unsigned long long); //@} ///@name Conversion operators ///These methods can be used independent of the DataType. If you already know the DataType, you should use a cast operator! /// <BR>For conversion of string DataValues to numeric types, first use toString() and then the conversion methods of String. //@{ /** @brief Conversion to String @p full_precision Controls number of fractional digits for all double types or lists of double, 3 digits when false, and 15 when true. **/ String toString(bool full_precision = true) const; ///Conversion to QString QString toQString() const; //@} /// returns the type of value stored DataType valueType() const; /** @brief Test if the value is empty @note A DataValue containing an empty string ("") does not count as empty! */ bool isEmpty() const; ///@name Methods to handle units ///These methods are used when the DataValue has an associated unit. //@{ /// returns the type of value stored UnitType getUnitType() const; void setUnitType(const UnitType & u); /// Check if the value has a unit bool hasUnit() const; /// Return the unit associated to this DataValue. const int32_t & getUnit() const; /// Sets the unit to the given String. void setUnit(const int32_t & unit); //@} /// output stream operator friend OPENMS_DLLAPI std::ostream& operator<<(std::ostream&, const DataValue&); /// Equality comparator friend OPENMS_DLLAPI bool operator==(const DataValue&, const DataValue&); /// Smaller than comparator (for lists we use the size) friend OPENMS_DLLAPI bool operator<(const DataValue&, const DataValue&); /// Greater than comparator (for lists we use the size) friend OPENMS_DLLAPI bool operator>(const DataValue&, const DataValue&); /// Equality comparator friend OPENMS_DLLAPI bool operator!=(const DataValue&, const DataValue&); protected: /// Type of the currently stored value DataType value_type_; /// Type of the currently stored unit UnitType unit_type_; /// The unit of the data value (if it has one) using UO identifier, otherwise -1. int32_t unit_; /// Space to store the data union { SignedSize ssize_; double dou_; String* str_; StringList* str_list_; IntList* int_list_; DoubleList* dou_list_; } data_; private: /// Clears the current state of the DataValue and release every used memory. void clear_() noexcept; }; } // namespace OpenMS // Hash function specialization for DataValue namespace std { /** * @brief Hash function for DataValue. * * Hashes based on the value type, value content, and unit information. * This ensures consistency with operator== which compares all these fields. * * @note For DOUBLE_VALUE, operator== uses epsilon comparison (fabs < 1e-6), * so we round to 6 decimal places before hashing to maintain consistency. * For DOUBLE_LIST, we use toString() since list comparison is exact. */ template<> struct hash<OpenMS::DataValue> { std::size_t operator()(const OpenMS::DataValue& dv) const noexcept { std::size_t seed = 0; // Hash the value type OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(dv.valueType()))); // Hash the value content based on type if (!dv.isEmpty()) { switch (dv.valueType()) { case OpenMS::DataValue::DOUBLE_VALUE: { // operator== uses fabs(a - b) < 1e-6 for doubles, so we round to 6 decimal places // to ensure equal values (per operator==) produce identical hashes double val = static_cast<double>(dv); // Round to 6 decimal places: multiply by 1e6, round, then hash as int64 int64_t rounded = static_cast<int64_t>(std::round(val * 1e6)); OpenMS::hash_combine(seed, OpenMS::hash_int(rounded)); break; } default: // For all other types (string, int, lists), use toString() which is consistent with operator== OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(dv.toString())); break; } } // Hash unit information if present if (dv.hasUnit()) { OpenMS::hash_combine(seed, OpenMS::hash_int(static_cast<int>(dv.getUnitType()))); OpenMS::hash_combine(seed, OpenMS::hash_int(dv.getUnit())); } return seed; } }; } // namespace std
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/DATASTRUCTURES/Date.h
.h
2,221
93
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg$ // $Authors: Marc Sturm $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/DATASTRUCTURES/String.h> #include <OpenMS/OpenMSConfig.h> #include <QtCore/QDate> namespace OpenMS { /** @brief Date Class. This class implements date handling. Import and export to/from both string and integers is possible. @ingroup Datastructures */ class OPENMS_DLLAPI Date : public QDate { public: /** @brief Default constructor Fills the object with an undefined date: 00/00/0000 */ Date() = default; /// Copy constructor Date(const Date& date) = default; /// Copy constructor from Qt base class Date(const QDate& date); /// Move constructor Date(Date&&) = default; /// Assignment operator Date& operator=(const Date& source) = default; /// Move assignment operator Date& operator=(Date&&) & = default; /** @brief sets data from a string The following date formats are supported: - mm/dd/yyyy - dd.mm.yyyy - yyyy-mm-dd @exception Exception::ParseError is thrown if the date is given in the wrong format */ void set(const String& date); /** @brief sets data from three integers @exception Exception::ParseError is thrown if an invalid date is given */ void set(UInt month, UInt day, UInt year); /// Returns the current date static Date today(); /** @brief Returns a string representation of the date Uses the iso/ansi date format: 'yyyy-mm-dd' */ String get() const; /** @brief Fills the arguments with the date Give the numbers in the following order: month, day and year. */ void get(UInt& month, UInt& day, UInt& year) const; ///Sets the undefined date: 00/00/0000 void clear(); protected: }; } // namespace OPENMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/DATASTRUCTURES/FASTAContainer.h
.h
18,063
516
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow $ // $Authors: Chris Bielow $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/CONCEPT/Exception.h> #include <OpenMS/CONCEPT/LogStream.h> #include <OpenMS/DATASTRUCTURES/String.h> #include <OpenMS/DATASTRUCTURES/ListUtils.h> #include <OpenMS/DATASTRUCTURES/StringUtilsSimple.h> #include <OpenMS/FORMAT/FASTAFile.h> #include <functional> #include <fstream> #include <unordered_map> #include <memory> #include <utility> #include <vector> #include <boost/regex.hpp> namespace OpenMS { struct TFI_File; ///< template parameter for file-based FASTA access struct TFI_Vector; ///< template parameter for vector-based FASTA access /** @brief This class allows for a chunk-wise single linear read over a (large) FASTA file, with spurious (since potentially slow) access to earlier entries which are currently not in the active chunk. Internally uses FASTAFile class to read single sequences. FASTAContainer supports two template specializations FASTAContainer<TFI_File> and FASTAContainer<TFI_Vector>. FASTAContainer<TFI_File> will make FASTA entries available chunk-wise from start to end by loading it from a FASTA file. This avoids having to load the full file into memory. While loading, the container will memorize the file offsets of each entry, allowing to read an arbitrary i'th entry again from disk. If possible, only entries from the currently cached chunk should be queried, otherwise access will be slow. FASTAContainer<TFI_Vector> simply takes an existing vector of FASTAEntries and provides the same interface (with a potentially huge speed benefit over FASTAContainer<TFI_File> since it does not need disk access, but at the cost of memory). If an algorithm searches through a FASTA file linearly, you can use FASTAContainer<TFI_File> to pre-load a small chunk and start working, while loading the next chunk in a background thread and swap it in when the active chunk was processed. */ template<typename TBackend> class FASTAContainer; // prototype /** @brief FASTAContainer<TFI_File> will make FASTA entries available chunk-wise from start to end by loading it from a FASTA file. This avoids having to load the full file into memory. While loading, the container will memorize the file offsets of each entry, allowing to read an arbitrary i'th entry again from disk. If possible, only entries from the currently cached chunk should be queried, otherwise access will be slow. Internally uses FASTAFile class to read single sequences. */ template<> class FASTAContainer<TFI_File> { public: FASTAContainer() = delete; /// C'tor with FASTA filename FASTAContainer(const String& FASTA_file) : f_(), offsets_(), data_fg_(), data_bg_(), chunk_offset_(0), filename_(FASTA_file) { f_.readStart(FASTA_file); } /// how many entries were read and got swapped out already size_t getChunkOffset() const { return chunk_offset_; } /** @brief Swaps in the background cache of entries, read previously via @p cacheChunk() If you call this function without a prior call to @p cacheChunk(), the cache will be empty. @return true if cache contains data; false if empty @note Should be invoked by a single thread, followed by a barrier to sync access of subsequent calls to chunkAt() */ bool activateCache() { chunk_offset_ += data_fg_.size(); data_fg_.swap(data_bg_); data_bg_.clear(); // just in case someone calls activateCache() multiple times... return !data_fg_.empty(); } /** @brief Prefetch a new cache in the background, with up to @p suggested_size entries (or fewer upon reaching end-of-file) Call @p activateCache() afterwards to make the data available via @p chunkAt() or @p readAt(). @param[in] suggested_size Number of FASTA entries to read from disk @return true if new data is available; false if background data is empty */ bool cacheChunk(int suggested_size) { data_bg_.clear(); data_bg_.reserve(suggested_size); FASTAFile::FASTAEntry p; for (int i = 0; i < suggested_size; ++i) { std::streampos spos = f_.position(); if (!f_.readNext(p)) break; data_bg_.push_back(std::move(p)); offsets_.push_back(spos); } return !data_bg_.empty(); } /// number of entries in active cache size_t chunkSize() const { return data_fg_.size(); } /** @brief Retrieve a FASTA entry at cache position @p pos (fast) Requires prior call to activateCache(). Index @p pos must be smaller than chunkSize(). @note: can be used by multiple threads at a time (until activateCache() is called) */ const FASTAFile::FASTAEntry& chunkAt(size_t pos) const { return data_fg_[pos]; } /** @brief Retrieve a FASTA entry at global position @p pos (must not be behind the currently active chunk, but can be smaller) This query is fast, if @p pos contains the currently active chunk, and slow (read from disk) for earlier entries. Can be used before reaching the end of the file, since it will reset the file position after its done reading (if reading from disk is required), but must not be used for entries beyond the active chunk (unseen data). @param[out] protein Return value @param[in] pos Absolute entry number in FASTA file @return true if reading was successful; false otherwise (e.g. EOF) @throw Exception::IndexOverflow if @p pos is beyond active chunk @note: not multi-threading safe (use chunkAt())! */ bool readAt(FASTAFile::FASTAEntry& protein, size_t pos) { // check if position is currently cached... if (chunk_offset_ <= pos && pos < chunk_offset_ + chunkSize()) { protein = data_fg_[pos - chunk_offset_]; return true; } // read anew from disk... if (pos >= offsets_.size()) { throw Exception::IndexOverflow(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, pos, offsets_.size()); } std::streampos spos = f_.position(); // save old position if (!f_.setPosition(offsets_[pos])) return false; bool r = f_.readNext(protein); f_.setPosition(spos); // restore old position return r; } /// is the FASTA file empty? bool empty() { // trusting the FASTA file can be read... return f_.atEnd() && offsets_.empty(); } /// resets reading of the FASTA file, enables fresh reading of the FASTA from the beginning void reset() { offsets_.clear(); data_fg_.clear(); data_bg_.clear(); chunk_offset_ = 0; f_.readStart(filename_); } /** @brief NOT the number of entries in the FASTA file, but merely the number of already read entries (since we do not know how many are still to come) @note Data in the background cache is included here, i.e. access to size()-1 using readAt() might be slow if activateCache() was not called yet. */ size_t size() const { return offsets_.size(); } private: FASTAFile f_; ///< FASTA file connection std::vector<std::streampos> offsets_; ///< internal byte offsets into FASTA file for random access reading of previous entries. std::vector<FASTAFile::FASTAEntry> data_fg_; ///< active (foreground) data std::vector<FASTAFile::FASTAEntry> data_bg_; ///< prefetched (background) data; will become the next active data size_t chunk_offset_; ///< number of entries before the current chunk std::string filename_;///< FASTA file name }; /** @brief FASTAContainer<TFI_Vector> simply takes an existing vector of FASTAEntries and provides the same interface with a potentially huge speed benefit over FASTAContainer<TFI_File> since it does not need disk access, but at the cost of memory. */ template<> class FASTAContainer<TFI_Vector> { public: FASTAContainer() = delete; /** @brief C'tor for already existing data (by reference). An internal reference will be kept. Make sure the data is not deleted during the lifetime of FASTAContainer */ FASTAContainer(const std::vector<FASTAFile::FASTAEntry>& data) : data_(data) { } /// always 0, since this specialization requires/supports no chunking size_t getChunkOffset() const { return 0; } /** @brief no-op (since data is already fully available as vector) @return true only on the first call; false on subsequent calls */ bool activateCache() { if (!activate_count_) { activate_count_ = 1; return true; } return false; } /** @brief no-op (since data is already fully available as vector) @return true only on the first call; false on subsequent calls */ bool cacheChunk(int /*suggested_size*/) { if (!cache_count_) { cache_count_ = 1; return true; } return false; } /** @brief active data spans the full range, i.e. size of container @return the size of the underlying vector */ size_t chunkSize() const { return data_.size(); } /// fast access to chunked (i.e. all) entries const FASTAFile::FASTAEntry& chunkAt(size_t pos) const { return data_[pos]; } /// fast access to an entry bool readAt(FASTAFile::FASTAEntry& protein, size_t pos) const { protein = data_[pos]; return true; } /// calls empty() on underlying vector bool empty() const { return data_.empty(); } /// calls size() on underlying vector size_t size() const { return data_.size(); } /// required for template parameters! void reset() { activate_count_ = 0; cache_count_ = 0; } private: const std::vector<FASTAFile::FASTAEntry>& data_; ///< reference to existing data int activate_count_ = 0; int cache_count_ = 0; }; /** @brief Helper class for calculations on decoy proteins */ class DecoyHelper { public: struct Result { bool success; ///< did more than 40% of proteins have the *same* prefix or suffix String name; ///< on success, what was the decoy string? bool is_prefix; ///< on success, was it a prefix or suffix bool operator==(const Result& rhs) const { return success == rhs.success && name == rhs.name && is_prefix == rhs.is_prefix; } }; /** @brief struct for intermediate results needed for calculations on decoy proteins */ struct DecoyStatistics { std::unordered_map<std::string, std::pair<Size, Size>> decoy_count; ///< map decoys to counts of occurrences as prefix/suffix std::unordered_map<std::string, std::string> decoy_case_sensitive; ///< map case insensitive strings back to original case (as used in fasta) Size all_prefix_occur{0}; ///< number of proteins with found decoy_prefix Size all_suffix_occur{0}; ///< number of proteins with found decoy_suffix Size all_proteins_count{0}; ///< number of all checked proteins bool operator==(const DecoyStatistics& rhs) const { return decoy_count == rhs.decoy_count && decoy_case_sensitive == rhs.decoy_case_sensitive && all_prefix_occur == rhs.all_prefix_occur && all_suffix_occur == rhs.all_suffix_occur && all_proteins_count == rhs.all_proteins_count; } }; // decoy strings inline static const std::vector<std::string> affixes = { "decoy", "dec", "reverse", "rev", "reversed", "__id_decoy", "xxx", "shuffled", "shuffle", "pseudo", "random" }; // setup prefix- and suffix regex strings inline static const std::string regexstr_prefix = std::string("^(") + ListUtils::concatenate<std::string>(affixes, "_*|") + "_*)"; inline static const std::string regexstr_suffix = std::string("(_") + ListUtils::concatenate<std::string>(affixes, "*|_") + ")$"; /** @brief Heuristic to determine the decoy string given a set of protein names For tested decoy strings see DecoyHelper::affixes. Both prefix and suffix is tested and if one of the candidates above is found in at least 40% of all proteins, it is returned as the winner (see DecoyHelper::Result). */ template<typename T> static Result findDecoyString(FASTAContainer<T>& proteins) { // calls function to search for decoys in input data DecoyStatistics decoy_stats = countDecoys(proteins); // DEBUG ONLY: print counts of found decoys for (const auto &a : decoy_stats.decoy_count) { OPENMS_LOG_DEBUG << a.first << "\t" << a.second.first << "\t" << a.second.second << std::endl; } // less than 40% of proteins are decoys -> won't be able to determine a decoy string and its position // return default values if (static_cast<double>(decoy_stats.all_prefix_occur + decoy_stats.all_suffix_occur) < 0.4 * static_cast<double>(decoy_stats.all_proteins_count)) { OPENMS_LOG_ERROR << "Unable to determine decoy string (not enough occurrences; <40%)!" << std::endl; return {false, "?", true}; } if (decoy_stats.all_prefix_occur == decoy_stats.all_suffix_occur) { OPENMS_LOG_ERROR << "Unable to determine decoy string (prefix and suffix occur equally often)!" << std::endl; return {false, "?", true}; } // Decoy prefix occurred at least 80% of all prefixes + observed in at least 40% of all proteins -> set it as prefix decoy for (const auto& pair : decoy_stats.decoy_count) { const std::string & case_insensitive_decoy_string = pair.first; const std::pair<Size, Size>& prefix_suffix_counts = pair.second; double freq_prefix = static_cast<double>(prefix_suffix_counts.first) / static_cast<double>(decoy_stats.all_prefix_occur); double freq_prefix_in_proteins = static_cast<double>(prefix_suffix_counts.first) / static_cast<double>(decoy_stats.all_proteins_count); if (freq_prefix >= 0.8 && freq_prefix_in_proteins >= 0.4) { if (prefix_suffix_counts.first != decoy_stats.all_prefix_occur) { OPENMS_LOG_WARN << "More than one decoy prefix observed!" << std::endl; OPENMS_LOG_WARN << "Using most frequent decoy prefix (" << (int)(freq_prefix * 100) << "%)" << std::endl; } return { true, decoy_stats.decoy_case_sensitive[case_insensitive_decoy_string], true}; } } // Decoy suffix occurred at least 80% of all suffixes + observed in at least 40% of all proteins -> set it as suffix decoy for (const auto& pair : decoy_stats.decoy_count) { const std::string& case_insensitive_decoy_string = pair.first; const std::pair<Size, Size>& prefix_suffix_counts = pair.second; double freq_suffix = static_cast<double>(prefix_suffix_counts.second) / static_cast<double>(decoy_stats.all_suffix_occur); double freq_suffix_in_proteins = static_cast<double>(prefix_suffix_counts.second) / static_cast<double>(decoy_stats.all_proteins_count); if (freq_suffix >= 0.8 && freq_suffix_in_proteins >= 0.4) { if (prefix_suffix_counts.second != decoy_stats.all_suffix_occur) { OPENMS_LOG_WARN << "More than one decoy suffix observed!" << std::endl; OPENMS_LOG_WARN << "Using most frequent decoy suffix (" << (int)(freq_suffix * 100) << "%)" << std::endl; } return { true, decoy_stats.decoy_case_sensitive[case_insensitive_decoy_string], false}; } } OPENMS_LOG_ERROR << "Unable to determine decoy string and its position. Please provide a decoy string and its position as parameters." << std::endl; return {false, "?", true}; } /** @brief Function to count the occurrences of decoy strings in a given set of protein names For tested decoy strings see DecoyHelper::affixes. Returns all data needed for interpretation (see DecoyHelper::DecoyStatistics). */ template<typename T> static DecoyStatistics countDecoys(FASTAContainer<T>& proteins) { // common decoy strings in FASTA files // note: decoy prefixes/suffices must be provided in lower case DecoyStatistics ds; // setup regexes const boost::regex pattern_prefix(regexstr_prefix); const boost::regex pattern_suffix(regexstr_suffix); constexpr size_t PROTEIN_CACHE_SIZE = 4e5; while (true) { proteins.cacheChunk(PROTEIN_CACHE_SIZE); if (!proteins.activateCache()) break; auto prot_count = (SignedSize)proteins.chunkSize(); ds.all_proteins_count += prot_count; boost::smatch sm; for (SignedSize i = 0; i < prot_count; ++i) { String seq = proteins.chunkAt(i).identifier; String seq_lower = seq; seq_lower.toLower(); // search for prefix bool found_prefix = boost::regex_search(seq_lower, sm, pattern_prefix); if (found_prefix) { std::string match = sm[0]; ds.all_prefix_occur++; // increase count of observed prefix ds.decoy_count[match].first++; // store observed (case sensitive and with special characters) std::string seq_decoy = StringUtils::prefix(seq, match.length()); ds.decoy_case_sensitive[match] = seq_decoy; } // search for suffix bool found_suffix = boost::regex_search(seq_lower, sm, pattern_suffix); if (found_suffix) { std::string match = sm[0]; ds.all_suffix_occur++; // increase count of observed suffix ds.decoy_count[match].second++; // store observed (case sensitive and with special characters) std::string seq_decoy = StringUtils::suffix(seq, match.length()); ds.decoy_case_sensitive[match] = seq_decoy; } } } return ds; } private: using DecoyStringToAffixCount = std::unordered_map<std::string, std::pair<Size, Size>>; using CaseInsensitiveToCaseSensitiveDecoy = std::unordered_map<std::string, std::string>; }; } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/DATASTRUCTURES/Param.h
.h
25,000
665
// 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/ParamValue.h> #include <OpenMS/OpenMSConfig.h> #include <cstddef> #include <iterator> #include <set> #include <string> #include <map> namespace OpenMS { namespace Logger { class LogStream; } /** @brief Management and storage of parameters / INI files. This class provides a means to associate string names to int/double/string/StringList values. It allows for parameter hierarchies and to save/load the data as XML. Hierarchy levels are separated from each other by colons. @n Example: 'common:file_options:default_file_open_path = /share/' Each parameter and section has a description. Newline characters in the description are possible. Each parameter can be annotated with an arbitrary number of tags. Tags must not contain comma characters! @n E.g. the <i>advanced</i> tag indicates if this parameter is shown to all users or in advanced mode only. @see DefaultParamHandler @ingroup Datastructures */ class OPENMS_DLLAPI Param { public: /// Parameter entry used to store the actual information inside of a Param entry struct OPENMS_DLLAPI ParamEntry { /// Default constructor ParamEntry(); /// Constructor with name, description, value and advanced flag ParamEntry(const std::string& n, const ParamValue& v, const std::string& d, const std::vector<std::string>& t = std::vector<std::string>()); /// Copy constructor ParamEntry(const ParamEntry&) = default; /// Move constructor ParamEntry(ParamEntry&&) = default; /// Destructor ~ParamEntry(); /// Assignment operator ParamEntry& operator=(const ParamEntry&) = default; /// Move assignment operator ParamEntry& operator=(ParamEntry&&) & = default; /// Check if 'value' fulfills restrictions bool isValid(std::string& message) const; /// Equality operator (only name and value are compared) bool operator==(const ParamEntry& rhs) const; /// Name of the entry std::string name; /// Description of the entry std::string description; /// Value associated with the entry ParamValue value; /// Tags list, used e.g. for advanced parameter tag std::set<std::string> tags; ///@name Restrictions to accepted values (used in checkDefaults) //@{ double min_float; ///< Default: - std::numeric_limits<double>::max() double max_float; ///< Default: std::numeric_limits<double>::max() int min_int; ///< Default: - std::numeric_limits<Int>::max() int max_int; ///< Default: std::numeric_limits<Int>::max() std::vector<std::string> valid_strings; ///< Default: empty //@} }; ///Node inside a Param object which is used to build the internal tree struct OPENMS_DLLAPI ParamNode { ///Iterator for child nodes typedef std::vector<ParamNode>::iterator NodeIterator; ///Iterator for entries typedef std::vector<ParamEntry>::iterator EntryIterator; ///Iterator for child nodes typedef std::vector<ParamNode>::const_iterator ConstNodeIterator; ///Iterator for entries typedef std::vector<ParamEntry>::const_iterator ConstEntryIterator; /// Default constructor ParamNode(); /// Constructor with name and description ParamNode(const std::string& n, const std::string& d); /// Copy constructor ParamNode(const ParamNode&) = default; /// Move constructor ParamNode(ParamNode&&) = default; /// Destructor ~ParamNode(); /// Assignment operator ParamNode& operator=(const ParamNode&) = default; /// Move assignment operator ParamNode& operator=(ParamNode&&) & = default; /// Equality operator (name, entries and subnodes are compared) bool operator==(const ParamNode& rhs) const; /** @brief Look up entry of this node (local search) Returns the end iterator if no entry is found */ EntryIterator findEntry(const std::string& name); /** @brief Look up subnode of this node (local search) Returns the end iterator if no entry is found */ NodeIterator findNode(const std::string& name); /** @brief Look up the parent node of the entry or node corresponding to @p name (tree search) Returns 0 if no entry is found */ ParamNode* findParentOf(const std::string& name); /** @brief Look up the entry corresponding to @p name (tree search) Returns 0 if no entry is found */ ParamEntry* findEntryRecursive(const std::string& name); ///Inserts a @p node with the given @p prefix void insert(const ParamNode& node, const std::string& prefix = ""); ///Inserts an @p entry with the given @p prefix void insert(const ParamEntry& entry, const std::string& prefix = ""); ///Returns the number of entries in the whole subtree size_t size() const; ///Returns the name suffix of a @p key (the part behind the last ':' character) std::string suffix(const std::string& key) const; /// Name of the node std::string name; /// Description of the node std::string description; /// Entries (leafs) in the node std::vector<ParamEntry> entries; /// Subnodes std::vector<ParamNode> nodes; }; public: /// Forward const iterator for the Param class class OPENMS_DLLAPI ParamIterator { public: // Iterator type definitions for C++ standard library compatibility using iterator_category = std::forward_iterator_tag; using value_type = Param::ParamEntry; using difference_type = std::ptrdiff_t; using pointer = const Param::ParamEntry*; using reference = const Param::ParamEntry&; /// Struct that captures information on entered / left nodes for ParamIterator struct OPENMS_DLLAPI TraceInfo { /// Constructor with name, description, and open flag inline TraceInfo(const std::string& n, const std::string& d, bool o) : name(n), description(d), opened(o) { } /// name of the node std::string name; /// description of the node std::string description; /// If it was opened (true) or closed (false) bool opened; }; /// Default constructor used to create a past-the-end iterator ParamIterator(); /// Constructor for begin iterator ParamIterator(const Param::ParamNode& root); /// Destructor ~ParamIterator(); /// Dereferencing const Param::ParamEntry& operator*(); /// Dereferencing const Param::ParamEntry* operator->(); /// Prefix increment operator ParamIterator& operator++(); /// Postfix increment operator ParamIterator operator++(int); /// Equality operator bool operator==(const ParamIterator& rhs) const; /// Equality operator bool operator!=(const ParamIterator& rhs) const; /// Returns the absolute path of the current element (including all sections) std::string getName() const; /// Returns the traceback of the opened and closed sections const std::vector<TraceInfo>& getTrace() const; protected: /// Pointer to the root node const Param::ParamNode* root_; /// Index of the current ParamEntry (-1 means invalid) int current_; /// Pointers to the ParamNodes we are in std::vector<const Param::ParamNode*> stack_; /// Node traversal data during last ++ operation. std::vector<TraceInfo> trace_; }; /// Default constructor Param(); /// Copy constructor Param(const Param&) = default; /// Move constructor Param(Param&&) = default; /// Destructor ~Param(); /// Assignment operator Param& operator=(const Param&) = default; /// Move assignment operator Param& operator=(Param&&) & = default; /// Equality operator bool operator==(const Param& rhs) const; /// Begin iterator for the internal tree ParamIterator begin() const; /// End iterator for the internal tree ParamIterator end() const; ///@name Accessors for single parameters //@{ /** @brief Sets a value. @param[in] key String key. Can contain ':' which separates section names @param[in] value The actual value @param[in] description Verbose description of the parameter @param[in] tags list of tags associated to this parameter */ void setValue(const std::string& key, const ParamValue& value, const std::string& description = "", const std::vector<std::string>& tags = std::vector<std::string>()); /** @brief Returns a value of a parameter. @exception Exception::ElementNotFound is thrown if the parameter does not exists. */ const ParamValue& getValue(const std::string& key) const; /** @brief Returns the type of a parameter. @exception Exception::ElementNotFound is thrown if the parameter does not exists. */ ParamValue::ValueType getValueType(const std::string& key) const; /** @brief Returns the whole parameter entry. @exception Exception::ElementNotFound is thrown if the parameter does not exists. */ const ParamEntry& getEntry(const std::string& key) const; /** @brief Tests if a parameter is set (expecting its fully qualified name, e.g., TextExporter:1:proteins_only) @param[in] key The fully qualified name of the parameter to check. @return True if the parameter exists, false otherwise. */ bool exists(const std::string& key) const; /** @brief Checks whether a section is present. @param[in] key The key of the section to be searched for. May or may not contain ":" suffix. @return True if the section exists, false otherwise. */ bool hasSection(const std::string& key) const; /** @brief Find leaf node by name (if it exists). @param[in] leaf The name of the parameter to find excluding the path parameter, e.g., given the parameter TextExporter:1:proteins_only the leaf would be named proteins_only. @return Returns end() if leaf does not exist. */ ParamIterator findFirst(const std::string& leaf) const; /** @brief Find next leaf node by name (if it exists), not considering the @p start_leaf @param[in] leaf The name of the parameter to find excluding the path parameter, e.g., given the parameter TextExporter:1:proteins_only the leaf would be named proteins_only. @param[in] start_leaf The already found leaf, that should not be considered during this search. @return Returns end() if leaf does not exist. */ ParamIterator findNext(const std::string& leaf, const ParamIterator& start_leaf) const; //@} ///@name Tags handling //@{ /** @brief Adds the tag @p tag to the entry @p key E.g. "advanced", "required", "input file", "output file" @exception Exception::ElementNotFound is thrown if the parameter does not exists. @exception Exception::InvalidValue is thrown if the tag contain a comma character. */ void addTag(const std::string& key, const std::string& tag); /** @brief Adds the tags in the list @p tags to the entry @p key @exception Exception::ElementNotFound is thrown if the parameter does not exists. @exception Exception::InvalidValue is thrown if a tag contain a comma character. */ void addTags(const std::string& key, const std::vector<std::string>& tags); /** @brief Returns if the parameter @p key has a tag Example: The tag 'advanced' is used in the GUI to determine which parameters are always displayed and which parameters are displayed only in 'advanced mode'. @exception Exception::ElementNotFound is thrown if the parameter does not exists. */ bool hasTag(const std::string& key, const std::string& tag) const; /** @brief Returns the tags of entry @p key @exception Exception::ElementNotFound is thrown if the parameter does not exists. */ std::vector<std::string> getTags(const std::string& key) const; /** @brief Removes all tags from the entry @p key @exception Exception::ElementNotFound is thrown if the parameter does not exists. */ void clearTags(const std::string& key); //@} ///@name Descriptions handling //@{ /** @brief Returns the description of a parameter. @exception Exception::ElementNotFound is thrown if the parameter does not exists. */ const std::string& getDescription(const std::string& key) const; /** @brief Sets a description for an existing section Descriptions for values cannot be set with this method. They have to be set when inserting the value itself. @exception Exception::ElementNotFound is thrown if the section does not exists. */ void setSectionDescription(const std::string& key, const std::string& description); /** @brief Returns the description corresponding to the section with name @p key. If the section does not exist an empty string is returned. */ const std::string& getSectionDescription(const std::string& key) const; /** @brief Adds a parameter section under the path @p key with the given @p description. If the section already exists, the description is only overwritten if not empty. */ void addSection(const std::string& key, const std::string& description); //@} ///@name Manipulation of the whole parameter set //@{ ///Returns the number of entries (leafs). size_t size() const; ///Returns if there are no entries. bool empty() const; /// Deletes all entries void clear(); /// Insert all values of @p param and adds the prefix @p prefix. /// You should append ':' to prefix manually when you want it to be a section. void insert(const std::string& prefix, const Param& param); /** @brief Remove the entry @p key or a section @p key (when suffix is ':') Remove deletes either an entry or a section (when @p key ends with ':'), by matching the exact name. No partial matches are accepted. If an empty internal node remains, the tree is pruned until every node has either a successor node or a leaf, i.e. no naked nodes remain. */ void remove(const std::string& key); /** @brief Remove all entries that start with @p prefix Partial are valid as well. All entries and sections which match the prefix are deleted. If an empty internal node remains, the tree is pruned until every node has either a successor node or a leaf, i.e. no naked nodes remain. */ void removeAll(const std::string& prefix); /** @brief Returns a new Param object containing all entries that start with @p prefix. @param[in] prefix should contain a ':' at the end if you want to extract a subtree. Otherwise not only nodes, but as well values with that prefix are copied. @param[in] remove_prefix indicates if the prefix is removed before adding entries to the new Param */ Param copy(const std::string& prefix, bool remove_prefix = false) const; /** @brief Returns a new Param object containing all entries in the given subset. @param[in] subset The subset of Param nodes that should be copied out of the object here. Includes values etc. Does not check any compatibility. Just matches the names. @note Only matches entries and nodes at the root=top level and copies over whole subtrees if matched. This function is mainly used for copying subsection parameters that were not registered as as an actual subsection e.g. for backwards compatibility of param names. */ Param copySubset(const Param& subset) const; /** @brief Rescue parameter <b>values</b> from @p p_outdated to current param Calls update(p_outdated, true, add_unknown, false, false, OPENMS_LOG_WARN) and returns its value. */ bool update(const Param& p_outdated, const bool add_unknown = false); /** @brief Rescue parameter <b>values</b> from @p p_outdated to current param Calls update(p_outdated, true, add_unknown, false, false, stream) and returns its value. */ bool update(const Param& p_outdated, const bool add_unknown, Logger::LogStream& stream); /** @brief Rescue parameter <b>values</b> from @p p_outdated to current param All parameters present in both param objects will be transferred into this object, given that: <ul> <li>the name is equal</li> <li>the type is equal</li> <li>the value from @p p_outdated meets the new restrictions</li> </ul> Not transferred are values from parameter "version" (to preserve the new version) or "type" (to preserve layout). @param[in] p_outdated Old/outdated param object, whose values (as long as they are still valid) are used to update this object @param[in] verbose Print information about expected value updates @param[in] add_unknown Add unknown parameters from @p p_outdated to this param object. @param[in] fail_on_invalid_values Return false if outdated parameters hold invalid values @param[in] fail_on_unknown_parameters Return false if outdated parameters contain unknown parameters (takes precedence over @p add_unknown) @param[out] stream The stream where all the logging output is send to. @return true on success, false on failure */ bool update(const Param& p_outdated, bool verbose, bool add_unknown, bool fail_on_invalid_values, bool fail_on_unknown_parameters, Logger::LogStream& stream); /** @brief Adds missing parameters from the given param @p toMerge to this param. Existing parameters will not be modified. @param[in] toMerge The Param object from which parameters should be added to this param. */ void merge(const Param& toMerge); //@} ///@name Default value handling //@{ /** @brief Insert all values of @p defaults and adds the prefix @p prefix, if the values are not already set. @param[in] defaults The default values. @param[in] prefix The prefix to add to all defaults. @param[in] showMessage If <tt>true</tt> each default that is actually set is printed to stdout as well. @see checkDefaults */ void setDefaults(const Param& defaults, const std::string& prefix = "", bool showMessage = false); /** @brief Checks the current parameter entries against given @p defaults Several checks are performed: - If a parameter is present for which no default value is specified, a warning is issued to @p os. - If the type of a parameter and its default do not match, an exception is thrown. - If a string parameter contains an invalid string, an exception is thrown. - If parameter entry is a string list, an exception is thrown, if one or more list members are invalid strings - If a numeric parameter is out of the valid range, an exception is thrown. - If entry is a numeric list an exception is thrown, if one or more list members are out of the valid range @param[in] name The name that is used in error messages. @param[in] defaults The default values. @param[in] prefix The prefix where to check for the defaults. Warnings etc. will be send to OPENMS_LOG_WARN. @exception Exception::InvalidParameter is thrown if errors occur during the check */ void checkDefaults(const std::string& name, const Param& defaults, const std::string& prefix = "") const; //@} ///@name Restriction handling //@{ /** @brief Sets the valid strings for the parameter @p key. It is only checked in checkDefaults(). @exception Exception::InvalidParameter is thrown, if one of the strings contains a comma character @exception Exception::ElementNotFound exception is thrown, if the parameter is no string/stringlist parameter */ void setValidStrings(const std::string& key, const std::vector<std::string>& strings); /** @brief Gets he valid strings for the parameter @p key. @exception Exception::ElementNotFound exception is thrown, if the parameter is no string/stringlist parameter */ const std::vector<std::string>& getValidStrings(const std::string& key) const; /** @brief Sets the minimum value for the integer or integer list parameter @p key. It is only checked in checkDefaults(). @exception Exception::ElementNotFound is thrown if @p key is not found or if the parameter type is wrong */ void setMinInt(const std::string& key, int min); /** @brief Sets the maximum value for the integer or integer list parameter @p key. It is only checked in checkDefaults(). @exception Exception::ElementNotFound is thrown if @p key is not found or if the parameter type is wrong */ void setMaxInt(const std::string& key, int max); /** @brief Sets the minimum value for the floating point or floating point list parameter @p key. It is only checked in checkDefaults(). @exception Exception::ElementNotFound is thrown if @p key is not found or if the parameter type is wrong */ void setMinFloat(const std::string& key, double min); /** @brief Sets the maximum value for the floating point or floating point list parameter @p key. It is only checked in checkDefaults(). @exception Exception::ElementNotFound is thrown if @p key is not found or if the parameter type is wrong */ void setMaxFloat(const std::string& key, double max); //@} ///@name Command line parsing //@{ /** @brief Parses command line arguments This method discriminates three types of arguments:<BR> (1) options (starting with '-') that have a text argument<BR> (2) options (starting with '-') that have no text argument<BR> (3) text arguments (not starting with '-') Command line arguments '-a avalue -b -c bvalue misc1 misc2' would be stored like this:<BR> "prefix:-a" -> "avalue"<BR> "prefix:-b" -> ""<BR> "prefix:-c" -> "bvalue"<BR> "prefix:misc" -> list("misc1","misc2")<BR> @param[in] argc argc variable from command line @param[in] argv argv variable from command line @param[in] prefix prefix for all options */ void parseCommandLine(const int argc, const char** argv, const std::string& prefix = ""); /** @brief Parses command line arguments to specified key locations. Parses command line arguments to specified key locations and stores the result internally. @param[in] argc argc variable from command line @param[in] argv argv variable from command line @param[out] options_with_one_argument a map of options that are followed by one argument (with key where they are stored) @param[out] options_without_argument a map of options that are not followed by an argument (with key where they are stored). Options specified on the command line are set to the string 'true'. @param[out] options_with_multiple_argument a map of options that are followed by several arguments (with key where they are stored) @param[out] misc key where a StringList of all non-option arguments are stored @param[out] unknown key where a StringList of all unknown options are stored */ void parseCommandLine(const int argc, const char** argv, const std::map<std::string, std::string>& options_with_one_argument, const std::map<std::string, std::string>& options_without_argument, const std::map<std::string, std::string>& options_with_multiple_argument, const std::string& misc = "misc", const std::string& unknown = "unknown"); //@} protected: /** @brief Returns a mutable reference to a parameter entry. @exception Exception::ElementNotFound is thrown for unset parameters */ ParamEntry& getEntry_(const std::string& key) const; /// Constructor from a node which is used as root node Param(const Param::ParamNode& node); /// Invisible root node that stores all the data mutable Param::ParamNode root_; }; /// Output of Param to a stream. OPENMS_DLLAPI std::ostream& operator<<(std::ostream& os, const Param& param); } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/DATASTRUCTURES/Compomer.h
.h
10,838
334
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow $ // $Authors: Chris Bielow $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/CONCEPT/HashUtils.h> #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/DATASTRUCTURES/Adduct.h> #include <OpenMS/DATASTRUCTURES/ListUtils.h> #include <OpenMS/OpenMSConfig.h> #include <functional> #include <map> #include <vector> namespace OpenMS { class String; /** @brief Holds information on an edge connecting two features from a (putative) charge ladder A Compomer represents the chemical composition difference between two mass spectrometry features. It stores information about the adducts (ions, molecules, or atoms) that explain the mass and charge differences between these features. The Compomer has two sides: - LEFT side: adducts subtracted from the first feature - RIGHT side: adducts added to the first feature This model allows representing the relationship between features that correspond to the same analyte but with different adduct compositions or charge states. The Compomer maintains metadata such as: - Net charge (difference between right and left sides) - Total mass difference - Probability score of this adduct combination - Expected RT shift caused by the adducts This class is used extensively in the feature decharging and adduct annotation processes. @ingroup Datastructures */ class OPENMS_DLLAPI Compomer { public: /** @brief Enumeration for specifying which side of the compomer to operate on - LEFT: The left side (adducts subtracted from the first feature) - RIGHT: The right side (adducts added to the first feature) - BOTH: Both sides of the compomer */ enum SIDE {LEFT, RIGHT, BOTH}; /// Type definition for one side of a compomer (maps adduct labels to Adduct objects) typedef std::map<String, Adduct> CompomerSide; /** @brief Container for both sides of a compomer Vector with exactly two elements: - [0] = left side (adducts subtracted) - [1] = right side (adducts added) */ typedef std::vector<CompomerSide> CompomerComponents; /** @brief Default Constructor Initializes an empty compomer with zero net charge, mass, and probability. */ Compomer(); /** @brief Constructor with net-charge, mass, and probability @param[in] net_charge Net charge of the compomer (right side - left side) @param[in] mass Mass difference represented by the compomer @param[in] log_p Log probability of this adduct combination */ Compomer(Int net_charge, double mass, double log_p); /** @brief Copy constructor @param[in] p Source compomer to copy from */ Compomer(const Compomer& p); /** @brief Assignment Operator @param[in] source Source compomer to assign from @return Reference to this object */ Compomer& operator=(const Compomer& source); /** @brief Add an adduct to a specific side of the compomer Adds the specified amount of the adduct to the given side and updates the compomer's properties (net charge, mass, etc.). @param[in] a The adduct to add @param[in] side Which side to add the adduct to (0=LEFT, 1=RIGHT) */ void add(const Adduct& a, UInt side); /** @brief Determines if two compomers conflict with each other Checks if these two compomers can coexist for one feature by examining if they have conflicting adduct compositions on the specified sides. @param[in] cmp The other Compomer to compare against @param[in] side_this Which side of this compomer to check (0=LEFT, 1=RIGHT) @param[in] side_other Which side of the other compomer to check (0=LEFT, 1=RIGHT) @return True if the compomers conflict (cannot coexist), false otherwise */ bool isConflicting(const Compomer& cmp, UInt side_this, UInt side_other) const; /** @brief Set a unique identifier for this compomer @param[in] id The unique ID to assign */ void setID(const Size& id); /** @brief Get the unique identifier of this compomer @return The unique ID of this compomer */ const Size& getID() const; /** @brief Get both sides (left and right) of this compomer @return Reference to the compomer components (left and right sides) */ const CompomerComponents& getComponent() const; /** @brief Get the net charge of this compomer The net charge is calculated as the difference between the right and left sides. @return Net charge value */ const Int& getNetCharge() const; /** @brief Get the total mass difference represented by this compomer @return Mass difference in Da */ const double& getMass() const; /** @brief Get the sum of positive charges in this compomer @return Total positive charges */ const Int& getPositiveCharges() const; /** @brief Get the sum of negative charges in this compomer @return Total negative charges */ const Int& getNegativeCharges() const; /** @brief Get the log probability of this adduct combination Higher values indicate more likely combinations. @return Log probability value */ const double& getLogP() const; /** @brief Get the expected retention time shift caused by this compomer @return Expected RT shift value */ const double& getRTShift() const; /** @brief Get a string representation of all adducts in this compomer @return String representation of adducts on both sides */ String getAdductsAsString() const; /** @brief Get a string representation of adducts on a specific side @param[in] side Which side to get adducts for (LEFT, RIGHT, or BOTH) @return String representation of adducts on the specified side */ String getAdductsAsString(UInt side) const; /** @brief Check if the compomer contains only a single adduct on the specified side @param[out] a Output parameter that will contain the adduct if found @param[in] side Which side to check (LEFT or RIGHT) @return True if only a single adduct is present on the specified side */ bool isSingleAdduct(Adduct& a, const UInt side) const; /** @brief Remove all adducts of type @p a Remove ALL instances of the given adduct, BUT use the given adducts parameters (charge, logp, mass etc) to update the compomers members **/ Compomer removeAdduct(const Adduct& a) const; /** @brief Remove all adducts of type @p a from @p side (LEFT or RIGHT) remove ALL instances of the given adduct from the given side (LEFT or RIGHT), BUT use the given adducts parameters (charge, logp, mass etc) to update the compomers members */ Compomer removeAdduct(const Adduct& a, const UInt side) const; /** @brief Returns the adduct labels from @p side (LEFT or RIGHT) Get a list of labels for the @p side (useful for assigning channels (light, heavy etc) to features). */ StringList getLabels(const UInt side) const; /** @brief Add a complete set of adducts to a specific side of the compomer @param[in] add_side The set of adducts to add @param[in] side Which side to add the adducts to (LEFT or RIGHT) */ void add(const CompomerSide& add_side, UInt side); /** @brief Comparison operator for sorting compomers Sorts compomers by (in order of importance): 1. Net charge 2. Mass 3. Probability @param[in] c1 First compomer to compare @param[in] c2 Second compomer to compare @return True if c1 should be ordered before c2 */ friend OPENMS_DLLAPI bool operator<(const Compomer& c1, const Compomer& c2); /** @brief Output stream operator for printing compomer contents @param[in,out] os Output stream to write to @param[in] cmp Compomer to print @return Reference to the output stream */ friend OPENMS_DLLAPI std::ostream& operator<<(std::ostream& os, const Compomer& cmp); /** @brief Equality comparison operator @param[in] a First compomer to compare @param[in] b Second compomer to compare @return True if the compomers are equal */ friend OPENMS_DLLAPI bool operator==(const Compomer& a, const Compomer& b); private: CompomerComponents cmp_; ///< Adducts of left and right side Int net_charge_; ///< Net charge (right - left) double mass_; ///< Net mass (right - left) Int pos_charges_; ///< Sum of positive charges Int neg_charges_; ///< Sum of negative charges double log_p_; ///< Log probability of this adduct combination double rt_shift_; ///< Expected net RT shift (-shift_leftside + shift_rightside) Size id_; ///< Unique identifier for this compomer }; // \Compomer } // namespace OpenMS // Hash function specialization for Compomer // Note: Only hash fields used in operator== (cmp_, net_charge_, mass_, pos_charges_, neg_charges_, log_p_, id_) // Do NOT hash rt_shift_ as it is not compared in operator== namespace std { template<> struct hash<OpenMS::Compomer> { std::size_t operator()(const OpenMS::Compomer& c) const noexcept { std::size_t seed = OpenMS::hash_int(c.getNetCharge()); OpenMS::hash_combine(seed, OpenMS::hash_float(c.getMass())); OpenMS::hash_combine(seed, OpenMS::hash_int(c.getPositiveCharges())); OpenMS::hash_combine(seed, OpenMS::hash_int(c.getNegativeCharges())); OpenMS::hash_combine(seed, OpenMS::hash_float(c.getLogP())); OpenMS::hash_combine(seed, OpenMS::hash_int(c.getID())); // Hash the compomer components (vector<map<String, Adduct>>) const auto& components = c.getComponent(); OpenMS::hash_combine(seed, OpenMS::hash_int(components.size())); for (const auto& side : components) { OpenMS::hash_combine(seed, OpenMS::hash_int(side.size())); for (const auto& [key, adduct] : side) { OpenMS::hash_combine(seed, OpenMS::fnv1a_hash_string(key)); OpenMS::hash_combine(seed, std::hash<OpenMS::Adduct>{}(adduct)); } } return seed; } }; } // namespace std
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/DATASTRUCTURES/GridFeature.h
.h
2,055
76
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hendrik Weisser $ // $Authors: Steffen Sass, Hendrik Weisser $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/CONCEPT/Types.h> #include <OpenMS/OpenMSConfig.h> #include <set> namespace OpenMS { class BaseFeature; class AASequence; /** * @brief Representation of a feature in a hash grid. * * A GridFeature can be stored in a HashGrid and points to a BaseFeature (Feature or ConsensusFeature). Used for QT feature grouping (see QTClusterFinder). */ class OPENMS_DLLAPI GridFeature { private: /// Reference to the contained feature const BaseFeature& feature_; /// Index of the feature map or consensus map Size map_index_; /// Index of the feature in the map Size feature_index_; /// Set of peptide sequences annotated to the feature std::set<AASequence> annotations_; public: /** * @brief Detailed constructor * @param[in] feature Reference to the contained feature * @param[in] map_index Index of the feature map or consensus map * @param[in] feature_index Index of the feature in the map */ GridFeature(const BaseFeature& feature, Size map_index, Size feature_index); /// Returns the feature const BaseFeature& getFeature() const; /// Destructor virtual ~GridFeature(); /// Returns the map index Size getMapIndex() const; /// Returns the feature index Size getFeatureIndex() const; /// Returns the ID of the GridFeature (same as the feature index) Int getID() const; /// Returns the set of peptide sequences annotated to the cluster center const std::set<AASequence>& getAnnotations() const; /// Returns the feature RT double getRT() const; /// Returns the feature m/z double getMZ() const; }; }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/DATASTRUCTURES/ListUtilsIO.h
.h
2,303
83
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Stephan Aiche $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/DATASTRUCTURES/String.h> #include <iterator> #include <ostream> #include <vector> // This header collects io relevant parts of ListUtils. Separating the from the // rest avoids inclusion of ostream headers in a lot of classes. namespace OpenMS { /** @brief Output stream operator for std::vectors. @param[in,out] os The target stream. @param[in] v The vector to write to stream. */ template <typename T> inline std::ostream& operator<<(std::ostream& os, const std::vector<T>& v) { os << "["; if (!v.empty()) { for (auto it = v.begin(); it < v.end() - 1; ++it) { // convert to String manually, since this is much faster than ostream build-in conversion; // If T is a String, the compiler will (hopefully) elide the copy os << String(*it) << ", "; } os << String(v.back()); } os << "]"; return os; } template<typename T> struct VecLowPrecision { const std::vector<T>& value; VecLowPrecision(const std::vector<T>& v) : value(v) {} }; /// modified version of the stream operator (works for vectors of float, double, long double) which prints only /// three fractional digits; usage 'os << VecLowPrecision(my_vec);' template <typename T> inline std::ostream& operator<<(std::ostream& os, const VecLowPrecision<T>& val) { os << "["; const auto& v = val.value; if (!v.empty()) { for (auto it = v.begin(); it < v.end() - 1; ++it) { // convert to String manually, since this is much faster than ostreams build-in conversion; os << String(*it, false) << ", "; } os << String(v.back(), false); } os << "]"; return os; } /// Operator for appending entries with less code template <typename TString> inline std::vector<String>& operator<<(std::vector<String>& sl, const TString& string) { sl.push_back(string); return sl; } }
Unknown
3D
OpenMS/OpenMS
src/openms/include/OpenMS/DATASTRUCTURES/Utils/MapUtilities.h
.h
3,552
129
// 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/config.h> #include <OpenMS/METADATA/PeptideIdentification.h> #include <OpenMS/METADATA/PeptideIdentificationList.h> #include <vector> namespace OpenMS { /** @brief Utilities for Feature and ConsensusMap @ingroup Datastructures */ template <class MapType> class MapUtilities { public: /// applies a function on all PeptideHits or only assigned ones template <class T> void applyFunctionOnPeptideHits(T&& f, bool include_unassigned = true) { for (auto& feat : static_cast<MapType&>(*this)) { applyFunctionOnPeptideHits_(feat.getPeptideIdentifications(), f); } if (include_unassigned) { applyFunctionOnPeptideHits_(static_cast<MapType&>(*this).getUnassignedPeptideIdentifications(), f); } } /// applies a function on all PeptideIDs or only assigned ones template <class T> void applyFunctionOnPeptideIDs(T&& f, bool include_unassigned = true) { for (auto& feat : static_cast<MapType&>(*this)) { applyFunctionOnPeptideIDs_(feat.getPeptideIdentifications(), f); } if (include_unassigned) { applyFunctionOnPeptideIDs_(static_cast<MapType&>(*this).getUnassignedPeptideIdentifications(), f); } } /// applies a const function on all PeptideHits or only assigned ones template <class T> void applyFunctionOnPeptideHits(T&& f, bool include_unassigned = true) const { for (const auto& feat : static_cast<MapType const&>(*this)) { applyFunctionOnPeptideHits_(feat.getPeptideIdentifications(), f); } if (include_unassigned) { applyFunctionOnPeptideHits_(static_cast<MapType const&>(*this).getUnassignedPeptideIdentifications(), f); } } /// applies a const function on all PeptideIDs or only assigned ones template <class T> void applyFunctionOnPeptideIDs(T&& f, bool include_unassigned = true) const { for (const auto& feat : static_cast<MapType const&>(*this)) { applyFunctionOnPeptideIDs_(feat.getPeptideIdentifications(), f); } if (include_unassigned) { applyFunctionOnPeptideIDs_(static_cast<MapType const&>(*this).getUnassignedPeptideIdentifications(), f); } } private: template <class T> void applyFunctionOnPeptideIDs_(PeptideIdentificationList& idvec, T&& f) { for (auto& id : idvec) { f(id); } } template <class T> void applyFunctionOnPeptideHits_(PeptideIdentificationList& idvec, T&& f) { for (auto& id : idvec) { for (auto& hit : id.getHits()) { f(hit); } } } template <class T> void applyFunctionOnPeptideIDs_(const PeptideIdentificationList& idvec, T&& f) const { for (const auto& id : idvec) { f(id); } } template <class T> void applyFunctionOnPeptideHits_(const PeptideIdentificationList& idvec, T&& f) const { for (const auto& id : idvec) { for (const auto& hit : id.getHits()) { f(hit); } } } }; } // namespace OpenMS
Unknown
3D
OpenMS/OpenMS
src/openms/extern/Quadtree/include/Quadtree.h
.h
10,094
315
#pragma once #include <cassert> #include <algorithm> #include <array> #include <memory> #include <type_traits> #include <vector> #include "Box.h" namespace quadtree { template<typename T, typename GetBox, typename Equal = std::equal_to<T>, typename Float = float> class Quadtree { static_assert(std::is_convertible_v<std::invoke_result_t<GetBox, const T&>, Box<Float>>, "GetBox must be a callable of signature Box<Float>(const T&)"); static_assert(std::is_convertible_v<std::invoke_result_t<Equal, const T&, const T&>, bool>, "Equal must be a callable of signature bool(const T&, const T&)"); static_assert(std::is_arithmetic_v<Float>); public: Quadtree(const Box<Float>& box, const GetBox& getBox = GetBox(), const Equal& equal = Equal()) : mBox(box), mRoot(std::make_unique<Node>()), mGetBox(getBox), mEqual(equal) { } void add(const T& value) { add(mRoot.get(), 0, mBox, value); } void remove(const T& value) { remove(mRoot.get(), mBox, value); } std::vector<T> query(const Box<Float>& box) const { auto values = std::vector<T>(); query(mRoot.get(), mBox, box, values); return values; } std::vector<std::pair<T, T>> findAllIntersections() const { auto intersections = std::vector<std::pair<T, T>>(); findAllIntersections(mRoot.get(), intersections); return intersections; } Box<Float> getBox() const { return mBox; } private: static constexpr auto Threshold = std::size_t(16); static constexpr auto MaxDepth = std::size_t(8); struct Node { std::array<std::unique_ptr<Node>, 4> children; std::vector<T> values; }; Box<Float> mBox; std::unique_ptr<Node> mRoot; GetBox mGetBox; Equal mEqual; bool isLeaf(const Node* node) const { return !static_cast<bool>(node->children[0]); } Box<Float> computeBox(const Box<Float>& box, int i) const { auto origin = box.getTopLeft(); auto childSize = box.getSize() / static_cast<Float>(2); switch (i) { // North West case 0: return Box<Float>(origin, childSize); // Norst East case 1: return Box<Float>(Vector2<Float>(origin.x + childSize.x, origin.y), childSize); // South West case 2: return Box<Float>(Vector2<Float>(origin.x, origin.y + childSize.y), childSize); // South East case 3: return Box<Float>(origin + childSize, childSize); default: assert(false && "Invalid child index"); return Box<Float>(); } } int getQuadrant(const Box<Float>& nodeBox, const Box<Float>& valueBox) const { auto center = nodeBox.getCenter(); // West if (valueBox.getRight() < center.x) { // North West if (valueBox.getBottom() < center.y) return 0; // South West else if (valueBox.top >= center.y) return 2; // Not contained in any quadrant else return -1; } // East else if (valueBox.left >= center.x) { // North East if (valueBox.getBottom() < center.y) return 1; // South East else if (valueBox.top >= center.y) return 3; // Not contained in any quadrant else return -1; } // Not contained in any quadrant else return -1; } void add(Node* node, std::size_t depth, const Box<Float>& box, const T& value) { assert(node != nullptr); assert(box.contains(mGetBox(value))); if (isLeaf(node)) { // Insert the value in this node if possible if (depth >= MaxDepth || node->values.size() < Threshold) node->values.push_back(value); // Otherwise, we split and we try again else { split(node, box); add(node, depth, box, value); } } else { auto i = getQuadrant(box, mGetBox(value)); // Add the value in a child if the value is entirely contained in it if (i != -1) add(node->children[static_cast<std::size_t>(i)].get(), depth + 1, computeBox(box, i), value); // Otherwise, we add the value in the current node else node->values.push_back(value); } } void split(Node* node, const Box<Float>& box) { assert(node != nullptr); assert(isLeaf(node) && "Only leaves can be split"); // Create children for (auto& child : node->children) child = std::make_unique<Node>(); // Assign values to children auto newValues = std::vector<T>(); // New values for this node for (const auto& value : node->values) { auto i = getQuadrant(box, mGetBox(value)); if (i != -1) node->children[static_cast<std::size_t>(i)]->values.push_back(value); else newValues.push_back(value); } node->values = std::move(newValues); } bool remove(Node* node, const Box<Float>& box, const T& value) { assert(node != nullptr); assert(box.contains(mGetBox(value))); if (isLeaf(node)) { // Remove the value from node removeValue(node, value); return true; } else { // Remove the value in a child if the value is entirely contained in it auto i = getQuadrant(box, mGetBox(value)); if (i != -1) { if (remove(node->children[static_cast<std::size_t>(i)].get(), computeBox(box, i), value)) return tryMerge(node); } // Otherwise, we remove the value from the current node else removeValue(node, value); return false; } } void removeValue(Node* node, const T& value) { // Find the value in node->values auto it = std::find_if(std::begin(node->values), std::end(node->values), [this, &value](const auto& rhs){ return mEqual(value, rhs); }); assert(it != std::end(node->values) && "Trying to remove a value that is not present in the node"); // Swap with the last element and pop back *it = std::move(node->values.back()); node->values.pop_back(); } bool tryMerge(Node* node) { assert(node != nullptr); assert(!isLeaf(node) && "Only interior nodes can be merged"); auto nbValues = node->values.size(); for (const auto& child : node->children) { if (!isLeaf(child.get())) return false; nbValues += child->values.size(); } if (nbValues <= Threshold) { node->values.reserve(nbValues); // Merge the values of all the children for (const auto& child : node->children) { for (const auto& value : child->values) node->values.push_back(value); } // Remove the children for (auto& child : node->children) child.reset(); return true; } else return false; } void query(Node* node, const Box<Float>& box, const Box<Float>& queryBox, std::vector<T>& values) const { assert(node != nullptr); assert(queryBox.intersects(box)); for (const auto& value : node->values) { if (queryBox.intersects(mGetBox(value))) values.push_back(value); } if (!isLeaf(node)) { for (auto i = std::size_t(0); i < node->children.size(); ++i) { auto childBox = computeBox(box, static_cast<int>(i)); if (queryBox.intersects(childBox)) query(node->children[i].get(), childBox, queryBox, values); } } } void findAllIntersections(Node* node, std::vector<std::pair<T, T>>& intersections) const { // Find intersections between values stored in this node // Make sure to not report the same intersection twice for (auto i = std::size_t(0); i < node->values.size(); ++i) { for (auto j = std::size_t(0); j < i; ++j) { if (mGetBox(node->values[i]).intersects(mGetBox(node->values[j]))) intersections.emplace_back(node->values[i], node->values[j]); } } if (!isLeaf(node)) { // Values in this node can intersect values in descendants for (const auto& child : node->children) { for (const auto& value : node->values) findIntersectionsInDescendants(child.get(), value, intersections); } // Find intersections in children for (const auto& child : node->children) findAllIntersections(child.get(), intersections); } } void findIntersectionsInDescendants(Node* node, const T& value, std::vector<std::pair<T, T>>& intersections) const { // Test against the values stored in this node for (const auto& other : node->values) { if (mGetBox(value).intersects(mGetBox(other))) intersections.emplace_back(value, other); } // Test against values stored into descendants of this node if (!isLeaf(node)) { for (const auto& child : node->children) findIntersectionsInDescendants(child.get(), value, intersections); } } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/Quadtree/include/Box.h
.h
1,433
67
#pragma once #include "Vector2.h" namespace quadtree { template<typename T> class Box { public: T left; T top; T width; // Must be positive T height; // Must be positive constexpr Box(T Left = 0, T Top = 0, T Width = 0, T Height = 0) noexcept : left(Left), top(Top), width(Width), height(Height) { } constexpr Box(const Vector2<T>& position, const Vector2<T>& size) noexcept : left(position.x), top(position.y), width(size.x), height(size.y) { } constexpr T getRight() const noexcept { return left + width; } constexpr T getBottom() const noexcept { return top + height; } constexpr Vector2<T> getTopLeft() const noexcept { return Vector2<T>(left, top); } constexpr Vector2<T> getCenter() const noexcept { return Vector2<T>(left + width / 2, top + height / 2); } constexpr Vector2<T> getSize() const noexcept { return Vector2<T>(width, height); } constexpr bool contains(const Box<T>& box) const noexcept { return left <= box.left && box.getRight() <= getRight() && top <= box.top && box.getBottom() <= getBottom(); } constexpr bool intersects(const Box<T>& box) const noexcept { return !(left >= box.getRight() || getRight() <= box.left || top >= box.getBottom() || getBottom() <= box.top); } }; }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/Quadtree/include/Vector2.h
.h
705
47
#pragma once namespace quadtree { template<typename T> class Vector2 { public: T x; T y; constexpr Vector2<T>(T X = 0, T Y = 0) noexcept : x(X), y(Y) { } constexpr Vector2<T>& operator+=(const Vector2<T>& other) noexcept { x += other.x; y += other.y; return *this; } constexpr Vector2<T>& operator/=(T t) noexcept { x /= t; y /= t; return *this; } }; template<typename T> constexpr Vector2<T> operator+(Vector2<T> lhs, const Vector2<T>& rhs) noexcept { lhs += rhs; return lhs; } template<typename T> constexpr Vector2<T> operator/(Vector2<T> vec, T t) noexcept { vec /= t; return vec; } }
Unknown
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/FFT/DIF.hpp
.hpp
1,845
60
#ifndef _DIF_HPP #define _DIF_HPP #include <iostream> #include <cmath> #include "RealFFTPostprocessor.hpp" #include "DIFButterfly.hpp" template<unsigned char LOG_N, bool SHUFFLE> class DIF { public: inline static void fft1d(cpx* __restrict const data) { DIFButterfly< 1ul << LOG_N >::apply(data); if (SHUFFLE) RecursiveShuffle<cpx, LOG_N>::apply(data); } // Note: Here N refers to the full length of the equivalent complex // FFT (i.e., the FFT of N cpx values where all imaginary components // are 0). The actual allocation should be N/2+1 packed cpx values. inline static void real_fft1d_packed(cpx* __restrict const data) { const unsigned long int LOG_N_PACKED = LOG_N-1; DIF<LOG_N_PACKED, SHUFFLE>::fft1d(data); static_assert(SHUFFLE, "DIF on reals must be used with reordered data (the performance cost of inlining the shuffle operations is worse than simply shuffling)"); RealFFTPostprocessor<LOG_N>::apply(data); } inline static void real_ifft1d_packed(cpx* __restrict const data) { const unsigned long int LOG_N_PACKED = LOG_N-1; const unsigned long int N_PACKED = 1ul<<LOG_N_PACKED; RealFFTPostprocessor<LOG_N>::apply_inverse(data); // Conj.: for (unsigned long int k=0; k<=N_PACKED; ++k) data[k] = data[k].conj(); // FFT: DIF<LOG_N_PACKED, SHUFFLE>::fft1d(data); // Conj.: for (unsigned long int k=0; k<=N_PACKED; ++k) data[k] = data[k].conj(); // Scale: for (unsigned long int k=0; k<=N_PACKED; ++k) data[k] *= 1.0/N_PACKED; } }; template<bool SHUFFLE> class DIF<0u, SHUFFLE> { public: inline static void fft1d(cpx* __restrict const /*data*/) { } inline static void real_fft1d_packed(cpx* __restrict const /*data*/) { } inline static void real_ifft1d_packed(cpx* __restrict const /*data*/) { } }; #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/FFT/DIFButterfly.hpp
.hpp
4,306
184
#ifndef _DIFBUTTERFLY_HPP #define _DIFBUTTERFLY_HPP #include "Twiddles.hpp" template<unsigned long N> class DIFButterfly { public: // Can improve speed, but makes compilation very resource intensive // for larger N: // __attribute__((always_inline)) inline static void apply(cpx* __restrict const data) { // Butterfly, then multiply twiddles into second half of list: cpx twiddle = cpx{1.0, 0.0}; for (unsigned long i=0; i<N/2; ++i) { cpx temp = data[(i + N/2)]; data[(i + N/2)] = data[i] - temp; data[(i + N/2)] *= twiddle; data[i] += temp; // Compute next twiddle factor: Twiddles<N/2>::advance(twiddle); } DIFButterfly<N/2>::apply(data); DIFButterfly<N/2>::apply(data+N/2); } }; template<> class DIFButterfly<0ul> { public: inline static void apply(cpx* __restrict const) { // do nothing } }; template<> class DIFButterfly<1ul> { public: inline static void apply(cpx* __restrict const) { // do nothing } }; // Same as DITButterfly<2>: template<> class DIFButterfly<2ul> { public: // __attribute__((always_inline)) inline static void apply(cpx* __restrict const data) { data[1] = data[0] - data[1]; data[0] = data[0] + data[0] - data[1]; } }; // Same as DITButterfly<4>, but shuffled so [1] and [2] are swapped: template<> class DIFButterfly<4ul> { public: // __attribute__((always_inline)) inline static void apply(cpx* __restrict const data) { // Note: index written even when index is zero for // clarity; however, all constant multiplications will be // computed at compile time: cpx t = data[2]; data[2] = data[0] - t; data[0] += t; t = data[3]; data[3] = cpx{data[1].i - t.i, t.r - data[1].r}; data[1] += t; t = data[1]; data[1] = data[0] - t; data[0] += t; t = data[3]; data[3] = data[2] - t; data[2] += t; } }; // No need to manually swap, because <4> is called manually, as it would be above: template<> class DIFButterfly<8ul> { public: // __attribute__((always_inline)) inline static void apply(cpx* __restrict const data) { const double sqrt2Over2 = Twiddles<4>::sin(); cpx temp = data[4]; data[4] = data[0] - temp; data[0] += temp; cpx twiddle{sqrt2Over2, -sqrt2Over2}; temp = data[5]; data[5] = data[1] - temp; data[5] *= twiddle; data[1] += temp; twiddle = cpx{0.0, -1.0}; temp = data[6]; data[6] = data[2] - temp; data[6] *= twiddle; data[2] += temp; twiddle = cpx{-sqrt2Over2, -sqrt2Over2}; temp = data[7]; data[7] = data[3] - temp; data[7] *= twiddle; data[3] += temp; DIFButterfly<4ul>::apply(data); DIFButterfly<4ul>::apply(data+4); } }; // No need to manually swap, because <8> is called manually, as it would be above: template<> class DIFButterfly<16ul> { public: // __attribute__((always_inline)) inline static void apply(cpx* __restrict const data) { const double sqrt2Over2 = Twiddles<4>::sin(); const double sinPiOver8 = Twiddles<8>::sin(); const double cosPiOver8 = Twiddles<8>::cos(); cpx temp = data[8]; data[8] = data[0] - temp; data[0] += temp; cpx twiddle{cosPiOver8, -sinPiOver8}; temp = data[9]; data[9] = data[1] - temp; data[9] *= twiddle; data[1] += temp; twiddle = cpx{sqrt2Over2, -sqrt2Over2}; temp = data[10]; data[10] = data[2] - temp; data[10] *= twiddle; data[2] += temp; twiddle = cpx{sinPiOver8, -cosPiOver8}; temp = data[11]; data[11] = data[3] - temp; data[11] *= twiddle; data[3] += temp; twiddle = cpx{0.0, -1.0}; temp = data[12]; data[12] = data[4] - temp; data[12] *= twiddle; data[4] += temp; twiddle = cpx{-sinPiOver8, -cosPiOver8}; temp = data[13]; data[13] = data[5] - temp; data[13] *= twiddle; data[5] += temp; twiddle = cpx{-sqrt2Over2, -sqrt2Over2}; temp = data[14]; data[14] = data[6] - temp; data[14] *= twiddle; data[6] += temp; twiddle = cpx{-cosPiOver8, -sinPiOver8}; temp = data[15]; data[15] = data[7] - temp; data[15] *= twiddle; data[7] += temp; DIFButterfly<8ul>::apply(data); DIFButterfly<8ul>::apply(data+8); } }; #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/FFT/DIT.hpp
.hpp
1,891
62
#ifndef _DIT_HPP #define _DIT_HPP #include <iostream> #include <cmath> #include "RealFFTPostprocessor.hpp" #include "DITButterfly.hpp" template<unsigned char LOG_N, bool SHUFFLE> class DIT { public: inline static void fft1d(cpx* __restrict const data) { if (SHUFFLE) RecursiveShuffle<cpx, LOG_N>::apply(data); DITButterfly< 1ul << LOG_N >::apply(data); } // Note: Here N refers to the full length of the equivalent complex // FFT (i.e., the FFT of N cpx values where all imaginary components // are 0). The actual allocation should be N/2+1/2 packed cpx values. inline static void real_fft1d_packed(cpx* __restrict const data) { const unsigned long LOG_N_PACKED = LOG_N-1; DIT<LOG_N_PACKED, SHUFFLE>::fft1d(data); // Data must be in order, so real FFT cleanup is safe: RealFFTPostprocessor<LOG_N>::apply(data); } inline static void real_ifft1d_packed(cpx* __restrict const data) { const unsigned long LOG_N_PACKED = LOG_N-1; const unsigned long N_PACKED = 1ul<<LOG_N_PACKED; static_assert(SHUFFLE, "Inverse DIT on reals must be used with reordered data (the performance cost of inlining the shuffle operations is worse than simply shuffling)"); RealFFTPostprocessor<LOG_N>::apply_inverse(data); // Conj.: for (unsigned long k=0; k<=N_PACKED; ++k) data[k] = data[k].conj(); // FFT: DIT<LOG_N_PACKED, SHUFFLE>::fft1d(data); // Conj.: for (unsigned long k=0; k<=N_PACKED; ++k) data[k] = data[k].conj(); // Scale: for (unsigned long k=0; k<=N_PACKED; ++k) data[k] *= 1.0/N_PACKED; } }; template<bool SHUFFLE> class DIT<0u, SHUFFLE> { public: inline static void fft1d(cpx* __restrict const /*data*/) { } inline static void real_fft1d_packed(cpx* __restrict const /*data*/) { } inline static void real_ifft1d_packed(cpx* __restrict const /*data*/) { } }; #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/FFT/shape_to_log_shape.hpp
.hpp
1,819
62
#ifndef _SHAPE_TO_LOG_SHAPE_HPP #define _SHAPE_TO_LOG_SHAPE_HPP inline unsigned char integer_log2(unsigned long val) { // Note: that can be sped up using bit twiddling (cast to float, // etc.) or using the clz opcode. But it's still reasonably fast as // is: unsigned char res = round( log2(val) ); #ifdef SHAPE_CHECK assert( (1ul<<res) == val); #endif return res; } inline Vector<unsigned char> shape_to_log_shape(const Vector<unsigned long> & shape) { Vector<unsigned char> log_shape(shape.size()); for (unsigned char k=0; k<shape.size(); ++k) log_shape[k] = integer_log2(shape[k]); return log_shape; } inline unsigned long real_length_to_packed_length(unsigned long len) { if (len == 0) return 0; return len / 2 + 1; } inline unsigned long packed_length_to_real_length(unsigned long packed_len) { if (packed_len == 0) return 0; if (packed_len == 1) return 1; return (packed_len - 1)*2; } // Note: returns log_shape for equivalent complex FFT: inline Vector<unsigned char> packed_shape_to_log_shape(const Vector<unsigned long> & packed_shape) { Vector<unsigned char> log_equiv_shape(packed_shape.size()); unsigned char k; for (k=0; k<packed_shape.size()-1; ++k) log_equiv_shape[k] = integer_log2( packed_shape[k] ); log_equiv_shape[k] = integer_log2( packed_length_to_real_length(packed_shape[k]) ); return log_equiv_shape; } inline Vector<unsigned char> reversed_packed_shape_to_log_shape(const Vector<unsigned long> & packed_shape) { Vector<unsigned char> log_equiv_shape(packed_shape.size()); unsigned char k=0; log_equiv_shape[k] = integer_log2( packed_length_to_real_length(packed_shape[k]) ); for (k=1; k<packed_shape.size(); ++k) log_equiv_shape[k] = integer_log2( packed_shape[k] ); return log_equiv_shape; } #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/FFT/DITButterfly.hpp
.hpp
4,017
170
#ifndef _DITBUTTERFLY_HPP #define _DITBUTTERFLY_HPP #include "Twiddles.hpp" template<unsigned long N> class DITButterfly { public: // Can improve speed, but makes compilation very resource intensive // for larger N: // __attribute__((always_inline)) inline static void apply(cpx* __restrict const data) { DITButterfly<N/2>::apply(data); DITButterfly<N/2>::apply(data+N/2); cpx twiddle = cpx{1.0, 0.0}; for (unsigned long i=0; i<N/2; ++i) { cpx temp = data[(i + N/2)]*twiddle; data[(i + N/2)] = data[i] - temp; data[i] += temp; // Compute next twiddle factor: Twiddles<N/2>::advance(twiddle); } } }; template<> class DITButterfly<0ul> { public: inline static void apply(cpx* __restrict const) { // do nothing } }; template<> class DITButterfly<1ul> { public: inline static void apply(cpx* __restrict const) { // do nothing } }; template<> class DITButterfly<2ul> { public: // __attribute__((always_inline)) inline static void apply(cpx* __restrict const data) { data[1] = data[0] - data[1]; data[0] = data[0] + data[0] - data[1]; // x = x + x - y // equivalent to // x <<= 1 // x += y // data[0] += data[0]; // data[0] -= data[1]; } }; template<> class DITButterfly<4ul> { public: // __attribute__((always_inline)) inline static void apply(cpx* __restrict const data) { // Note: index written even when index is zero for // clarity; however, all constant multiplications will be // computed at compile time: cpx t = data[1]; data[1] = data[0] - t; data[0] += t; t = data[3]; data[3] = cpx{data[2].i - t.i, t.r - data[2].r}; data[2] += t; t = data[2]; data[2] = data[0] - t; data[0] += t; t = data[3]; data[3] = data[1] - t; data[1] += t; } }; template<> class DITButterfly<8ul> { public: // __attribute__((always_inline)) inline static void apply(cpx* __restrict const data) { DITButterfly<4ul>::apply(data); DITButterfly<4ul>::apply(data+4); const double sqrt2Over2 = Twiddles<4>::sin(); cpx temp = data[4]; data[4] = data[0] - temp; data[0] += temp; cpx twiddle{sqrt2Over2, -sqrt2Over2}; temp = data[(1 + 4)]*twiddle; data[(1 + 4)] = data[1] - temp; data[1] += temp; twiddle = cpx{0.0, -1.0}; temp = data[(2 + 4)]*twiddle; data[(2 + 4)] = data[2] - temp; data[2] += temp; twiddle = cpx{-sqrt2Over2, -sqrt2Over2}; temp = data[(3 + 4)]*twiddle; data[(3 + 4)] = data[3] - temp; data[3] += temp; } }; template<> class DITButterfly<16ul> { public: // __attribute__((always_inline)) inline static void apply(cpx* __restrict const data) { DITButterfly<8ul>::apply(data); DITButterfly<8ul>::apply(data+8); const double sqrt2Over2 = Twiddles<4>::sin(); const double sinPiOver8 = Twiddles<8>::sin(); const double cosPiOver8 = Twiddles<8>::cos(); cpx temp = data[8]; data[8] = data[0] - temp; data[0] += temp; cpx twiddle{cosPiOver8, -sinPiOver8}; temp = data[(1 + 8)]*twiddle; data[(1 + 8)] = data[1] - temp; data[1] += temp; twiddle = cpx{sqrt2Over2, -sqrt2Over2}; temp = data[(2 + 8)]*twiddle; data[(2 + 8)] = data[2] - temp; data[2] += temp; twiddle = cpx{sinPiOver8, -cosPiOver8}; temp = data[(3 + 8)]*twiddle; data[(3 + 8)] = data[3] - temp; data[3] += temp; twiddle = cpx{0, -1.0}; temp = data[(4 + 8)]*twiddle; data[(4 + 8)] = data[4] - temp; data[4] += temp; twiddle = cpx{-sinPiOver8, -cosPiOver8}; temp = data[(5 + 8)]*twiddle; data[(5 + 8)] = data[5] - temp; data[5] += temp; twiddle = cpx{-sqrt2Over2, -sqrt2Over2}; temp = data[(6 + 8)]*twiddle; data[(6 + 8)] = data[6] - temp; data[6] += temp; twiddle = cpx{-cosPiOver8, -sinPiOver8}; temp = data[(7 + 8)]*twiddle; data[(7 + 8)] = data[7] - temp; data[7] += temp; } }; #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/FFT/RealFFTPostprocessor.hpp
.hpp
2,970
99
#ifndef _REALFFTPOSTPROCESSOR_HPP #define _REALFFTPOSTPROCESSOR_HPP #include "cpx.hpp" #include "Twiddles.hpp" template<unsigned int LOG_N> class RealFFTPostprocessor { public: // Note: Here N refers to the full length of the equivalent complex // FFT (as above): inline static void apply(cpx* const data) { const unsigned long N = 1ul<<LOG_N; // Postprocessing to convert FFT to equivalent real FFT: cpx bias = data[0]; data[0].r = bias.r + bias.i; data[0].i = 0.0; data[N/2].r = bias.r - bias.i; data[N/2].i = 0.0; cpx current_twiddle{1.0,0.0}; Twiddles<N/2>::advance(current_twiddle); unsigned long k; for (k=1; k<=N/4; ++k) { cpx x1 = 0.5*(data[k] + data[N/2-k].conj()); cpx x2 = 0.5*(data[k] - data[N/2-k].conj()); cpx temp = x2 * cpx{ current_twiddle.i, -current_twiddle.r }; data[k] = x1 + temp; data[N/2-k] = (x1 - temp).conj(); Twiddles<N/2>::advance(current_twiddle); //current_twiddle = current_twiddle * first_twiddle; } } inline static void apply_inverse(cpx* const data) { const unsigned long N = 1ul<<LOG_N; // Use 1D FFT result on packed to compute full FFT: cpx bias = data[0]; cpx last = data[N/2]; // Note: final element is not used, and so does not need to be // created; only create the first element. data[0].r = (bias.r + last.r)/2.0; data[0].i = (bias.r - last.r)/2.0; // Unnecessary, but tidy: data[N/2] = cpx{0.0,0.0}; cpx current_twiddle{1.0,0.0}; Twiddles<N/2>::advance(current_twiddle); unsigned long k; for (k=1; k<=N/4; ++k) { cpx from_back = data[N/2-k].conj(); cpx x1 = 0.5*(data[k] + from_back); cpx temp = 0.5*(data[k] - from_back); // Perform cpx x2 = temp / currentTwiddle (where twiddle is // first swapped to (i,-r) to match the forward version // apply(...), implemented above): cpx x2 = temp * cpx{current_twiddle.i, current_twiddle.r}; // Important: store data[k] after data[N/2-k] so that when k=N/4 // and both indices are the same, the data[k] version is used // (it will give the correct imaginary sign): data[N/2-k] = (x1 - x2).conj(); data[k] = x1 + x2; Twiddles<N/2>::advance(current_twiddle); // current_twiddle = current_twiddle * first_twiddle; } } }; template<> class RealFFTPostprocessor<0u> { public: // Note: Here N refers to the full length of the equivalent complex // FFT (as above): inline static void apply(cpx* const /*data*/) { } inline static void apply_inverse(cpx* const /*data*/) { } }; // Note: could specialize real postprocessing for small lengths. The // compiler may be able to do this automatically by simply unrolling // the loop, since the cpx operations are forced to be inline; // however, with FFT butterflies, explicitly specializing yielded a // small performance boost, so it may be similar here. #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/FFT/Twiddles.hpp
.hpp
2,071
63
#ifndef TWIDDLES_H #define TWIDDLES_H #define _USE_MATH_DEFINES #include <cmath> #include "cpx.hpp" template<unsigned long int N> class Twiddles { public: inline static void advance(cpx & current) { current += current * delta(); } inline static constexpr cpx delta() { // Used in the recurrence // current_twiddle += current_twiddle * delta, // which will produce the next twiddle on the unit circle. // Note that it would be mathematically equivalent to perform // current_twiddle *= simple_delta // where simple_delta = cpx{cos(), -sin()}. // However, when the FFT size is large, cos(2*pi / N) \approx 1, // and so signal is lost by using the // cosine. -2.0*squared(Twiddles<N*2>::sin()) equals 1-cos(2*pi/N) // (see below). However, to get the numeric benefit, the 1 must // not be added (leaving -cos(2*pi/N)). Thus advancing // current_twiddle = current_twiddle * naive_delta is equivalent // to assigning current_twiddle = current_twiddle * (delta-1) + // current_twiddle which is the same as current_twiddle += // current_twiddle * delta. // This final form leaves the real and imag parts of the delta // close to zero but applies a recurrence equivalent to the naive. return cpx{-2.0*squared(Twiddles<N*2>::sin()), -sin()}; // Derivation of why cos(theta)-1 = -2*sin(theta/2)**2: // Using naive recurrence above: // ( cos(theta/2) + sin(theta/2)j ) **2 --> // ( cos(theta) + sin(theta)j ). // Thus cos(theta) = cos(theta/2)**2 - sin(theta/2)**2. // Also, 1 = cos(theta/2)**2 + sin(theta/2)**2. // subtracting the 1 =... equation from the cos(theta) // =... equation yields // cos(theta)-1 = -2*sin(theta/2)**2. } inline static constexpr double sin() { return ::sin(M_PI/N); } inline static constexpr double cos() { // return ::cos(M_PI/N); // Reduces to sin() calls: return 1-2.0*squared(Twiddles<N*2>::sin()); } protected: inline static constexpr double squared(double x) { return x*x; } }; #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/FFT/cpx.hpp
.hpp
2,440
109
#ifndef _CPX_HPP #define _CPX_HPP #include <ostream> // in MSVC M_PI constant is non-standard #define _USE_MATH_DEFINES #include <math.h> struct cpx { static constexpr double PrintEpsilon = 1e-12; double r; double i; constexpr cpx(): r(0.0), i(0.0) { } constexpr cpx(double rVal): r(rVal), i(0.0) { } constexpr cpx(double rVal, double iVal): r(rVal), i(iVal) { } EVERGREEN_ALWAYS_INLINE cpx operator+=(cpx rhs){ r += rhs.r; i += rhs.i; return *this; } EVERGREEN_ALWAYS_INLINE cpx operator-=(cpx rhs){ r -= rhs.r; i -= rhs.i; return *this; } // Slightly faster than * operator (needs only one temporary double): EVERGREEN_ALWAYS_INLINE const cpx & operator *=(cpx rhs) { double temp = r; r *= rhs.r; r -= i*rhs.i; i = temp*rhs.i+i*rhs.r; return *this; } EVERGREEN_ALWAYS_INLINE const cpx & operator *=(double scale) { r *= scale; i *= scale; return *this; } EVERGREEN_ALWAYS_INLINE const cpx & operator /=(double denom) { denom = 1.0/denom; r *= denom; i *= denom; return *this; } EVERGREEN_ALWAYS_INLINE cpx conj() const { return cpx{r, -i}; } }; EVERGREEN_ALWAYS_INLINE cpx operator *(cpx lhs, cpx rhs) { // Gauss' method for multiplying complex numbers turns out not to be // faster after compiler optimizations; here is the naive method: return cpx{lhs.r*rhs.r-lhs.i*rhs.i, lhs.r*rhs.i+lhs.i*rhs.r}; } EVERGREEN_ALWAYS_INLINE cpx operator *(double lhs, cpx rhs) { rhs.r *= lhs; rhs.i *= lhs; return rhs; } EVERGREEN_ALWAYS_INLINE cpx operator -(cpx lhs, cpx rhs){ return cpx{lhs.r-rhs.r, lhs.i-rhs.i}; } EVERGREEN_ALWAYS_INLINE cpx operator +(cpx lhs, cpx rhs){ return cpx{lhs.r+rhs.r, lhs.i+rhs.i}; } EVERGREEN_ALWAYS_INLINE cpx operator /(cpx lhs, double rhs) { lhs.r /= rhs; lhs.i /= rhs; return lhs; } EVERGREEN_ALWAYS_INLINE bool operator ==(cpx lhs, cpx rhs){ return (lhs.r == rhs.r) && (lhs.i == rhs.i); } inline std::ostream & operator << (std::ostream & os, cpx cmplx) { if ( fabs(cmplx.r) >= cpx::PrintEpsilon && fabs(cmplx.i) >= cpx::PrintEpsilon ) { os << cmplx.r; if (cmplx.i > 0) os << '+'; os << cmplx.i << 'j' ; return os; } if ( fabs(cmplx.r) >= cpx::PrintEpsilon ) return ( os << cmplx.r ); if ( fabs(cmplx.i) >= cpx::PrintEpsilon ) return (os << cmplx.i << 'j' ); return (os << 0.0); } #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/FFT/FFT.hpp
.hpp
17,699
466
#ifndef _FFT_HPP #define _FFT_HPP // #include this file to import all FFT utilities from this // subdirectory. const unsigned char FFT1D_MAX_LOG_N = 16u; #include "../BitReversedShuffle/RecursiveShuffle.hpp" #include "DIF.hpp" #include "DIT.hpp" #include "../Tensor/Tensor.hpp" #include "shape_to_log_shape.hpp" #include <assert.h> // Note: template-recursive method may no longer be faster because you // could use the OpenMP SIMD pragma in an iterative implementation // Note that these are chosen to use Tensor rather than a TensorView // or WritableTensorView; even though views do not support striding, // they do allow the memory to be non-contiguous (in the case of // multidimensional FFT). For FFT performance, the data should be in a // contiguous block of memory. // FFT1D should be either DIF or DIT: template <template <unsigned char, bool> class FFT1D, bool SHUFFLE, bool UNDO_TRANSPOSE> class NDFFTEnvironment { public: // Wrapping in NDFFTEnvironment allows the following classes to only // depend on a single template parameter, LOG_NEXT_FROM_RIGHT; // therefore, it can be searched with LinearTemplateSearch: template<unsigned char LOG_N> class SingleFFT1D { public: inline static void apply(cpx* __restrict data) { FFT1D<LOG_N, SHUFFLE>::fft1d(data); } }; template<unsigned char LOG_N> class SingleIFFT1D { public: inline static void apply(cpx* __restrict data) { for (unsigned long k=0; k<(1ul<<LOG_N); ++k) data[k] = data[k].conj(); FFT1D<LOG_N, SHUFFLE>::fft1d(data); const double scale = 1.0 / (1ul<<LOG_N); for (unsigned long k=0; k<(1ul<<LOG_N); ++k) { data[k] = data[k].conj(); data[k] *= scale; } } }; template<unsigned char LOG_N> class RowFFTs { public: inline static void apply(cpx* __restrict data, const unsigned long flat, const bool freshly_zero_padded) { // Row FFTs: unsigned long k; for (k=0; k<(flat>>1); k+=(1ul<<LOG_N)) FFT1D<LOG_N, SHUFFLE>::fft1d(data+k); if ( ! freshly_zero_padded ) for (; k<flat; k+=(1ul<<LOG_N)) FFT1D<LOG_N, SHUFFLE>::fft1d(data+k); } }; // Note: not needed for ND IFFT (which conjugates, perform ND FFTs, // conjugates, and scales), but used for consistency so that 1D FFTs // have an easy access point for performing 1D FFTs and IFFTs (with // only one template parameter, LOG_N, allowing use of // LinearTemplateSearch); this can reduce overhead when a 1D FFT or // iFFT is needed. template<unsigned char LOG_N> class RowIFFTs { public: inline static void apply(cpx* __restrict data, const unsigned long flat) { for (unsigned long k=0; k<flat; ++k) data[k] = data[k].conj(); RowFFTs<LOG_N>::apply(data, flat, false); const double scale = 1.0 / flat; for (unsigned long k=0; k<flat; ++k) { data[k] = data[k].conj(); data[k] *= scale; } } }; // Note: it may be possible to exploit freshly_zero_padded for a // speedup in this transposition code as well: template<unsigned char LOG_NEXT_FROM_RIGHT> static void transpose_so_next_dimension_becomes_row(cpx* __restrict & data, cpx* __restrict & buffer, const unsigned long flat, const unsigned long prod_shape_from_right) { if ((1ul<<LOG_NEXT_FROM_RIGHT) > 1 && prod_shape_from_right > 1) { for (unsigned long k=0; k<flat; k+=(1ul<<LOG_NEXT_FROM_RIGHT)*prod_shape_from_right) MatrixTranspose<cpx>::apply_buffered(buffer + k, data + k, 1ul<<LOG_NEXT_FROM_RIGHT, prod_shape_from_right); std::swap(data, buffer); } } template<unsigned char LOG_NEXT_FROM_RIGHT> static void undo_transpositions(cpx* __restrict & data, cpx* __restrict & buffer, const unsigned long flat, const unsigned long prod_shape_from_right) { if ((1ul<<LOG_NEXT_FROM_RIGHT) > 1 && prod_shape_from_right > 1) { for (unsigned long k=0; k<flat; k+=(1ul<<LOG_NEXT_FROM_RIGHT)*prod_shape_from_right) MatrixTranspose<cpx>::apply_buffered(buffer + k, data + k, prod_shape_from_right, 1ul<<LOG_NEXT_FROM_RIGHT); std::swap(data, buffer); } } template<unsigned char LOG_NEXT_FROM_RIGHT> class RowFFTsAndTransposes { public: inline static void apply(cpx* __restrict & data, cpx* __restrict & buffer, const unsigned long flat, const unsigned long prod_shape_from_right) { // Transpose: transpose_so_next_dimension_becomes_row<LOG_NEXT_FROM_RIGHT>(data, buffer, flat, prod_shape_from_right); // Row FFTs: RowFFTs<LOG_NEXT_FROM_RIGHT>::apply(data, flat, false); // Undo transpose: if (UNDO_TRANSPOSE) undo_transpositions<LOG_NEXT_FROM_RIGHT>(data, buffer, flat, prod_shape_from_right); } }; template<unsigned char LOG_N> class SingleRealFFT1D { public: inline static void apply(cpx* __restrict data) { FFT1D<LOG_N, SHUFFLE>::real_fft1d_packed(data); } }; template<unsigned char LOG_N> class SingleRealIFFT1D { public: inline static void apply(cpx* __restrict data) { FFT1D<LOG_N, SHUFFLE>::real_ifft1d_packed(data); } }; template<unsigned char LOG_N> class RealRowFFTs { public: inline static void apply(cpx* __restrict data, const unsigned long flat, const bool freshly_zero_padded) { // This will only be performed on final axis, so do not bother // transposing. // Row FFTs: const unsigned long SINGLE_FFT_LEN = real_length_to_packed_length(1ul<<LOG_N); unsigned long k; for (k=0; k<flat>>1; k+=SINGLE_FFT_LEN) FFT1D<LOG_N, SHUFFLE>::real_fft1d_packed(data+k); if ( ! freshly_zero_padded ) for (; k<flat; k+=SINGLE_FFT_LEN) FFT1D<LOG_N, SHUFFLE>::real_fft1d_packed(data+k); } }; template<unsigned char LOG_N> class RealRowIFFTs { public: inline static void apply(cpx* __restrict data, const unsigned long flat) { // This will only be performed on final axis, so do not bother // transposing. // Row IFFTs: const unsigned long SINGLE_FFT_LEN = real_length_to_packed_length(1ul<<LOG_N); for (unsigned long k=0; k<flat; k+=SINGLE_FFT_LEN) FFT1D<LOG_N, SHUFFLE>::real_ifft1d_packed(data+k); } }; // This class is for performing a full multidimensional FFT by // moving right to left, performing row FFTs and transposing as // necessary: class NDFFT { public: inline static void fft(cpx* __restrict & data, cpx* __restrict & buffer, const unsigned char* __restrict const log_shape, int dimension, const bool freshly_zero_padded) { unsigned long flat = 1ul<<sum(log_shape, dimension); unsigned long prod_shape_from_right=1; if (dimension > 0) { // Apply last axis using freshly_zero_padded: LinearTemplateSearch<0u, FFT1D_MAX_LOG_N, RowFFTs >::apply(log_shape[dimension-1], data, flat, freshly_zero_padded); prod_shape_from_right *= (1ul<<log_shape[dimension-1]); // Other axes no longer guarantee freshly_zero_padded: --dimension; for (; dimension>0; --dimension) { LinearTemplateSearch<0u, FFT1D_MAX_LOG_N, RowFFTsAndTransposes >::apply(log_shape[dimension-1], data, buffer, flat, prod_shape_from_right); prod_shape_from_right *= (1ul<<log_shape[dimension-1]); } } } inline static void ifft(cpx* __restrict & data, cpx* __restrict & buffer, const unsigned char* __restrict const log_shape, int dimension) { unsigned long flat = 1ul<<sum(log_shape, dimension); // Conjugate: for (unsigned long k=0; k<flat; ++k) data[k] = data[k].conj(); // FFT: fft(data, buffer, log_shape, dimension, false); // Conjugate and scale: const double scale = 1.0 / flat; for (unsigned long k=0; k<flat; ++k) { data[k] = data[k].conj(); data[k] *= scale; } } inline static void real_fft_packed(cpx* __restrict & data, cpx* __restrict & buffer, const unsigned char* __restrict const log_shape, int dimension, const bool freshly_zero_padded) { unsigned long prod_shape_from_right = real_length_to_packed_length(1ul<<log_shape[dimension-1]); unsigned long flat = (1ul<<sum(log_shape, dimension-1))*prod_shape_from_right; // axis dimension-1 performed on reals: if (dimension > 0) { --dimension; // Final axis can use freshly_zero_padded: // Force SHUFFLE=true: LinearTemplateSearch<0u, FFT1D_MAX_LOG_N, NDFFTEnvironment<FFT1D, true, UNDO_TRANSPOSE>::template RealRowFFTs>::apply(log_shape[dimension], data, flat, freshly_zero_padded); // Remaining axes use freshly_zero_padded = false: for (; dimension>0; --dimension) { LinearTemplateSearch<0u, FFT1D_MAX_LOG_N, RowFFTsAndTransposes >::apply(log_shape[dimension-1], data, buffer, flat, prod_shape_from_right); prod_shape_from_right *= (1ul<<log_shape[dimension-1]); } } } inline static void real_ifft_packed(cpx* __restrict & data, cpx* __restrict & buffer, const unsigned char* __restrict const log_shape, int dimension) { unsigned long prod_shape_from_right, real_axis, flat; if (UNDO_TRANSPOSE) { real_axis = real_length_to_packed_length(1ul<<log_shape[dimension-1]); prod_shape_from_right = real_axis; flat = (1ul<<sum(log_shape, dimension-1))*prod_shape_from_right; } else { real_axis = real_length_to_packed_length(1ul<<log_shape[0]); prod_shape_from_right = 1ul; flat = real_axis * (1ul<<sum(log_shape+1, dimension-1)); } // Real axis will been scaled; therefore, scale with length // flat/real_axis to fix remaining axes: const double scale = real_axis / double(flat); // 1.0 / length for (unsigned long k=0; k<flat; ++k) data[k] = data[k].conj(); if (UNDO_TRANSPOSE) { // Since inverse on real axis is not performed first, // conjugate: for (unsigned char dim=dimension-1; dim>=1; --dim) { LinearTemplateSearch<0u, FFT1D_MAX_LOG_N, RowFFTsAndTransposes >::apply(log_shape[dim-1], data, buffer, flat, prod_shape_from_right); prod_shape_from_right *= (1ul<<log_shape[dim-1]); } for (unsigned long k=0; k<flat; ++k) { data[k] = data[k].conj(); data[k] *= scale; } // Final axis was originally reals; however, it should be // performed last: // Force SHUFFLE=true: LinearTemplateSearch<0u, FFT1D_MAX_LOG_N, NDFFTEnvironment<FFT1D, true, UNDO_TRANSPOSE>::template RealRowIFFTs>::apply(log_shape[dimension-1], data, flat); } else { // When UNDO_TRANSPOSE is false, the first axis will contain // packed reals: for (unsigned char dim=dimension-1; dim>=1; --dim) { LinearTemplateSearch<0u, FFT1D_MAX_LOG_N, RowFFTsAndTransposes >::apply(log_shape[dim], data, buffer, flat, prod_shape_from_right); prod_shape_from_right *= (1ul<<log_shape[dim]); } for (unsigned long k=0; k<flat; ++k) { data[k] = data[k].conj(); data[k] *= scale; } // The order of all other axes has been reversed; swap the // first axis (the packed reals) with the block of all other // axes: if (real_axis > 1 && prod_shape_from_right > 1) { MatrixTranspose<cpx>::apply_buffered(buffer, data, real_axis, prod_shape_from_right); std::swap(data, buffer); } // Force SHUFFLE=true: LinearTemplateSearch<0u, FFT1D_MAX_LOG_N, NDFFTEnvironment<FFT1D, true, UNDO_TRANSPOSE>::template RealRowIFFTs>::apply(log_shape[0], data, flat); } } }; }; template <template <unsigned char, bool> class FFT1D, bool SHUFFLE, bool UNDO_TRANSPOSE, bool FORWARD_FFT, bool FRESHLY_ZERO_PADDED> inline void execute_fft(Tensor<cpx> & ten) { Vector<unsigned char> log_shape = shape_to_log_shape(ten.data_shape()); cpx* __restrict buffer_a = &ten[0ul]; // A buffer is necessary to perform transpositions: Tensor<cpx> buffer(ten.data_shape()); cpx* __restrict buffer_b = &buffer[0ul]; if (FORWARD_FFT) NDFFTEnvironment<FFT1D, SHUFFLE, UNDO_TRANSPOSE>::NDFFT::fft(buffer_a, buffer_b, &log_shape[0], ten.dimension(), FRESHLY_ZERO_PADDED); else NDFFTEnvironment<FFT1D, SHUFFLE, UNDO_TRANSPOSE>::NDFFT::ifft(buffer_a, buffer_b, &log_shape[0], ten.dimension()); // buffer_a is the destination; if, after swapping, buffer_a is // not the same as the pointer used in ten, then swap: if (buffer_a != &ten[0ul]) ten = std::move(buffer); if ( ! UNDO_TRANSPOSE ) // Axes have been reversed: ten.reshape( reversed(ten.data_shape()) ); } template <template <unsigned char, bool> class FFT1D, bool SHUFFLE, bool UNDO_TRANSPOSE, bool FORWARD_FFT, bool FRESHLY_ZERO_PADDED> void execute_real_fft_packed(Tensor<cpx> & ten) { Vector<unsigned char> log_shape; if (UNDO_TRANSPOSE || FORWARD_FFT) // packed reals are on final axis: log_shape = packed_shape_to_log_shape(ten.data_shape()); else // packed reals are on first axis: log_shape = reversed_packed_shape_to_log_shape(ten.data_shape()); cpx* __restrict buffer_a = &ten[0ul]; // A buffer is necessary to perform transpositions: Tensor<cpx> buffer(ten.data_shape()); cpx* __restrict buffer_b = &buffer[0ul]; if (FORWARD_FFT) NDFFTEnvironment<FFT1D, SHUFFLE, UNDO_TRANSPOSE>::NDFFT::real_fft_packed(buffer_a, buffer_b, &log_shape[0], ten.dimension(), FRESHLY_ZERO_PADDED); else { NDFFTEnvironment<FFT1D, SHUFFLE, UNDO_TRANSPOSE>::NDFFT::real_ifft_packed(buffer_a, buffer_b, &log_shape[0], ten.dimension()); } if (buffer_a != &ten[0ul]) ten = std::move(buffer); if ( ! UNDO_TRANSPOSE ) // Axes have been reversed: ten.reshape( reversed(ten.data_shape()) ); } template <template <unsigned char, bool> class FFT1D, bool SHUFFLE, bool UNDO_TRANSPOSE, bool FRESHLY_ZERO_PADDED=false> inline void apply_fft(Tensor<cpx> & ten) { if (ten.dimension() == 0 || ten.flat_size() == 0) { } else if (ten.dimension() == 1) LinearTemplateSearch<0u, FFT1D_MAX_LOG_N, NDFFTEnvironment<FFT1D, SHUFFLE, false>::template SingleFFT1D >::apply(log2(ten.flat_size()), &ten[0ul]); else execute_fft<FFT1D, SHUFFLE, UNDO_TRANSPOSE, true, FRESHLY_ZERO_PADDED>(ten); } template <template <unsigned char, bool> class FFT1D, bool SHUFFLE, bool UNDO_TRANSPOSE> void apply_ifft(Tensor<cpx> & ten) { if (ten.dimension() == 0 || ten.flat_size() == 0) { } else if (ten.dimension() == 1) LinearTemplateSearch<0u, FFT1D_MAX_LOG_N, NDFFTEnvironment<FFT1D, SHUFFLE, false>::template SingleIFFT1D >::apply(log2(ten.flat_size()), &ten[0ul]); else execute_fft<FFT1D, SHUFFLE, UNDO_TRANSPOSE, false, false>(ten); } template <template <unsigned char, bool> class FFT1D, bool SHUFFLE, bool UNDO_TRANSPOSE, bool FRESHLY_ZERO_PADDED=false> Tensor<cpx> fft(Tensor<cpx> ten) { Tensor<cpx> ten_prime = ten; apply_fft<FFT1D, SHUFFLE, UNDO_TRANSPOSE, FRESHLY_ZERO_PADDED>(ten); return ten; } template <template <unsigned char, bool> class FFT1D, bool SHUFFLE, bool UNDO_TRANSPOSE> Tensor<cpx> ifft(Tensor<cpx> ten) { apply_ifft<FFT1D, SHUFFLE, UNDO_TRANSPOSE>(ten); return ten; } template <template <unsigned char, bool> class FFT1D, bool SHUFFLE, bool UNDO_TRANSPOSE, bool FRESHLY_ZERO_PADDED=false> void apply_real_fft_packed(Tensor<cpx> & ten) { if (ten.dimension() == 0 || ten.flat_size() == 0) { } else if (ten.dimension() == 1) LinearTemplateSearch<0u, FFT1D_MAX_LOG_N, NDFFTEnvironment<FFT1D, true, UNDO_TRANSPOSE>::template SingleRealFFT1D >::apply(integer_log2( packed_length_to_real_length(ten.flat_size()) ), &ten[0ul]); else execute_real_fft_packed<FFT1D, SHUFFLE, UNDO_TRANSPOSE, true, FRESHLY_ZERO_PADDED>(ten); } template <template <unsigned char, bool> class FFT1D, bool SHUFFLE, bool UNDO_TRANSPOSE> void apply_real_ifft_packed(Tensor<cpx> & ten) { if (ten.dimension() == 0 || ten.flat_size() == 0) { } else if (ten.dimension() == 1) LinearTemplateSearch<0u, FFT1D_MAX_LOG_N, NDFFTEnvironment<FFT1D, true, UNDO_TRANSPOSE>::template SingleRealIFFT1D >::apply(integer_log2( packed_length_to_real_length(ten.flat_size()) ), &ten[0ul]); else execute_real_fft_packed<FFT1D, SHUFFLE, UNDO_TRANSPOSE, false, false>(ten); } template <template <unsigned char, bool> class FFT1D, bool SHUFFLE, bool UNDO_TRANSPOSE, bool FRESHLY_ZERO_PADDED=false> Tensor<cpx> real_fft(const Tensor<double> & ten) { if (ten.dimension() == 0) return Tensor<cpx>(); Vector<unsigned long> shape = ten.data_shape(); shape[shape.size()-1] = real_length_to_packed_length(shape[shape.size()-1])*2; Tensor<double> larger(std::move(shape)); embed(larger, ten); Tensor<cpx> packed = Tensor<cpx>::create_reinterpreted(std::move(larger)); apply_real_fft_packed<FFT1D, SHUFFLE, UNDO_TRANSPOSE, FRESHLY_ZERO_PADDED>(packed); return packed; } template <template <unsigned char, bool> class FFT1D, bool SHUFFLE, bool UNDO_TRANSPOSE> Tensor<double> real_ifft(const Tensor<cpx> & ten) { if (ten.dimension() == 0) return Tensor<double>(); Tensor<cpx> larger = ten; apply_real_ifft_packed<FFT1D, SHUFFLE, UNDO_TRANSPOSE>(larger); Tensor<double> larger_reals = Tensor<double>::create_reinterpreted(std::move(larger)); Vector<unsigned long> shape; if (UNDO_TRANSPOSE) shape = ten.data_shape(); else shape = reversed(ten.data_shape()); shape[shape.size()-1] = packed_length_to_real_length(shape[shape.size()-1]); Tensor<double> smaller(std::move(shape)); // Cut slice of larger into smaller (this could also be done by // creating a TensorView of larger from {0,0,...} to // smaller.data_shape() and then calling embed): apply_tensors([](double & small_val, double large_val){ small_val = large_val; }, smaller.data_shape(), smaller, larger_reals); return smaller; } // Note: there is a small unexploited speedup that would detect when // any axes have length 1, and would perform the equivalent FFT with // those axes removed. The result will be the same, but it will be // faster. #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/Convolution/naive_convolve.hpp
.hpp
4,628
122
#ifndef _NAIVE_CONVOLVE_HPP #define _NAIVE_CONVOLVE_HPP #include "../Tensor/Tensor.hpp" #include "custom_pow.hpp" // O(n^2); use for testing and on small problems: template <typename T> Tensor<T> naive_convolve(const Tensor<T> & lhs, const Tensor<T> & rhs) { #ifdef SHAPE_CHECK assert(lhs.dimension() == rhs.dimension()); assert(lhs.data_shape() + rhs.data_shape() >= 1ul); #endif if (lhs.dimension() == 0) return Tensor<T>(); Tensor<T> result(lhs.data_shape() + rhs.data_shape() - 1ul); Vector<unsigned long> counter_result(result.dimension()); enumerate_for_each_tensors([&counter_result, &result, &rhs](const_tup_t counter_lhs, const unsigned char /*dim_lhs*/, T lhs_val) { enumerate_for_each_tensors([&counter_result, &result, &rhs, &counter_lhs, &lhs_val](const_tup_t counter_rhs, const unsigned char dim_rhs, T rhs_val) { for (unsigned char i=0; i<dim_rhs; ++i) counter_result[i] = counter_lhs[i] + counter_rhs[i]; unsigned long result_flat = tuple_to_index(counter_result, result.data_shape(), dim_rhs); result[result_flat] += lhs_val * rhs_val; }, rhs.data_shape(), rhs); }, lhs.data_shape(), lhs); return result; } template <typename T> Tensor<T> naive_max_convolve(const Tensor<T> & lhs, const Tensor<T> & rhs) { #ifdef SHAPE_CHECK assert(lhs.dimension() == rhs.dimension()); assert(lhs.data_shape() + rhs.data_shape() >= 1ul); #endif if (lhs.dimension() == 0) return Tensor<T>(); Tensor<T> result(lhs.data_shape() + rhs.data_shape() - 1ul); Vector<unsigned long> counter_result(result.dimension()); enumerate_for_each_tensors([&counter_result, &result, &rhs](const_tup_t counter_lhs, const unsigned char /*dim_lhs*/, T lhs_val) { enumerate_for_each_tensors([&counter_result, &result, &rhs, &counter_lhs, &lhs_val](const_tup_t counter_rhs, const unsigned char dim_rhs, T rhs_val) { for (unsigned char i=0; i<dim_rhs; ++i) counter_result[i] = counter_lhs[i] + counter_rhs[i]; unsigned long result_flat = tuple_to_index(counter_result, result.data_shape(), dim_rhs); result[result_flat] = std::max(result[result_flat], lhs_val * rhs_val); }, rhs.data_shape(), rhs); }, lhs.data_shape(), lhs); return result; } template <typename T> Tensor<T> naive_p_convolve(const Tensor<T> & lhs, const Tensor<T> & rhs, double p_goal) { #ifdef SHAPE_CHECK assert(lhs.dimension() == rhs.dimension()); assert(lhs.data_shape() + rhs.data_shape() >= 1ul); #endif if (lhs.dimension() == 0) return Tensor<T>(); Tensor<T> max_result(lhs.data_shape() + rhs.data_shape() - 1ul); Vector<unsigned long> counter_result(max_result.dimension()); // For numeric stability, perform three passes. On the first pass, // perform max max-convolution (this gets the largest element of // each u vector). On the second pass, apply p-norm. On third pass, // scale by max value. enumerate_for_each_tensors( [&counter_result, &max_result, &rhs](const_tup_t counter_lhs, const unsigned char /*dim_lhs*/, T lhs_val) { enumerate_for_each_tensors([&counter_result, &max_result, &rhs, &counter_lhs, &lhs_val](const_tup_t counter_rhs, const unsigned char dim_rhs, T rhs_val) { for (unsigned char i=0; i<dim_rhs; ++i) counter_result[i] = counter_lhs[i] + counter_rhs[i]; unsigned long result_flat = tuple_to_index(counter_result, max_result.data_shape(), dim_rhs); max_result[result_flat] = std::max( max_result[result_flat], lhs_val*rhs_val ); }, rhs.data_shape(), rhs); }, lhs.data_shape(), lhs); Tensor<T> result(max_result.data_shape()); // Apply p-norms: enumerate_for_each_tensors([&counter_result, &result, &rhs, &max_result, &p_goal](const_tup_t counter_lhs, const unsigned char /*dim_lhs*/, T lhs_val) { enumerate_for_each_tensors([&counter_result, &result, &rhs, &counter_lhs, &lhs_val, &max_result, &p_goal](const_tup_t counter_rhs, const unsigned char dim_rhs, T rhs_val) { for (unsigned char i=0; i<dim_rhs; ++i) counter_result[i] = counter_lhs[i] + counter_rhs[i]; unsigned long result_flat = tuple_to_index(counter_result, result.data_shape(), dim_rhs); // Note: using tau_denom is too conservative, but it may be // good to use some numeric epsilon here. if (max_result[result_flat] > 0.0) result[result_flat] += custom_pow(lhs_val * rhs_val / max_result[result_flat], p_goal); }, rhs.data_shape(), rhs); }, lhs.data_shape(), lhs); for (unsigned long k=0; k<result.flat_size(); ++k) result[k] = custom_pow(result[k], 1.0/p_goal); result.flat() *= max_result.flat(); return result; } #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/Convolution/any_and_all.hpp
.hpp
346
19
#ifndef _ANY_AND_ALL_HPP #define _ANY_AND_ALL_HPP inline bool any(const Vector<bool> & rhs) { for (unsigned long k=0; k<rhs.size(); ++k) if (rhs[k]) return true; return false; } inline bool all(const Vector<bool> & rhs) { for (unsigned long k=0; k<rhs.size(); ++k) if (! rhs[k]) return false; return true; } #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/Convolution/p_convolve.hpp
.hpp
22,229
546
#ifndef _P_CONVOLVE_HPP #define _P_CONVOLVE_HPP // See Pfeuffer and Serang 2016 JMLR for details. Note that this // implementation does not yet perform the linear regression // correction from the reference above (which would further improve // accuracy). #include <array> #include <set> #include "naive_convolve.hpp" #include "fft_convolve.hpp" // Used in numeric p-convolution: const double tau_denom = 1e-9; // Empirically chosen runtime constant of FFT convolution: const double FFT_CONV_RUNTIME_CONSTANT = 10.0; // Speedup in runtime constant of naive when p=1 or p=inf relative to // naive for arbitrary p (because they do not need to compute pow): const double SPEEDUP_OF_NAIVE_P1_OR_PINF = 2.0; // The reasoning behind possible choices of p^*_max is described in // Pfeuffer and Serang 2016 JMLR (it is a heuristically reasonable // compromise between accuracy and speed): const double MAX_P_NUMERIC = log2(0.7) / log2(0.999) * 2; inline Tensor<double> fft_p_convolve_to_p(const Tensor<double> & lhs, const Tensor<double> & rhs, double p_goal) { // Note: does not check if values are nonnegative (this is done one // time in numeric_p_convolve so as to not check repeatedly). Tensor<double> lhs_pow = lhs, rhs_pow = rhs; for (unsigned long k=0; k<lhs_pow.flat_size(); ++k) lhs_pow[k] = custom_pow(lhs_pow[k], p_goal); for (unsigned long k=0; k<rhs_pow.flat_size(); ++k) rhs_pow[k] = custom_pow(rhs_pow[k], p_goal); Tensor<double> res = fft_convolve(lhs_pow, rhs_pow); for (unsigned long k=0; k<rhs_pow.flat_size(); ++k) res[k] = fabs(res[k]); return res; } // Note: this iterative method for computing pow makes the algorithm // in O(n log(n) |P|^2); however, this is still significantly faster // than using pow. inline double fast_pow_from_interleaved_p_index(double val, unsigned int p_ind) { for (unsigned int i=0; i<p_ind/2; ++i) val *= val; // Interleaved powers of 2: e.g., p=[1,1.5,2,3,4,6,8 ...], so // p_ind=5 corresponds to 6, which is not a power of 2, so perform // sqrt(val^3) for final step: // Faster version of if (p_ind % 2 == 1): if ( (p_ind & 1u) == 1) val = sqrt(val*val*val); return val; } inline Tensor<double> fft_p_convolve_to_p_from_p_index(const Tensor<double> & lhs, const Tensor<double> & rhs, unsigned int p_ind) { // Note: does not check if values are nonnegative (this is done one // time in numeric_p_convolve so as to not check repeatedly). // Note: could possibly pass these by reference to prevent multiple // allocations. Vector<unsigned long> conv_shape_doubles = padded_convolution_shape(lhs, rhs); Tensor<double> lhs_padded_doubles(conv_shape_doubles); Tensor<double> rhs_padded_doubles(conv_shape_doubles); // Embed in larger and take to p: apply_tensors([p_ind](double & lhs_padded, double lhs) { lhs_padded = fast_pow_from_interleaved_p_index(lhs, p_ind); }, lhs.view_shape(), lhs_padded_doubles, lhs); apply_tensors([p_ind](double & rhs_padded, double rhs) { rhs_padded = fast_pow_from_interleaved_p_index(rhs, p_ind); }, rhs.view_shape(), rhs_padded_doubles, rhs); Tensor<double> res = fft_convolve_already_padded_rvalue(std::move(lhs_padded_doubles), std::move(rhs_padded_doubles), lhs.data_shape() + rhs.data_shape() - 1ul); for (unsigned long k=0; k<res.flat_size(); ++k) res[k] = fabs(res[k]); return res; } inline Vector<double> interleaved_powers_of_2(unsigned int log_max_p) { Vector<double> result(2*log_max_p+1); // Length should be odd (final power of two will occur outside the loop): double val = 1.0; unsigned int k; for (k=0; k<(result.size()-1)/2; ++k) { result[2*k] = val; result[2*k+1] = val*1.5; val *= 2.0; } result[2*k] = val; return result; } inline double best_tau_fft_for_length(unsigned long flat_length) { // Note: Based on the empirical data (mentioned below), using a // statically defined tau of 1e-5 should be roughly large enough // for the largest supported FFT with length 2^32; however, it // will be unnecessarily strict //return 1e-5; // Based on empirical error data (using the maximum error from the // lowest and highest values in a list) on a large range of 1D // sizes. Note that there is likely a theoretical basis for // believing the error will grow logarithmically with the length, as // mentioned very briefly in Pfeuffer and Serang 2016. const double log_x1 = log(1e3); const double log_y1 = log(2e-12); const double min_tau = 1e-12; const double log_x2 = log(4e6); const double log_y2 = log(2e-8); const double slope = (log_y2-log_y1) / (log_x2-log_x1); const double bias = log_y1 - slope*log_x1; const double tau_val = exp(bias + slope*log(double(flat_length))); // Using 15* expected optimal tau value to be conservative in case // the log vs. log linear curve is slightly jagged or is slightly // concave up (also the benchmark data used to fit the error used // complex FFT convolution, whereas this now uses real FFT for real // convolutions, which uses a recurrence that lowers the accuracy // slightly compared to using a cache of complex exponentials). If // necessary, more recent empirical data can be taken. Also, note // that this may be conservative since it uses the flat size for // multidimensional problems (whereas it is unknown but possible // that the numeric stability may be limited by the largest axis, // etc.): // Note: the FFT estimates of the norms should be monotonic whenever // the FFT is stable (i.e., the p-norm should be >= the 2p-norm). If // not, the p-norm estimate may work, but the quadratic and linear // estimates may be unstable. return std::max(15*tau_val, min_tau); } inline static double linear_projection(const std::array<double,2> & norms, double p1, double p2, double p_goal) { // assumes norms[0] is not too close to zero (single stable norm should never = 0) double delta = p2-p1; double root = norms[1] / norms[0]; if ( fabs(root) < tau_denom ) // when it's unstable to solve the linear (via division), return // the p-norm estimate using the highest stable p (note that the // sequence of p was chosen to not exceed p_goal): return custom_pow(norms[1], 1.0/p2); double alpha = custom_pow(root, 1.0/delta); double n = norms[0] / custom_pow(alpha, p1); return alpha * custom_pow(n, 1.0/p_goal); } inline double check_nan_call_linear_projection(double val, const std::array<double,4> & norms, double p1, double p2, double p_goal){ if(std::isnan(val)){ const std::array<double,2> lin_norms{{norms[2], norms[3]}}; return linear_projection(lin_norms, p1, p2, p_goal); } return val; } inline double quadratic_projection(const std::array<double,4> & norms, double p1, double p2, double p_goal) { double delta = p2-p1; // Quadrataic coefficients from the null space of the matrix of norms: double c = norms[1]*norms[3] - norms[2]*norms[2]; double b = norms[1]*norms[2] - norms[0]*norms[3]; double a = norms[0]*norms[2] - norms[1]*norms[1]; // Solve c + b*x + a*x^2 == 0. if ( fabs(a) > tau_denom ) { double disc = b*b - 4*a*c; if ( disc >= 0.0 ) { double root1 = (-b + sqrt(disc)) / (2*a); double root2 = (-b - sqrt(disc)) / (2*a); if ( root1 >= 0.0 && root2 >= 0.0 ) { // only perform when numerically stable: double alpha1 = custom_pow(root1, 1.0/delta); double alpha2 = custom_pow(root2, 1.0/delta); // Ensure alpha1 > alpha2: if ( alpha2 > alpha1 ) std::swap(alpha1, alpha2); double alpha1_up_p1 = custom_pow(alpha1,p1); double alpha1_up_p2 = custom_pow(alpha1,p2); double alpha2_up_p1 = custom_pow(alpha2,p1); double alpha2_up_p2 = custom_pow(alpha2,p2); double denom = alpha1_up_p2*alpha2_up_p1 - alpha1_up_p1*alpha2_up_p2; if ( fabs(denom) > tau_denom ) { double n1 = ( norms[1]*alpha2_up_p1 - norms[0]*alpha2_up_p2 ) / denom; double n2 = ( norms[0]*alpha1_up_p2 - norms[1]*alpha1_up_p1 ) / denom; if ( alpha1 > tau_denom ) return check_nan_call_linear_projection(alpha1 * custom_pow( n1 + n2*custom_pow(alpha2/alpha1,p_goal), 1.0/p_goal ), norms, p1, p2, p_goal); return check_nan_call_linear_projection(custom_pow(n1 * custom_pow(alpha1,p_goal) + n2 * custom_pow(alpha2,p_goal), 1.0/p_goal), norms, p1, p2, p_goal); } } } } const std::array<double,2> lin_norms{{norms[2], norms[3]}}; return linear_projection(lin_norms, p1, p2, p_goal); } inline void compute_quadratic_projections(const std::vector<Tensor<double> > & p_index_to_norms, const Vector<double> & all_p, double p_goal, Tensor<double> & result, const Tensor<bool> & solved, const Tensor<int> & highest_stable_p_index) { // Note: It may potentially be worth tranposing so that norms for a // given index are in cache order. // Fill in remaining entries in result: for (unsigned long i=0; i<result.flat_size(); ++i) if ( ! solved[i] ) { // Compute quadratic projection of p-norm: int highest_stable = highest_stable_p_index[i]; double result_at_index; // Powers of 2 are even indices (highest in sequence of 4 // evenly spaced points must be a power of 2): // Note: it may be more efficient to replace this if...else // ladder with a switch statement: // Use & 1 as a faster replacement for % 2: if (highest_stable >= 4 && (highest_stable & 1u) == 0) { // 5 points available {0,1,2,3,4,...} --> 4 evenly spaced points std::array<double, 4> norms{{p_index_to_norms[highest_stable-4][i],p_index_to_norms[highest_stable-2][i],p_index_to_norms[highest_stable-1][i],p_index_to_norms[highest_stable][i]}}; result_at_index = quadratic_projection(norms, all_p[highest_stable-1], all_p[highest_stable], p_goal); } // Use & 1 as a faster replacement for % 2: else if (highest_stable >= 5 && (highest_stable & 1u) == 1) { // Use highest_stable-1, since you're dropping by 1 to reach the next power of 2: std::array<double, 4> norms{{p_index_to_norms[highest_stable-5][i],p_index_to_norms[highest_stable-3][i],p_index_to_norms[highest_stable-2][i],p_index_to_norms[highest_stable-1][i]}}; result_at_index = quadratic_projection(norms, all_p[highest_stable-2], all_p[highest_stable-1], p_goal); } else if (highest_stable >= 1) { // 2 evenly points available std::array<double, 2> norms{{p_index_to_norms[highest_stable-1][i],p_index_to_norms[highest_stable][i]}}; result_at_index = linear_projection(norms, all_p[highest_stable-1], all_p[highest_stable], p_goal); } else { // only one point stable // TODO: could divide by length of u vector to improve error: // (\| u \|_p^p / len(u))^(1/p) result_at_index = custom_pow(p_index_to_norms[highest_stable][i], 1.0/all_p[highest_stable]); } result[i] = result_at_index; } } // Note: This function is slow, but it should be called quite rarely. inline double naive_p_convolve_at_index(const Tensor<double> & lhs, const Tensor<double> & rhs, const Vector<unsigned long> & ind, double p_goal) { double max_val = 0.0; Vector<unsigned long> rhs_ind(ind.size()); enumerate_for_each_tensors([&ind, &rhs_ind, &rhs, &max_val](const_tup_t lhs_tup, const unsigned char dim, double lhs_val){ for (unsigned char i=0; i<dim; ++i) rhs_ind[i] = ind[i] - lhs_tup[i]; // Note: Using TensorView once would be much faster: if (rhs_ind < rhs.data_shape()) max_val = std::max(max_val, lhs_val*rhs[rhs_ind]); }, lhs.data_shape(), lhs); if (max_val == 0.0) return max_val; // Divide by max_val before taking to power p_goal to preserve precision: double res = 0.0; enumerate_for_each_tensors([&ind, &rhs_ind, &rhs, max_val, &res, p_goal](const_tup_t lhs_tup, const unsigned char dim, double lhs_val){ for (unsigned char i=0; i<dim; ++i) rhs_ind[i] = ind[i] - lhs_tup[i]; // Note: Using TensorView once would be much faster: if (rhs_ind < rhs.data_shape()) res += custom_pow(lhs_val*rhs[rhs_ind]/max_val, p_goal); }, lhs.data_shape(), lhs); return max_val*custom_pow(res, 1.0/p_goal); } inline void perform_affine_correction(const Tensor<double> & lhs, const Tensor<double> & rhs, const double p_goal, const Tensor<int> & highest_stable_p_index, Tensor<double> & result) { // Note: for greater performance, this could be a bitset: std::set<int> used_p_indices; for (unsigned long i=0; i<result.flat_size(); ++i) used_p_indices.insert(highest_stable_p_index[i]); for (int p_ind : used_p_indices) { // Find min and max result values and their tuple indices: double min_res_in_contour = std::numeric_limits<double>::infinity(); Vector<unsigned long> min_index(result.dimension()); double max_res_in_contour = 0.0; Vector<unsigned long> max_index(result.dimension()); enumerate_for_each_tensors([&min_res_in_contour, &min_index, &max_res_in_contour, &max_index, p_ind](const_tup_t tup, const unsigned char dim, double res_val, int res_p_ind) { if (res_p_ind == p_ind) { if (res_val < min_res_in_contour) { min_res_in_contour = res_val; for (unsigned char i=0; i<dim; ++i) min_index[i] = tup[i]; } if (res_val > max_res_in_contour) { max_res_in_contour = res_val; for (unsigned char i=0; i<dim; ++i) max_index[i] = tup[i]; } } }, result.data_shape(), result, highest_stable_p_index); // Compute exact p-convolution at min_index and max_index: double exact_at_min_index = naive_p_convolve_at_index(lhs, rhs, min_index, p_goal); double exact_at_max_index = naive_p_convolve_at_index(lhs, rhs, max_index, p_goal); const double denom = max_res_in_contour - min_res_in_contour; if (denom > tau_denom) { const double contour_slope = (exact_at_max_index - exact_at_min_index) / denom; // new_est = contour_bias + contour_slope * old_est // new_est = exact_at_min_index + contour_slope * (old_est - min_res_in_contour) // contour_bias = exact_at_min_index - contour_slope*min_res_in_contour const double contour_bias = exact_at_min_index - contour_slope*min_res_in_contour; for (unsigned long i=0; i<result.flat_size(); ++i) { if (highest_stable_p_index[i] == p_ind) { double & res_val = result[i]; res_val = contour_bias + res_val*contour_slope; } } } } } inline Tensor<double> numeric_p_convolve_helper(const Tensor<double> & lhs, const Tensor<double> & rhs, double max_p, double p_goal) { if (p_goal >= 1.0) { // Note: max_p should already be <= p_goal unsigned int log_max_p = log2(max_p); Vector<double> all_p = interleaved_powers_of_2( log_max_p ); double tau_fft = best_tau_fft_for_length( std::max(lhs.flat_size(), rhs.flat_size()) ); Vector<unsigned long> res_shape = lhs.data_shape() + rhs.data_shape() - 1ul; Tensor<int> highest_stable_p_index(res_shape); // Use std::vector as a container: Vector<T> is for numeric T types // only and does not call constructors, etc.: std::vector<Tensor<double> > p_index_to_norms(all_p.size()); // Initialized to false, since default value is 0: Tensor<bool> solved(res_shape); Tensor<double> result; // Note: isinf may not work on every compiler when aggressive // optimizations are turned on: if ( ! std::isinf(p_goal) ) { /* p-norm is not included in powers of two sequence. therefore, try p-norm directly here (you may get lucky and have all results numerically stable with p, and so you only need a single FFT) */ // Note: can avoid ^p when p is a power of 2 here: result = fft_p_convolve_to_p(lhs, rhs, p_goal); for (unsigned long k=0; k<result.flat_size(); ++k) if ( result[k] > tau_fft ) { result[k] = custom_pow(result[k], 1.0/p_goal); solved[k] = true; } if (all(solved.flat())) return result; // If p_goal is in the power of two sequence, then add it to the // collection so that the convolution is not recomputed: // (Do not use custom_pow, because it may be less stable) if ( 1ul<<(unsigned int)log_max_p == p_goal ) p_index_to_norms[p_index_to_norms.size()-1] = result; } else // result has not yet been allocated: result = Tensor<double>(res_shape); Tensor<bool> sufficient_for_projection = solved; // Note: this loop is a strong candidate for parallelization // (although it might require some massaging with OpenMP, since // this loop can return as soon as all indices have been // sufficiently computed) for (int p_ind=(int)all_p.size()-1; p_ind>=0; --p_ind) { // If p_goal is in all_p, it has already been added to p_index_to_norms: if ( all_p[p_ind] != p_goal ) { // The following replaces calling with pow: // p_index_to_norms[p_ind] = fft_p_convolve_to_p(lhs, rhs, p_ind); p_index_to_norms[p_ind] = fft_p_convolve_to_p_from_p_index(lhs, rhs, p_ind); } const Tensor<double> & row = p_index_to_norms[p_ind]; for (unsigned long k=0; k<highest_stable_p_index.flat_size(); ++k) if ( ! solved[k] ) // Since it is going in descending order, stop assigning to // highest_stable_p_index if it has already been assigned a // nonzero value: if ( highest_stable_p_index[k] == 0 && row[k] > tau_fft ) highest_stable_p_index[k] = p_ind; for (unsigned long k=0; k<highest_stable_p_index.flat_size(); ++k) // powers of 2 are the even indices (highest in sequence of 4 // evenly spaced points must be a power of 2): // Use & 1 == 0 as a faster replacement for % 2 == 0: if ( ( (highest_stable_p_index[k] & 1u) == 0 && highest_stable_p_index[k] - p_ind >= 5 ) || highest_stable_p_index[k] - p_ind >= 6 ) { sufficient_for_projection[k] = true; } // Check if enough contours of p have been solved at every index // so that the desired level of extrapolation; if so, break: // Note: A potentially large speedup may be possible here by // stopping once n - cardinality(sufficient_for_projection) is < // some constant; those remaining constant number of indices // could be solved each in O(n), potentially preventing a full // O(n log(n)) convolution from being computed for smaller // values of p. if (all(sufficient_for_projection.flat())) break; } compute_quadratic_projections(p_index_to_norms, all_p, p_goal, result, solved, highest_stable_p_index); perform_affine_correction(lhs, rhs, p_goal, highest_stable_p_index, result); return result; } else { #ifndef NUMERIC_CHECK // Note: Negative p_goal could be processed by taking 1.0/value // for each value and using positive p. assert(p_goal >= 0); #endif // p < 1 // Assume that for p<1, raw p-convolution (without piecewise) is // numerically stable (it will decrease the dynamic range of the data). Tensor<double> result = fft_p_convolve_to_p(lhs, rhs, p_goal); for (unsigned long i=0; i<result.flat_size(); ++i) result[i] = custom_pow(result[i], 1.0/p_goal); return result; } } inline Tensor<double> numeric_p_convolve(const Tensor<double> & lhs, const Tensor<double> & rhs, double p_goal) { #ifdef SHAPE_CHECK assert(lhs.dimension() == rhs.dimension()); #endif #ifdef NUMERIC_CHECK // Numeric p-convolution is only for nonnegative values; it may be // possible on all values by encoding the sign into complex numbers // and then performing a complex convolution instead of a real // convolution: assert( lhs.flat() >= 0.0 ); assert( rhs.flat() >= 0.0 ); // Note: When p_goal is negative, believe could use 1/lhs and 1/rhs with -p_goal: assert(p_goal > 0.0); #endif Vector<unsigned long> res_shape = lhs.data_shape() + rhs.data_shape() - 1ul; // Empirically, at a flat size of 64, the fft version becomes more // efficient than naive. But because of doubling all but the last // axis in real fft convolution (for zero padding), there is roughly // a 2^(dim-1) slowdown on fft version (using a linear runtime for // fft, which is realistic for small lengths where the log2 factor // should be negligable for an efficient implementation). unsigned long flat_size = flat_length(static_cast<unsigned long*>(res_shape), res_shape.size()); double max_p = std::min(p_goal, MAX_P_NUMERIC); double approx_fft_conv_runtime = flat_size*log2(flat_size)*log2(max_p)*FFT_CONV_RUNTIME_CONSTANT; double approx_naive_conv_runtime = flat_size*flat_size; if (p_goal == 1.0) { if ( approx_fft_conv_runtime*SPEEDUP_OF_NAIVE_P1_OR_PINF > approx_naive_conv_runtime ){ return naive_convolve(lhs, rhs); } } else if (std::isinf(p_goal)) { // When true max-convolution is wanted, then the cost of computing // naive version is slightly improved, because it does not need to // use pow function. if ( approx_fft_conv_runtime*SPEEDUP_OF_NAIVE_P1_OR_PINF > approx_naive_conv_runtime ){ return naive_max_convolve(lhs, rhs); } } else { if ( flat_size*log2(flat_size)*log2(max_p)*FFT_CONV_RUNTIME_CONSTANT > flat_size*flat_size ){ return naive_p_convolve(lhs, rhs, p_goal); } } double lhs_max = max(lhs.flat()); double rhs_max = max(rhs.flat()); // Don't divide by 0; if lhs_max or rhs_max == 0, return Tensor full of 0 values: if (lhs_max == 0.0 || rhs_max == 0.0) return Tensor<double>(lhs.data_shape() + rhs.data_shape() - 1ul); Tensor<double> lhs_prime = lhs; lhs_prime.flat() /= lhs_max; Tensor<double> rhs_prime = rhs; rhs_prime.flat() /= rhs_max; Tensor<double> res = numeric_p_convolve_helper(lhs_prime, rhs_prime, max_p, p_goal); res.flat() *= lhs_max*rhs_max; // Correct instability for values very close to zero: when the phase // can make the sign negative, force the value to be nonnegative: for (unsigned long k=0; k<res.flat_size(); ++k) res[k] = fabs(res[k]); return res; } #endif
Unknown
3D
OpenMS/OpenMS
src/openms/extern/evergreen/src/Convolution/custom_pow.hpp
.hpp
1,187
59
#ifndef _CUSTOM_POW_HPP #define _CUSTOM_POW_HPP // greater numeric stability than the one listed below: inline double fast_pow(double a, const double b) { // calculate approximation with just the fraction of the exponent int exp = (int) b; union { double d; int x[2]; } u = { a }; u.x[1] = (int)((b - exp) * (u.x[1] - 1072632447) + 1072632447); u.x[0] = 0; // exponentiation by squaring with the exponent's integer part // double r = u.d makes everything much slower, not sure why double r = 1.0; while (exp) { if (exp & 1) { r *= a; } a *= a; exp >>= 1; } return r * u.d; } inline double faster_pow(const double a, const double b) { union { double d; struct { int a; int b; } s; } u = { a }; u.s.b = (int)(b * (u.s.b - 1072632447) + 1072632447); u.s.a = 0; return u.d; } inline double custom_pow(double a, const double b) { #ifdef FASTER_POW #pragma message( "using faster pow" ) return faster_pow(a,b); #else #ifdef FAST_POW #pragma message( "using fast pow" ) return fast_pow(a,b); #else // #pragma message( "using pow" ) return pow(a,b); #endif #endif } #endif
Unknown