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/source/DATASTRUCTURES/DBoundingBox.cpp
.cpp
490
16
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: $ // -------------------------------------------------------------------------- #include <OpenMS/DATASTRUCTURES/DBoundingBox.h> namespace OpenMS { DBoundingBox<1> default_boundingbox_1; DBoundingBox<2> default_boundingbox_2; }
C++
3D
OpenMS/OpenMS
src/openms/source/DATASTRUCTURES/CVMappingTerm.cpp
.cpp
2,985
130
// 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 $ // -------------------------------------------------------------------------- #include <OpenMS/DATASTRUCTURES/CVMappingTerm.h> using namespace std; namespace OpenMS { // CV term implementation CVMappingTerm::CVMappingTerm() : use_term_name_(false), use_term_(false), is_repeatable_(false), allow_children_(false) { } CVMappingTerm::CVMappingTerm(const CVMappingTerm& rhs) = default; CVMappingTerm::~CVMappingTerm() = default; CVMappingTerm& CVMappingTerm::operator=(const CVMappingTerm& rhs) { if (this != &rhs) { accession_ = rhs.accession_; use_term_name_ = rhs.use_term_name_; use_term_ = rhs.use_term_; term_name_ = rhs.term_name_; is_repeatable_ = rhs.is_repeatable_; allow_children_ = rhs.allow_children_; cv_identifier_ref_ = rhs.cv_identifier_ref_; } return *this; } bool CVMappingTerm::operator==(const CVMappingTerm& rhs) const { return accession_ == rhs.accession_ && use_term_name_ == rhs.use_term_name_ && use_term_ == rhs.use_term_ && term_name_ == rhs.term_name_ && is_repeatable_ == rhs.is_repeatable_ && allow_children_ == rhs.allow_children_ && cv_identifier_ref_ == rhs.cv_identifier_ref_; } bool CVMappingTerm::operator!=(const CVMappingTerm& rhs) const { return !(*this == rhs); } void CVMappingTerm::setAccession(const String& accession) { accession_ = accession; } const String& CVMappingTerm::getAccession() const { return accession_; } void CVMappingTerm::setUseTermName(bool use_term_name) { use_term_name_ = use_term_name; } bool CVMappingTerm::getUseTermName() const { return use_term_name_; } void CVMappingTerm::setUseTerm(bool use_term) { use_term_ = use_term; } bool CVMappingTerm::getUseTerm() const { return use_term_; } void CVMappingTerm::setTermName(const String& term_name) { term_name_ = term_name; } const String& CVMappingTerm::getTermName() const { return term_name_; } void CVMappingTerm::setIsRepeatable(bool is_repeatable) { is_repeatable_ = is_repeatable; } bool CVMappingTerm::getIsRepeatable() const { return is_repeatable_; } void CVMappingTerm::setAllowChildren(bool allow_children) { allow_children_ = allow_children; } bool CVMappingTerm::getAllowChildren() const { return allow_children_; } void CVMappingTerm::setCVIdentifierRef(const String& cv_identifier_ref) { cv_identifier_ref_ = cv_identifier_ref; } const String& CVMappingTerm::getCVIdentifierRef() const { return cv_identifier_ref_; } } // namespace OpenMS
C++
3D
OpenMS/OpenMS
src/openms/source/DATASTRUCTURES/ToolDescription.cpp
.cpp
3,561
104
// 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 $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/LogStream.h> #include <OpenMS/DATASTRUCTURES/ToolDescription.h> using namespace std; namespace OpenMS { namespace Internal { // C'Tor with arguments ToolDescriptionInternal::ToolDescriptionInternal(const bool p_is_internal, const String& p_name, const String& p_category, const StringList& p_types) : is_internal(p_is_internal), name(p_name), category(p_category), types(p_types) { } ToolDescriptionInternal::ToolDescriptionInternal(const String& p_name, const StringList& p_types) : name(p_name), category(), types(p_types) { } bool ToolDescriptionInternal::operator==(const ToolDescriptionInternal& rhs) const { if (this == &rhs) return true; return is_internal == rhs.is_internal && name == rhs.name && category == rhs.category && types == rhs.types; } bool ToolDescriptionInternal::operator<(const ToolDescriptionInternal& rhs) const { if (this == &rhs) return false; return name + "." + ListUtils::concatenate(types, ",") < rhs.name + "." + ListUtils::concatenate(rhs.types, ","); } // C'Tor for internal TOPP tools ToolDescription::ToolDescription(const String& p_name, const String& p_category, const StringList& p_types) : ToolDescriptionInternal(true, p_name, p_category, p_types) { } void ToolDescription::addExternalType(const String& type, const ToolExternalDetails& details) { types.push_back(type); external_details.push_back(details); } void ToolDescription::append(const ToolDescription& other) { // sanity check if (is_internal != other.is_internal || name != other.name //|| category != other.category || (is_internal && !external_details.empty()) || (other.is_internal && !other.external_details.empty()) || (!is_internal && external_details.size() != types.size()) || (!other.is_internal && other.external_details.size() != other.types.size()) ) { throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Extending (external) ToolDescription failed!", ""); } // append types and external information types.insert(types.end(), other.types.begin(), other.types.end()); external_details.insert(external_details.end(), other.external_details.begin(), other.external_details.end()); // check that types are unique std::set<String> unique_check; unique_check.insert(types.begin(), types.end()); if (unique_check.size() != types.size()) { OPENMS_LOG_ERROR << "A type appears at least twice for the TOPP tool '" << name << "'. Types given are '" << ListUtils::concatenate(types, ", ") << "'\n"; if (name == "GenericWrapper") { OPENMS_LOG_ERROR << "Check the .ttd files in your share/ folder and remove duplicate types!\n"; } throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "see above!", ""); } } } Internal::ToolDescription bla; } // namespace OpenMS
C++
3D
OpenMS/OpenMS
src/openms/source/DATASTRUCTURES/DateTime.cpp
.cpp
7,503
320
// 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 $ // -------------------------------------------------------------------------- #include <OpenMS/DATASTRUCTURES/DateTime.h> #include <OpenMS/DATASTRUCTURES/String.h> #include <OpenMS/CONCEPT/Exception.h> #include <QtCore/QDateTime> // very expensive to include! using namespace std; namespace OpenMS { DateTime::DateTime() : dt_(new QDateTime) { } DateTime::DateTime(const DateTime& date) : dt_(new QDateTime(*date.dt_)) { } DateTime::DateTime(DateTime&& rhs) noexcept : dt_(rhs.dt_.release()) { } DateTime& DateTime::operator=(const DateTime& source) { if (&source == this) { return *this; } if (dt_ == nullptr) { // *this is in a 'moved-from' state; we need to create a dt_ object first dt_ = make_unique<QDateTime>(*source.dt_); } else { *dt_ = *source.dt_; } return *this; } DateTime& DateTime::operator=(DateTime&& source) & noexcept { if (&source == this) { return *this; } std::swap(dt_, source.dt_); return *this; } DateTime::~DateTime() = default; bool DateTime::operator==(const DateTime& rhs) const { return (*dt_ == *rhs.dt_); } bool DateTime::operator!=(const DateTime& rhs) const { return !(*this == rhs); } bool DateTime::operator<(const DateTime& rhs) const { return (*dt_ < *rhs.dt_); } bool DateTime::isValid() const { return dt_->isValid(); } String DateTime::toString(const std::string& format) const { return dt_->toString(QString::fromStdString(format)).toStdString(); } void DateTime::set(const String& date) { clear(); if (date.has('.') && !date.has('T')) { *dt_ = (QDateTime::fromString(date.c_str(), "dd.MM.yyyy hh:mm:ss")); } else if (date.has('/')) { *dt_ = (QDateTime::fromString(date.c_str(), "MM/dd/yyyy hh:mm:ss")); } else if (date.has('-')) { if (date.has('T')) { if (date.has('+')) { // remove timezone part, since Qt cannot handle this, check if we also have a millisecond part if (date.has('.')) { *dt_ = (QDateTime::fromString(date.prefix('+').c_str(), "yyyy-MM-ddThh:mm:ss.zzz")); } else { *dt_ = (QDateTime::fromString(date.prefix('+').c_str(), "yyyy-MM-ddThh:mm:ss")); } } else { *dt_ = (QDateTime::fromString(date.c_str(), "yyyy-MM-ddThh:mm:ss")); } } else if (date.has('Z')) { *dt_ = (QDateTime::fromString(date.c_str(), "yyyy-MM-ddZ")); } else if (date.has('+')) { *dt_ = (QDateTime::fromString(date.c_str(), "yyyy-MM-dd+hh:mm")); } else { *dt_ = (QDateTime::fromString(date.c_str(), "yyyy-MM-dd hh:mm:ss")); } } if (!dt_->isValid()) { *dt_ = QDateTime::fromString(date.c_str()); // ddd MMM d YYYY format as found in (old?) protXML files } if (!dt_->isValid()) { throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, date, "Invalid date time string"); } } void DateTime::set(UInt month, UInt day, UInt year, UInt hour, UInt minute, UInt second) { dt_->setDate(QDate(year, month, day)); dt_->setTime(QTime(hour, minute, second)); if (!dt_->isValid()) { String date_time = String(year) + "-" + String(month) + "-" + String(day) + " " + String(hour) + ":" + String(minute) + ":" + String(second); throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, date_time, "Invalid date time"); } } DateTime DateTime::now() { DateTime d; *d.dt_ = QDateTime::currentDateTime(); return d; } String DateTime::get() const { if (dt_->isValid()) { return dt_->toString("yyyy-MM-dd hh:mm:ss"); } return "0000-00-00 00:00:00"; } void DateTime::get(UInt& month, UInt& day, UInt& year, UInt& hour, UInt& minute, UInt& second) const { const QDate& temp_date = dt_->date(); const QTime& temp_time = dt_->time(); year = temp_date.year(); month = temp_date.month(); day = temp_date.day(); hour = temp_time.hour(); minute = temp_time.minute(); second = temp_time.second(); } void DateTime::clear() { *dt_ = QDateTime(); } void DateTime::setDate(const String& date) { QDate temp_date; if (date.has('-')) { temp_date = QDate::fromString(date.c_str(), "yyyy-MM-dd"); } else if (date.has('.')) { temp_date = QDate::fromString(date.c_str(), "dd-MM-yyyy"); } else if (date.has('/')) { temp_date = QDate::fromString(date.c_str(), "MM/dd/yyyy"); } else { throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, date, "Could not set date"); } if (!temp_date.isValid()) { throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, date, "Could not set date"); } dt_->setDate(temp_date); } void DateTime::setTime(const String& time) { QTime temp_time; temp_time = QTime::fromString(time.c_str(), "hh:mm:ss"); if (!temp_time.isValid()) { throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, time, "Could not set time"); } dt_->setTime(temp_time); } void DateTime::setDate(UInt month, UInt day, UInt year) { QDate temp_date; if (!temp_date.setDate(year, month, day)) { throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String(year) + "-" + String(month) + "-" + String(day), "Could not set date"); } dt_->setDate(temp_date); } void DateTime::setTime(UInt hour, UInt minute, UInt second) { QTime temp_time; if (!temp_time.setHMS(hour, minute, second)) { throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String(hour) + ":" + String(minute) + ":" + String(second), "Could not set time"); } dt_->setTime(temp_time); } void DateTime::getDate(UInt& month, UInt& day, UInt& year) const { const QDate& temp_date = dt_->date(); month = temp_date.month(); day = temp_date.day(); year = temp_date.year(); } String DateTime::getDate() const { if (dt_->isValid()) { return dt_->date().toString("yyyy-MM-dd"); } return "0000-00-00"; } void DateTime::getTime(UInt& hour, UInt& minute, UInt& second) const { const QTime& temp_time =dt_->time(); hour = temp_time.hour(); minute = temp_time.minute(); second = temp_time.second(); } String DateTime::getTime() const { if (dt_->isValid()) { return dt_->time().toString("hh:mm:ss"); } return "00:00:00"; } DateTime& DateTime::addSecs(int s) { *dt_ = dt_->addSecs(s); return *this; } bool DateTime::isNull() const { return dt_->isNull(); } // static DateTime DateTime::fromString(const std::string& date, const std::string& format) { DateTime d; *d.dt_ = QDateTime::fromString(QString::fromStdString(date), QString::fromStdString(format)); return d; } } // namespace OpenMS
C++
3D
OpenMS/OpenMS
src/openms/source/DATASTRUCTURES/DistanceMatrix.cpp
.cpp
514
16
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Mathias Walzer $ // $Authors: $ // -------------------------------------------------------------------------- #include <OpenMS/DATASTRUCTURES/DistanceMatrix.h> namespace OpenMS { DistanceMatrix<int> default_distancematrix_int; DistanceMatrix<double> default_distancematrix_double; }
C++
3D
OpenMS/OpenMS
src/openms/source/DATASTRUCTURES/MatchedIterator.cpp
.cpp
445
17
// 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 $ // -------------------------------------------------------------------------- // #include <OpenMS/DATASTRUCTURES/MatchedIterator.h> namespace OpenMS { } // namespace OpenMS
C++
3D
OpenMS/OpenMS
src/openms/source/DATASTRUCTURES/ParamValue.cpp
.cpp
21,355
822
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Authors: Ruben Grünberg $ // -------------------------------------------------------------------------- #include <OpenMS/DATASTRUCTURES/ParamValue.h> #include <OpenMS/DATASTRUCTURES/String.h> #include <OpenMS/CONCEPT/Exception.h> #include <sstream> #include <cmath> namespace OpenMS { const ParamValue ParamValue::EMPTY; // default ctor ParamValue::ParamValue() : value_type_(EMPTY_VALUE) { } // destructor ParamValue::~ParamValue() { clear_(); } //------------------------------------------------------------------- // ctor for all supported types a ParamValue object can hold //-------------------------------------------------------------------- ParamValue::ParamValue(long double p) : value_type_(DOUBLE_VALUE) { data_.dou_ = p; } ParamValue::ParamValue(double p) : value_type_(DOUBLE_VALUE) { data_.dou_ = p; } ParamValue::ParamValue(float p) : value_type_(DOUBLE_VALUE) { data_.dou_ = p; } ParamValue::ParamValue(short int p) : value_type_(INT_VALUE) { data_.ssize_ = p; } ParamValue::ParamValue(unsigned short int p) : value_type_(INT_VALUE) { data_.ssize_ = p; } ParamValue::ParamValue(int p) : value_type_(INT_VALUE) { data_.ssize_ = p; } ParamValue::ParamValue(unsigned int p) : value_type_(INT_VALUE) { data_.ssize_ = p; } ParamValue::ParamValue(long int p) : value_type_(INT_VALUE) { data_.ssize_ = p; } ParamValue::ParamValue(unsigned long int p) : value_type_(INT_VALUE) { data_.ssize_ = p; } ParamValue::ParamValue(long long p) : value_type_(INT_VALUE) { data_.ssize_ = p; } ParamValue::ParamValue(unsigned long long p) : value_type_(INT_VALUE) { data_.ssize_ = p; } ParamValue::ParamValue(const char* p) : value_type_(STRING_VALUE) { data_.str_ = new std::string(p); } ParamValue::ParamValue(const std::string& p) : value_type_(STRING_VALUE) { data_.str_ = new std::string(p); } ParamValue::ParamValue(const std::vector<std::string>& p) : value_type_(STRING_LIST) { data_.str_list_ = new std::vector<std::string>(p); } ParamValue::ParamValue(const std::vector<int>& p) : value_type_(INT_LIST) { data_.int_list_ = new std::vector<int>(p); } ParamValue::ParamValue(const std::vector<double>& p) : value_type_(DOUBLE_LIST) { data_.dou_list_ = new std::vector<double>(p); } //-------------------------------------------------------------------- // copy and move constructors //-------------------------------------------------------------------- ParamValue::ParamValue(const ParamValue& p) : value_type_(p.value_type_) { switch (value_type_) { case STRING_VALUE: data_.str_ = new std::string(*p.data_.str_); break; case STRING_LIST: data_.str_list_ = new std::vector<std::string>(*p.data_.str_list_); break; case INT_LIST: data_.int_list_ = new std::vector<int>(*p.data_.int_list_); break; case DOUBLE_LIST: data_.dou_list_ = new std::vector<double>(*p.data_.dou_list_); break; default: data_ = p.data_; break; } } ParamValue::ParamValue(ParamValue&& rhs) noexcept : value_type_(std::move(rhs.value_type_)), data_(std::move(rhs.data_)) { // clean up rhs, take ownership of data_ // NOTE: value_type_ == EMPTY_VALUE implies data_ is empty and can be reset rhs.value_type_ = EMPTY_VALUE; } void ParamValue::clear_() noexcept { switch (value_type_) { case STRING_VALUE: delete data_.str_; break; case STRING_LIST: delete data_.str_list_; break; case INT_LIST: delete data_.int_list_; break; case DOUBLE_LIST: delete data_.dou_list_; break; default: break; } value_type_ = EMPTY_VALUE; } //-------------------------------------------------------------------- // copy and move assignment operators //-------------------------------------------------------------------- ParamValue& ParamValue::operator=(const ParamValue& p) { // Check for self-assignment if (this == &p) { return *this; } // clean up clear_(); // assign switch (p.value_type_) { case STRING_VALUE: data_.str_ = new std::string(*p.data_.str_); break; case STRING_LIST: data_.str_list_ = new std::vector<std::string>(*p.data_.str_list_); break; case INT_LIST: data_.int_list_ = new std::vector<int>(*p.data_.int_list_); break; case DOUBLE_LIST: data_.dou_list_ = new std::vector<double>(*p.data_.dou_list_); break; default: data_ = p.data_; break; } // copy type value_type_ = p.value_type_; return *this; } /// Move assignment operator ParamValue& ParamValue::operator=(ParamValue&& rhs) noexcept { // Check for self-assignment if (this == &rhs) { return *this; } // clean up *this clear_(); // assign values to *this data_ = rhs.data_; value_type_ = rhs.value_type_; // clean up rhs rhs.value_type_ = EMPTY_VALUE; return *this; } //-------------------------------------------------------------------- // assignment conversion operator //-------------------------------------------------------------------- ParamValue& ParamValue::operator=(const char* arg) { clear_(); data_.str_ = new std::string(arg); value_type_ = STRING_VALUE; return *this; } ParamValue& ParamValue::operator=(const std::string& arg) { clear_(); data_.str_ = new std::string(arg); value_type_ = STRING_VALUE; return *this; } ParamValue& ParamValue::operator=(const std::vector<std::string>& arg) { clear_(); data_.str_list_ = new std::vector<std::string>(arg); value_type_ = STRING_LIST; return *this; } ParamValue& ParamValue::operator=(const std::vector<int>& arg) { clear_(); data_.int_list_ = new std::vector<int>(arg); value_type_ = INT_LIST; return *this; } ParamValue& ParamValue::operator=(const std::vector<double>& arg) { clear_(); data_.dou_list_ = new std::vector<double>(arg); value_type_ = DOUBLE_LIST; return *this; } ParamValue& ParamValue::operator=(const long double arg) { clear_(); data_.dou_ = arg; value_type_ = DOUBLE_VALUE; return *this; } ParamValue& ParamValue::operator=(const double arg) { clear_(); data_.dou_ = arg; value_type_ = DOUBLE_VALUE; return *this; } ParamValue& ParamValue::operator=(const float arg) { clear_(); data_.dou_ = arg; value_type_ = DOUBLE_VALUE; return *this; } ParamValue& ParamValue::operator=(const short int arg) { clear_(); data_.ssize_ = arg; value_type_ = INT_VALUE; return *this; } ParamValue& ParamValue::operator=(const unsigned short int arg) { clear_(); data_.ssize_ = arg; value_type_ = INT_VALUE; return *this; } ParamValue& ParamValue::operator=(const int arg) { clear_(); data_.ssize_ = arg; value_type_ = INT_VALUE; return *this; } ParamValue& ParamValue::operator=(const unsigned arg) { clear_(); data_.ssize_ = arg; value_type_ = INT_VALUE; return *this; } ParamValue& ParamValue::operator=(const long int arg) { clear_(); data_.ssize_ = arg; value_type_ = INT_VALUE; return *this; } ParamValue& ParamValue::operator=(const unsigned long arg) { clear_(); data_.ssize_ = arg; value_type_ = INT_VALUE; return *this; } ParamValue& ParamValue::operator=(const long long arg) { clear_(); data_.ssize_ = arg; value_type_ = INT_VALUE; return *this; } ParamValue& ParamValue::operator=(const unsigned long long arg) { clear_(); data_.ssize_ = arg; value_type_ = INT_VALUE; return *this; } //--------------------------------------------------------------------------- // Conversion operators //---------------------------------------------------------------------------- ParamValue::operator long double() const { if (value_type_ == EMPTY_VALUE) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not convert ParamValue::EMPTY to long double"); } else if (value_type_ == INT_VALUE) { return (long double)(data_.ssize_); } return data_.dou_; } ParamValue::operator double() const { if (value_type_ == EMPTY_VALUE) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not convert ParamValue::EMPTY to double"); } else if (value_type_ == INT_VALUE) { return double(data_.ssize_); } return data_.dou_; } ParamValue::operator float() const { if (value_type_ == EMPTY_VALUE) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not convert ParamValue::EMPTY to float"); } else if (value_type_ == INT_VALUE) { return float(data_.ssize_); } return data_.dou_; } ParamValue::operator short int() const { if (value_type_ != INT_VALUE) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not convert non-integer ParamValue to short int"); } return data_.ssize_; } ParamValue::operator unsigned short int() const { if (value_type_ != INT_VALUE) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not convert non-integer ParamValue to UInt"); } if (data_.ssize_ < 0.0) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not convert negative integer ParamValue to unsigned short int"); } return data_.ssize_; } ParamValue::operator int() const { if (value_type_ != INT_VALUE) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not convert non-integer ParamValue to int"); } return data_.ssize_; } ParamValue::operator unsigned int() const { if (value_type_ != INT_VALUE) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not convert non-integer ParamValue to unsigned int"); } if (data_.ssize_ < 0.0) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not convert negative integer ParamValue to unsigned int"); } return data_.ssize_; } ParamValue::operator long int() const { if (value_type_ != INT_VALUE) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not convert non-integer ParamValue to long int"); } return data_.ssize_; } ParamValue::operator unsigned long int() const { if (value_type_ != INT_VALUE) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not convert non-integer ParamValue to unsigned long int"); } if (data_.ssize_ < 0.0) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not convert negative integer ParamValue to unsigned long int"); } return data_.ssize_; } ParamValue::operator long long() const { if (value_type_ != INT_VALUE) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not convert non-integer ParamValue to Int"); } return data_.ssize_; } ParamValue::operator unsigned long long() const { if (value_type_ != INT_VALUE) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not convert non-integer ParamValue to UInt"); } if (data_.ssize_ < 0.0) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not convert negative integer ParamValue to UInt"); } return data_.ssize_; } ParamValue::operator std::string() const { if (value_type_ != STRING_VALUE) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not convert non-string ParamValue to string"); } return *(data_.str_); } ParamValue::operator std::vector<std::string>() const { return this->toStringVector(); } ParamValue::operator std::vector<int>() const { return this->toIntVector(); } ParamValue::operator std::vector<double>() const { return this->toDoubleVector(); } // Convert ParamValues to char* const char* ParamValue::toChar() const { switch (value_type_) { case STRING_VALUE: return data_.str_->c_str(); break; case EMPTY_VALUE: return nullptr; break; default: throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not convert non-string ParamValue to char*"); break; } } std::string ParamValue::toString(bool full_precision) const { std::string str; switch (value_type_) { case EMPTY_VALUE: return ""; break; case STRING_VALUE: return *data_.str_; break; case INT_VALUE: return std::to_string(data_.ssize_); break; case DOUBLE_VALUE: { return doubleToString(data_.dou_, full_precision); } break; case STRING_LIST: str = "["; if (!data_.str_list_->empty()) { for (std::vector<std::string>::const_iterator it = data_.str_list_->begin(); it != data_.str_list_->end() - 1; ++it) { str += *it + ", "; } str += data_.str_list_->back(); } str += "]"; break; case INT_LIST: str = "["; if (!data_.int_list_->empty()) { for (std::vector<int>::const_iterator it = data_.int_list_->begin(); it != data_.int_list_->end() - 1; ++it) { str += std::to_string(*it) + ", "; } str += std::to_string(data_.int_list_->back()); } str += "]"; break; case DOUBLE_LIST: str = "["; if (!data_.dou_list_->empty()) { for (std::vector<double>::const_iterator it = data_.dou_list_->begin(); it != data_.dou_list_->end() - 1; ++it) { str += doubleToString(*it, full_precision) + ", "; } str += doubleToString(data_.dou_list_->back(), full_precision); } str += "]"; break; default: throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not convert ParamValue to String"); break; } return str; } std::vector<std::string> ParamValue::toStringVector() const { if (value_type_ != STRING_LIST) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not convert non-std::vector<std::string> ParamValue to std::vector<std::string>"); } return *(data_.str_list_); } std::vector<int> ParamValue::toIntVector() const { if (value_type_ != INT_LIST) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not convert non-std::vector<int> ParamValue to std::vector<int>"); } return *(data_.int_list_); } std::vector<double> ParamValue::toDoubleVector() const { if (value_type_ != DOUBLE_LIST) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not convert non-std::vector<double> ParamValue to std::vector<double>"); } return *(data_.dou_list_); } bool ParamValue::toBool() const { if (value_type_ != STRING_VALUE) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not convert non-string ParamValue to bool."); } else if (!(*(data_.str_) == "true" || *(data_.str_) == "false")) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not convert '" + *(data_.str_) + "' to bool. Valid stings are 'true' and 'false'."); } return *(data_.str_) == "true"; } // ----------------- Comparator ---------------------- bool operator==(const ParamValue& a, const ParamValue& b) { if (a.value_type_ == b.value_type_) { switch (a.value_type_) { case ParamValue::EMPTY_VALUE: return true; break; case ParamValue::STRING_VALUE: return *(a.data_.str_) == *(b.data_.str_); break; case ParamValue::STRING_LIST: return *(a.data_.str_list_) == *(b.data_.str_list_); break; case ParamValue::INT_LIST: return *(a.data_.int_list_) == *(b.data_.int_list_); break; case ParamValue::DOUBLE_LIST: return *(a.data_.dou_list_) == *(b.data_.dou_list_); break; case ParamValue::INT_VALUE: return a.data_.ssize_ == b.data_.ssize_; break; case ParamValue::DOUBLE_VALUE: return a.data_.dou_ == b.data_.dou_; //return std::fabs(a.data_.dou_ - b.data_.dou_) < 1e-6; This would add an include for <cmath> break; } } return false; } bool operator<(const ParamValue& a, const ParamValue& b) { if (a.value_type_ == b.value_type_) { switch (a.value_type_) { case ParamValue::EMPTY_VALUE: return false; break; case ParamValue::STRING_VALUE: return *(a.data_.str_) < *(b.data_.str_); break; case ParamValue::STRING_LIST: return a.data_.str_list_->size() < b.data_.str_list_->size(); break; case ParamValue::INT_LIST: return a.data_.int_list_->size() < b.data_.int_list_->size(); break; case ParamValue::DOUBLE_LIST: return a.data_.dou_list_->size() < b.data_.dou_list_->size(); break; case ParamValue::INT_VALUE: return a.data_.ssize_ < b.data_.ssize_; break; case ParamValue::DOUBLE_VALUE: return a.data_.dou_ < b.data_.dou_; break; } } return false; } bool operator>(const ParamValue& a, const ParamValue& b) { if (a.value_type_ == b.value_type_) { switch (a.value_type_) { case ParamValue::EMPTY_VALUE: return false; break; case ParamValue::STRING_VALUE: return *(a.data_.str_) > *(b.data_.str_); break; case ParamValue::STRING_LIST: return a.data_.str_list_->size() > b.data_.str_list_->size(); break; case ParamValue::INT_LIST: return a.data_.int_list_->size() > b.data_.int_list_->size(); break; case ParamValue::DOUBLE_LIST: return a.data_.dou_list_->size() > b.data_.dou_list_->size(); break; case ParamValue::INT_VALUE: return a.data_.ssize_ > b.data_.ssize_; break; case ParamValue::DOUBLE_VALUE: return a.data_.dou_ > b.data_.dou_; break; } } return false; } bool operator!=(const ParamValue& a, const ParamValue& b) { return !(a == b); } // ----------------- Output operator ---------------------- /// for doubles or lists of doubles, you get full precision. Use ParamValue::toString(false) if you only need low precision std::ostream& operator<<(std::ostream& os, const ParamValue& p) { switch (p.value_type_) { case ParamValue::STRING_VALUE: os << *(p.data_.str_); break; case ParamValue::STRING_LIST: os << "["; if (!p.data_.str_list_->empty()) { for (auto it = p.data_.str_list_->begin(), end = p.data_.str_list_->end() - 1; it != end; ++it) { os << *it << ", "; } os << p.data_.str_list_->back(); } os << "]"; break; case ParamValue::INT_LIST: os << "["; if (!p.data_.int_list_->empty()) { for (auto it = p.data_.int_list_->begin(), end = p.data_.int_list_->end() - 1; it != end; ++it) { os << *it << ", "; } os << p.data_.int_list_->back(); } os << "]"; break; case ParamValue::DOUBLE_LIST: os << "["; if (!p.data_.dou_list_->empty()) { for (auto it = p.data_.dou_list_->begin(), end = p.data_.dou_list_->end() - 1; it != end; ++it) { os << *it << ", "; } os << p.data_.dou_list_->back(); } os << "]"; break; case ParamValue::INT_VALUE: os << p.data_.ssize_; break; case ParamValue::DOUBLE_VALUE: os << p.data_.dou_; break; case ParamValue::EMPTY_VALUE: break; } return os; } std::string ParamValue::doubleToString(double value, bool full_precision) { return String(value, full_precision); } } //namespace
C++
3D
OpenMS/OpenMS
src/openms/source/DATASTRUCTURES/LPWrapper.cpp
.cpp
24,250
805
// 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 $ // -------------------------------------------------------------------------- #include <OpenMS/DATASTRUCTURES/LPWrapper.h> #include <OpenMS/CONCEPT/LogStream.h> #include <OpenMS/CONCEPT/Exception.h> #include <OpenMS/config.h> #ifdef OPENMS_HAS_COINOR // only include COINOR if we actually use it... #ifdef _MSC_VER //disable some COIN-OR warnings that distract from ours #pragma warning( push ) // save warning state #pragma warning( disable : 4267 ) #else #pragma GCC diagnostic ignored "-Wunused-parameter" #endif // CoinModel.h uses 'register' as decorator, e.g. 'register int x;' which is deprecated in C++17, // and causes compile errors in MSVC when /permissive- is enabled (which Qt6 adds indirectly) // (patching contrib is not an option, since coin may be fetched from other sources on Linux) // Hack: Undefine 'register' to avoid this issue #define register #ifdef OPENMS_HAS_COIN_INCLUDE_SUBDIR_IS_COIN #include "coin/CoinModel.hpp" #include "coin/OsiClpSolverInterface.hpp" #include "coin/CbcModel.hpp" #include "coin/CbcHeuristic.hpp" #include "coin/CbcHeuristicLocal.hpp" #include "coin/CglGomory.hpp" #include "coin/CglKnapsackCover.hpp" #include "coin/CglOddHole.hpp" #include "coin/CglClique.hpp" #include "coin/CglMixedIntegerRounding.hpp" #else #include "coin-or/CoinModel.hpp" #include "coin-or/OsiClpSolverInterface.hpp" #include "coin-or/CbcModel.hpp" #include "coin-or/CbcHeuristic.hpp" #include "coin-or/CbcHeuristicLocal.hpp" #include "coin-or/CglGomory.hpp" #include "coin-or/CglKnapsackCover.hpp" #include "coin-or/CglOddHole.hpp" #include "coin-or/CglClique.hpp" #include "coin-or/CglMixedIntegerRounding.hpp" #endif #undef register // undo hack #ifdef _MSC_VER #pragma warning( pop ) // restore old warning state #else #pragma GCC diagnostic warning "-Wunused-parameter" #endif #else // no COINOR #include <glpk.h> #endif namespace OpenMS { LPWrapper::LPWrapper() { // note: should this mechanism ever change, also look at TOPP/OpenMSInfo.cpp #ifdef OPENMS_HAS_COINOR solver_ = SOLVER_COINOR; model_ = new CoinModel; #else solver_ = SOLVER_GLPK; lp_problem_ = glp_create_prob(); #endif } LPWrapper::~LPWrapper() { #ifdef OPENMS_HAS_COINOR delete model_; #else glp_delete_prob(lp_problem_); #endif } Int LPWrapper::addRow(const std::vector<Int>& row_indices, const std::vector<double>& row_values, const String& name) // return index { if (row_indices.size() != row_values.size()) { throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Indices and values vectors differ in size"); } #ifdef OPENMS_HAS_COINOR model_->addRow((int)row_indices.size(), row_indices.data(), row_values.data(), -COIN_DBL_MAX, COIN_DBL_MAX, name.c_str()); return model_->numberRows() - 1; #else std::vector<Int> row_indices_ = row_indices; std::vector<double> row_values_ = row_values; const Int index = glp_add_rows(lp_problem_, 1); // glpk accesses arrays beginning at index 1-> we have to insert an empty value at the front row_indices_.insert(row_indices_.begin(), -1); row_values_.insert(row_values_.begin(), -1); for (Int& row_index : row_indices_) { ++row_index; } glp_set_mat_row(lp_problem_, index, (int)row_indices_.size() - 1, row_indices_.data(), row_values_.data()); glp_set_row_name(lp_problem_, index, name.c_str()); return index - 1; #endif } Int LPWrapper::addColumn() { #ifdef OPENMS_HAS_COINOR model_->addColumn(0, nullptr, nullptr, 0, 0); // new columns are initially fixed at zero, like in glpk return model_->numberColumns() - 1; #else return glp_add_cols(lp_problem_, 1) - 1; #endif } Int LPWrapper::addColumn(const std::vector<Int>& column_indices, const std::vector<double>& column_values, const String& name) { if (column_indices.empty()) { throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Column indices for Row are empty"); } if (column_indices.size() != column_values.size()) { throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Indices and values vectors differ in size"); } #ifdef OPENMS_HAS_COINOR model_->addColumn((int)column_indices.size(), column_indices.data(), column_values.data(), -COIN_DBL_MAX, COIN_DBL_MAX, 0.0, name.c_str()); return model_->numberColumns() - 1; #else std::vector<Int> column_indices_ = column_indices; std::vector<double> column_values_ = column_values; const Int index = glp_add_cols(lp_problem_, 1); // glpk accesses arrays beginning at index 1-> we have to insert an empty value at the front column_indices_.insert(column_indices_.begin(), -1); column_values_.insert(column_values_.begin(), -1); for (Int& column_index : column_indices_) { ++column_index; } glp_set_mat_col(lp_problem_, index, (int)column_indices_.size() - 1, column_indices_.data(), column_values_.data()); glp_set_col_name(lp_problem_, index, name.c_str()); return index - 1; #endif } Int LPWrapper::addRow(const std::vector<Int>& row_indices, const std::vector<double>& row_values, const String& name, double lower_bound, double upper_bound, Type type) { const Int index = addRow(row_indices, row_values, name); #ifdef OPENMS_HAS_COINOR switch (type) { case UNBOUNDED: // unbounded model_->setRowBounds(index, -COIN_DBL_MAX, COIN_DBL_MAX); break; case LOWER_BOUND_ONLY: // only lower bound model_->setRowBounds(index, lower_bound, COIN_DBL_MAX); break; case UPPER_BOUND_ONLY: // only upper bound model_->setRowBounds(index, -COIN_DBL_MAX, upper_bound); break; default: // double-bounded or fixed model_->setRowBounds(index, lower_bound, upper_bound); break; } #else glp_set_row_bnds(lp_problem_, index + 1, type, lower_bound, upper_bound); #endif return index; // in addRow index is decreased already } Int LPWrapper::addColumn(const std::vector<Int>& column_indices, const std::vector<double>& column_values, const String& name, double lower_bound, double upper_bound, Type type) //return index { const Int index = addColumn(column_indices, column_values, name); #ifdef OPENMS_HAS_COINOR switch (type) { case UNBOUNDED: // unbounded model_->setColumnBounds(index, -COIN_DBL_MAX, COIN_DBL_MAX); break; case LOWER_BOUND_ONLY: // only lower bound model_->setColumnBounds(index, lower_bound, COIN_DBL_MAX); break; case UPPER_BOUND_ONLY: // only upper bound model_->setColumnBounds(index, -COIN_DBL_MAX, upper_bound); break; default: // double-bounded or fixed model_->setColumnBounds(index, lower_bound, upper_bound); break; } #else glp_set_col_bnds(lp_problem_, index + 1, type, lower_bound, upper_bound); #endif return index; // in addColumn index is decreased already } void LPWrapper::deleteRow(Int index) { #ifdef OPENMS_HAS_COINOR model_->deleteRow(index); #else int num[] = { 0, index + 1 }; // glpk starts reading at pos 1 glp_del_rows(lp_problem_, 1, num); #endif } void LPWrapper::setElement(Int row_index, Int column_index, double value) { if (row_index >= getNumberOfRows() || column_index >= getNumberOfColumns()) { throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Invalid index given", String("invalid column_index or row_index")); } #ifdef OPENMS_HAS_COINOR model_->setElement(row_index, column_index, value); #else const Int length = glp_get_mat_row(lp_problem_, row_index + 1, nullptr, nullptr); // get row length std::vector<double> values(length + 1); std::vector<Int> indices(length + 1); glp_get_mat_row(lp_problem_, row_index + 1, indices.data(), values.data()); bool found = false; for (Int i = 1; i <= length; ++i) { if (indices[i] == column_index + 1) { values[i] = value; found = true; break; } } if (!found) // if this entry wasn't existing before we have to enter it { std::vector<Int> n_indices(length + 2); std::vector<double> n_values(length + 2); for (Int i = 0; i <= length; ++i) { n_indices[i] = indices[i]; n_values[i] = values[i]; } // now add new value n_indices[length + 1] = column_index + 1; // glpk starts reading at pos 1 n_values[length + 1] = value; glp_set_mat_row(lp_problem_, row_index + 1, length, n_indices.data(), n_values.data()); } else { glp_set_mat_row(lp_problem_, row_index + 1, length, indices.data(), values.data()); } #endif } double LPWrapper::getElement(Int row_index, Int column_index) { if (row_index >= getNumberOfRows() || column_index >= getNumberOfColumns()) { throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Invalid index given", String("invalid column_index or row_index")); } #ifdef OPENMS_HAS_COINOR return model_->getElement(row_index, column_index); #else const Int length = glp_get_mat_row(lp_problem_, row_index + 1, nullptr, nullptr); std::vector<double> values(length + 1); std::vector<Int> indices(length + 1); glp_get_mat_row(lp_problem_, row_index + 1, indices.data(), values.data()); for (Int i = 1; i <= length; ++i) { if (indices[i] == column_index + 1) return values[i]; } return 0.; #endif } void LPWrapper::setColumnName(Int index, const String& name) { #ifdef OPENMS_HAS_COINOR model_->setColumnName(index, name.c_str()); #else glp_set_col_name(lp_problem_, index + 1, name.c_str()); #endif } void LPWrapper::setRowName(Int index, const String& name) { #ifdef OPENMS_HAS_COINOR model_->setRowName(index, name.c_str()); #else glp_set_row_name(lp_problem_, index + 1, name.c_str()); #endif } void LPWrapper::setColumnBounds(Int index, double lower_bound, double upper_bound, Type type) { #ifdef OPENMS_HAS_COINOR switch (type) { case UNBOUNDED: // unbounded model_->setColumnBounds(index, -COIN_DBL_MAX, COIN_DBL_MAX); break; case LOWER_BOUND_ONLY: // only lower bound model_->setColumnBounds(index, lower_bound, COIN_DBL_MAX); break; case UPPER_BOUND_ONLY: // only upper bound model_->setColumnBounds(index, -COIN_DBL_MAX, upper_bound); break; default: // double-bounded or fixed model_->setColumnBounds(index, lower_bound, upper_bound); break; } #else glp_set_col_bnds(lp_problem_, index + 1, type, lower_bound, upper_bound); #endif } void LPWrapper::setRowBounds(Int index, double lower_bound, double upper_bound, Type type) { #ifdef OPENMS_HAS_COINOR switch (type) { case UNBOUNDED: // unbounded model_->setRowBounds(index, -COIN_DBL_MAX, COIN_DBL_MAX); break; case LOWER_BOUND_ONLY: // only lower bound model_->setRowBounds(index, lower_bound, COIN_DBL_MAX); break; case UPPER_BOUND_ONLY: // only upper bound model_->setRowBounds(index, -COIN_DBL_MAX, upper_bound); break; default: // double-bounded or fixed model_->setRowBounds(index, lower_bound, upper_bound); break; } #else glp_set_row_bnds(lp_problem_, index + 1, type, lower_bound, upper_bound); #endif } void LPWrapper::setColumnType(Int index, VariableType type) // 1- continuous, 2- integer, 3- binary { #ifdef OPENMS_HAS_COINOR if (type == 1) model_->setContinuous(index); else if (type == 3) { OPENMS_LOG_WARN << "Coin-Or only knows Integer variables, setting variable to integer type"; model_->setColumnIsInteger(index, true); } else model_->setColumnIsInteger(index, true); #else glp_set_col_kind(lp_problem_, index + 1, (int)type); #endif } LPWrapper::VariableType LPWrapper::getColumnType(Int index) { #ifdef OPENMS_HAS_COINOR if (model_->isInteger(index)) { return INTEGER; } else return CONTINUOUS; #else return (VariableType)glp_get_col_kind(lp_problem_, index + 1); #endif } void LPWrapper::setObjective(Int index, double obj_value) { #ifdef OPENMS_HAS_COINOR model_->setObjective(index, obj_value); #else glp_set_obj_coef(lp_problem_, index + 1, obj_value); #endif } void LPWrapper::setObjectiveSense(LPWrapper::Sense sense) { #ifdef OPENMS_HAS_COINOR if (sense == LPWrapper::MIN) model_->setOptimizationDirection(1); else model_->setOptimizationDirection(-1); // -1 maximize #else glp_set_obj_dir(lp_problem_, (int)sense); #endif } Int LPWrapper::getNumberOfColumns() { #ifdef OPENMS_HAS_COINOR return model_->numberColumns(); #else return glp_get_num_cols(lp_problem_); #endif } Int LPWrapper::getNumberOfRows() { #ifdef OPENMS_HAS_COINOR return model_->numberRows(); #else return glp_get_num_rows(lp_problem_); #endif } String LPWrapper::getColumnName(Int index) { #ifdef OPENMS_HAS_COINOR return model_->getColumnName(index); #else return String(glp_get_col_name(lp_problem_, index + 1)); #endif } String LPWrapper::getRowName(Int index) { #ifdef OPENMS_HAS_COINOR return model_->getRowName(index); #else return String(glp_get_row_name(lp_problem_, index + 1)); #endif } Int LPWrapper::getRowIndex(const String& name) { #ifdef OPENMS_HAS_COINOR return model_->row(name.c_str()); #else glp_create_index(lp_problem_); return glp_find_row(lp_problem_, name.c_str()) - 1; #endif } Int LPWrapper::getColumnIndex(const String& name) { #ifdef OPENMS_HAS_COINOR return model_->column(name.c_str()); #else glp_create_index(lp_problem_); return glp_find_col(lp_problem_, name.c_str()) - 1; #endif } LPWrapper::SOLVER LPWrapper::getSolver() const { return solver_; } #ifdef OPENMS_HAS_COINOR void LPWrapper::readProblem(const String& filename, const String& /*format*/) { // delete old model and create a new model in its place (using same ptr) delete model_; model_ = new CoinModel(filename.c_str()); } #else void LPWrapper::readProblem(const String& filename, const String& format) // format=(LP,MPS,GLPK) { // delete old model and create a new model in its place (using same ptr) glp_erase_prob(lp_problem_); if (format == "LP") { glp_read_lp(lp_problem_, nullptr, filename.c_str()); } else if (format == "MPS") { glp_read_mps(lp_problem_, GLP_MPS_FILE, nullptr, filename.c_str()); } else if (format == "GLPK") { glp_read_prob(lp_problem_, 0, filename.c_str()); } else throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "invalid LP format, allowed are LP, MPS, GLPK"); } #endif void LPWrapper::writeProblem(const String& filename, const WriteFormat format) const { #ifdef OPENMS_HAS_COINOR if (format == FORMAT_MPS) { model_->writeMps(filename.c_str()); } else { throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Invalid LP format, allowed is MPS"); } #else if (format == FORMAT_LP) { glp_write_lp(lp_problem_, nullptr, filename.c_str()); } else if (format == FORMAT_MPS) { glp_write_mps(lp_problem_, GLP_MPS_FILE, nullptr, filename.c_str()); } else if (format == FORMAT_GLPK) { glp_write_prob(lp_problem_, 0, filename.c_str()); } else throw Exception::IllegalArgument(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Invalid LP format, allowed are LP, MPS, GLPK"); #endif } #ifdef OPENMS_HAS_COINOR Int LPWrapper::solve(SolverParam& /*solver_param*/, const Size verbose_level) #else Int LPWrapper::solve(SolverParam& solver_param, const Size /*verbose_level*/) #endif { OPENMS_LOG_INFO << "Using solver '" << (solver_ == LPWrapper::SOLVER_GLPK ? "glpk" : "coinor") << "' ...\n"; #ifdef OPENMS_HAS_COINOR //Removed ifdef and OsiOslSolverInterface because Windows couldn't find it/both flags failed. For linux on the other hand the flags worked. But as far as I know we prefer CLP as solver anyway so no need to look for different solvers. //#ifdef COIN_HAS_CLP OsiClpSolverInterface solver; //#elif COIN_HAS_OSL // OsiOslSolverInterface solver; //#endif solver.loadFromCoinModel(*model_); /* Now let MIP calculate a solution */ // Pass to solver CbcModel model(solver); model.setObjSense(model_->optimizationDirection()); // -1 = maximize, 1=minimize model.solver()->setHintParam(OsiDoReducePrint, true, OsiHintTry); // Output details model.messageHandler()->setLogLevel(verbose_level > 1 ? 2 : 0); model.solver()->messageHandler()->setLogLevel(verbose_level > 1 ? 1 : 0); //CglProbing generator1; //generator1.setUsingObjective(true); CglGomory generator2; generator2.setLimit(300); CglKnapsackCover generator3; CglOddHole generator4; generator4.setMinimumViolation(0.005); generator4.setMinimumViolationPer(0.00002); generator4.setMaximumEntries(200); CglClique generator5; generator5.setStarCliqueReport(false); generator5.setRowCliqueReport(false); //CglFlowCover flowGen; CglMixedIntegerRounding mixedGen; // Add in generators (you should prefer the ones used often and disable the others as they increase solution time) //model.addCutGenerator(&generator1,-1,"Probing"); model.addCutGenerator(&generator2, -1, "Gomory"); model.addCutGenerator(&generator3, -1, "Knapsack"); //model.addCutGenerator(&generator4,-1,"OddHole"); // segfaults model.addCutGenerator(&generator5, -10, "Clique"); //model.addCutGenerator(&flowGen,-1,"FlowCover"); model.addCutGenerator(&mixedGen, -1, "MixedIntegerRounding"); // Heuristics CbcRounding heuristic1(model); model.addHeuristic(&heuristic1); CbcHeuristicLocal heuristic2(model); model.addHeuristic(&heuristic2); // set maximum allowed CPU time before forced stop (dangerous!) //model.setDblParam(CbcModel::CbcMaximumSeconds,60.0*1); // Do initial solve to continuous model.initialSolve(); // solve model.branchAndBound(); // if (verbose_level > 0) OPENMS_LOG_INFO << " Branch and cut took " << CoinCpuTime()-time1 << " seconds, " // << model.getNodeCount()<<" nodes with objective " // << model.getObjValue() // << (!model.status() ? " Finished" : " Not finished") // << std::endl; for (Int i = 0; i < model_->numberColumns(); ++i) { solution_.push_back(model.solver()->getColSolution()[i]); } OPENMS_LOG_INFO << (model.isProvenOptimal() ? "Optimal solution found!" : "No solution found!") << "\n"; return model.status(); #else glp_iocp solver_param_glp; glp_init_iocp(&solver_param_glp); solver_param_glp.msg_lev = solver_param.message_level; solver_param_glp.br_tech = solver_param.branching_tech; solver_param_glp.bt_tech = solver_param.backtrack_tech; solver_param_glp.pp_tech = solver_param.preprocessing_tech; if (solver_param.enable_feas_pump_heuristic) { solver_param_glp.fp_heur = GLP_ON; } if (solver_param.enable_gmi_cuts) { solver_param_glp.gmi_cuts = GLP_ON; } if (solver_param.enable_mir_cuts) { solver_param_glp.mir_cuts = GLP_ON; } if (solver_param.enable_cov_cuts) { solver_param_glp.cov_cuts = GLP_ON; } if (solver_param.enable_clq_cuts) { solver_param_glp.clq_cuts = GLP_ON; } solver_param_glp.mip_gap = solver_param.mip_gap; solver_param_glp.tm_lim = solver_param.time_limit; solver_param_glp.out_frq = solver_param.output_freq; solver_param_glp.out_dly = solver_param.output_delay; if (solver_param.enable_presolve) { solver_param_glp.presolve = GLP_ON; } if (solver_param.enable_binarization) { solver_param_glp.binarize = GLP_ON; // only with presolve } return glp_intopt(lp_problem_, &solver_param_glp); #endif } LPWrapper::SolverStatus LPWrapper::getStatus() { #ifdef OPENMS_HAS_COINOR return LPWrapper::UNDEFINED; #else Int status = glp_mip_status(lp_problem_); switch (status) { case 4: return LPWrapper::NO_FEASIBLE_SOL; case 5: return LPWrapper::OPTIMAL; case 2: return LPWrapper::FEASIBLE; default: return LPWrapper::UNDEFINED; } #endif } double LPWrapper::getObjectiveValue() { #ifdef OPENMS_HAS_COINOR double const * const obj = model_->objectiveArray(); double obj_val = 0.; for (Int i = 0; i < model_->numberColumns(); ++i) { obj_val += obj[i] * getColumnValue(i); } return obj_val; #else return glp_mip_obj_val(lp_problem_); #endif } double LPWrapper::getColumnValue(Int index) { #ifdef OPENMS_HAS_COINOR return solution_[index]; #else // glpk uses arrays beginning at pos 1, so we need to shift return glp_mip_col_val(lp_problem_, index + 1); #endif } double LPWrapper::getColumnUpperBound(Int index) { #ifdef OPENMS_HAS_COINOR return model_->getColumnUpper(index); #else return glp_get_col_ub(lp_problem_, index + 1); #endif } double LPWrapper::getColumnLowerBound(Int index) { #ifdef OPENMS_HAS_COINOR return model_->getColumnLower(index); #else return glp_get_col_lb(lp_problem_, index + 1); #endif } double LPWrapper::getRowUpperBound(Int index) { #ifdef OPENMS_HAS_COINOR return model_->getRowUpper(index); #else return glp_get_row_ub(lp_problem_, index + 1); #endif } double LPWrapper::getRowLowerBound(Int index) { #ifdef OPENMS_HAS_COINOR return model_->getRowLower(index); #else return glp_get_row_lb(lp_problem_, index + 1); #endif } double LPWrapper::getObjective(Int index) { #ifdef OPENMS_HAS_COINOR return model_->objective(index); #else return glp_get_obj_coef(lp_problem_, index + 1); #endif } LPWrapper::Sense LPWrapper::getObjectiveSense() { #ifdef OPENMS_HAS_COINOR if (model_->optimizationDirection() == 1) return LPWrapper::MIN; else return LPWrapper::MAX; #else if (glp_get_obj_dir(lp_problem_) == 1) { return LPWrapper::MIN; } else { return LPWrapper::MAX; } #endif } Int LPWrapper::getNumberOfNonZeroEntriesInRow(Int idx) { #ifdef OPENMS_HAS_COINOR const Int n_cols = getNumberOfColumns(); std::vector<Int> ind(n_cols); std::vector<double> values(n_cols); Int nonzeroentries = 0; model_->getRow(idx, ind.data(), values.data()); for (Int i = 0; i < n_cols; i++) { nonzeroentries += values[i] != 0 ? 1 : 0; } return nonzeroentries; #else /* Non-zero coefficient count in the row. */ // glpk uses arrays beginning at pos 1, so we need to shift return glp_get_mat_row(lp_problem_, idx + 1, nullptr, nullptr); #endif } void LPWrapper::getMatrixRow(Int idx, std::vector<Int>& indexes) { #ifdef OPENMS_HAS_COINOR indexes.clear(); Int n_cols = getNumberOfColumns(); std::vector<Int> ind(n_cols); std::vector<double> values(n_cols); model_->getRow(idx, ind.data(), values.data()); for (Int i = 0; i < n_cols; ++i) { if (values[i] != 0) indexes.push_back(ind[i]); } #else Int size = getNumberOfNonZeroEntriesInRow(idx); std::vector<int> ind(size + 1); glp_get_mat_row(lp_problem_, idx + 1, ind.data(), nullptr); indexes.clear(); for (Int i = 1; i <= size; ++i) { indexes.push_back(ind[i] - 1); } #endif } } // namespace
C++
3D
OpenMS/OpenMS
src/openms/source/DATASTRUCTURES/DPosition.cpp
.cpp
578
19
// 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 $ // -------------------------------------------------------------------------- #include <OpenMS/DATASTRUCTURES/DPosition.h> namespace OpenMS { DPosition<1> default_dposition_1; DPosition<2> default_dposition_2; DPosition<1, Int> default_int_dposition_1; DPosition<2, Int> default_int_dposition_2; }
C++
3D
OpenMS/OpenMS
src/openms/source/DATASTRUCTURES/MassExplainer.cpp
.cpp
11,168
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 $ // -------------------------------------------------------------------------- #include <OpenMS/DATASTRUCTURES/MassExplainer.h> #include <OpenMS/CHEMISTRY/EmpiricalFormula.h> #include <OpenMS/DATASTRUCTURES/Compomer.h> #include <OpenMS/CONCEPT/LogStream.h> #include <iostream> #include <utility> #undef DEBUG_FD namespace OpenMS { MassExplainer::MassExplainer() : explanations_(), adduct_base_(), q_min_(1), q_max_(5), max_span_(3), max_neutrals_(0) { init_(true); } /// Constructor MassExplainer::MassExplainer(AdductsType adduct_base) : explanations_(), adduct_base_(std::move(adduct_base)), q_min_(1), q_max_(5), max_span_(3), max_neutrals_(0) { init_(true); } /// Constructor MassExplainer::MassExplainer(Int q_min, Int q_max, Int max_span, double thresh_logp) : explanations_(), adduct_base_(), q_min_(q_min), q_max_(q_max), max_span_(max_span), thresh_p_(thresh_logp), max_neutrals_(0) { init_(false); } /// Constructor MassExplainer::MassExplainer(AdductsType adduct_base, Int q_min, Int q_max, Int max_span, double thresh_logp, Size max_neutrals) : explanations_(), adduct_base_(std::move(adduct_base)), q_min_(q_min), q_max_(q_max), max_span_(max_span), thresh_p_(thresh_logp), max_neutrals_(max_neutrals) { init_(false); } /// check consistency of input /// @param[in] init_thresh_p set default threshold (set to "false" to keep current value) void MassExplainer::init_(bool init_thresh_p) { if (init_thresh_p) { // every compound with log_p_<thresh_p_ will be discarded // we allow at most two Na+ thresh_p_ = log(0.15) * 2 + log(0.7) * (q_max_ - 2); } // check consistency of members if (q_max_ < q_min_) { Int tmp = q_max_; q_max_ = q_min_; q_min_ = tmp; std::cerr << __FILE__ << ": Warning! \"q_max < q_min\" needed fixing!\n"; } if (max_span_ > (q_max_ - q_min_ + 1)) { max_span_ = q_max_ - q_min_ + 1; std::cerr << __FILE__ << ": Warning! \"max_span_ > (q_max - q_min + 1)\" needed fixing!\n"; } if (adduct_base_.empty()) { //default adducts are: H+, Na+, K+, NH4+ // do NOT use "+" in empirical formula, as every + will add a proton weight! adduct_base_.push_back(createAdduct_("H", 1, 0.7)); adduct_base_.push_back(createAdduct_("Na", 1, 0.1)); adduct_base_.push_back(createAdduct_("NH4", 1, 0.1)); adduct_base_.push_back(createAdduct_("K", 1, 0.1)); } } /// Assignment operator MassExplainer& MassExplainer::operator=(const MassExplainer& rhs) { if (this == &rhs) { return *this; } explanations_ = rhs.explanations_; adduct_base_ = rhs.adduct_base_; q_min_ = rhs.q_min_; q_max_ = rhs.q_max_; max_span_ = rhs.max_span_; thresh_p_ = rhs.thresh_p_; return *this; } /// Destructor MassExplainer::~MassExplainer() = default; //@} /// fill map with possible mass-differences along with their explanation void MassExplainer::compute() { // differentiate between neutral and charged adducts AdductsType adduct_neutral, adduct_charged; for (AdductsType::const_iterator it = adduct_base_.begin(); it != adduct_base_.end(); ++it) { if (it->getCharge() == 0) { adduct_neutral.push_back(*it); } else { adduct_charged.push_back(*it); } } // calculate some initial boundaries that can be used to shorten the enumeration process //Int q_comp_min = -max_span_; //minimal expected charge of compomer //Int q_comp_max = max_span_; //maximal expected charge of compomer Int max_pq = q_max_; //maximal number of positive adduct-charges for a compomer //Int max_nq = q_max_; //maximal number of negative adduct-charges for a compomer for (AdductsType::const_iterator it = adduct_charged.begin(); it != adduct_charged.end(); ++it) { std::vector<Adduct> new_adducts; //create new compomers Int i = 1; //warning: the following code assumes that max_nq == max_pq!! while (abs(i * it->getCharge()) <= max_pq) { Adduct a(*it); // positive amount a.setAmount(i); // this might not be a valid compomer (e.g. due to net_charge excess) // ... but when combined with other adducts it might become feasible again new_adducts.push_back(a); ++i; } // combine all new compomers with existing compomers std::vector<Adduct>::const_iterator new_it; std::vector<Adduct>::const_iterator new_begin = new_adducts.begin(); std::vector<Adduct>::const_iterator new_end = new_adducts.end(); std::size_t idx_last = explanations_.size(); for (size_t ci = 0; ci < idx_last; ++ci) { for (new_it = new_begin; new_it != new_end; ++new_it) { Compomer cmpl(explanations_[ci]); cmpl.add(*new_it, Compomer::LEFT); explanations_.push_back(cmpl); Compomer cmpr(explanations_[ci]); cmpr.add(*new_it, Compomer::RIGHT); explanations_.push_back(cmpr); } } // finally add new compomers to the list itself for (new_it = new_begin; new_it != new_end; ++new_it) { Compomer cmpl; cmpl.add(*new_it, Compomer::LEFT); explanations_.push_back(cmpl); Compomer cmpr; cmpr.add(*new_it, Compomer::RIGHT); explanations_.push_back(cmpr); } OPENMS_LOG_DEBUG << "valid explanations: " << explanations_.size() << " after " << it->getFormula() << std::endl; } // END adduct add std::vector<Compomer> valids_only; for (size_t ci = 0; ci < explanations_.size(); ++ci) { if (compomerValid_(explanations_[ci])) { valids_only.push_back(explanations_[ci]); } } explanations_.swap(valids_only); // add neutral adducts Size size_of_explanations = explanations_.size(); for (AdductsType::const_iterator it_neutral = adduct_neutral.begin(); it_neutral != adduct_neutral.end(); ++it_neutral) { std::cout << "Adding neutral: " << *it_neutral << "\n"; for (Int n = 1; n <= (SignedSize)max_neutrals_; ++n) { // neutral itself: Compomer cmpr1; cmpr1.add((*it_neutral) * n, Compomer::RIGHT); explanations_.push_back(cmpr1); Compomer cmpr2; cmpr2.add((*it_neutral) * n, Compomer::LEFT); explanations_.push_back(cmpr2); // neutral in combination with others for (Size i = 0; i < size_of_explanations; ++i) { { Compomer cmpr(explanations_[i]); cmpr.add((*it_neutral) * n, Compomer::RIGHT); explanations_.push_back(cmpr); } { Compomer cmpr(explanations_[i]); cmpr.add((*it_neutral) * n, Compomer::LEFT); explanations_.push_back(cmpr); } } } } // sort according to (in-order) net-charge, mass, probability std::sort(explanations_.begin(), explanations_.end()); // set Ids of compomers, which allows to uniquely identify them (for later lookup) for (size_t i = 0; i < explanations_.size(); ++i) { explanations_[i].setID(i); } #ifdef DEBUG_FD for (size_t ci = 0; ci < explanations_.size(); ++ci) { std::cerr << explanations_[ci] << " "; } #endif std::cout << "MassExplainer table size: " << explanations_.size() << "\n"; } //@name Accessors //@{ /// Sets the set of possible adducts void MassExplainer::setAdductBase(AdductsType adduct_base) { adduct_base_ = std::move(adduct_base); } /// Returns the set of adducts MassExplainer::AdductsType MassExplainer::getAdductBase() const { return adduct_base_; } /// return a compomer by its Id (useful after a query() ). const Compomer& MassExplainer::getCompomerById(Size id) const { return explanations_[id]; } //@} /// search the mass database for explanations /// @param[in] net_charge net charge of compomer /// @param[in] mass_to_explain mass in Da that needs explanation /// @param[in] mass_delta allowed deviation from exact mass /// @param[in] thresh_log_p minimal log probability required /// @param[in] firstExplanation begin range with candidates according to net_charge and mass /// @param[in] lastExplanation end range SignedSize MassExplainer::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 { #ifdef DEBUG_FD if (fabs(mass_to_explain) < 120.0) { std::cout << "query: qnet=" << net_charge << "; explain_mass=" << mass_to_explain << "; delta=+-" << mass_delta << "\n"; } #endif Compomer cmp_low(net_charge, static_cast<double>(mass_to_explain) - fabs(mass_delta), 1); firstExplanation = lower_bound(explanations_.begin(), explanations_.end(), cmp_low); Compomer cmp_high(net_charge, static_cast<double>(mass_to_explain) + fabs(mass_delta), static_cast<double>(thresh_log_p)); lastExplanation = lower_bound(explanations_.begin(), explanations_.end(), cmp_high); return std::distance(firstExplanation, lastExplanation); } ///check if the generated compomer is valid judged by its probability, charges etc bool MassExplainer::compomerValid_(const Compomer& cmp) const { // probability ok? if (cmp.getLogP() < thresh_p_) { return false; } // limit the net charge by the maximal span of co-features if (abs(cmp.getNetCharge()) >= max_span_) { return false; } if (cmp.getNegativeCharges() > q_max_) { return false; } if (cmp.getPositiveCharges() > q_max_) { return false; } //TODO include mass? //if (abs(cmp.mass_) > mass_max_) return false; //std::cout << "valid:: " << cmp <<"\n"; return true; } /// create a proper adduct from formula and charge and probability Adduct MassExplainer::createAdduct_(const String& formula, const Int charge, const double p) const { EmpiricalFormula ef(formula); OPENMS_LOG_DEBUG << "createAdduct_: " << formula << " " << charge << "\n"; //effectively subtract charge electron masses: (-H plus one Proton)*charge ef -= EmpiricalFormula("H" + String(charge)); // subtracts x hydrogen ef.setCharge(charge); // adds x protons Adduct a(charge, 1, ef.getMonoWeight(), formula, log(p), 0); return a; } }
C++
3D
OpenMS/OpenMS
src/openms/source/DATASTRUCTURES/Compomer.cpp
.cpp
10,386
358
// 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 $ // -------------------------------------------------------------------------- #include <OpenMS/DATASTRUCTURES/Adduct.h> #include <OpenMS/DATASTRUCTURES/Compomer.h> #include <OpenMS/CHEMISTRY/EmpiricalFormula.h> #include <iostream> using namespace std; namespace OpenMS { /// Default Constructor Compomer::Compomer() : cmp_(2), net_charge_(0), mass_(0), pos_charges_(0), neg_charges_(0), log_p_(0), rt_shift_(0), id_(0) { } /// Constructor with net-charge and mass Compomer::Compomer(Int net_charge, double mass, double log_p) : cmp_(2), net_charge_(net_charge), mass_(mass), pos_charges_(0), neg_charges_(0), log_p_(log_p), rt_shift_(0), id_(0) { } /// Copy C'tor Compomer::Compomer(const Compomer& p) = default; /// Assignment Operator Compomer& Compomer::operator=(const Compomer& source) { if (&source == this) { return *this; } cmp_ = source.cmp_; net_charge_ = source.net_charge_; mass_ = source.mass_; pos_charges_ = source.pos_charges_; neg_charges_ = source.neg_charges_; log_p_ = source.log_p_; rt_shift_ = source.rt_shift_; id_ = source.id_; return *this; } /// Add a.amount of Adduct @param[in] a to Compomer's @param side and update its properties void Compomer::add(const Adduct& a, UInt side) { if (side >= BOTH) { throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Compomer::add() does not support this value for 'side'!", String(side)); } if (a.getAmount() < 0) { std::cerr << "Compomer::add() was given adduct with negative amount! Are you sure this is what you want?!\n"; } //if (a.getCharge() < 0) //{ // std::cerr << "Compomer::add() was given adduct with negative charge! Are you sure this is what you want?!\n"; //} if (cmp_[side].count(a.getFormula()) == 0) { cmp_[side][a.getFormula()] = a; } else { cmp_[side][a.getFormula()] += a; //update adducts amount } int mult[] = {-1, 1}; net_charge_ += a.getAmount() * a.getCharge() * mult[side]; mass_ += a.getAmount() * a.getSingleMass() * mult[side]; pos_charges_ += std::max(a.getAmount() * a.getCharge() * mult[side], 0); neg_charges_ -= std::min(a.getAmount() * a.getCharge() * mult[side], 0); log_p_ += std::fabs((float)a.getAmount()) * a.getLogProb(); rt_shift_ += a.getAmount() * a.getRTShift() * mult[side]; } /** * indicates if these two compomers can coexist for one feature * @param[in] cmp The other Compomer we compare to * @param[in] side_this Indicates which "side"(negative or positive adducts) we are looking at. Negative adducts belong to the left side of the ChargePair. * @param[in] side_other See above. */ bool Compomer::isConflicting(const Compomer& cmp, UInt side_this, UInt side_other) const { if (side_this >= BOTH) { throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Compomer::isConflicting() does not support this value for 'side_this'!", String(side_this)); } if (side_other >= BOTH) { throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Compomer::isConflicting() does not support this value for 'side_other'!", String(side_other)); } bool conflict_found = false; // size is equal - we need to check more thorough... if (cmp_[side_this].size() == cmp.getComponent()[side_other].size()) { for (CompomerSide::const_iterator it = cmp_[side_this].begin(); it != cmp_[side_this].end(); ++it) { // is it there at all?! if yes: has it the same amount?! CompomerSide::const_iterator it2 = cmp.getComponent()[side_other].find(it->first); if (it2 == cmp.getComponent()[side_other].end() || it2->second.getAmount() != it->second.getAmount()) { conflict_found = true; break; } } } else { conflict_found = true; } // if (conflict_found) std::cout << "found conflict!! between \n" << (*this) << "and\n" << cmp << " at sides i:" << (left_this?"left":"right") << " and j:" << (left_other?"left":"right") << "\n" // << "with implicits i:" << implicit_this.getAmount() << " && j: " << implicit_other.getAmount() << "\n"; return conflict_found; } /// set an Id which allows unique identification of a compomer void Compomer::setID(const Size& id) { id_ = id; } /// return Id which allows unique identification of this compomer const Size& Compomer::getID() const { return id_; } const Compomer::CompomerComponents& Compomer::getComponent() const { return cmp_; } /// net charge of compomer (i.e. difference between left and right side of compomer) const Int& Compomer::getNetCharge() const { return net_charge_; } /// mass of all contained adducts const double& Compomer::getMass() const { return mass_; } /// summed positive charges of contained adducts const Int& Compomer::getPositiveCharges() const { return pos_charges_; } /// summed negative charges of contained adducts const Int& Compomer::getNegativeCharges() const { return neg_charges_; } /// return log probability const double& Compomer::getLogP() const { return log_p_; } /// return RT shift induced by this compomer const double& Compomer::getRTShift() const { return rt_shift_; } String Compomer::getAdductsAsString() const { return "(" + getAdductsAsString(LEFT) + ") --> (" + getAdductsAsString(RIGHT) + ")"; } String Compomer::getAdductsAsString(UInt side) const { if (side >= BOTH) { throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Compomer::getAdductsAsString() does not support this value for 'side'!", String(side)); } String r; for (const auto& [formula, adduct] : cmp_[side]) { Int f = adduct.getAmount(); if (formula.has('+')) { throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "An Adduct contains implicit charge. This is not allowed!", formula); } EmpiricalFormula ef(formula); ef = ef * f; r += ef.toString(); } return r; } bool Compomer::isSingleAdduct(Adduct& a, const UInt side) const { if (side >= BOTH) { throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Compomer::isSimpleAdduct() does not support this value for 'side'!", String(side)); } if (cmp_[side].size() != 1) { return false; } if (cmp_[side].count(a.getFormula()) == 0) { return false; } return true; } Compomer Compomer::removeAdduct(const Adduct& a) const { Compomer tmp = removeAdduct(a, LEFT); tmp = tmp.removeAdduct(a, RIGHT); return tmp; } Compomer Compomer::removeAdduct(const Adduct& a, const UInt side) const { if (side >= BOTH) { throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Compomer::removeAdduct() does not support this value for 'side'!", String(side)); } Compomer tmp(*this); if (tmp.cmp_[side].count(a.getFormula()) > 0) { { // how many instances does this side contain? Int amount = tmp.cmp_[side][a.getFormula()].getAmount(); int mult[] = {-1, 1}; //const Adduct &to_remove = tmp.cmp_[side][a.getFormula()]; tmp.net_charge_ -= amount * a.getCharge() * mult[side]; tmp.mass_ -= amount * a.getSingleMass() * mult[side]; tmp.pos_charges_ -= std::max(amount * a.getCharge() * mult[side], 0); tmp.neg_charges_ -= -std::min(amount * a.getCharge() * mult[side], 0); tmp.log_p_ -= std::fabs((float)amount) * a.getLogProb(); tmp.rt_shift_ -= amount * a.getRTShift() * mult[side]; } // remove entry from map tmp.cmp_[side].erase(a.getFormula()); } return tmp; } StringList Compomer::getLabels(const UInt side) const { if (side >= BOTH) { throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Compomer::getLabels() does not support this value for 'side'!", String(side)); } StringList tmp; for (CompomerSide::const_iterator it = this->cmp_[side].begin(); it != this->cmp_[side].end(); ++it) { if (!it->second.getLabel().empty()) { tmp.push_back(it->second.getLabel()); } } return tmp; } /// Adds @p add_side to this compomer. void Compomer::add(const CompomerSide& add_side, UInt side) { for (CompomerSide::const_iterator it = add_side.begin(); it != add_side.end(); ++it) { this->add(it->second, side); } } /// Sort compomer by (in order of importance): net-charge, mass, probability OPENMS_DLLAPI bool operator<(const Compomer& c1, const Compomer& c2) { // how to sort Compomers: // first by net_charge if (c1.net_charge_ < c2.net_charge_) { return true; } else if (c1.net_charge_ > c2.net_charge_) { return false; } else { // then my mass if (c1.mass_ < c2.mass_) { return true; } else if (c1.mass_ > c2.mass_) { return false; } else { // then by log probability (most probable compomers first!) return c1.log_p_ > c2.log_p_; } } } /// Print the contents of a Compomer to a stream. OPENMS_DLLAPI std::ostream& operator<<(std::ostream& os, const Compomer& cmp) { os << "Compomer: "; os << "Da " << cmp.mass_ << "; q_net " << cmp.net_charge_ << "; logP " << cmp.log_p_ << "[[ "; os << cmp.getAdductsAsString(); os << " ]]\n"; return os; } bool operator==(const Compomer& a, const Compomer& b) { return a.cmp_ == b.cmp_ && a.net_charge_ == b.net_charge_ && a.mass_ == b.mass_ && a.pos_charges_ == b.pos_charges_ && a.neg_charges_ == b.neg_charges_ && a.log_p_ == b.log_p_ && a.id_ == b.id_; } }
C++
3D
OpenMS/OpenMS
src/openms/source/DATASTRUCTURES/DRange.cpp
.cpp
472
16
// 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 $ // -------------------------------------------------------------------------- #include <OpenMS/DATASTRUCTURES/DRange.h> namespace OpenMS { DRange<1> default_drange_1; DRange<2> default_drange_2; }
C++
3D
OpenMS/OpenMS
src/openms/source/DATASTRUCTURES/DataValue.cpp
.cpp
25,599
936
// 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 $ // -------------------------------------------------------------------------- #include <OpenMS/DATASTRUCTURES/DataValue.h> #include <OpenMS/DATASTRUCTURES/ListUtilsIO.h> #include <OpenMS/DATASTRUCTURES/ParamValue.h> #include <QtCore/QString> #include <sstream> using namespace std; namespace OpenMS { const DataValue DataValue::EMPTY; // default ctor DataValue::DataValue() : value_type_(EMPTY_VALUE), unit_type_(OTHER), unit_(-1) { } // destructor DataValue::~DataValue() { clear_(); } const std::string DataValue::NamesOfDataType[] = { "String", "Int", "Double", "StringList", "IntList", "DoubleList", "Empty" }; //------------------------------------------------------------------- // ctor for all supported types a DataValue object can hold //-------------------------------------------------------------------- DataValue::DataValue(long double p) : value_type_(DOUBLE_VALUE), unit_type_(OTHER), unit_(-1) { data_.dou_ = p; } DataValue::DataValue(double p) : value_type_(DOUBLE_VALUE), unit_type_(OTHER), unit_(-1) { data_.dou_ = p; } DataValue::DataValue(float p) : value_type_(DOUBLE_VALUE), unit_type_(OTHER), unit_(-1) { data_.dou_ = p; } DataValue::DataValue(short int p) : value_type_(INT_VALUE), unit_type_(OTHER), unit_(-1) { data_.ssize_ = p; } DataValue::DataValue(unsigned short int p) : value_type_(INT_VALUE), unit_type_(OTHER), unit_(-1) { data_.ssize_ = p; } DataValue::DataValue(int p) : value_type_(INT_VALUE), unit_type_(OTHER), unit_(-1) { data_.ssize_ = p; } DataValue::DataValue(unsigned int p) : value_type_(INT_VALUE), unit_type_(OTHER), unit_(-1) { data_.ssize_ = p; } DataValue::DataValue(long int p) : value_type_(INT_VALUE), unit_type_(OTHER), unit_(-1) { data_.ssize_ = p; } DataValue::DataValue(unsigned long int p) : value_type_(INT_VALUE), unit_type_(OTHER), unit_(-1) { data_.ssize_ = p; } DataValue::DataValue(long long p) : value_type_(INT_VALUE), unit_type_(OTHER), unit_(-1) { data_.ssize_ = p; } DataValue::DataValue(unsigned long long p) : value_type_(INT_VALUE), unit_type_(OTHER), unit_(-1) { data_.ssize_ = p; } DataValue::DataValue(const char* p) : value_type_(STRING_VALUE), unit_type_(OTHER), unit_(-1) { data_.str_ = new String(p); } DataValue::DataValue(const string& p) : value_type_(STRING_VALUE), unit_type_(OTHER), unit_(-1) { data_.str_ = new String(p); } DataValue::DataValue(const QString& p) : value_type_(STRING_VALUE), unit_type_(OTHER), unit_(-1) { data_.str_ = new String(p); } DataValue::DataValue(const String& p) : value_type_(STRING_VALUE), unit_type_(OTHER), unit_(-1) { data_.str_ = new String(p); } DataValue::DataValue(const StringList& p) : value_type_(STRING_LIST), unit_type_(OTHER), unit_(-1) { data_.str_list_ = new StringList(p); } DataValue::DataValue(const IntList& p) : value_type_(INT_LIST), unit_type_(OTHER), unit_(-1) { data_.int_list_ = new IntList(p); } DataValue::DataValue(const DoubleList& p) : value_type_(DOUBLE_LIST), unit_type_(OTHER), unit_(-1) { data_.dou_list_ = new DoubleList(p); } DataValue::DataValue(const ParamValue& p) : unit_type_(OTHER), unit_(-1) { switch (p.valueType()) { case ParamValue::EMPTY_VALUE: value_type_ = EMPTY_VALUE; break; case ParamValue::INT_VALUE: value_type_ = INT_VALUE; data_.ssize_ = p; break; case ParamValue::DOUBLE_VALUE: value_type_ = DOUBLE_VALUE; data_.dou_ = p; break; case ParamValue::STRING_VALUE: value_type_ = STRING_VALUE; data_.str_ = new String(p.toChar()); break; case ParamValue::INT_LIST: value_type_ = INT_LIST; data_.int_list_ = new IntList(p.toIntVector()); break; case ParamValue::DOUBLE_LIST: value_type_ = DOUBLE_LIST; data_.dou_list_ = new DoubleList(p.toDoubleVector()); break; case ParamValue::STRING_LIST: value_type_ = STRING_LIST; data_.str_list_ = new StringList(ListUtils::toStringList<std::string>(p)); break; } } //-------------------------------------------------------------------- // copy and move constructors //-------------------------------------------------------------------- DataValue::DataValue(const DataValue& p) : value_type_(p.value_type_), unit_type_(p.unit_type_), unit_(p.unit_), data_(p.data_) { if (value_type_ == STRING_VALUE) { data_.str_ = new String(*(p.data_.str_)); } else if (value_type_ == STRING_LIST) { data_.str_list_ = new StringList(*(p.data_.str_list_)); } else if (value_type_ == INT_LIST) { data_.int_list_ = new IntList(*(p.data_.int_list_)); } else if (value_type_ == DOUBLE_LIST) { data_.dou_list_ = new DoubleList(*(p.data_.dou_list_)); } } DataValue::DataValue(DataValue&& rhs) noexcept : value_type_(std::move(rhs.value_type_)), unit_type_(std::move(rhs.unit_type_)), unit_(std::move(rhs.unit_)), data_(std::move(rhs.data_)) { // clean up rhs, take ownership of data_ // NOTE: value_type_ == EMPTY_VALUE implies data_ is empty and can be reset rhs.value_type_ = EMPTY_VALUE; rhs.unit_type_ = OTHER; rhs.unit_ = -1; } void DataValue::clear_() noexcept { if (value_type_ == STRING_LIST) { delete(data_.str_list_); } else if (value_type_ == STRING_VALUE) { delete(data_.str_); } else if (value_type_ == INT_LIST) { delete(data_.int_list_); } else if (value_type_ == DOUBLE_LIST) { delete(data_.dou_list_); } value_type_ = EMPTY_VALUE; unit_type_ = OTHER; unit_ = -1; } //-------------------------------------------------------------------- // copy and move assignment operators //-------------------------------------------------------------------- DataValue& DataValue::operator=(const DataValue& p) { // Check for self-assignment if (this == &p) { return *this; } // clean up clear_(); // assign if (p.value_type_ == STRING_LIST) { data_.str_list_ = new StringList(*(p.data_.str_list_)); } else if (p.value_type_ == STRING_VALUE) { data_.str_ = new String(*(p.data_.str_)); } else if (p.value_type_ == INT_LIST) { data_.int_list_ = new IntList(*(p.data_.int_list_)); } else if (p.value_type_ == DOUBLE_LIST) { data_.dou_list_ = new DoubleList(*(p.data_.dou_list_)); } else { data_ = p.data_; } // copy type value_type_ = p.value_type_; unit_type_ = p.unit_type_; unit_ = p.unit_; return *this; } /// Move assignment operator DataValue& DataValue::operator=(DataValue&& rhs) noexcept { // Check for self-assignment if (this == &rhs) { return *this; } // clean up *this clear_(); // assign values to *this data_ = rhs.data_; value_type_ = rhs.value_type_; unit_type_ = rhs.unit_type_; unit_ = rhs.unit_; // clean up rhs rhs.value_type_ = EMPTY_VALUE; rhs.unit_type_ = OTHER; rhs.unit_ = -1; return *this; } //-------------------------------------------------------------------- // assignment conversion operator //-------------------------------------------------------------------- DataValue& DataValue::operator=(const char* arg) { clear_(); data_.str_ = new String(arg); value_type_ = STRING_VALUE; return *this; } DataValue& DataValue::operator=(const std::string& arg) { clear_(); data_.str_ = new String(arg); value_type_ = STRING_VALUE; return *this; } DataValue& DataValue::operator=(const String& arg) { clear_(); data_.str_ = new String(arg); value_type_ = STRING_VALUE; return *this; } DataValue& DataValue::operator=(const QString& arg) { clear_(); data_.str_ = new String(arg); value_type_ = STRING_VALUE; return *this; } DataValue& DataValue::operator=(const StringList& arg) { clear_(); data_.str_list_ = new StringList(arg); value_type_ = STRING_LIST; return *this; } DataValue& DataValue::operator=(const IntList& arg) { clear_(); data_.int_list_ = new IntList(arg); value_type_ = INT_LIST; return *this; } DataValue& DataValue::operator=(const DoubleList& arg) { clear_(); data_.dou_list_ = new DoubleList(arg); value_type_ = DOUBLE_LIST; return *this; } DataValue& DataValue::operator=(const long double arg) { clear_(); data_.dou_ = arg; value_type_ = DOUBLE_VALUE; return *this; } DataValue& DataValue::operator=(const double arg) { clear_(); data_.dou_ = arg; value_type_ = DOUBLE_VALUE; return *this; } DataValue& DataValue::operator=(const float arg) { clear_(); data_.dou_ = arg; value_type_ = DOUBLE_VALUE; return *this; } DataValue& DataValue::operator=(const short int arg) { clear_(); data_.ssize_ = arg; value_type_ = INT_VALUE; return *this; } DataValue& DataValue::operator=(const unsigned short int arg) { clear_(); data_.ssize_ = arg; value_type_ = INT_VALUE; return *this; } DataValue& DataValue::operator=(const int arg) { clear_(); data_.ssize_ = arg; value_type_ = INT_VALUE; return *this; } DataValue& DataValue::operator=(const unsigned arg) { clear_(); data_.ssize_ = arg; value_type_ = INT_VALUE; return *this; } DataValue& DataValue::operator=(const long int arg) { clear_(); data_.ssize_ = arg; value_type_ = INT_VALUE; return *this; } DataValue& DataValue::operator=(const unsigned long arg) { clear_(); data_.ssize_ = arg; value_type_ = INT_VALUE; return *this; } DataValue& DataValue::operator=(const long long arg) { clear_(); data_.ssize_ = arg; value_type_ = INT_VALUE; return *this; } DataValue& DataValue::operator=(const unsigned long long arg) { clear_(); data_.ssize_ = arg; value_type_ = INT_VALUE; return *this; } //--------------------------------------------------------------------------- // Conversion operators //---------------------------------------------------------------------------- DataValue::operator long double() const { if (value_type_ == EMPTY_VALUE) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not convert DataValue of type '" + NamesOfDataType[value_type_] + "' to long double"); } else if (value_type_ == INT_VALUE) { return (long double)(data_.ssize_); } return data_.dou_; } DataValue::operator double() const { if (value_type_ == EMPTY_VALUE) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not convert DataValue of type '" + NamesOfDataType[value_type_] + "' to double"); } else if (value_type_ == INT_VALUE) { return double(data_.ssize_); } return data_.dou_; } DataValue::operator float() const { if (value_type_ == EMPTY_VALUE) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not convert DataValue of type '" + NamesOfDataType[value_type_] + "' to float"); } else if (value_type_ == INT_VALUE) { return float(data_.ssize_); } return data_.dou_; } DataValue::operator short int() const { if (value_type_ != INT_VALUE) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not convert non-integer DataValue of type '" + NamesOfDataType[value_type_] + "' and value '" + this->toString(true) + "' to short int"); } return data_.ssize_; } DataValue::operator unsigned short int() const { if (value_type_ != INT_VALUE) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not convert non-integer DataValue of type '" + NamesOfDataType[value_type_] + "' and value '" + this->toString(true) + "' to unsigned short int"); } if (data_.ssize_ < 0.0) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not convert negative integer DataValue with value '" + String(data_.ssize_) + "' to unsigned short int"); } return data_.ssize_; } DataValue::operator int() const { if (value_type_ != INT_VALUE) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not convert non-integer DataValue of type '" + NamesOfDataType[value_type_] + "' and value '" + this->toString(true) + "' to int"); } return data_.ssize_; } DataValue::operator unsigned int() const { if (value_type_ != INT_VALUE) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not convert non-integer DataValue of type '" + NamesOfDataType[value_type_] + "' and value '" + this->toString(true) + "' to unsigned int"); } if (data_.ssize_ < 0.0) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not convert negative integer DataValue with value '" + String(data_.ssize_) + "' to unsigned int"); } return data_.ssize_; } DataValue::operator long int() const { if (value_type_ != INT_VALUE) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not convert non-integer DataValue of type '" + NamesOfDataType[value_type_] + "' and value '" + this->toString(true) + "' to long int"); } return data_.ssize_; } DataValue::operator unsigned long int() const { if (value_type_ != INT_VALUE) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not convert non-integer DataValue of type '" + NamesOfDataType[value_type_] + "' and value '" + this->toString(true) + "' to unsigned long int"); } if (data_.ssize_ < 0.0) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not convert negative integer DataValue with value '" + String(data_.ssize_) + "' to unsigned long int"); } return data_.ssize_; } DataValue::operator long long() const { if (value_type_ != INT_VALUE) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not convert non-integer DataValue of type '" + NamesOfDataType[value_type_] + "' and value '" + this->toString(true) + "' to long"); } return data_.ssize_; } DataValue::operator unsigned long long() const { if (value_type_ != INT_VALUE) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not convert non-integer DataValue of type '" + NamesOfDataType[value_type_] + "' and value '" + this->toString(true) + "' to unsigned long"); } if (data_.ssize_ < 0.0) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not convert negative integer DataValue with value '" + String(data_.ssize_) + "' to unsigned long long"); } return data_.ssize_; } DataValue::operator ParamValue() const { switch (value_type_) { case EMPTY_VALUE: return ParamValue(); case INT_VALUE: return ParamValue(int(*this)); case DOUBLE_VALUE: return ParamValue(double(*this)); case STRING_VALUE: return ParamValue(std::string(*this)); case INT_LIST: return ParamValue(this->toIntList()); case DOUBLE_LIST: return ParamValue(this->toDoubleList()); case STRING_LIST: { // DataValue uses OpenMS::String while ParamValue uses std:string. // Therefore the StringList isn't castable. vector<std::string> v; for (const String& s : this->toStringList()) { v.push_back(s); } return ParamValue(v); } default: throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Type of DataValue is unknown!"); } throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Type of DataValue is unknown!"); } DataValue::operator std::string() const { if (value_type_ != STRING_VALUE) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not convert non-string DataValue of type '" + NamesOfDataType[value_type_] + "' and value '" + this->toString(true) + "' to string"); } return *(data_.str_); } DataValue::operator StringList() const { return this->toStringList(); } DataValue::operator IntList() const { return this->toIntList(); } DataValue::operator DoubleList() const { return this->toDoubleList(); } // Convert DataValues to char* const char* DataValue::toChar() const { switch (value_type_) { case DataValue::STRING_VALUE: return const_cast<const char*>(data_.str_->c_str()); case DataValue::EMPTY_VALUE: return nullptr; default: throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not convert DataValue of type '" + NamesOfDataType[value_type_] + "' and value '" + this->toString(true) + "' to char*"); } } StringList DataValue::toStringList() const { if (value_type_ != STRING_LIST) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not convert non-StringList DataValue of type '" + NamesOfDataType[value_type_] + "' and value '" + this->toString(true) + "' to StringList"); } return *(data_.str_list_); } IntList DataValue::toIntList() const { if (value_type_ != INT_LIST) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not convert non-IntList DataValue of type '" + NamesOfDataType[value_type_] + "' and value '" + this->toString(true) + "' to IntList"); } return *(data_.int_list_); } DoubleList DataValue::toDoubleList() const { if (value_type_ != DOUBLE_LIST) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not convert non-DoubleList DataValue of type '" + NamesOfDataType[value_type_] + "' and value '" + this->toString(true) + "' to DoubleList"); } return *(data_.dou_list_); } // Convert DataValues to String String DataValue::toString(bool full_precision) const { std::stringstream ss; switch (value_type_) { case DataValue::EMPTY_VALUE: break; case DataValue::STRING_VALUE: return *(data_.str_); case DataValue::STRING_LIST: ss << *(data_.str_list_); break; case DataValue::INT_LIST: ss << *(data_.int_list_); break; case DataValue::DOUBLE_LIST: if (full_precision) { ss << *(data_.dou_list_); } else { ss << VecLowPrecision<double>(*(data_.dou_list_)); } break; case DataValue::INT_VALUE: return String(data_.ssize_); case DataValue::DOUBLE_VALUE: return String(data_.dou_, full_precision); default: throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not convert DataValue of type '" + NamesOfDataType[value_type_] + "' to String"); } return ss.str(); } QString DataValue::toQString() const { return toString(true).toQString(); } bool DataValue::toBool() const { if (value_type_ != STRING_VALUE) { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Could not convert non-string DataValue of type '" + NamesOfDataType[value_type_] + "' and value '" + this->toString(true) + "' to bool"); } else if (*(data_.str_) != "true" && *(data_.str_) != "false") { throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String("Could not convert non-string DataValue of type '") + NamesOfDataType[value_type_] + "' and value '" + *(data_.str_) + "' to bool. Valid stings are 'true' and 'false'."); } return *(data_.str_) == "true"; } // ----------------- Comparator ---------------------- bool operator==(const DataValue& a, const DataValue& b) { if (a.value_type_ == b.value_type_ && a.unit_type_ == b.unit_type_ && a.unit_ == b.unit_) { switch (a.value_type_) { case DataValue::EMPTY_VALUE: return b.value_type_ == DataValue::EMPTY_VALUE; case DataValue::STRING_VALUE: return *(a.data_.str_) == *(b.data_.str_); case DataValue::STRING_LIST: return *(a.data_.str_list_) == *(b.data_.str_list_); case DataValue::INT_LIST: return *(a.data_.int_list_) == *(b.data_.int_list_); case DataValue::DOUBLE_LIST: return *(a.data_.dou_list_) == *(b.data_.dou_list_); case DataValue::INT_VALUE: return a.data_.ssize_ == b.data_.ssize_; case DataValue::DOUBLE_VALUE: return fabs(a.data_.dou_ - b.data_.dou_) < 1e-6; default: throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Type of DataValue is unkown!"); } } return false; } bool operator<(const DataValue& a, const DataValue& b) { if (a.value_type_ == b.value_type_) { switch (a.value_type_) { case DataValue::EMPTY_VALUE: return false; case DataValue::STRING_VALUE: return *(a.data_.str_) < *(b.data_.str_); case DataValue::STRING_LIST: return a.data_.str_list_->size() < b.data_.str_list_->size(); case DataValue::INT_LIST: return a.data_.int_list_->size() < b.data_.int_list_->size(); case DataValue::DOUBLE_LIST: return a.data_.dou_list_->size() < b.data_.dou_list_->size(); case DataValue::INT_VALUE: return a.data_.ssize_ < b.data_.ssize_; case DataValue::DOUBLE_VALUE: return a.data_.dou_ < b.data_.dou_; default: throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Type of DataValue is unkown!"); } } return false; } bool operator>(const DataValue& a, const DataValue& b) { if (a.value_type_ == b.value_type_) { switch (a.value_type_) { case DataValue::EMPTY_VALUE: return false; case DataValue::STRING_VALUE: return *(a.data_.str_) > *(b.data_.str_); case DataValue::STRING_LIST: return a.data_.str_list_->size() > b.data_.str_list_->size(); case DataValue::INT_LIST: return a.data_.int_list_->size() > b.data_.int_list_->size(); case DataValue::DOUBLE_LIST: return a.data_.dou_list_->size() > b.data_.dou_list_->size(); case DataValue::INT_VALUE: return a.data_.ssize_ > b.data_.ssize_; case DataValue::DOUBLE_VALUE: return a.data_.dou_ > b.data_.dou_; default: throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Type of DataValue is unkown!"); } } return false; } bool operator!=(const DataValue& a, const DataValue& b) { return !(a == b); } // ----------------- Output operator ---------------------- /// for doubles or lists of doubles, you get full precision. Use DataValue::toString(false) if you only need low precision std::ostream& operator<<(std::ostream& os, const DataValue& p) { switch (p.value_type_) { case DataValue::STRING_VALUE: os << *(p.data_.str_); break; case DataValue::STRING_LIST: os << *(p.data_.str_list_); break; case DataValue::INT_LIST: os << *(p.data_.int_list_); break; case DataValue::DOUBLE_LIST: os << *(p.data_.dou_list_); break; case DataValue::INT_VALUE: os << String(p.data_.ssize_); break; // using our String conversion (faster than os) case DataValue::DOUBLE_VALUE: os << String(p.data_.dou_); break; // using our String conversion (faster than os) case DataValue::EMPTY_VALUE: break; default: throw Exception::ConversionError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Type of DataValue is unkown!"); } return os; } // ----------------- Unit methods ---------------------- const int32_t& DataValue::getUnit() const { return unit_; } void DataValue::setUnit(const int32_t& unit) { unit_ = unit; } DataValue::DataType DataValue::valueType() const { return value_type_; } bool DataValue::isEmpty() const { return value_type_ == EMPTY_VALUE; } DataValue::UnitType DataValue::getUnitType() const { return unit_type_; } void DataValue::setUnitType(const DataValue::UnitType & u) { unit_type_ = u; } bool DataValue::hasUnit() const { return unit_ != -1; } } // namespace OpenMS
C++
3D
OpenMS/OpenMS
src/openms/source/DATASTRUCTURES/ConstRefVector.cpp
.cpp
658
18
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: $ // -------------------------------------------------------------------------- #include <OpenMS/DATASTRUCTURES/ConstRefVector.h> #include <OpenMS/KERNEL/FeatureMap.h> namespace OpenMS { ConstRefVector<FeatureMap > default_constrefvector; ConstRefVector<FeatureMap >::Iterator default_constrefvector_iterator; ConstRefVector<FeatureMap >::ConstIterator default_constrefvector_constiterator; }
C++
3D
OpenMS/OpenMS
src/openms/source/DATASTRUCTURES/GridFeature.cpp
.cpp
1,763
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 $ // -------------------------------------------------------------------------- #include <OpenMS/DATASTRUCTURES/GridFeature.h> #include <OpenMS/KERNEL/BaseFeature.h> #include <OpenMS/METADATA/PeptideIdentification.h> using namespace std; namespace OpenMS { GridFeature::GridFeature(const BaseFeature& feature, Size map_index, Size feature_index) : feature_(feature), map_index_(map_index), feature_index_(feature_index), annotations_() { const PeptideIdentificationList& peptides = feature.getPeptideIdentifications(); for (PeptideIdentificationList::const_iterator pep_it = peptides.begin(); pep_it != peptides.end(); ++pep_it) { if (pep_it->getHits().empty()) { continue; // shouldn't be the case } annotations_.insert(pep_it->getHits()[0].getSequence()); } } GridFeature::~GridFeature() = default; const BaseFeature& GridFeature::getFeature() const { return feature_; } Size GridFeature::getMapIndex() const { return map_index_; } Size GridFeature::getFeatureIndex() const { return feature_index_; } Int GridFeature::getID() const { return (Int)feature_index_; } const set<AASequence>& GridFeature::getAnnotations() const { return annotations_; } double GridFeature::getRT() const { return feature_.getRT(); } double GridFeature::getMZ() const { return feature_.getMZ(); } }
C++
3D
OpenMS/OpenMS
src/openms/source/DATASTRUCTURES/Date.cpp
.cpp
1,805
83
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg$ // $Authors: Marc Sturm $ // -------------------------------------------------------------------------- #include <OpenMS/DATASTRUCTURES/Date.h> #include <OpenMS/CONCEPT/Exception.h> using namespace std; namespace OpenMS { Date::Date(const QDate& date) : QDate(date) { } void Date::set(const String& date) { clear(); //check for format (german/english) if (date.has('.')) { QDate::operator=(QDate::fromString(date.c_str(), "dd.MM.yyyy")); } else if (date.has('/')) { QDate::operator=(QDate::fromString(date.c_str(), "MM/dd/yyyy")); } else if (date.has('-')) { QDate::operator=(QDate::fromString(date.c_str(), "yyyy-MM-dd")); } if (!isValid()) { throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, date, "Is no valid german, english or iso date"); } } void Date::set(UInt month, UInt day, UInt year) { if (!setDate(year, month, day)) { throw Exception::ParseError(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, String(year) + "-" + String(month) + "-" + String(day), "Invalid date"); } } Date Date::today() { return QDate::currentDate(); } String Date::get() const { if (QDate::isValid()) { return toString("yyyy-MM-dd"); } return "0000-00-00"; } void Date::get(UInt& month, UInt& day, UInt& year) const { day = QDate::day(); month = QDate::month(); year = QDate::year(); } void Date::clear() { QDate::operator=(QDate()); } } // namespace OpenMS
C++
3D
OpenMS/OpenMS
src/openms/source/DATASTRUCTURES/OSWData.cpp
.cpp
4,397
129
// 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 $ // -------------------------------------------------------------------------- #include <OpenMS/DATASTRUCTURES/OSWData.h> #include <OpenMS/CONCEPT/Exception.h> #include <OpenMS/KERNEL/MSExperiment.h> namespace OpenMS { const char* OSWHierarchy::LevelName[] = { "protein", "peptide", "feature/peakgroup", "transition" }; void OSWData::addProtein(OSWProtein&& prot) { // check if transitions are known checkTransitions_(prot); proteins_.push_back(std::move(prot)); } void OSWData::clear() { transitions_.clear(); proteins_.clear(); } void OSWData::clearProteins() { proteins_.clear(); } void OSWData::buildNativeIDResolver(const MSExperiment& chrom_traces) { // first check if the MSExperiment originates from the same run by checking for matching run-ids if (chrom_traces.getSqlRunID() != getRunID()) { throw Exception::Precondition(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "The RUN.ID of the sqMass/MSExperiment ('" + String(chrom_traces.getSqlRunID()) + "') and the OSW file ('" + String(getRunID()) + "') does not match. " "Please use a recent version of OpenSwathWorkflow to create matching data."); } Size chrom_count = chrom_traces.getChromatograms().size(); for (Size i = 0; i < chrom_count; ++i) { const auto& chrom = chrom_traces.getChromatograms()[i]; UInt32 nid; try { nid = chrom.getNativeID().toInt(); } catch (...) { // probably a precursor native ID, e.g. 5543_precursor_i0 .. currently not handled. continue; } if (transitions_.find(nid) == transitions_.end()) { throw Exception::MissingInformation(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Transition with nativeID " + (String(nid)) + " not found in OSW data. Make sure the OSW data was loaded!"); } transID_to_index_[nid] = (UInt32)i; } } UInt OSWData::fromNativeID(int transition_id) const { auto it = transID_to_index_.find(transition_id); if (it == transID_to_index_.end()) { throw Exception::InvalidValue(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Native ID not found in sqMass file. Did you load the correct file (corresponding sqMass + OSW file)?", String(transition_id)); } return it->second; } void OSWData::checkTransitions_(const OSWProtein& prot) const { for (const auto& pc : prot.getPeptidePrecursors()) { for (const auto& f : pc.getFeatures()) { for (const auto& tr : f.getTransitionIDs()) { if (transitions_.find(tr) == transitions_.end()) { throw Exception::Precondition(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION, "Transition with ID " + String(tr) + " was referenced in Protein/Precursor/Feature but is not known!"); } } } } } OSWProtein::OSWProtein(const String& accession, const Size id, std::vector<OSWPeptidePrecursor>&& peptides) : accession_(accession), id_(id), peptides_(std::move(peptides)) {} OSWPeptidePrecursor::OSWPeptidePrecursor(const String& seq, const short charge, const bool decoy, const float precursor_mz, std::vector<OSWPeakGroup>&& features) : seq_(seq), charge_(charge), decoy_(decoy), precursor_mz_(precursor_mz), features_(std::move(features)) { } OSWPeakGroup::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) : rt_experimental_(rt_experimental), rt_left_width_(rt_left_width), rt_right_width_(rt_right_width), rt_delta_(rt_delta), q_value_(q_value), transition_ids_(std::move(transition_ids)) { } OSWTransition::OSWTransition(const String& annotation, const UInt32 id, const float product_mz, const char type, const bool is_decoy) : annotation_(annotation), id_(id), product_mz_(product_mz), type_(type), is_decoy_(is_decoy) {} }
C++
3D
OpenMS/OpenMS
src/tests/topp/ProteomicsLFQTestScripts/run_fast.sh
.sh
1,047
17
#!/bin/bash ./bin/ProteomicsLFQ -in ../share/OpenMS/examples/FRACTIONS/BSA1_F1.mzML ../share/OpenMS/examples/FRACTIONS/BSA1_F2.mzML ../share/OpenMS/examples/FRACTIONS/BSA2_F1.mzML \ ../share/OpenMS/examples/FRACTIONS/BSA2_F2.mzML ../share/OpenMS/examples/FRACTIONS/BSA3_F1.mzML ../share/OpenMS/examples/FRACTIONS/BSA3_F2.mzML \ -ids ../share/OpenMS/examples/FRACTIONS/BSA1_F1.idXML ../share/OpenMS/examples/FRACTIONS/BSA1_F2.idXML ../share/OpenMS/examples/FRACTIONS/BSA2_F1.idXML ../share/OpenMS/examples/FRACTIONS/BSA2_F2.idXML ../share/OpenMS/examples/FRACTIONS/BSA3_F1.idXML ../share/OpenMS/examples/FRACTIONS/BSA3_F2.idXML \ -design ../share/OpenMS/examples/FRACTIONS/BSA_design.tsv \ -Alignment:max_rt_shift 0 \ -fasta ../share/OpenMS/examples/TOPPAS/data/BSA_Identification/18Protein_SoCe_Tr_detergents_trace_target_decoy.fasta \ -targeted_only true \ -transfer_ids "false" \ -mass_recalibration "false" \ -out_cxml BSA.consensusXML \ -out_msstats BSA.csv \ -out BSA.mzTab -threads 4 ./bin/FileInfo -in BSA.consensusXML -out BSA.fileinfo
Shell
3D
OpenMS/OpenMS
src/tests/topp/ProteomicsLFQTestScripts/run_BSA.sh
.sh
1,865
39
#!/bin/bash export PATH="$PATH:/Users/pfeuffer/git/OpenMS-inference-src/cmake-build-debug/bin" export PATH="$PATH:/Users/pfeuffer/git/THIRDPARTY/MacOS/64bit/percolator" export MSGF_PATH="/Users/pfeuffer/git/THIRDPARTY/All/MSGFPlus/MSGFPlus.jar" #input data export DATA_PATH="/Users/pfeuffer/git/OpenMS-inference-src/share/OpenMS/examples/FRACTIONS/" # perform search, score calibration, and PSM-level q-value/PEP estimation # percolator doesn't work on the small file so we use IDPEP instead for f in ${DATA_PATH}/*.mzML; do echo $f fn=${f%.mzML} # filename and path without mzML extension # search ( we need multiple matches so we can build a proper decoy model on this small dataset) MSGFPlusAdapter -in ${f} -out ${fn}.idXML -database ${DATA_PATH}../TOPPAS/data/BSA_Identification/18Protein_SoCe_Tr_detergents_trace_target_decoy.fasta -executable ${MSGF_PATH} -max_precursor_charge 5 -matches_per_spec 10 # annotate target/decoy and protein links PeptideIndexer -fasta ${DATA_PATH}../TOPPAS/data/BSA_Identification/18Protein_SoCe_Tr_detergents_trace_target_decoy.fasta -in ${fn}.idXML -out ${fn}.idXML -enzyme:specificity none IDPosteriorErrorProbability -in ${fn}.idXML -out ${fn}.idXML -out_plot ${fn}_fit.txt done # changeed protein FDR filtering threshold... ProteomicsLFQ -in \ ${DATA_PATH}/BSA1.mzML ${DATA_PATH}/BSA2.mzML ${DATA_PATH}/BSA3.mzML \ -ids \ ${DATA_PATH}/BSA1.idXML ${DATA_PATH}/BSA2.idXML ${DATA_PATH}/BSA3.idXML \ -design ${DATA_PATH}/experimental_design.tsv \ -Alignment:max_rt_shift 0.1 \ -fasta ${DATA_PATH}/../TOPPAS/data/BSA_Identification/18Protein_SoCe_Tr_detergents_trace_target_decoy.fasta -targeted_only "true" \ -transfer_ids "false" \ -proteinFDR 0.3 \ -mass_recalibration "false" \ -out_msstats "BSA_targeted_only.csv" \ -out_cxml "BSA_targeted_only.consensusXML" \ -out BSA_targeted_only.mzTab -debug 0 \
Shell
3D
OpenMS/OpenMS
src/tests/topp/ProteomicsLFQTestScripts/run_lfq.sh
.sh
3,175
52
#!bin/bash export PATH="$PATH:/home/sachsenb/OpenMS/openms-build-tmp/bin" export PATH="$PATH:/home/sachsenb/OpenMS/THIRDPARTY/Linux/64bit/Percolator" export MSGF_PATH="/home/sachsenb/OpenMS/THIRDPARTY/All/MSGFPlus/MSGFPlus.jar" #input data export DATA_PATH="/home/sachsenb/OpenMS/openms-build/yasset_iPRG2015" # perform search, score calibration, and PSM-level q-value/PEP estimation for f in ${DATA_PATH}/*.mzML; do echo $f fn=${f%.mzML} # filename and path without mzML extension # search with default fixed and variable mods MSGFPlusAdapter -in ${f} -out ${fn}.idXML -database ${DATA_PATH}/iPRG2015_decoy.fasta -executable ${MSGF_PATH} -max_precursor_charge 5 -threads 10 # annotate target/decoy and protein links PeptideIndexer -fasta ${DATA_PATH}/iPRG2015_decoy.fasta -in ${fn}.idXML -out ${fn}.idXML -enzyme:specificity none # run percolator so we get well calibrated PEPs and q-values PSMFeatureExtractor -in ${fn}.idXML -out ${fn}.idXML PercolatorAdapter -in ${fn}.idXML -out ${fn}.idXML -percolator_executable percolator -post_processing_tdc -subset_max_train 100000 FalseDiscoveryRate -in ${fn}.idXML -out ${fn}.idXML -algorithm:add_decoy_peptides -algorithm:add_decoy_proteins # pre-filter to 5% PSM-level FDR to reduce data IDFilter -in ${fn}.idXML -out ${fn}.idXML -score:pep 0.05 # switch to PEP score IDScoreSwitcher -in ${fn}.idXML -out ${fn}.idXML -old_score q-value -new_score MS:1001493 -new_score_orientation lower_better -new_score_type "Posterior Error Probability" done ########################### ProteomicsLFQ -in \ ${DATA_PATH}/JD_06232014_sample1_A.mzML ${DATA_PATH}/JD_06232014_sample1_B.mzML ${DATA_PATH}/JD_06232014_sample1_C.mzML \ ${DATA_PATH}/JD_06232014_sample2_A.mzML ${DATA_PATH}/JD_06232014_sample2_B.mzML ${DATA_PATH}/JD_06232014_sample2_C.mzML \ ${DATA_PATH}/JD_06232014_sample3_A.mzML ${DATA_PATH}/JD_06232014_sample3_B.mzML ${DATA_PATH}/JD_06232014_sample3_C.mzML \ ${DATA_PATH}/JD_06232014_sample4_A.mzML ${DATA_PATH}/JD_06232014_sample4_B.mzML ${DATA_PATH}/JD_06232014_sample4_C.mzML \ -ids \ ${DATA_PATH}/JD_06232014_sample1_A.idXML ${DATA_PATH}/JD_06232014_sample1_B.idXML ${DATA_PATH}/JD_06232014_sample1_C.idXML \ ${DATA_PATH}/JD_06232014_sample2_A.idXML ${DATA_PATH}/JD_06232014_sample2_B.idXML ${DATA_PATH}/JD_06232014_sample2_C.idXML \ ${DATA_PATH}/JD_06232014_sample3_A.idXML ${DATA_PATH}/JD_06232014_sample3_B.idXML ${DATA_PATH}/JD_06232014_sample3_C.idXML \ ${DATA_PATH}/JD_06232014_sample4_A.idXML ${DATA_PATH}/JD_06232014_sample4_B.idXML ${DATA_PATH}/JD_06232014_sample4_C.idXML \ -design ${DATA_PATH}/experimental_design.tsv \ -Alignment:max_rt_shift 0.1 \ -fasta ${DATA_PATH}/iPRG2015_decoy.fasta -targeted_only "true" \ -transfer_ids "false" \ -mass_recalibration "true" \ -out_msstats "iPRG2015_targeted_only.csv" \ -out_cxml "iPRG2015_targeted_only.consensusXML" \ -out iPRG2015_targeted_only.mzTab \ > iPRG2015_targeted_only.log FileInfo -in iPRG2015_targeted_only.consensusXML > iPRG2015_targeted_only.fileinfo Rscript ./home/sachsenb/OpenMS/share/OpenMS/SCRIPTS/ProteomicsLFQ.R iPRG2015_targeted_only.csv iPRG2015_targeted_only.mzTab iPRG2015_targeted_only_final.mzTab
Shell
3D
OpenMS/OpenMS
src/tests/external/ExampleLibraryFile.h
.h
630
28
// 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 <string> //optional namespace... however you like it namespace OpenMSExternal { class ExampleLibraryFile { public: static std::string printSomething(); // just to have a dependency to OpenMS in the lib void loadAndSaveFeatureXML(); }; }
Unknown
3D
OpenMS/OpenMS
src/tests/external/ExampleLibraryFile.cpp
.cpp
1,061
38
// 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 $ // -------------------------------------------------------------------------- #include "ExampleLibraryFile.h" #include <OpenMS/KERNEL/Feature.h> #include <OpenMS/KERNEL/FeatureMap.h> #include <OpenMS/FORMAT/FileHandler.h> using namespace std; using namespace OpenMS; //optional namespace... however you like it namespace OpenMSExternal { std::string ExampleLibraryFile::printSomething() { return "this is the external library."; } void ExampleLibraryFile::loadAndSaveFeatureXML() { FeatureMap fm; Feature feature; fm.push_back(feature); String tmpfilename = "tmpfile.featureXML"; FileHandler().storeFeatures(tmpfilename, fm, {FileTypes::FEATUREXML}); FeatureMap fm2; FileHandler().storeFeatures(tmpfilename, fm2, {FileTypes::FEATUREXML}); } }
C++
3D
OpenMS/OpenMS
src/tests/external/TestExternalCode.cpp
.cpp
1,082
37
// 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 $ // -------------------------------------------------------------------------- #include <OpenMS/KERNEL/MSExperiment.h> #include <OpenMS/FORMAT/FileHandler.h> #include "ExampleLibraryFile.h" using namespace OpenMS; using namespace OpenMSExternal; int main(int argc, char * argv[]) { std::cout << "Call OpenMS function from ExampleLibraryFile" << std::endl; ExampleLibraryFile().loadAndSaveFeatureXML(); std::string s = ExampleLibraryFile::printSomething(); std::cout << "From external lib: " << s << "\n"; PeakMap exp; FileHandler f; String tmpfilename = "tmpfile.mzML"; f.storeExperiment(tmpfilename,exp, {FileTypes::MZML}); f.loadExperiment(tmpfilename,exp, {FileTypes::MZML}); std::cout << "Loading and storing of mzML worked!\n"; std::cout << "All good and well!\n"; return 0; }
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms_gui/include/GUI/TSGDialog_test.h
.h
1,352
59
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Tom Waschischeck $ // $Authors: Tom Waschischeck $ // -------------------------------------------------------------------------- #include <QtTest/QtTest> #include <QtGui> #include <QtWidgets/QSpinBox> #include <OpenMS/VISUAL/DIALOGS/TheoreticalSpectrumGenerationDialog.h> #include <ui_TheoreticalSpectrumGenerationDialog.h> #define UI dialog_.ui_ namespace OpenMS { class TestTSGDialog : public QObject { Q_OBJECT public: TestTSGDialog() : dialog_() {} ~TestTSGDialog() { dialog_.destroy(); } private slots: void testConstruction(); void testGui(); void testParameterImport(); void testSpectrumCalculation(); void testErrors(); private: template<typename T> // template for QSpinBox and QDoubleSpinBox void testSpinBox_(T* box, std::string str_value = "2"); void testIonsIntensities_(); void testSequenceInput_(QString input); void testIsotopeModel_(bool skip_none = false); void checkMessageBoxExists_(); void testMessageBoxes_(); TheoreticalSpectrumGenerationDialog dialog_; }; }
Unknown
3D
OpenMS/OpenMS
src/tests/class_tests/openms_gui/include/GUI/TOPPView_test.h
.h
2,800
98
// 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 $ // -------------------------------------------------------------------------- #ifndef TEST_GUI_TESTTOPPVIEW_H #define TEST_GUI_TESTTOPPVIEW_H #include <QtTest/QtTest> #include <QtGui> #include <QQueue> #include <OpenMS/DATASTRUCTURES/String.h> namespace OpenMS { class String; /** @todo write a proper GUI base class for the scheduler below (Chris) */ class TestTOPPView: public QObject { Q_OBJECT /** @brief Store information on timed keyboard input events Store the time offset, the key sequence and the expected window title. */ struct ScheduleInfo { ScheduleInfo() : delay(0) {} ScheduleInfo(QString p_keys, QString p_title, int p_delay) : keys(p_keys), title(p_title), delay(p_delay) {} QString keys; //< key sequence QString title;//< expected window title int delay; //< delay in ms when event is fired off }; public slots: /** @brief Slot that tries to process the current event queue for modal dialogs until its empty. Slot that tries to process the current event queue for modal dialogs until its empty. The function will repeatedly invoke itself until the queue is empty, to allow other incoming events (e.g. loading a file) to be processed in between two scheduled dialogs. */ void simulateClick_(); private slots: void testGui(); private: /** @brief Schedule a keyboard input using a QTimer signal to direct input to a modal window. Modal windows have their own event queue and once launched will halt the execution of the test script until closed. This implies one cannot simply direct keyboard input to them. To do that we pre-schedule the input in the main event loop using a timer. The keyboard input sequence @p key_sequence and a subsequent 'return' key press is then issued when the time out occurs, given that the current window has the correct @p title! Otherwise the event is rescheduled until the title is correct. The @p delay then the timer pops is relative to the last timed events successfull completion. */ void scheduleModalWidget_(const QString& key_sequence, const QString& title, const int delay=100); /** @brief Waits until the scheduled event queue is emtpy Waits until the scheduled event queue is emtpy. */ void waitForModalWidget(const int max_wait, const String& line); /// event queue for modal/popup dialogs QQueue<ScheduleInfo> modal_key_sequence_; }; } #endif
Unknown
3D
OpenMS/OpenMS
src/tests/class_tests/openms_gui/source/FileWatcher_test.cpp
.cpp
1,247
48
// 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 $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/VISUAL/FileWatcher.h> ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace std; START_TEST(ControlledVocabulary, "$Id$") ///////////////////////////////////////////////////////////// FileWatcher* ptr = nullptr; FileWatcher* nullPointer = nullptr; START_SECTION(FileWatcher(QObject *parent=0)) ptr = new FileWatcher(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION(~FileWatcher()) delete ptr; END_SECTION START_SECTION(void setDelayInSeconds(double delay)) NOT_TESTABLE END_SECTION START_SECTION(void addFile(const String& path)) NOT_TESTABLE END_SECTION START_SECTION(void removeFile(const String& path)) NOT_TESTABLE END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms_gui/source/GUIHelpers_test.cpp
.cpp
1,463
52
// 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 $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> /////////////////////////// #include <OpenMS/VISUAL/MISC/GUIHelpers.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(GUIHelpers, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// START_SECTION(([EXTRA] size_t OverlapDetector::placeItem(double x_start, double x_end))) GUIHelpers::OverlapDetector od(3); TEST_EQUAL(od.placeItem(1, 3), 0); TEST_EQUAL(od.placeItem(1, 3), 1); TEST_EQUAL(od.placeItem(1, 3), 2); TEST_EQUAL(od.placeItem(1, 3), 0); TEST_EQUAL(od.placeItem(4, 8), 0); TEST_EQUAL(od.placeItem(5, 11), 1); TEST_EQUAL(od.placeItem(9, 10), 0); TEST_EQUAL(od.placeItem(12, 20), 0); TEST_EQUAL(od.placeItem(12, 18), 1); TEST_EQUAL(od.placeItem(12, 19), 2); TEST_EQUAL(od.placeItem(16, 25), 1); TEST_EQUAL(od.placeItem(16, 25), 2); TEST_EQUAL(od.placeItem(16, 25), 0); END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms_gui/source/MultiGradient_test.cpp
.cpp
10,179
293
// 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 $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> /////////////////////////// #include <OpenMS/VISUAL/MultiGradient.h> #include <QtGui/QColor> #include <OpenMS/CONCEPT/Types.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(MultiGradient, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// MultiGradient* d10_ptr = nullptr; MultiGradient* d10_nullPointer = nullptr; START_SECTION((MultiGradient())) d10_ptr = new MultiGradient(); TEST_NOT_EQUAL(d10_ptr, d10_nullPointer) END_SECTION START_SECTION((~MultiGradient())) delete d10_ptr; END_SECTION START_SECTION((InterpolationMode getInterpolationMode() const)) TEST_EQUAL(MultiGradient().getInterpolationMode(),MultiGradient::IM_LINEAR) END_SECTION START_SECTION((void setInterpolationMode(InterpolationMode mode))) MultiGradient mg; mg.setInterpolationMode(MultiGradient::IM_STAIRS); TEST_EQUAL(mg.getInterpolationMode(),MultiGradient::IM_STAIRS) END_SECTION START_SECTION((Size size() const)) MultiGradient mg; TEST_EQUAL(mg.size(),2); END_SECTION START_SECTION((UInt position(UInt index))) MultiGradient mg; TEST_EQUAL(mg.position(0),0); TEST_EQUAL(mg.position(1),100); END_SECTION START_SECTION((QColor color(UInt index))) MultiGradient mg; TEST_EQUAL(mg.color(0)==Qt::white,true); TEST_EQUAL(mg.color(1)==Qt::black,true); END_SECTION START_SECTION((void insert(double position, QColor color))) MultiGradient mg; mg.insert(50,Qt::red); TEST_EQUAL(mg.size(),3); TEST_EQUAL(mg.position(0),0); TEST_EQUAL(mg.position(1),50); TEST_EQUAL(mg.position(2),100); TEST_EQUAL(mg.color(0)==Qt::white,true); TEST_EQUAL(mg.color(1)==Qt::red,true); TEST_EQUAL(mg.color(2)==Qt::black,true); mg.insert(50,Qt::red); TEST_EQUAL(mg.size(),3); TEST_EQUAL(mg.position(0),0); TEST_EQUAL(mg.position(1),50); TEST_EQUAL(mg.position(2),100); TEST_EQUAL(mg.color(0)==Qt::white,true); TEST_EQUAL(mg.color(1)==Qt::red,true); TEST_EQUAL(mg.color(2)==Qt::black,true); mg.insert(25,Qt::green); mg.insert(75,Qt::blue); TEST_EQUAL(mg.size(),5); TEST_EQUAL(mg.position(0),0); TEST_EQUAL(mg.position(1),25); TEST_EQUAL(mg.position(2),50); TEST_EQUAL(mg.position(3),75); TEST_EQUAL(mg.position(4),100); TEST_EQUAL(mg.color(0)==Qt::white,true); TEST_EQUAL(mg.color(1)==Qt::green,true); TEST_EQUAL(mg.color(2)==Qt::red,true); TEST_EQUAL(mg.color(3)==Qt::blue,true); TEST_EQUAL(mg.color(4)==Qt::black,true); mg.insert(76,Qt::magenta); TEST_EQUAL(mg.size(),6); TEST_EQUAL(mg.position(0),0); TEST_EQUAL(mg.position(1),25); TEST_EQUAL(mg.position(2),50); TEST_EQUAL(mg.position(3),75); TEST_EQUAL(mg.position(4),76); TEST_EQUAL(mg.position(5),100); TEST_EQUAL(mg.color(0)==Qt::white,true); TEST_EQUAL(mg.color(1)==Qt::green,true); TEST_EQUAL(mg.color(2)==Qt::red,true); TEST_EQUAL(mg.color(3)==Qt::blue,true); TEST_EQUAL(mg.color(4)==Qt::magenta,true); TEST_EQUAL(mg.color(5)==Qt::black,true); END_SECTION START_SECTION((bool remove(double position))) MultiGradient mg; mg.insert(25,Qt::green); mg.insert(50,Qt::red); mg.insert(75,Qt::blue); mg.remove(50); TEST_EQUAL(mg.size(),4); TEST_EQUAL(mg.position(0),0); TEST_EQUAL(mg.position(1),25); TEST_EQUAL(mg.position(2),75); TEST_EQUAL(mg.position(3),100); TEST_EQUAL(mg.color(0)==Qt::white,true); TEST_EQUAL(mg.color(1)==Qt::green,true); TEST_EQUAL(mg.color(2)==Qt::blue,true); TEST_EQUAL(mg.color(3)==Qt::black,true); mg.remove(25); TEST_EQUAL(mg.size(),3); TEST_EQUAL(mg.position(0),0); TEST_EQUAL(mg.position(1),75); TEST_EQUAL(mg.position(2),100); TEST_EQUAL(mg.color(0)==Qt::white,true); TEST_EQUAL(mg.color(1)==Qt::blue,true); TEST_EQUAL(mg.color(2)==Qt::black,true); mg.remove(75); TEST_EQUAL(mg.size(),2); TEST_EQUAL(mg.position(0),0); TEST_EQUAL(mg.position(1),100); TEST_EQUAL(mg.color(0)==Qt::white,true); TEST_EQUAL(mg.color(1)==Qt::black,true); END_SECTION START_SECTION((bool exists(double position))) MultiGradient mg; mg.insert(25,Qt::green); mg.insert(50,Qt::red); mg.insert(75,Qt::blue); TEST_EQUAL(mg.exists(0),true); TEST_EQUAL(mg.exists(1),false); TEST_EQUAL(mg.exists(25),true); TEST_EQUAL(mg.exists(49),false); TEST_EQUAL(mg.exists(50),true); TEST_EQUAL(mg.exists(51),false); TEST_EQUAL(mg.exists(75),true); TEST_EQUAL(mg.exists(99),false); TEST_EQUAL(mg.exists(100),true); END_SECTION START_SECTION((QColor interpolatedColorAt(double position) const)) MultiGradient mg; TEST_EQUAL(mg.interpolatedColorAt(0)==Qt::white,true); TEST_EQUAL(mg.interpolatedColorAt(25)==QColor(191,191,191),true); TEST_EQUAL(mg.interpolatedColorAt(50)==QColor(127,127,127),true); TEST_EQUAL(mg.interpolatedColorAt(75)==QColor(63,63,63),true); TEST_EQUAL(mg.interpolatedColorAt(100)==Qt::black,true); mg.insert(50,Qt::red); TEST_EQUAL(mg.interpolatedColorAt(0)==Qt::white,true); TEST_EQUAL(mg.interpolatedColorAt(25)==QColor(255,127,127),true); TEST_EQUAL(mg.interpolatedColorAt(50)==Qt::red,true); TEST_EQUAL(mg.interpolatedColorAt(75)==QColor(127,0,0),true); TEST_EQUAL(mg.interpolatedColorAt(100)==Qt::black,true); mg.insert(50,Qt::green); TEST_EQUAL(mg.interpolatedColorAt(0)==Qt::white,true); TEST_EQUAL(mg.interpolatedColorAt(25)==QColor(127,255,127),true); TEST_EQUAL(mg.interpolatedColorAt(50)==Qt::green,true); TEST_EQUAL(mg.interpolatedColorAt(75)==QColor(0,127,0),true); TEST_EQUAL(mg.interpolatedColorAt(100)==Qt::black,true); mg.insert(50,Qt::blue); TEST_EQUAL(mg.interpolatedColorAt(0)==Qt::white,true); TEST_EQUAL(mg.interpolatedColorAt(25)==QColor(127,127,255),true); TEST_EQUAL(mg.interpolatedColorAt(50)==Qt::blue,true); TEST_EQUAL(mg.interpolatedColorAt(75)==QColor(0,0,127),true); TEST_EQUAL(mg.interpolatedColorAt(100)==Qt::black,true); MultiGradient mg2; mg2.setInterpolationMode(MultiGradient::IM_STAIRS); TEST_EQUAL(mg2.interpolatedColorAt(0)==Qt::white,true); TEST_EQUAL(mg2.interpolatedColorAt(25)==Qt::white,true); TEST_EQUAL(mg2.interpolatedColorAt(100)==Qt::black,true); mg2.insert(50,Qt::red); TEST_EQUAL(mg2.interpolatedColorAt(0)==Qt::white,true); TEST_EQUAL(mg2.interpolatedColorAt(49)==Qt::white,true); TEST_EQUAL(mg2.interpolatedColorAt(50)==Qt::red,true); TEST_EQUAL(mg2.interpolatedColorAt(51)==Qt::red,true); TEST_EQUAL(mg2.interpolatedColorAt(99)==Qt::red,true); TEST_EQUAL(mg2.interpolatedColorAt(100)==Qt::black,true); END_SECTION START_SECTION((QColor interpolatedColorAt(double position, double min, double max) const)) MultiGradient mg; mg.insert(50,Qt::red); TEST_EQUAL(mg.interpolatedColorAt(0,0,100)==Qt::white,true); TEST_EQUAL(mg.interpolatedColorAt(25,0,100)==QColor(255,127,127),true); TEST_EQUAL(mg.interpolatedColorAt(50,0,100)==Qt::red,true); TEST_EQUAL(mg.interpolatedColorAt(75,0,100)==QColor(127,0,0),true); TEST_EQUAL(mg.interpolatedColorAt(100,0,100)==Qt::black,true); MultiGradient mg2; mg2.setInterpolationMode(MultiGradient::IM_STAIRS); mg2.insert(50,Qt::red); TEST_EQUAL(mg2.interpolatedColorAt(0)==Qt::white,true); TEST_EQUAL(mg2.interpolatedColorAt(49)==Qt::white,true); TEST_EQUAL(mg2.interpolatedColorAt(50)==Qt::red,true); TEST_EQUAL(mg2.interpolatedColorAt(51)==Qt::red,true); TEST_EQUAL(mg2.interpolatedColorAt(99)==Qt::red,true); TEST_EQUAL(mg2.interpolatedColorAt(100)==Qt::black,true); END_SECTION START_SECTION((void activatePrecalculationMode(double min, double max, UInt steps))) NOT_TESTABLE END_SECTION START_SECTION((QColor precalculatedColorAt(double position) const )) MultiGradient mg; mg.insert(0,Qt::white); mg.insert(100,Qt::blue); mg.activatePrecalculationMode(-50.0,50.0,100); //Test precalclulated Values TEST_EQUAL(mg.precalculatedColorAt(-50.0).red(),255); TEST_EQUAL(mg.precalculatedColorAt(-50.0).green(),255); TEST_EQUAL(mg.precalculatedColorAt(-50.0).blue(),255); TEST_EQUAL(mg.precalculatedColorAt(-25.0).red(),193); TEST_EQUAL(mg.precalculatedColorAt(-25.0).green(),193); TEST_EQUAL(mg.precalculatedColorAt(-25.0).blue(),255); TEST_EQUAL(mg.precalculatedColorAt(0.0).red(),128); TEST_EQUAL(mg.precalculatedColorAt(0.0).green(),128); TEST_EQUAL(mg.precalculatedColorAt(0.0).blue(),255); TEST_EQUAL(mg.precalculatedColorAt(25.0).red(),64); TEST_EQUAL(mg.precalculatedColorAt(25.0).green(),64); TEST_EQUAL(mg.precalculatedColorAt(25.0).blue(),255); TEST_EQUAL(mg.precalculatedColorAt(50.0).red(),2); TEST_EQUAL(mg.precalculatedColorAt(50.0).green(),2); TEST_EQUAL(mg.precalculatedColorAt(50.0).blue(),255); END_SECTION START_SECTION((void deactivatePrecalculationMode())) MultiGradient mg; mg.activatePrecalculationMode(-50,50,100); mg.deactivatePrecalculationMode(); NOT_TESTABLE END_SECTION START_SECTION((std::string toString() const)) MultiGradient mg; TEST_EQUAL(mg.toString(),"Linear|0,#ffffff;100,#000000") mg.setInterpolationMode(MultiGradient::IM_STAIRS); mg.insert(50,Qt::red); TEST_EQUAL(mg.toString(),"Stairs|0,#ffffff;50,#ff0000;100,#000000") END_SECTION START_SECTION((void fromString(const std::string& gradient))) MultiGradient mg; mg.fromString("Linear|0,#ff0000;100,#000000"); TEST_EQUAL(mg.getInterpolationMode(),MultiGradient::IM_LINEAR) TEST_EQUAL(mg.size(),2) TEST_EQUAL(mg.color(0)==Qt::red, true); TEST_EQUAL(mg.color(1)==Qt::black, true); TEST_EQUAL(mg.position(0), 0); TEST_EQUAL(mg.position(1), 100); mg.fromString("Stairs|0,#ffffff;50,#ff0000;100,#000000"); TEST_EQUAL(mg.getInterpolationMode(),MultiGradient::IM_STAIRS) TEST_EQUAL(mg.size(),3) TEST_EQUAL(mg.color(0)==Qt::white, true); TEST_EQUAL(mg.color(1)==Qt::red, true); TEST_EQUAL(mg.color(2)==Qt::black, true); TEST_EQUAL(mg.position(0), 0); TEST_EQUAL(mg.position(1), 50); TEST_EQUAL(mg.position(2), 100); END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms_gui/source/AxisTickCalculator_test.cpp
.cpp
1,899
63
// 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 $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> /////////////////////////// #include <OpenMS/VISUAL/AxisTickCalculator.h> #include <OpenMS/KERNEL/MSSpectrum.h> /////////////////////////// using namespace OpenMS; START_TEST(AxisTickCalculator, "$Id$") ///////////////////////////////////////////////////////////// START_SECTION((static void calcGridLines(double x1, double x2, GridVector& grid))) std::vector<std::vector<double> > vector1; AxisTickCalculator::calcGridLines(1.0,4.0,vector1); TEST_EQUAL(2,vector1.size()); TEST_EQUAL(4,vector1[0].size()); TEST_REAL_SIMILAR(1.0,vector1[0][0]); TEST_REAL_SIMILAR(2.0,vector1[0][1]); TEST_REAL_SIMILAR(3.0,vector1[0][2]); TEST_REAL_SIMILAR(4.0,vector1[0][3]); END_SECTION START_SECTION((static void calcLogGridLines(double x1, double x2, GridVector& grid))) std::vector<std::vector<double> > vector1; AxisTickCalculator::calcLogGridLines(log10(10.0),log10(100.0),vector1); TEST_EQUAL(1,vector1[0].size()); TEST_EQUAL(8,vector1[1].size()); TEST_REAL_SIMILAR(1.0,vector1[0][0]); TEST_REAL_SIMILAR( 1.30103 ,vector1[1][0]); TEST_REAL_SIMILAR( 1.47712 ,vector1[1][1]); TEST_REAL_SIMILAR( 1.60206 ,vector1[1][2]); TEST_REAL_SIMILAR( 1.69897 ,vector1[1][3]); TEST_REAL_SIMILAR( 1.77815 ,vector1[1][4]); TEST_REAL_SIMILAR( 1.8451 ,vector1[1][5]); TEST_REAL_SIMILAR( 1.90309 ,vector1[1][6]); TEST_REAL_SIMILAR( 1.95425 ,vector1[1][7]); END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms_gui/source/GUI/TOPPView_test.cpp
.cpp
4,522
130
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow $ // $Authors: Chris Bielow $ // -------------------------------------------------------------------------- #include <TOPPView_test.h> #include <QTimer> #include <QElapsedTimer> #include <OpenMS/VISUAL/APPLICATIONS/TOPPViewBase.h> #include <OpenMS/SYSTEM/File.h> #include <OpenMS/VISUAL/EnhancedTabBar.h> #include <OpenMS/CONCEPT/ProgressLogger.h> #include <OpenMS/VISUAL/GUIProgressLoggerImpl.h> using namespace OpenMS; void TestTOPPView::scheduleModalWidget_(const QString& key_sequence, const QString& title, const int delay) { modal_key_sequence_.enqueue(ScheduleInfo(key_sequence, title, delay)); std::cerr << "scheduled for window " << title.toStdString() << "\n"; if (modal_key_sequence_.size()==1) // only schedule if this is the first entry { QTimer::singleShot(delay, this, SLOT(simulateClick_())); } } void TestTOPPView::waitForModalWidget(const int max_wait, const String& line) { // test if accumulated scheduled time is less than max_wait int min_required_time = 0; foreach(ScheduleInfo i, modal_key_sequence_) { min_required_time+=i.delay; } if (min_required_time > max_wait) { QFAIL ( String("Test is bound to fail due to a time restriction in line " + line + ". Please rethink!").c_str()); } QElapsedTimer t; t.start(); while (!modal_key_sequence_.isEmpty () && max_wait > t.elapsed()) { QTest::qWait(50); } if (!modal_key_sequence_.isEmpty ()) { QWARN ( String("Modal dialogs timed out in line " + line + ". The following tests will most likely fail.").c_str()); modal_key_sequence_.clear(); } } void TestTOPPView::simulateClick_() { if (!modal_key_sequence_.isEmpty ()) { ScheduleInfo entry = modal_key_sequence_.head(); std::cerr << "processing entry: '" << entry.keys.toStdString() << "' with dialog title '" << entry.title.toStdString() << "'\n"; // search for a window QWidget * dialog = QApplication::activeModalWidget(); if (!dialog) dialog = QApplication::activePopupWidget(); if (!dialog) dialog = QApplication::activeWindow(); if (!dialog || (dialog->windowTitle() != entry.title)) { std::cerr << "item not found rescheduling...\n"; QTimer::singleShot(100, this, SLOT(simulateClick_())); return; } QTest::keyClicks(dialog,entry.keys,Qt::NoModifier,20); QTest::keyClick(dialog,static_cast<Qt::Key>(Qt::Key_Return),Qt::NoModifier,20); QApplication::processEvents(); // remove from queue modal_key_sequence_.dequeue(); } if (!modal_key_sequence_.isEmpty ()) { std::cerr << "Q not empty... rescheduling...\n"; QTimer::singleShot(modal_key_sequence_.head().delay, this, SLOT(simulateClick_())); } } void TestTOPPView::testGui() { // inject the GUIProgressLoggerImpl to be used by OpenMS lib via an extern variable make_gui_progress_logger = []() -> ProgressLogger::ProgressLoggerImpl* { return new GUIProgressLoggerImpl(); }; TOPPViewBase tv(TOPPViewBase::TOOL_SCAN::SKIP_SCAN); tv.show(); QApplication::processEvents(); QTest::qWait(1000); #if 1 //def __APPLE__ // MAC OS does not support entering a filename via keyboard in the file-open menu tv.addDataFile(File::getOpenMSDataPath() + "/examples/peakpicker_tutorial_1.mzML", false, false); QCOMPARE(tv.tab_bar_.tabText(tv.tab_bar_.currentIndex()), QString("peakpicker_tutorial_1 (1D)")); #else scheduleModalWidget_("peakpicker_tutorial_1.mzML", "Open file(s)",1000); // Open File dialog scheduleModalWidget_("", "Open data options for peakpicker_tutorial_1.mzML",1000); // layer data options dialog // open file dialog QTest::keyClicks(&tv,"f", Qt::AltModifier); QApplication::processEvents(); // before we open the File-Open Dialog, we need to schedule the planned keyboard input // as this dialog is modal and won't return. // launch the modal widget QTest::keyClicks(0,"e"); QApplication::processEvents(); waitForModalWidget(15000, __LINE__); #endif // compare the name of the opened tab QCOMPARE(tv.tab_bar_.tabText(tv.tab_bar_.currentIndex()), QString("peakpicker_tutorial_1 (1D)")); } // expands to a simple main() method that runs all the test functions QTEST_MAIN(TestTOPPView)
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms_gui/source/GUI/TSGDialog_test.cpp
.cpp
17,083
436
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Tom Waschischeck $ // $Authors: Tom Waschischeck $ // -------------------------------------------------------------------------- #include <TSGDialog_test.h> #include <OpenMS/DATASTRUCTURES/Param.h> #include <OpenMS/KERNEL/MSSpectrum.h> #include <QtWidgets/QPushButton> #include <QtWidgets/QMessageBox> #include <qdebug.h> using namespace OpenMS; using namespace std; // delay in ms // higher values together with 'dialog_.show();' can be useful for debugging this test constexpr int DELAY {5}; template<typename T> void TestTSGDialog::testSpinBox_(T* box, string str_value) { if (box == nullptr) return; double value = stod(str_value); // skip illegal input if (!(value >= box->minimum() && value <= box->maximum())) return; box->clear(); // simulate keyboard input QTest::keyClicks(box, QString::fromStdString(str_value)); QTest::qWait(DELAY); // verify change QVERIFY(value == double(box->value())); // double cast needed because of template } void TestTSGDialog::testIsotopeModel_(bool skip_none) { // QTest::mouseClick needs the exact position of the interactable part of the radio button // If someone knows how to get this position, please adapt this code. if (skip_none) { QVERIFY(!UI->model_none_button->isEnabled()); } else { UI->model_none_button->click(); QTest::qWait(DELAY); QVERIFY(!(UI->max_iso_spinbox->isEnabled())); QVERIFY(!(UI->max_iso_label->isEnabled())); QVERIFY(!(UI->max_iso_prob_spinbox->isEnabled())); QVERIFY(!(UI->max_iso_prob_label->isEnabled())); } UI->model_coarse_button->click(); QTest::qWait(DELAY); QVERIFY(UI->max_iso_spinbox->isEnabled()); QVERIFY(UI->max_iso_label->isEnabled()); QVERIFY(!(UI->max_iso_prob_spinbox->isEnabled())); QVERIFY(!(UI->max_iso_prob_label->isEnabled())); testSpinBox_(UI->max_iso_spinbox); UI->model_fine_button->click(); QTest::qWait(DELAY); QVERIFY(!(UI->max_iso_spinbox->isEnabled())); QVERIFY(!(UI->max_iso_label->isEnabled())); QVERIFY(UI->max_iso_prob_spinbox->isEnabled()); QVERIFY(UI->max_iso_prob_label->isEnabled()); testSpinBox_(UI->max_iso_prob_spinbox); } void OpenMS::TestTSGDialog::testIonsIntensities_() { int input_type; if (dialog_.seq_type_ == TheoreticalSpectrumGenerationDialog::SequenceType::PEPTIDE) input_type = 0; else if (dialog_.seq_type_ == TheoreticalSpectrumGenerationDialog::SequenceType::RNA) input_type = 1; else // Metabolite input_type = 2; for (size_t i = 0; i < dialog_.check_boxes_.size(); ++i) { // get the item QListWidgetItem* item = UI->ion_types->item(i); QVERIFY(item); const TheoreticalSpectrumGenerationDialog::CheckBox* curr_box = &dialog_.check_boxes_.at(i); // get intensity spin box corresponding to current check box QDoubleSpinBox** spin_ptr = curr_box->ptr_to_spin_box; if (curr_box->state.at(input_type) != CheckBoxState::HIDDEN) { // check state before clicking Qt::CheckState prev = item->checkState(); // get the rectangular coordinates of the item QRect rect = UI->ion_types->visualItemRect(item); // imitate the click on check box c QTest::mouseClick(UI->ion_types->viewport(), Qt::LeftButton, Qt::NoModifier, rect.center()); QTest::qWait(DELAY); // verfiy the check state changed QVERIFY2(prev != item->checkState(), qPrintable("Clicking on '" + item->text() + "' didn't change its state.")); if (spin_ptr == nullptr) continue; testSpinBox_(*spin_ptr); } else { // if ion type isn't supported, check if the ion and its intensity are hidden QVERIFY2(item->isHidden(), qPrintable(item->text() + " wasn't hidden.")); if (spin_ptr == nullptr) continue; QVERIFY2((*spin_ptr)->isHidden(), qPrintable("Spin box of '" + item->text() + "' wasn't hidden.")); } } } void OpenMS::TestTSGDialog::testSequenceInput_(QString input) { UI->seq_input->clear(); QTest::keyClicks(UI->seq_input, input); QString read_seq = QString::fromStdString(std::string(dialog_.getSequence())); QVERIFY2(read_seq == UI->seq_input->text(), "Test of sequence input failed!"); } void OpenMS::TestTSGDialog::checkMessageBoxExists_() { // get the active window QWidget* active_widget = QApplication::activeModalWidget(); if (active_widget->inherits("QMessageBox")) // if it's a message box, close it { QMessageBox* mb = qobject_cast<QMessageBox*>(active_widget); QTest::keyClick(mb, Qt::Key_Enter); QVERIFY(true); return; } QVERIFY2(false, "Expected message box wasn't produced!"); } void TestTSGDialog::testMessageBoxes_() { // check empty sequence input UI->seq_input->clear(); QTimer::singleShot(DELAY, this, &TestTSGDialog::checkMessageBoxExists_); // calls the SLOT after DELAY ms passed UI->dialog_buttons->button(QDialogButtonBox::Ok)->click(); // check unparsible sequence input UI->seq_input->setText("J+-5!"); QTimer::singleShot(DELAY, this, &TestTSGDialog::checkMessageBoxExists_); UI->dialog_buttons->button(QDialogButtonBox::Ok)->click(); // unselect all ions to produce empty spectrum for (size_t i = 0; i < dialog_.check_boxes_.size(); ++i) { UI->ion_types->item(i)->setCheckState(Qt::CheckState::Unchecked); } QTimer::singleShot(DELAY, this, &TestTSGDialog::checkMessageBoxExists_); UI->dialog_buttons->button(QDialogButtonBox::Ok)->click(); } void TestTSGDialog::testConstruction() { // editable/interactable GUI parts QVERIFY2(UI->seq_type, "Sequence selection combo box not created."); QVERIFY2(UI->seq_input, "Sequence input line edit not created."); QVERIFY2(UI->charge_spinbox, "Charge spin box not created."); QVERIFY2(UI->max_iso_spinbox, "Max. isotope model spin box not created."); QVERIFY2(UI->max_iso_prob_spinbox, "Max. isotope probability spin box not created."); QVERIFY2(UI->ion_types, "Ion list widget not created."); QVERIFY2(UI->a_intensity, "A ion intensity spin box not created."); QVERIFY2(UI->a_b_intensity, "A-b ion intensity spin box not created."); QVERIFY2(UI->b_intensity, "B ion intensity spin box not created."); QVERIFY2(UI->c_intensity, "C ion intensity spin box not created."); QVERIFY2(UI->d_intensity, "D ion intensity spin box not created."); QVERIFY2(UI->w_intensity, "W ion intensity spin box not created."); QVERIFY2(UI->x_intensity, "X ion intensity spin box not created."); QVERIFY2(UI->y_intensity, "Y ion intensity spin box not created."); QVERIFY2(UI->z_intensity, "Z ion intensity spin box not created."); QVERIFY2(UI->rel_loss_intensity, "Relative loss intensity spin box not created."); QVERIFY2(UI->dialog_buttons, "Buttonbox not created."); // labels QVERIFY2(UI->enter_seq_label, "'Enter sequence' label not created."); QVERIFY2(UI->charge_label, "'Charge' label not created."); QVERIFY2(UI->ion_types_label, "'Generate' label not created."); QVERIFY2(UI->max_iso_label, "'Max. Isotope' label not created."); QVERIFY2(UI->max_iso_prob_label, "'Max. Isotope Probability in %' label not created."); QVERIFY2(UI->a_label, "'A-ions' label not created."); QVERIFY2(UI->a_b_label, "'A-b-ions' label not created."); QVERIFY2(UI->b_label, "'B-ions' label not created."); QVERIFY2(UI->c_label, "'C-ions' label not created."); QVERIFY2(UI->d_label, "'D-ions' label not created."); QVERIFY2(UI->w_label, "'W-ions' label not created."); QVERIFY2(UI->x_label, "'X-ions' label not created."); QVERIFY2(UI->y_label, "'Y-ions' label not created."); QVERIFY2(UI->z_label, "'Z-ions' label not created."); QVERIFY2(UI->rel_loss_label, "'Relative loss in %' label not created."); // group boxes QVERIFY2(UI->isotope_model, "Isotope model group box not created."); QVERIFY2(UI->intensities, "Intensity group box not created."); } void TestTSGDialog::testGui() { ////////////////////////////////////////////////////// // PEPTIDE // ////////////////////////////////////////////////////// UI->seq_type->setCurrentText("Peptide"); QTest::qWait(DELAY); // sequence input testSequenceInput_("PEPTIDE"); // charge testSpinBox_(UI->charge_spinbox); // isotope model QVERIFY2(!UI->isotope_model->isHidden(), "Isotope model hidden for 'Peptide' setting."); testIsotopeModel_(); // ion types and intensities testIonsIntensities_(); // check relative loss intensity manually UI->rel_loss_intensity->clear(); QTest::keyClicks(UI->rel_loss_intensity, "2"); QTest::qWait(DELAY); QVERIFY(2.0 == UI->rel_loss_intensity->value()); ////////////////////////////////////////////////////// // RNA // ////////////////////////////////////////////////////// UI->seq_type->setCurrentText("RNA"); QTest::qWait(DELAY); // sequence input testSequenceInput_("ACGUGCA"); // charge testSpinBox_(UI->charge_spinbox); // isotope model QVERIFY2(UI->isotope_model->isHidden(), "Isotope model not hidden for 'Peptide' setting."); // ion types and intensities testIonsIntensities_(); // check relative loss intensity manually QVERIFY(UI->rel_loss_intensity->isHidden()); QVERIFY(UI->rel_loss_label->isHidden()); ////////////////////////////////////////////////////// // Metabolite // ////////////////////////////////////////////////////// UI->seq_type->setCurrentText("Metabolite"); QTest::qWait(DELAY); // sequence input testSequenceInput_("C100H70N2O6"); // charge testSpinBox_(UI->charge_spinbox); // isotope model QVERIFY2(!UI->isotope_model->isHidden(), "Isotope model hidden for 'Metabolite' setting."); testIsotopeModel_(true); // ion types and intensities //testIonsIntensities_(); } void TestTSGDialog::testParameterImport() { // set some parameters UI->seq_type->setCurrentText("Peptide"); UI->charge_spinbox->setValue(3); UI->model_coarse_button->click(); UI->max_iso_spinbox->setValue(5); for (size_t i = 0; i < dialog_.check_boxes_.size(); ++i) { UI->ion_types->item(i)->setCheckState(Qt::CheckState::Checked); // just check all boxes // get intensity spin box corresponding to current check box QDoubleSpinBox** spin_ptr = dialog_.check_boxes_.at(i).ptr_to_spin_box; if (spin_ptr == nullptr) continue; (*spin_ptr)->setValue(1.23); } UI->rel_loss_intensity->setValue(16); // get the parameters from the dialog Param p = dialog_.getParam_(); // check if the returned parameters are correct QVERIFY2(int(p.getValue("charge")) == 3, "Parameter 'charge' wasn't set correctly."); QVERIFY2(string(p.getValue("isotope_model")) == "coarse", "Parameter 'isotope_model' wasn't set correctly. Expected 'coarse'."); QVERIFY2(int(p.getValue("max_isotope")) == 5, "Parameter 'max_isotope' wasn't set correctly."); QVERIFY2(string(p.getValue("add_a_ions")) == "true", "Parameter 'add_a_ions' wasn't set correctly."); QVERIFY2(double(p.getValue("a_intensity")) == 1.23, "Parameter 'a_intensity' wasn't set correctly."); QVERIFY2(string(p.getValue("add_b_ions")) == "true", "Parameter 'add_b_ions' wasn't set correctly."); QVERIFY2(double(p.getValue("b_intensity")) == 1.23, "Parameter 'b_intensity' wasn't set correctly."); QVERIFY2(string(p.getValue("add_c_ions")) == "true", "Parameter 'add_c_ions' wasn't set correctly."); QVERIFY2(double(p.getValue("c_intensity")) == 1.23, "Parameter 'c_intensity' wasn't set correctly."); QVERIFY2(string(p.getValue("add_x_ions")) == "true", "Parameter 'add_x_ions' wasn't set correctly."); QVERIFY2(double(p.getValue("x_intensity")) == 1.23, "Parameter 'x_intensity' wasn't set correctly."); QVERIFY2(string(p.getValue("add_y_ions")) == "true", "Parameter 'add_y_ions' wasn't set correctly."); QVERIFY2(double(p.getValue("y_intensity")) == 1.23, "Parameter 'y_intensity' wasn't set correctly."); QVERIFY2(string(p.getValue("add_z_ions")) == "true", "Parameter 'add_z_ions' wasn't set correctly."); QVERIFY2(double(p.getValue("z_intensity")) == 1.23, "Parameter 'z_intensity' wasn't set correctly."); QVERIFY2(string(p.getValue("add_losses")) == "true", "Parameter 'add_losses' wasn't set correctly."); QVERIFY2(double(p.getValue("relative_loss_intensity")) == 0.16, "Parameter 'relative_loss_intensity' wasn't set correctly."); QVERIFY2(string(p.getValue("add_abundant_immonium_ions")) == "true", "Parameter 'add_abundant_immonium_ions' wasn't set correctly."); QVERIFY2(string(p.getValue("add_precursor_peaks")) == "true", "Parameter 'add_precursor_peaks' wasn't set correctly."); // try the other isotope models UI->model_none_button->click(); p.clear(); p = dialog_.getParam_(); QVERIFY2(string(p.getValue("isotope_model")) == "none", "Parameter 'isotope_model' wasn't set correctly. Expected 'none'."); UI->model_fine_button->click(); UI->max_iso_prob_spinbox->setValue(16); p.clear(); p = dialog_.getParam_(); QVERIFY2(string(p.getValue("isotope_model")) == "fine", "Parameter 'isotope_model' wasn't set correctly. Expected 'fine'."); QVERIFY2(double(p.getValue("max_isotope_probability")) == 0.16, "Parameter 'max_isotope_probability' wasn't set correctly."); // check remaining ions for RNA input UI->seq_type->setCurrentText("RNA"); p.clear(); p = dialog_.getParam_(); QVERIFY2(string(p.getValue("add_a-B_ions")) == "true", "Parameter 'add_a-B_ions' wasn't set correctly."); QVERIFY2(double(p.getValue("a-B_intensity")) == 1.23, "Parameter 'a-B_intensity' wasn't set correctly."); QVERIFY2(string(p.getValue("add_d_ions")) == "true", "Parameter 'add_d_ions' wasn't set correctly."); QVERIFY2(double(p.getValue("d_intensity")) == 1.23, "Parameter 'd_intensity' wasn't set correctly."); QVERIFY2(string(p.getValue("add_w_ions")) == "true", "Parameter 'add_w_ions' wasn't set correctly."); QVERIFY2(double(p.getValue("w_intensity")) == 1.23, "Parameter 'w_intensity' wasn't set correctly."); // Metabolite input doesn't have any exclusive parameters that need to be tested. } void TestTSGDialog::testSpectrumCalculation() { // Spectrum generation settings don't really matter, since the dialog test shouldn't test the generators. // Hence, it is only checked if a spectrum was produced. UI->seq_type->setCurrentText("Peptide"); QTest::qWait(DELAY); UI->seq_input->setText("PEPTIDE"); // set peptide sequence to 'PEPTIDE' QTest::qWait(DELAY); QTest::mouseClick(UI->dialog_buttons->button(QDialogButtonBox::Ok), Qt::LeftButton); QTest::qWait(DELAY); MSSpectrum pep_spec = dialog_.getSpectrum(); QVERIFY2(!pep_spec.empty(), "Peptide input didn't produce a spectrum."); UI->seq_type->setCurrentText("RNA"); QTest::qWait(DELAY); UI->seq_input->setText("AGUCCG"); QTest::qWait(DELAY); QTest::mouseClick(UI->dialog_buttons->button(QDialogButtonBox::Ok), Qt::LeftButton); QTest::qWait(DELAY); MSSpectrum rna_spec = dialog_.getSpectrum(); QVERIFY2(!rna_spec.empty(), "RNA input didn't produce a spectrum."); UI->seq_type->setCurrentText("Metabolite"); QTest::qWait(DELAY); UI->seq_input->setText("C100H70N2O6"); QTest::qWait(DELAY); QTest::mouseClick(UI->dialog_buttons->button(QDialogButtonBox::Ok), Qt::LeftButton); QTest::qWait(DELAY); MSSpectrum meta_spec = dialog_.getSpectrum(); QVERIFY2(!meta_spec.empty(), "Metabolite input didn't produce a spectrum."); } void TestTSGDialog::testErrors() { UI->seq_type->setCurrentText("Peptide"); testMessageBoxes_(); UI->seq_type->setCurrentText("RNA"); testMessageBoxes_(); UI->seq_type->setCurrentText("Metabolite"); testMessageBoxes_(); } // expands to a simple main() method that runs all the private slots QTEST_MAIN(TestTSGDialog) // Sadly this doesn't work and yields a seq fault, when trying to access any member of the dropDownList. // That's why the combo box ('seq_type') is set manually and therefore not actually tested in this test. // I was unable to fix this, but maybe someone else will get this to work.. // sources: // https://gist.github.com/peteristhegreat/cbd8eaa0e565d0b82dbfb5c7fdc61c8d // https://vicrucann.github.io/tutorials/qttest-signals-qtreewidget/ // https://stackoverflow.com/questions/69283103/qts-qtest-doesnt-select-an-item-in-a-drop-down-list-with-a-click // // #include <qcombobox.h> // #include <qlistview.h> // // void TestTSGDialog::clickDropDown_(int row, QComboBox* comboBox) //{ // QListView* dropDownList = comboBox->findChild<QListView*>(); // QModelIndex foundIndex {dropDownList->model()->index(row, 0)}; // // QRect foundDropDownItem = dropDownList->visualRect(foundIndex); // QPoint foundDropDownItemPosition = foundDropDownItem.center(); // // QWidget* activeWidget = dropDownList->viewport(); // QTest::mouseClick(activeWidget, Qt::LeftButton, Qt::NoModifier, foundDropDownItemPosition); // QTest::qWait(DELAY); //}
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openswathalgo/Scoring_test.cpp
.cpp
16,547
460
// 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 $ // -------------------------------------------------------------------------- #include "OpenMS/OPENSWATHALGO/OpenSwathAlgoConfig.h" #include "OpenMS/OPENSWATHALGO/ALGO/Scoring.h" #ifdef USE_BOOST_UNIT_TEST // include boost unit test framework #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE MyTest #include <boost/test/unit_test.hpp> // macros for boost #define EPS_05 boost::test_tools::fraction_tolerance(1.e-5) #define TEST_REAL_SIMILAR(val1, val2) \ BOOST_CHECK ( boost::test_tools::check_is_close(val1, val2, EPS_05 )); #define TEST_EQUAL(val1, val2) BOOST_CHECK_EQUAL(val1, val2); #define END_SECTION #define START_TEST(var1, var2) #define END_TEST #else #include <algorithm> #include <OpenMS/CONCEPT/ClassTest.h> #define BOOST_AUTO_TEST_CASE START_SECTION using namespace OpenMS; #endif using namespace std; using namespace OpenSwath; /////////////////////////// START_TEST(Scoring, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// BOOST_AUTO_TEST_CASE(double_NormalizedManhattanDist_test) { // Numpy // arr1 = [ 0,1,3,5,2,0 ]; // arr2 = [ 1,3,5,2,0,0 ]; // arr1 = (arr1 / (sum(arr1) *1.0) ) // arr2 = (arr2 / (sum(arr2) *1.0) ) // deltas = [ abs(a-b) for (a,b) in zip(arr1, arr2) ] // sum(deltas) / 6 static const double arr1[] = {0,1,3,5,2,0}; static const double arr2[] = {1,3,5,2,0,0}; std::vector<double> data1 (arr1, arr1 + sizeof(arr1) / sizeof(arr1[0]) ); std::vector<double> data2 (arr2, arr2 + sizeof(arr2) / sizeof(arr2[0]) ); TEST_REAL_SIMILAR (Scoring::NormalizedManhattanDist(&data1[0], &data2[0], 6), 0.15151515) } END_SECTION BOOST_AUTO_TEST_CASE(double_RootMeanSquareDeviation_test) { // Numpy // arr1 = [ 0,1,3,5,2,0 ]; // arr2 = [ 1,3,5,2,0,0 ]; // res = [ (a-b)*(a-b) for (a,b) in zip(arr1, arr2) ] // sqrt(sum(res)/6.0) static const double arr1[] = {0,1,3,5,2,0}; static const double arr2[] = {1,3,5,2,0,0}; std::vector<double> data1 (arr1, arr1 + sizeof(arr1) / sizeof(arr1[0]) ); std::vector<double> data2 (arr2, arr2 + sizeof(arr2) / sizeof(arr2[0]) ); TEST_REAL_SIMILAR (Scoring::RootMeanSquareDeviation(&data1[0], &data2[0], 6), 1.91485421551) } END_SECTION BOOST_AUTO_TEST_CASE(double_SpectralAngle_test) { /* # example python code of two reference implementations # see https://stackoverflow.com/questions/2827393/angles-between-two-n-dimensional-vectors-in-python/13849249#13849249 import numpy as np def unit_vector(vector): """ Returns the unit vector of the vector. """ return np.array(vector) / max(1e-15, np.linalg.norm(vector)) def angle_between(v1, v2): """ Returns the angle in radians between vectors 'v1' and 'v2':: >>> angle_between((1, 0, 0), (0, 1, 0)) 1.5707963267948966 >>> angle_between((1, 0, 0), (1, 0, 0)) 0.0 >>> angle_between((1, 0, 0), (-1, 0, 0)) 3.141592653589793 >>> angle_between((0, 0, 0), (0, 0, 0)) # error or pi/2? 1.5707963267948966 """ v1_u = unit_vector(v1) v2_u = unit_vector(v2) return np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0)) def spectral_angle(v1, v2): """ Returns the angle in radians between vectors 'v1' and 'v2':: >>> spectral_angle((1, 0, 0), (0, 1, 0)) 1.5707963267948966 >>> spectral_angle((1, 0, 0), (1, 0, 0)) 0.0 >>> spectral_angle((1, 0, 0), (-1, 0, 0)) 3.141592653589793 >>> spectral_angle((0, 0, 0), (0, 0, 0)) # error or pi/2? 1.5707963267948966 """ numer = np.dot(v1, v2) v1_u = np.sqrt(np.dot(v1, v1)) v2_u = np.sqrt(np.dot(v2, v2)) denom = v1_u * v2_u theta = 0.0 if denom == 0 else numer / denom return np.arccos(np.clip(theta, -1.0, 1.0)) vecs = [ ((1, 0, 0), (0, 1, 0)), ((1, 0, 0), (1, 0, 0)), ((1, 0, 0), (-1, 0, 0)), ((0, 0, 0), (0, 0, 0)), ] for i in range(10): vecs.append((np.random.uniform(size=3), np.random.uniform(size=3))) for v1, v2 in vecs: a = angle_between(v1, v2) b = spectral_angle(v1, v2) if a != b: print(f'Failed:\n\tv1 = {v1}\n\tv2 = {v2}\n\ta = {a}\n\tb = {b}\n\ta - b = {a - b}') */ static constexpr double pi{3.141592653589793}; static constexpr double piOver2{0.5 * pi}; auto spectralAngle = []( std::vector<double> d1, std::vector<double> d2 ) -> double { return Scoring::SpectralAngle(&d1[0], &d2[0], d1.size()); }; // previous unit test TEST_REAL_SIMILAR ( spectralAngle({0,1,3,5,2,0}, {1,3,5,2,0,0}), 0.7699453419277419 ) // zero TEST_REAL_SIMILAR ( spectralAngle({0, 0, 0}, {0, 0, 0}), piOver2 ) // same TEST_REAL_SIMILAR ( spectralAngle({1, 0, 0}, {1, 0, 0}), 0.0 ) // reversed TEST_REAL_SIMILAR ( spectralAngle({1, 0, 0}, {-1, 0, 0}), pi ) // orthogonal TEST_REAL_SIMILAR ( spectralAngle({1, 0, 0}, {0, 1, 0}), piOver2 ) // random from python TEST_REAL_SIMILAR ( spectralAngle({0.03174064, 0.11582065, 0.63258941}, {0.71882213, 0.00087569, 0.36516896}), 1.0597217204768459 ) TEST_REAL_SIMILAR ( spectralAngle({0.6608937, 0.0726909, 0.40912141}, {0.52081914, 0.71088, 0.0175557}), 0.9449782659258582 ) TEST_REAL_SIMILAR ( spectralAngle({0.58858475, 0.08963515, 0.08578046}, {0.76180969, 0.72763536, 0.50090751}), 0.6547156284689354 ) TEST_REAL_SIMILAR ( spectralAngle({0.08653022, 0.11595108, 0.74268632}, {0.55176333, 0.16783033, 0.70364679}), 0.5418305329889055 ) } END_SECTION BOOST_AUTO_TEST_CASE(void_normalize_sum_test) // void normalize_sum(double x[], unsigned int n) { // arr1 = [ 0,1,3,5,2,0 ]; // n_arr1 = (arr1 / (sum(arr1) *1.0) ) static const double arr1[] = {0,1,3,5,2,0}; static const double arr2[] = {1,3,5,2,0,0}; std::vector<double> data1 (arr1, arr1 + sizeof(arr1) / sizeof(arr1[0]) ); std::vector<double> data2 (arr2, arr2 + sizeof(arr2) / sizeof(arr2[0]) ); Scoring::normalize_sum(&data1[0], 6); TEST_REAL_SIMILAR (data1[0], 0.0) TEST_REAL_SIMILAR (data1[1], 0.09090909) TEST_REAL_SIMILAR (data1[2], 0.27272727) TEST_REAL_SIMILAR (data1[3], 0.45454545) TEST_REAL_SIMILAR (data1[4], 0.18181818) TEST_REAL_SIMILAR (data1[5], 0.0) } END_SECTION BOOST_AUTO_TEST_CASE(standardize_data_test) //START_SECTION((void MRMFeatureScoring::standardize_data(std::vector<double>& data))) { // Numpy // arr1 = [ 0,1,3,5,2,0 ]; // arr2 = [ 1,3,5,2,0,0 ]; // (arr1 - mean(arr1) ) / std(arr1) // (arr2 - mean(arr2) ) / std(arr2) static const double arr1[] = {0,1,3,5,2,0}; static const double arr2[] = {1,3,5,2,0,0}; std::vector<double> data1 (arr1, arr1 + sizeof(arr1) / sizeof(arr1[0]) ); std::vector<double> data2 (arr2, arr2 + sizeof(arr2) / sizeof(arr2[0]) ); Scoring::standardize_data(data1); Scoring::standardize_data(data2); TEST_REAL_SIMILAR (data1[0], -1.03479296); TEST_REAL_SIMILAR (data1[1], -0.47036043); TEST_REAL_SIMILAR (data1[2], 0.65850461); TEST_REAL_SIMILAR (data1[3], 1.78736965); TEST_REAL_SIMILAR (data1[4], 0.09407209); TEST_REAL_SIMILAR (data1[5], -1.03479296); TEST_REAL_SIMILAR (data2[0], -0.47036043); TEST_REAL_SIMILAR (data2[1], 0.65850461); TEST_REAL_SIMILAR (data2[2], 1.78736965); TEST_REAL_SIMILAR (data2[3], 0.09407209); TEST_REAL_SIMILAR (data2[4], -1.03479296); TEST_REAL_SIMILAR (data2[5], -1.03479296); } END_SECTION BOOST_AUTO_TEST_CASE(test_calculateCrossCorrelation) //START_SECTION((MRMFeatureScoring::XCorrArrayType MRMFeatureScoring::calculateCrossCorrelation(std::vector<double>& data1, std::vector<double>& data2, int maxdelay, int lag))) { // Numpy // arr1 = [ 0,1,3,5,2,0 ]; // arr2 = [ 1,3,5,2,0,0 ]; // data1 = (arr1 - mean(arr1) ) / std(arr1) // data2 = (arr2 - mean(arr2) ) / std(arr2) // correlate(data1, data2, "same") / 6.0 static const double arr1[] = {0,1,3,5,2,0}; static const double arr2[] = {1,3,5,2,0,0}; std::vector<double> data1 (arr1, arr1 + sizeof(arr1) / sizeof(arr1[0]) ); std::vector<double> data2 (arr2, arr2 + sizeof(arr2) / sizeof(arr2[0]) ); Scoring::standardize_data(data1); Scoring::standardize_data(data2); OpenSwath::Scoring::XCorrArrayType result = Scoring::calculateCrossCorrelation(data1, data2, 2, 1); for(OpenSwath::Scoring::XCorrArrayType::iterator it = result.begin(); it != result.end(); it++) { it->second = it->second / 6.0; } TEST_REAL_SIMILAR (result.data[4].second, -0.7374631); // find( 2)-> TEST_REAL_SIMILAR (result.data[3].second, -0.567846); // find( 1)-> TEST_REAL_SIMILAR (result.data[2].second, 0.4159292); // find( 0)-> TEST_REAL_SIMILAR (result.data[1].second, 0.8215339); // find(-1)-> TEST_REAL_SIMILAR (result.data[0].second, 0.15634218); // find(-2)-> TEST_EQUAL (result.data[4].first, 2) TEST_EQUAL (result.data[3].first, 1) TEST_EQUAL (result.data[2].first, 0) TEST_EQUAL (result.data[1].first, -1) TEST_EQUAL (result.data[0].first, -2) } END_SECTION BOOST_AUTO_TEST_CASE(test_MRMFeatureScoring_normalizedCrossCorrelation) //START_SECTION((MRMFeatureScoring::XCorrArrayType MRMFeatureScoring::normalizedCrossCorrelation(std::vector<double>& data1, std::vector<double>& data2, int maxdelay, int lag))) { // Numpy // arr1 = [ 0,1,3,5,2,0 ]; // arr2 = [ 1,3,5,2,0,0 ]; // data1 = (arr1 - mean(arr1) ) / std(arr1) // data2 = (arr2 - mean(arr2) ) / std(arr2) // correlate(data1, data2, "same") static const double arr1[] = {0,1,3,5,2,0}; static const double arr2[] = {1,3,5,2,0,0}; std::vector<double> data1 (arr1, arr1 + sizeof(arr1) / sizeof(arr1[0]) ); std::vector<double> data2 (arr2, arr2 + sizeof(arr2) / sizeof(arr2[0]) ); OpenSwath::Scoring::XCorrArrayType result = Scoring::normalizedCrossCorrelation(data1, data2, 2, 1); TEST_REAL_SIMILAR (result.data[4].second, -0.7374631); // .find( 2) TEST_REAL_SIMILAR (result.data[3].second, -0.567846); // .find( 1) TEST_REAL_SIMILAR (result.data[2].second, 0.4159292); // .find( 0) TEST_REAL_SIMILAR (result.data[1].second, 0.8215339); // .find(-1) TEST_REAL_SIMILAR (result.data[0].second, 0.15634218); // .find(-2) TEST_EQUAL (result.data[4].first, 2) TEST_EQUAL (result.data[3].first, 1) TEST_EQUAL (result.data[2].first, 0) TEST_EQUAL (result.data[1].first, -1) TEST_EQUAL (result.data[0].first, -2) } END_SECTION BOOST_AUTO_TEST_CASE(test_MRMFeatureScoring_calcxcorr_legacy_mquest_) //START_SECTION((MRMFeatureScoring::XCorrArrayType MRMFeatureScoring::calcxcorr(std::vector<double>& data1, std::vector<double>& data2, bool normalize))) { static const double arr1[] = {0,1,3,5,2,0}; static const double arr2[] = {1,3,5,2,0,0}; std::vector<double> data1 (arr1, arr1 + sizeof(arr1) / sizeof(arr1[0]) ); std::vector<double> data2 (arr2, arr2 + sizeof(arr2) / sizeof(arr2[0]) ); OpenSwath::Scoring::XCorrArrayType result = Scoring::calcxcorr_legacy_mquest_(data1, data2, true); TEST_EQUAL (result.data.size(), 13) TEST_REAL_SIMILAR (result.data[4+4].second, -0.7374631); // .find( 2) TEST_REAL_SIMILAR (result.data[3+4].second, -0.567846); // .find( 1) TEST_REAL_SIMILAR (result.data[2+4].second, 0.4159292); // .find( 0) TEST_REAL_SIMILAR (result.data[1+4].second, 0.8215339); // .find(-1) TEST_REAL_SIMILAR (result.data[0+4].second, 0.15634218); // .find(-2) TEST_EQUAL (result.data[4+4].first, 2) TEST_EQUAL (result.data[3+4].first, 1) TEST_EQUAL (result.data[2+4].first, 0) TEST_EQUAL (result.data[1+4].first, -1) TEST_EQUAL (result.data[0+4].first, -2) } END_SECTION BOOST_AUTO_TEST_CASE(test_computeAndAppendRank) { /* * Requires Octave with installed MIToolbox y = [5.97543668746948 4.2749171257019 3.3301842212677 4.08597040176392 5.50307035446167 5.24326848983765 8.40812492370605 2.83419919013977 6.94378805160522 7.69957494735718 4.08597040176392]'; [~, ~, y_ranking] = unique(y); % Note: Matlab handles ties differently than Scoring::computeAndAppendRank, but this makes no difference for MI estimation. */ /*static const double arr2[] = { 15.8951349258423, 41.5446395874023, 76.0746307373047, 109.069435119629, 111.90364074707, 169.79216003418, 121.043930053711, 63.0136985778809, 44.6150207519531, 21.4926776885986, 7.93575811386108 };*/ std::vector<double> data1 {5.97543668746948, 4.2749171257019, 3.3301842212677, 4.08597040176392, 5.50307035446167, 5.24326848983765, 8.40812492370605, 2.83419919013977, 6.94378805160522, 7.69957494735718, 4.08597040176392}; std::vector<double> data2 {15.8951349258423, 41.5446395874023, 76.0746307373047, 109.069435119629, 111.90364074707, 169.79216003418, 121.043930053711, 63.0136985778809, 44.6150207519531, 21.4926776885986, 7.93575811386108}; std::vector<unsigned int> result; Scoring::computeAndAppendRank(data1, result); TEST_EQUAL (result[0],7); TEST_EQUAL (result[1],4); TEST_EQUAL (result[2],1); TEST_EQUAL (result[3],2); TEST_EQUAL (result[4],6); TEST_EQUAL (result[5],5); TEST_EQUAL (result[6],10); TEST_EQUAL (result[7],0); TEST_EQUAL (result[8],8); TEST_EQUAL (result[9],9); TEST_EQUAL (result[10],2); } END_SECTION BOOST_AUTO_TEST_CASE(test_rankedMutualInformation) { /* * Requires Octave with installed MIToolbox y = [5.97543668746948 4.2749171257019 3.3301842212677 4.08597040176392 5.50307035446167 5.24326848983765 8.40812492370605 2.83419919013977 6.94378805160522 7.69957494735718 4.08597040176392]'; x = [15.8951349258423 41.5446395874023 76.0746307373047 109.069435119629 111.90364074707 169.79216003418 121.043930053711 63.0136985778809 44.6150207519531 21.4926776885986 7.93575811386108]'; [~, ~, y_ranking] = unique(y); [~, ~, x_ranking] = unique(x); m1 = mi(x_ranking,y_ranking) */ std::vector<double> data1 = {5.97543668746948, 4.2749171257019, 3.3301842212677, 4.08597040176392, 5.50307035446167, 5.24326848983765, 8.40812492370605, 2.83419919013977, 6.94378805160522, 7.69957494735718, 4.08597040176392}; std::vector<double> data2 = {15.8951349258423, 41.5446395874023, 76.0746307373047, 109.069435119629, 111.90364074707, 169.79216003418, 121.043930053711, 63.0136985778809, 44.6150207519531, 21.4926776885986, 7.93575811386108}; std::vector<unsigned int> rank_vec1, rank_vec2; unsigned int max_rank1 = Scoring::computeAndAppendRank(data1, rank_vec1); unsigned int max_rank2 = Scoring::computeAndAppendRank(data2, rank_vec2); unsigned int max_rank_check1 = *std::max_element(rank_vec1.begin(), rank_vec1.end()); unsigned int max_rank_check2 = *std::max_element(rank_vec2.begin(), rank_vec2.end()); TEST_EQUAL (max_rank1, max_rank_check1); TEST_EQUAL (max_rank2, max_rank_check2); double result = Scoring::rankedMutualInformation(rank_vec1, rank_vec2, max_rank1, max_rank2); TEST_REAL_SIMILAR (result, 3.2776); rank_vec1 = {0}; rank_vec2 = {0}; result = Scoring::rankedMutualInformation(rank_vec1, rank_vec2, 0, 0); TEST_REAL_SIMILAR (result, 0); rank_vec1 = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; rank_vec2 = {0, 1, 5, 4, 4, 2, 3, 1, 0, 2}; result = Scoring::rankedMutualInformation(rank_vec1, rank_vec2, 0, 5); TEST_REAL_SIMILAR (result, 0); double result_symmetric = Scoring::rankedMutualInformation(rank_vec2, rank_vec1, 5, 0); TEST_REAL_SIMILAR (result, result_symmetric); rank_vec1 = {0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}; rank_vec2 = {0, 1, 5, 4, 4, 2, 3, 1, 0, 2, 6, 7, 7, 6, 5, 3}; result = Scoring::rankedMutualInformation(rank_vec1, rank_vec2, 7, 7); TEST_REAL_SIMILAR (result, 2); rank_vec1 = {0, 1, 2, 3, 4, 4, 5, 6, 5, 1}; rank_vec2 = {6, 7, 8, 4, 5, 1, 2, 0, 3, 0}; result = Scoring::rankedMutualInformation(rank_vec1, rank_vec2, 6, 8); TEST_REAL_SIMILAR (result, 2.52193); result_symmetric = Scoring::rankedMutualInformation(rank_vec2, rank_vec1, 8, 6); TEST_REAL_SIMILAR (result, result_symmetric); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openswathalgo/DiaHelpers_test.cpp
.cpp
1,675
60
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Witold Wolski $ // -------------------------------------------------------------------------- #include "OpenMS/OPENSWATHALGO/OpenSwathAlgoConfig.h" #include "OpenMS/OPENSWATHALGO/ALGO/StatsHelpers.h" #include "OpenMS/OPENSWATHALGO/DATAACCESS/SpectrumHelpers.h" #include <OpenMS/CONCEPT/ClassTest.h> using namespace OpenMS; using namespace std; /////////////////////////// START_TEST(DIAHelpers, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// START_SECTION(testDotProdScore) { double arr1[] = { 100., 200., 4., 30., 20. }; double arr2[] = { 100., 100., 4., 100., 200. }; std::vector<double> vec1; std::vector<double> vec2; vec1.assign(arr1, arr1 + sizeof(arr1) / sizeof(double)); vec2.assign(arr2, arr2 + sizeof(arr2) / sizeof(double)); /* x<-c(100., 200., 4., 30., 20.) y<-c(100., 100., 4., 100., 200.) xs<-sqrt(x) ys<-sqrt(y) xsn<-xs/sqrt(sum(xs*xs)) ysn<-ys/sqrt(sum(ys*ys)) sum(xsn*ysn) */ //0.8604286 double scor = OpenSwath::dotprodScoring(vec1,vec2); TEST_REAL_SIMILAR (scor, 0.8604286); //xsm <- xs/sum(xs) //ysm <-ys/sum(ys) //sum(fabs(ysm-xsm)) scor = OpenSwath::manhattanScoring(vec1,vec2); TEST_REAL_SIMILAR (scor, 0.4950837); //0.4950837 } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openswathalgo/SwathMap_test.cpp
.cpp
2,064
61
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Joshua Charkow$ // $Authors: Joshua Charkow$ // -------------------------------------------------------------------------- #include "OpenMS/OPENSWATHALGO/DATAACCESS/SwathMap.h" #include <OpenMS/CONCEPT/ClassTest.h> using namespace OpenMS; using namespace std; /////////////////////////// START_TEST(SwathMap, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// START_SECTION(testIsEqual) { // map 1 and map 2 are equal OpenSwath::SwathMap map1; OpenSwath::SwathMap map2; TEST_EQUAL(map1.isEqual(map2), true); // map 3 and map 4 are equal // map 5 is different because of ms1 // map 6,7 is different because of mz bounds OpenSwath::SwathMap map3(1.0, 2.0, 1.5, false); OpenSwath::SwathMap map4(1.0, 2.0, 1.5, false); OpenSwath::SwathMap map5(1.0, 2.0, 1.5, true); TEST_EQUAL(map3.isEqual(map4), true); TEST_EQUAL(map3.isEqual(map5), false); // map 6,7 are different from map 3 different because of mz bounds OpenSwath::SwathMap map6(1.0, 3.0, 2.0, false); OpenSwath::SwathMap map7(2.0, 3.0, 2.5, false); // map 8 should be the same as map 3 OpenSwath::SwathMap map8(1.0, 2.0, 1.5, -1, -1, false); TEST_EQUAL(map3.isEqual(map8), true); // map 9, 10 are equal OpenSwath::SwathMap map9(1.0, 2.0, 1.5, 1.0, 1.1, false); OpenSwath::SwathMap map10(1.0, 2.0, 1.5, 1.0, 1.1, false); TEST_EQUAL(map9.isEqual(map10), true); // map 11/12 is different from map 9 because of im bounds OpenSwath::SwathMap map11(1.0, 2.0, 1.5, 1.3, 1.4, false); OpenSwath::SwathMap map12(1.0, 2.0, 1.5, 1.0, 1.2, false); TEST_EQUAL(map9.isEqual(map11), false); TEST_EQUAL(map9.isEqual(map12), false); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openswathalgo/Datastructures_test.cpp
.cpp
3,412
107
// 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 $ // -------------------------------------------------------------------------- #include "OpenMS/OPENSWATHALGO/OpenSwathAlgoConfig.h" #include "OpenMS/OPENSWATHALGO/DATAACCESS/DataStructures.h" #include <OpenMS/CONCEPT/ClassTest.h> using namespace OpenMS; using namespace std; using namespace OpenSwath; /////////////////////////// START_TEST(DataStructures, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// START_SECTION(OSSpectrum_empty) { OSSpectrum s; TEST_EQUAL (s.getMZArray() == nullptr, false) TEST_EQUAL (s.getIntensityArray() == nullptr, false) TEST_EQUAL (s.getDriftTimeArray() == nullptr, true) TEST_EQUAL (s.getMZArray()->data.size(), 0) TEST_EQUAL (s.getIntensityArray()->data.size(), 0) } END_SECTION START_SECTION(OSSpectrum_data) { OSSpectrum s; BinaryDataArrayPtr mz(new BinaryDataArray); mz->data.push_back(1.5); BinaryDataArrayPtr inten(new BinaryDataArray); inten->data.push_back(100.1); BinaryDataArrayPtr im(new BinaryDataArray); im->data.push_back(300.1); im->description = "Ion Mobility"; // old format s.setMZArray(mz); s.setIntensityArray(inten); s.getDataArrays().push_back(im); TEST_EQUAL (s.getMZArray() == nullptr, false) TEST_EQUAL (s.getIntensityArray() == nullptr, false) TEST_EQUAL (s.getDriftTimeArray() == nullptr, false) TEST_EQUAL (s.getMZArray()->data.size(), 1) TEST_EQUAL (s.getIntensityArray()->data.size(), 1) TEST_EQUAL (s.getDriftTimeArray()->data.size(), 1) TEST_REAL_SIMILAR (s.getMZArray()->data[0], 1.5) TEST_REAL_SIMILAR (s.getIntensityArray()->data[0], 100.1) TEST_REAL_SIMILAR (s.getDriftTimeArray()->data[0], 300.1) } END_SECTION START_SECTION(OSSpectrum_data_2) { OSSpectrum s; BinaryDataArrayPtr mz(new BinaryDataArray); mz->data.push_back(1.5); BinaryDataArrayPtr inten(new BinaryDataArray); inten->data.push_back(100.1); BinaryDataArrayPtr im(new BinaryDataArray); im->data.push_back(300.1); im->description = "Ion Mobility (MS:1002476)"; // new format s.setMZArray(mz); s.setIntensityArray(inten); s.getDataArrays().push_back(im); TEST_EQUAL (s.getMZArray() == nullptr, false) TEST_EQUAL (s.getIntensityArray() == nullptr, false) TEST_EQUAL (s.getDriftTimeArray() == nullptr, false) TEST_EQUAL (s.getMZArray()->data.size(), 1) TEST_EQUAL (s.getIntensityArray()->data.size(), 1) TEST_EQUAL (s.getDriftTimeArray()->data.size(), 1) TEST_REAL_SIMILAR (s.getMZArray()->data[0], 1.5) TEST_REAL_SIMILAR (s.getIntensityArray()->data[0], 100.1) TEST_REAL_SIMILAR (s.getDriftTimeArray()->data[0], 300.1) s.getDataArrays().back()->description = ""; TEST_EQUAL (s.getDriftTimeArray() == nullptr, true) s.getDataArrays().back()->description = "Ion Mobility (blah)"; TEST_EQUAL (s.getDriftTimeArray() == nullptr, false) s.getDataArrays().back()->description = "Ion mOBILITY (blah)"; // wrong TEST_EQUAL (s.getDriftTimeArray() == nullptr, true) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openswathalgo/TestConvert.cpp
.cpp
1,143
38
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Witold Wolski $ // -------------------------------------------------------------------------- #include <OpenMS/OPENSWATHALGO/DATAACCESS/TransitionHelper.h> #include <OpenMS/OPENSWATHALGO/DATAACCESS/TransitionExperiment.h> #include <OpenMS/OPENSWATHALGO/DATAACCESS/Transitions.h> #include <OpenMS/CONCEPT/ClassTest.h> using namespace OpenMS; using namespace std; /////////////////////////// START_TEST(ITrans2Trans, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// START_SECTION(initializeXCorrMatrix) { OpenSwath::LightTargetedExperiment lte; OpenSwath::TargetedExperiment te; //OpenSwath::convert(lte, te); //TODO (wolski): write tests } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/IsotopeLabelingMDVs_test.cpp
.cpp
32,286
670
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Ahmed Khalil $ // $Authors: Ahmed Khalil $ // -------------------------------------------------------------------------- // #include <OpenMS/ANALYSIS/QUANTITATION/IsotopeLabelingMDVs.h> #include <OpenMS/CHEMISTRY/ISOTOPEDISTRIBUTION/CoarseIsotopePatternGenerator.h> #include <OpenMS/CHEMISTRY/ISOTOPEDISTRIBUTION/IsotopeDistribution.h> #include <OpenMS/CONCEPT/ClassTest.h> #include <cassert> using namespace OpenMS; START_TEST(IsotopeLabelingMDVs, "$Id$") IsotopeLabelingMDVs* ptr = nullptr; IsotopeLabelingMDVs* nullPointer = nullptr; START_SECTION((IsotopeLabelingMDVs())) ptr = new IsotopeLabelingMDVs(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((~IsotopeLabelingMDVs())) delete ptr; END_SECTION START_SECTION(( void IsotopeLabelingMDVs::calculateMDV( const Feature& measured_feature, Feature& normalized_featuremap, const String& mass_intensity_type, const String& feature_name) )) // case 1: intensity with norm max and norm sum (x) : intensity (peak area) not supplied // case 2: peak apex with norm max and norm sum : - Lactate1 & Lactate2 - peak_apex_int - norm_max // - Lactate1 & Lactate2 - peak_apex_int - norm_sum IsotopeLabelingMDVs isotopelabelingmdvs; // From CHO_190316_Flux.xlsx provided by Douglas McCloskey std::vector<double> L1_peak_apex_int {3.61e+08, 1.20e+04, 1.02e+05, 2.59e+04}; std::vector<double> L2_peak_apex_int {2.77e+07, 5.45e+04, 6.26e+05, 7.46e+04, 2.75e+04}; std::vector<double> L1_norm_max {1.00e+00, 3.324e-05, 2.825e-04, 7.174e-05}; std::vector<double> L1_norm_sum {9.9961e-01, 3.3228e-05, 2.8243e-04, 7.1717e-05}; std::vector<double> L2_norm_max {1.00e+00, 1.967e-03, 2.259e-02, 2.693e-03, 9.927e-04}; std::vector<double> L2_norm_sum {9.7252e-01, 1.9134e-03, 2.1978e-02, 2.6191e-03, 9.655e-04}; // Lactate1 & Lactate2 - peak_apex_int - norm_max OpenMS::Feature lactate_1_normmax; OpenMS::Feature lactate_1_normalized_normmax; std::vector<OpenMS::Feature> L1_subordinates_normmax; lactate_1_normmax.setMetaValue("PeptideRef", "Lactate1"); for (uint16_t i = 0; i < L1_peak_apex_int.size(); ++i) { OpenMS::Feature sub; sub.setMetaValue("native_id", "Lactate1_"+std::to_string(117+i)); sub.setMetaValue("peak_apex_int", L1_peak_apex_int[i]); L1_subordinates_normmax.push_back(sub); } lactate_1_normmax.setSubordinates(L1_subordinates_normmax); isotopelabelingmdvs.calculateMDV(lactate_1_normmax, lactate_1_normalized_normmax, IsotopeLabelingMDVs::MassIntensityType::NORM_MAX, "peak_apex_int"); for(size_t i = 0; i < lactate_1_normalized_normmax.getSubordinates().size(); ++i) { TEST_REAL_SIMILAR(lactate_1_normalized_normmax.getSubordinates().at(i).getMetaValue("peak_apex_int"), L1_norm_max.at(i)); } OpenMS::Feature lactate_2_normmax; OpenMS::Feature lactate_2_normalized_normmax; std::vector<OpenMS::Feature> L2_subordinates_normmax; lactate_2_normmax.setMetaValue("PeptideRef", "Lactate2"); for (uint16_t i = 0; i < L2_peak_apex_int.size(); ++i) { OpenMS::Feature sub; sub.setMetaValue("native_id", "Lactate2_"+std::to_string(219+i)); sub.setMetaValue("peak_apex_int", L2_peak_apex_int[i]); L2_subordinates_normmax.push_back(sub); } lactate_2_normmax.setSubordinates(L2_subordinates_normmax); isotopelabelingmdvs.calculateMDV(lactate_2_normmax, lactate_2_normalized_normmax, IsotopeLabelingMDVs::MassIntensityType::NORM_MAX, "peak_apex_int"); for(size_t i = 0; i < lactate_2_normalized_normmax.getSubordinates().size(); ++i) { TEST_REAL_SIMILAR(lactate_2_normalized_normmax.getSubordinates().at(i).getMetaValue("peak_apex_int"), L2_norm_max.at(i)); } // Lactate1 & Lactate2 - peak_apex_int - norm_sum OpenMS::Feature lactate_1_normsum; OpenMS::Feature lactate_1_normalized_normsum; std::vector<OpenMS::Feature> L1_subordinates_normsum; lactate_1_normsum.setMetaValue("PeptideRef", "Lactate1"); for (uint16_t i = 0; i < L1_peak_apex_int.size(); ++i) { OpenMS::Feature sub; sub.setMetaValue("native_id", "Lactate1_"+std::to_string(117+i)); sub.setMetaValue("peak_apex_int", L1_peak_apex_int[i]); L1_subordinates_normsum.push_back(sub); } lactate_1_normsum.setSubordinates(L1_subordinates_normsum); isotopelabelingmdvs.calculateMDV(lactate_1_normsum, lactate_1_normalized_normsum, IsotopeLabelingMDVs::MassIntensityType::NORM_SUM, "peak_apex_int"); for(size_t i = 0; i < lactate_1_normalized_normsum.getSubordinates().size(); ++i) { TEST_REAL_SIMILAR(lactate_1_normalized_normsum.getSubordinates().at(i).getMetaValue("peak_apex_int"), L1_norm_sum.at(i)); } OpenMS::Feature lactate_2_normsum; OpenMS::Feature lactate_2_normalized_normsum; std::vector<OpenMS::Feature> L2_subordinates_normsum; lactate_2_normsum.setMetaValue("PeptideRef", "Lactate2"); for (uint16_t i = 0; i < L2_peak_apex_int.size(); ++i) { OpenMS::Feature sub; sub.setMetaValue("native_id", "Lactate2_"+std::to_string(219+i)); sub.setMetaValue("peak_apex_int", L2_peak_apex_int[i]); L2_subordinates_normsum.push_back(sub); } lactate_2_normsum.setSubordinates(L2_subordinates_normsum); // isotopelabelingmdvs.calculateMDV(lactate_2_normsum, lactate_2_normalized_normsum, IsotopeLabelingMDVs::MassIntensityType::NORM_SUM, IsotopeLabelingMDVs::FeatureName::PEAK_APEX_INT); for(size_t i = 0; i < lactate_2_normalized_normsum.getSubordinates().size(); ++i) { TEST_REAL_SIMILAR(lactate_2_normalized_normsum.getSubordinates().at(i).getIntensity(), L2_norm_sum.at(i)); } END_SECTION START_SECTION(( void IsotopeLabelingMDVs::calculateMDVs( const FeatureMap& measured_feature, FeatureMap& normalized_featuremap, const String& mass_intensity_type, const String& feature_name) )) // case 1: intensity with norm max and norm sum (x) : intensity (peak area) not supplied // case 2: peak apex with norm max and norm sum : - Lactate1 & Lactate2 - peak_apex_int - norm_max // - Lactate1 & Lactate2 - peak_apex_int - norm_sum IsotopeLabelingMDVs isotopelabelingmdvs; // From CHO_190316_Flux.xlsx provided by Douglas McCloskey std::vector<double> L1_peak_apex_int {3.61e+08, 1.20e+04, 1.02e+05, 2.59e+04}; std::vector<double> L2_peak_apex_int {2.77e+07, 5.45e+04, 6.26e+05, 7.46e+04, 2.75e+04}; std::vector<double> L1_norm_max {1.00e+00, 3.324e-05, 2.825e-04, 7.174e-05}; std::vector<double> L1_norm_sum {9.9961e-01, 3.3228e-05, 2.8243e-04, 7.1717e-05}; std::vector<double> L2_norm_max {1.00e+00, 1.967e-03, 2.259e-02, 2.693e-03, 9.927e-04}; std::vector<double> L2_norm_sum {9.7252e-01, 1.9134e-03, 2.1978e-02, 2.6191e-03, 9.655e-04}; // Lactate1 & Lactate2 - peak_apex_int - norm_max OpenMS::Feature lactate_1_normmax; OpenMS::Feature lactate_1_normalized_normmax; std::vector<OpenMS::Feature> L1_subordinates_normmax; lactate_1_normmax.setMetaValue("PeptideRef", "Lactate1"); for (uint16_t i = 0; i < L1_peak_apex_int.size(); ++i) { OpenMS::Feature sub; sub.setMetaValue("native_id", "Lactate1_"+std::to_string(117+i)); sub.setMetaValue("peak_apex_int", L1_peak_apex_int[i]); L1_subordinates_normmax.push_back(sub); } lactate_1_normmax.setSubordinates(L1_subordinates_normmax); isotopelabelingmdvs.calculateMDV(lactate_1_normmax, lactate_1_normalized_normmax, IsotopeLabelingMDVs::MassIntensityType::NORM_MAX, "peak_apex_int"); for(size_t i = 0; i < lactate_1_normalized_normmax.getSubordinates().size(); ++i) { TEST_REAL_SIMILAR(lactate_1_normalized_normmax.getSubordinates().at(i).getMetaValue("peak_apex_int"), L1_norm_max.at(i)); } OpenMS::Feature lactate_2_normmax; OpenMS::Feature lactate_2_normalized_normmax; std::vector<OpenMS::Feature> L2_subordinates_normmax; lactate_2_normmax.setMetaValue("PeptideRef", "Lactate2"); for (uint16_t i = 0; i < L2_peak_apex_int.size(); ++i) { OpenMS::Feature sub; sub.setMetaValue("native_id", "Lactate2_"+std::to_string(219+i)); sub.setMetaValue("peak_apex_int", L2_peak_apex_int[i]); L2_subordinates_normmax.push_back(sub); } lactate_2_normmax.setSubordinates(L2_subordinates_normmax); isotopelabelingmdvs.calculateMDV(lactate_2_normmax, lactate_2_normalized_normmax, IsotopeLabelingMDVs::MassIntensityType::NORM_MAX, "peak_apex_int"); for(size_t i = 0; i < lactate_2_normalized_normmax.getSubordinates().size(); ++i) { TEST_REAL_SIMILAR(lactate_2_normalized_normmax.getSubordinates().at(i).getMetaValue("peak_apex_int"), L2_norm_max.at(i)); } // Lactate1 & Lactate2 - peak_apex_int - norm_sum OpenMS::Feature lactate_1_normsum; OpenMS::Feature lactate_1_normalized_normsum; std::vector<OpenMS::Feature> L1_subordinates_normsum; lactate_1_normsum.setMetaValue("PeptideRef", "Lactate1"); for (uint16_t i = 0; i < L1_peak_apex_int.size(); ++i) { OpenMS::Feature sub; sub.setMetaValue("native_id", "Lactate1_"+std::to_string(117+i)); sub.setMetaValue("peak_apex_int", L1_peak_apex_int[i]); L1_subordinates_normsum.push_back(sub); } lactate_1_normsum.setSubordinates(L1_subordinates_normsum); isotopelabelingmdvs.calculateMDV(lactate_1_normsum, lactate_1_normalized_normsum, IsotopeLabelingMDVs::MassIntensityType::NORM_SUM, "peak_apex_int"); for(size_t i = 0; i < lactate_1_normalized_normsum.getSubordinates().size(); ++i) { TEST_REAL_SIMILAR(lactate_1_normalized_normsum.getSubordinates().at(i).getMetaValue("peak_apex_int"), L1_norm_sum.at(i)); } OpenMS::Feature lactate_2_normsum; OpenMS::Feature lactate_2_normalized_normsum; std::vector<OpenMS::Feature> L2_subordinates_normsum; lactate_2_normsum.setMetaValue("PeptideRef", "Lactate2"); for (uint16_t i = 0; i < L2_peak_apex_int.size(); ++i) { OpenMS::Feature sub; sub.setMetaValue("native_id", "Lactate2_"+std::to_string(219+i)); sub.setMetaValue("peak_apex_int", L2_peak_apex_int[i]); L2_subordinates_normsum.push_back(sub); } lactate_2_normsum.setSubordinates(L2_subordinates_normsum); isotopelabelingmdvs.calculateMDV(lactate_2_normsum, lactate_2_normalized_normsum, IsotopeLabelingMDVs::MassIntensityType::NORM_SUM, "peak_apex_int"); for(size_t i = 0; i < lactate_2_normalized_normsum.getSubordinates().size(); ++i) { TEST_REAL_SIMILAR(lactate_2_normalized_normsum.getSubordinates().at(i).getMetaValue("peak_apex_int"), L2_norm_sum.at(i)); } OpenMS::FeatureMap lactate_normmax; OpenMS::FeatureMap lactate_normsum; OpenMS::FeatureMap lactate_normalized_normmax; OpenMS::FeatureMap lactate_normalized_normsum; lactate_normmax.push_back(lactate_1_normmax); lactate_normmax.push_back(lactate_2_normmax); lactate_normsum.push_back(lactate_1_normsum); lactate_normsum.push_back(lactate_2_normsum); isotopelabelingmdvs.calculateMDVs(lactate_normmax, lactate_normalized_normmax, IsotopeLabelingMDVs::MassIntensityType::NORM_MAX, "peak_apex_int"); isotopelabelingmdvs.calculateMDVs(lactate_normsum, lactate_normalized_normsum, IsotopeLabelingMDVs::MassIntensityType::NORM_SUM, "peak_apex_int"); for(size_t i = 0; i < lactate_normalized_normmax.size(); ++i) { for(size_t j = 0; j < lactate_normalized_normmax.at(i).getSubordinates().size(); ++j) { if (i == 0) // lactate_1 { TEST_REAL_SIMILAR(lactate_normalized_normmax.at(i).getSubordinates().at(j).getMetaValue("peak_apex_int"), L1_norm_max.at(j)); } else if (i == 1) // lactate_2 { TEST_REAL_SIMILAR(lactate_normalized_normmax.at(i).getSubordinates().at(j).getMetaValue("peak_apex_int"), L2_norm_max.at(j)); } } } for(size_t i = 0; i < lactate_normalized_normsum.size(); ++i) { for(size_t j = 0; j < lactate_normalized_normsum.at(i).getSubordinates().size(); ++j) { if (i == 0) // lactate_1 { TEST_REAL_SIMILAR(lactate_normalized_normsum.at(i).getSubordinates().at(j).getMetaValue("peak_apex_int"), L1_norm_sum.at(j)); } else if (i == 1) // lactate_2 { TEST_REAL_SIMILAR(lactate_normalized_normsum.at(i).getSubordinates().at(j).getMetaValue("peak_apex_int"), L2_norm_sum.at(j)); } } } END_SECTION START_SECTION(( void IsotopeLabelingMDVs::isotopicCorrection( const Feature& normalized_feature, Feature& corrected_feature, const Matrix<double>& correction_matrix), const std::string correction_matrix_agent )) // case 1: validating matrix inverse (separately tested) // case 2: validating corrected results (corrected peak_apex_int) IsotopeLabelingMDVs isotopelabelingmdvs; OpenMS::Feature lactate_1_normalized; OpenMS::Feature lactate_1_corrected; std::vector<std::vector<double>> correction_matrix_inversed(4, std::vector<double>(4,0)); // Correction Matrix extracted from "TOOLS FOR MASS ISOTOPOMER DATA EVALUATION IN 13C FLUX ANALYSIS, // Wahl et al, P.263, Table I" Matrix<double> correction_matrix_tBDMS; double correction_matrix_tBDMS_[4][4] = { {0.8213, 0.1053, 0.0734, 0.0000}, {0.8420, 0.0963, 0.0617, 0.0000}, {0.8466, 0.0957, 0.0343, 0.0233}, {0.8484, 0.0954, 0.0337, 0.0225} }; correction_matrix_tBDMS.setMatrix<double,4,4>(correction_matrix_tBDMS_); // L1_norm_max, L1_peak_apex_int From CHO_190316_Flux.xlsx provided by Douglas McCloskey // L1_corrected self calculated std::vector<double> L1_norm_max {1.00e+00, 3.324e-05, 2.825e-04, 7.174e-05}; std::vector<double> L1_corrected {-12.7699, 140.7289, -45.3788, -47.2081}; std::vector<Peak2D::IntensityType> L1_peak_apex_int {3.61e+08, 1.20e+04, 1.02e+05, 2.59e+04}; std::vector<OpenMS::Feature> L1_subordinates_normmax; lactate_1_normalized.setMetaValue("PeptideRef", "Lactate1"); for (uint16_t i = 0; i < L1_norm_max.size(); ++i) { OpenMS::Feature sub; sub.setMetaValue("native_id", "Lactate1_"+std::to_string(117+i)); sub.setMetaValue("peak_apex_int", L1_norm_max[i]); L1_subordinates_normmax.push_back(sub); } lactate_1_normalized.setSubordinates(L1_subordinates_normmax); isotopelabelingmdvs.isotopicCorrection(lactate_1_normalized, lactate_1_corrected, correction_matrix_tBDMS, IsotopeLabelingMDVs::DerivatizationAgent::NOT_SELECTED); for(size_t i = 0; i < lactate_1_corrected.getSubordinates().size(); ++i) { TEST_REAL_SIMILAR(lactate_1_corrected.getSubordinates().at(i).getMetaValue("peak_apex_int"), L1_corrected[i]); } isotopelabelingmdvs.isotopicCorrection(lactate_1_normalized, lactate_1_corrected, {}, IsotopeLabelingMDVs::DerivatizationAgent::TBDMS); for(size_t i = 0; i < lactate_1_corrected.getSubordinates().size(); ++i) { TEST_REAL_SIMILAR(lactate_1_corrected.getSubordinates().at(i).getMetaValue("peak_apex_int"), L1_corrected[i]); } END_SECTION START_SECTION(( void IsotopeLabelingMDVs::isotopicCorrections( const FeatureMap& normalized_feature, FeatureMap& corrected_feature, const Matrix<double>& correction_matrix, const std::string correction_matrix_agent) )) // case 1: validating corrected results (corrected peak_apex_int) IsotopeLabelingMDVs isotopelabelingmdvs; OpenMS::Feature lactate_1_normalized; OpenMS::FeatureMap lactate_1_featureMap; OpenMS::FeatureMap lactate_1_corrected_featureMap; std::vector<std::vector<double>> correction_matrix_inversed(4, std::vector<double>(4,0)); // Correction Matrix extracted from "TOOLS FOR MASS ISOTOPOMER DATA EVALUATION IN 13C FLUX ANALYSIS, // Wahl et al, P.263, Table I" Matrix<double> correction_matrix_tBDMS; double correction_matrix_tBDMS_[4][4] = { {0.8213, 0.1053, 0.0734, 0.0000}, {0.8420, 0.0963, 0.0617, 0.0000}, {0.8466, 0.0957, 0.0343, 0.0233}, {0.8484, 0.0954, 0.0337, 0.0225} }; correction_matrix_tBDMS.setMatrix<double, 4, 4>(correction_matrix_tBDMS_); // L1_norm_max, L1_peak_apex_int From CHO_190316_Flux.xlsx provided by Douglas McCloskey // L1_corrected self calculated std::vector<double> L1_norm_max {1.00e+00, 3.324e-05, 2.825e-04, 7.174e-05}; std::vector<double> L1_corrected {-12.7699, 140.7289, -45.3788, -47.2081}; std::vector<Peak2D::IntensityType> L1_peak_apex_int {3.61e+08, 1.20e+04, 1.02e+05, 2.59e+04}; std::vector<OpenMS::Feature> L1_subordinates_normmax; lactate_1_normalized.setMetaValue("PeptideRef", "Lactate1"); for (uint16_t i = 0; i < L1_norm_max.size(); ++i) { OpenMS::Feature sub; sub.setMetaValue("native_id", "Lactate1_"+std::to_string(117+i)); sub.setMetaValue("peak_apex_int", L1_norm_max[i]); L1_subordinates_normmax.push_back(sub); } lactate_1_normalized.setSubordinates(L1_subordinates_normmax); for(uint8_t i = 0; i < 3; ++i) { lactate_1_featureMap.push_back(lactate_1_normalized); } isotopelabelingmdvs.isotopicCorrections(lactate_1_featureMap, lactate_1_corrected_featureMap, correction_matrix_tBDMS, IsotopeLabelingMDVs::DerivatizationAgent::NOT_SELECTED); for(uint8_t i = 0; i < lactate_1_corrected_featureMap.size(); ++i) { for(uint8_t j = 0; j < lactate_1_corrected_featureMap.at(i).getSubordinates().size(); ++j) { TEST_REAL_SIMILAR(lactate_1_corrected_featureMap.at(i).getSubordinates().at(j).getMetaValue("peak_apex_int"), L1_corrected[j]); } } lactate_1_corrected_featureMap.clear(); isotopelabelingmdvs.isotopicCorrections(lactate_1_featureMap, lactate_1_corrected_featureMap, {}, IsotopeLabelingMDVs::DerivatizationAgent::TBDMS); for(uint8_t i = 0; i < lactate_1_corrected_featureMap.size(); ++i) { for(uint8_t j = 0; j <lactate_1_corrected_featureMap.at(i).getSubordinates().size(); ++j) { TEST_REAL_SIMILAR(lactate_1_corrected_featureMap.at(i).getSubordinates().at(j).getMetaValue("peak_apex_int"), L1_corrected[j]); } } END_SECTION START_SECTION(( void IsotopeLabelingMDVs::calculateIsotopicPurity( Feature& normalized_featuremap, const std::vector<double>& experiment_data, const std::string& isotopic_purity_name) )) // case 1: calculating isotopic purity on 1_2_13C, U_13C sample experiment data IsotopeLabelingMDVs isotopelabelingmdvs; OpenMS::Feature lactate_1_normalized; // L1_norm_max From CHO_190316_Flux.xlsx provided by Douglas McCloskey // L1_1_2_13C_glucose_experiment, L1_U_13C_glucose_experiment & L1_isotopic_purity_ground_truth // from "High-resolution 13C metabolic flux analysis",Long et al, doi:10.1038/s41596-019-0204-0, // P.2869, Box 4 std::vector<double> L1_norm_max {1.00e+00, 3.324e-05, 2.825e-04, 7.174e-05}; std::vector<double> L1_1_2_13C_glucose_experiment {0.5, 0.7, 98.8, 0.0, 0.0, 0.0}; std::vector<double> L1_U_13C_glucose_experiment {0.5, 0.0, 0.1, 0.2, 3.6, 95.5}; std::vector<double> L1_isotopic_purity_ground_truth {99.6469, 99.2517}; // [1_2_13C, U_13C] std::string L1_1_2_13C_glucose = "1_2-13C_glucose_experiment"; std::string L1_U_13C_glucose = "U-13C_glucose_experiment"; std::vector<OpenMS::Feature> L1_subordinates_normmax; lactate_1_normalized.setMetaValue("PeptideRef", "Lactate1"); for (uint16_t i = 0; i < L1_norm_max.size(); ++i) { OpenMS::Feature sub; sub.setMetaValue("native_id", "Lactate1_"+std::to_string(117+i)); sub.setMetaValue("peak_apex_int", L1_norm_max[i]); L1_subordinates_normmax.push_back(sub); } lactate_1_normalized.setSubordinates(L1_subordinates_normmax); isotopelabelingmdvs.calculateIsotopicPurity(lactate_1_normalized, L1_1_2_13C_glucose_experiment, L1_1_2_13C_glucose); TEST_REAL_SIMILAR( (double)(lactate_1_normalized.getMetaValue(L1_1_2_13C_glucose)) * 100, L1_isotopic_purity_ground_truth[0]); isotopelabelingmdvs.calculateIsotopicPurity(lactate_1_normalized, L1_U_13C_glucose_experiment, L1_U_13C_glucose); TEST_REAL_SIMILAR( (double)(lactate_1_normalized.getMetaValue(L1_U_13C_glucose)) * 100, L1_isotopic_purity_ground_truth[1]); END_SECTION START_SECTION(( void IsotopeLabelingMDVs::calculateIsotopicPurities( Feature& normalized_featuremap, const std::vector<std::vector<double>>& experiment_data, const std::vector<std::string>& isotopic_purity_names) )) // case 1: calculating isotopic purity on 1_2_13C, U_13C sample experiment data IsotopeLabelingMDVs isotopelabelingmdvs; OpenMS::Feature lactate_1_normalized; OpenMS::FeatureMap lactate_1_featureMap; // L1_norm_max From CHO_190316_Flux.xlsx provided by Douglas McCloskey // L1_1_2_13C_glucose_experiment, L1_U_13C_glucose_experiment & L1_isotopic_purity_ground_truth // from "High-resolution 13C metabolic flux analysis",Long et al, doi:10.1038/s41596-019-0204-0, // P.2869, Box 4 std::vector<double> L1_norm_max {1.00e+00, 3.324e-05, 2.825e-04, 7.174e-05}; std::vector<std::vector<double>> L1_1_2_13C_glucose_experiment {{0.5, 0.7, 98.8, 0.0, 0.0, 0.0},{0.5, 0.7, 98.8, 0.0, 0.0, 0.0},{0.5, 0.7, 98.8, 0.0, 0.0, 0.0}}; std::vector<std::vector<double>> L1_U_13C_glucose_experiment {{0.5, 0.0, 0.1, 0.2, 3.6, 95.5},{0.5, 0.0, 0.1, 0.2, 3.6, 95.5},{0.5, 0.0, 0.1, 0.2, 3.6, 95.5}}; std::vector<double> L1_isotopic_purity_ground_truth {99.6469, 99.2517}; // [1_2_13C, U_13C] std::vector<std::string> L1_1_2_13C_glucose = {"1_2-13C_glucose_experiment","1_2-13C_glucose_experiment","1_2-13C_glucose_experiment"}; std::vector<std::string> L1_U_13C_glucose = {"U-13C_glucose_experiment","U-13C_glucose_experiment","U-13C_glucose_experiment"}; std::vector<OpenMS::Feature> L1_subordinates_normmax; lactate_1_normalized.setMetaValue("PeptideRef", "Lactate1"); for (uint16_t i = 0; i < L1_norm_max.size(); ++i) { OpenMS::Feature sub; sub.setMetaValue("native_id", "Lactate1_"+std::to_string(117+i)); sub.setMetaValue("peak_apex_int", L1_norm_max[i]); L1_subordinates_normmax.push_back(sub); } lactate_1_normalized.setSubordinates(L1_subordinates_normmax); for(uint8_t i = 0; i < 3; ++i) { lactate_1_featureMap.push_back(lactate_1_normalized); } isotopelabelingmdvs.calculateIsotopicPurities(lactate_1_featureMap, L1_1_2_13C_glucose_experiment, L1_1_2_13C_glucose); for(uint8_t i = 0; i < lactate_1_featureMap.size(); ++i) { TEST_REAL_SIMILAR( (double)(lactate_1_featureMap.at(i).getMetaValue(L1_1_2_13C_glucose.at(i))) * 100, L1_isotopic_purity_ground_truth[0]); } isotopelabelingmdvs.calculateIsotopicPurities(lactate_1_featureMap, L1_U_13C_glucose_experiment, L1_U_13C_glucose); for(uint8_t i = 0; i < lactate_1_featureMap.size(); ++i) { TEST_REAL_SIMILAR( (double)(lactate_1_featureMap.at(i).getMetaValue(L1_U_13C_glucose.at(i))) * 100, L1_isotopic_purity_ground_truth[1]); } END_SECTION START_SECTION(( IsotopeLabelingMDVs::calculateMDVAccuracy( Feature& normalized_feature, const std::string& feature_name, const std::string& fragment_isotopomer_theoretical_formula) )) // case 1: calculating accuracy given measured values of 2 seperate features IsotopeLabelingMDVs isotopelabelingmdvs; OpenMS::Feature feature_1, feature_2; // L1_norm_max From CHO_190316_Flux.xlsx provided by Douglas McCloskey // accoa_C23H37N7O17P3S_MRM_measured_13 & fad_C27H32N9O15P2_EPI_measured_48 are extracted from // "MID Max: LC–MS/MS Method for Measuring the Precursor and Product Mass Isotopomer Distributions // of Metabolic Intermediates and Cofactors for Metabolic Flux Analysis Applications, McCloskey et al", // DOI: 10.1021/acs.analchem.5b03887, Supporting Information: Table S-2 std::vector<double> L1_norm_max {1.00e+00, 3.324e-05, 2.825e-04, 7.174e-05}; std::vector<double> accoa_C23H37N7O17P3S_MRM_measured_13 {0.627, 0.253, 0.096, 0.02, 0.004, 0.001}; std::vector<double> accoa_C23H37N7O17P3S_abs_diff {0.0632108, 0.0505238, 0.0119821, 0.0014131, 0.0000315, 0.0003232}; std::vector<double> fad_C27H32N9O15P2_EPI_measured_48 {0.638, 0.355, 0.1, 0.0, 0.0, 0.0}; std::vector<double> fad_C27H32N9O15P2_abs_diff {0.0570446, 0.1223954, 0.0407946, 0.0111298, 0.0017729, 0.0002426}; std::vector<double> Average_accuracy_groundtruth {0.02374, 0.03451}; // [accoa_13, fad_48] std::vector<OpenMS::Feature> L1_subordinates, L2_subordinates; feature_1.setMetaValue("PeptideRef", "accoa"); for (uint16_t i = 0; i < accoa_C23H37N7O17P3S_MRM_measured_13.size(); ++i) { OpenMS::Feature sub; sub.setMetaValue("native_id", "Lactate1_"+std::to_string(117+i)); sub.setMetaValue("peak_apex_int", accoa_C23H37N7O17P3S_MRM_measured_13[i]); L1_subordinates.push_back(sub); } feature_1.setSubordinates(L1_subordinates); feature_2.setMetaValue("PeptideRef", "fad"); for (uint16_t i = 0; i < fad_C27H32N9O15P2_EPI_measured_48.size(); ++i) { OpenMS::Feature sub; sub.setMetaValue("native_id", "Lactate2_"+std::to_string(117+i)); sub.setMetaValue("peak_apex_int", fad_C27H32N9O15P2_EPI_measured_48[i]); L2_subordinates.push_back(sub); } feature_2.setSubordinates(L2_subordinates); isotopelabelingmdvs.calculateMDVAccuracy(feature_1, "peak_apex_int", "C23H37N7O17P3S"); TEST_REAL_SIMILAR( feature_1.getMetaValue("average_accuracy"), Average_accuracy_groundtruth[0] ); for (size_t feature_subordinate = 0; feature_subordinate < feature_1.getSubordinates().size(); ++feature_subordinate) { TEST_REAL_SIMILAR( feature_1.getSubordinates().at(feature_subordinate).getMetaValue("absolute_difference"), accoa_C23H37N7O17P3S_abs_diff[feature_subordinate] ); } isotopelabelingmdvs.calculateMDVAccuracy(feature_2, "peak_apex_int", "C27H32N9O15P2"); TEST_REAL_SIMILAR( feature_2.getMetaValue("average_accuracy"), Average_accuracy_groundtruth[1] ); for (size_t feature_subordinate = 0; feature_subordinate < feature_2.getSubordinates().size(); ++feature_subordinate) { TEST_REAL_SIMILAR( feature_2.getSubordinates().at(feature_subordinate).getMetaValue("absolute_difference"), fad_C27H32N9O15P2_abs_diff[feature_subordinate] ); } END_SECTION START_SECTION(( IsotopeLabelingMDVs::calculateMDVAccuracies( FeatureMap& normalized_featureMap, const std::string& feature_name, const std::map<std::string, std::string>& fragment_isotopomer_theoretical_formulas) )) // case 1: calculating accuracy given theoretical and measured values IsotopeLabelingMDVs isotopelabelingmdvs; OpenMS::Feature feature_1, feature_2; OpenMS::FeatureMap featureMap_1, featureMap_2; // L1_norm_max From CHO_190316_Flux.xlsx provided by Douglas McCloskey // accoa_C23H37N7O17P3S_MRM_measured_13 & fad_C27H32N9O15P2_EPI_measured_48 are extracted from // "MID Max: LC–MS/MS Method for Measuring the Precursor and Product Mass Isotopomer Distributions // of Metabolic Intermediates and Cofactors for Metabolic Flux Analysis Applications, McCloskey et al", // DOI: 10.1021/acs.analchem.5b03887, Supporting Information: Table S-2 std::vector<double> L1_norm_max {1.00e+00, 3.324e-05, 2.825e-04, 7.174e-05}; std::vector<double> accoa_C23H37N7O17P3S_MRM_measured_13 {0.627, 0.253, 0.096, 0.02, 0.004, 0.001}; std::vector<double> accoa_C23H37N7O17P3S_abs_diff {0.0632108, 0.0505238, 0.0119821, 0.0014131, 0.0000315, 0.0003232}; std::vector<double> fad_C27H32N9O15P2_EPI_measured_48 {0.638, 0.355, 0.1, 0.0, 0.0, 0.0}; std::vector<double> fad_C27H32N9O15P2_abs_diff {0.0570446, 0.1223954, 0.0407946, 0.0111298, 0.0017729, 0.0002426}; std::vector<double> Average_accuracy_groundtruth {0.02374, 0.03451}; // [accoa_13, fad_48] std::map<std::string,std::string> theoretical_formulas {{"accoa","C23H37N7O17P3S"},{"fad","C27H32N9O15P2"}}; std::vector<OpenMS::Feature> L1_subordinates, L2_subordinates; feature_1.setMetaValue("PeptideRef", "accoa"); for (uint16_t i = 0; i < accoa_C23H37N7O17P3S_MRM_measured_13.size(); ++i) { OpenMS::Feature sub; sub.setMetaValue("native_id", "Lactate1_"+std::to_string(117+i)); sub.setMetaValue("peak_apex_int", accoa_C23H37N7O17P3S_MRM_measured_13[i]); L1_subordinates.push_back(sub); } feature_1.setSubordinates(L1_subordinates); for (uint8_t i = 0; i < 3; ++i) { featureMap_1.push_back(feature_1); } feature_2.setMetaValue("PeptideRef", "fad"); for (uint16_t i = 0; i < fad_C27H32N9O15P2_EPI_measured_48.size(); ++i) { OpenMS::Feature sub; sub.setMetaValue("native_id", "Lactate2_"+std::to_string(117+i)); sub.setMetaValue("peak_apex_int", fad_C27H32N9O15P2_EPI_measured_48[i]); // TODO:test for a missing val L2_subordinates.push_back(sub); } feature_2.setSubordinates(L2_subordinates); for (uint8_t i = 0; i < 3; ++i) { featureMap_2.push_back(feature_2); } isotopelabelingmdvs.calculateMDVAccuracies(featureMap_1, "peak_apex_int", theoretical_formulas); for (size_t i = 0; i < featureMap_1.size(); ++i) { TEST_REAL_SIMILAR(featureMap_1.at(i).getMetaValue("average_accuracy"), Average_accuracy_groundtruth[0]); for (size_t feature_subordinate = 0; feature_subordinate < featureMap_1.at(i).getSubordinates().size(); ++feature_subordinate) { TEST_REAL_SIMILAR(featureMap_1.at(i).getSubordinates().at(feature_subordinate).getMetaValue("absolute_difference"), accoa_C23H37N7O17P3S_abs_diff[feature_subordinate]); } } isotopelabelingmdvs.calculateMDVAccuracies(featureMap_2, "peak_apex_int", theoretical_formulas); for (size_t i = 0; i < featureMap_2.size(); ++i) { TEST_REAL_SIMILAR(featureMap_2.at(i).getMetaValue("average_accuracy"), Average_accuracy_groundtruth[1]); for (size_t feature_subordinate = 0; feature_subordinate < featureMap_2.at(i).getSubordinates().size(); ++feature_subordinate) { TEST_REAL_SIMILAR(featureMap_2.at(i).getSubordinates().at(feature_subordinate).getMetaValue("absolute_difference"), fad_C27H32N9O15P2_abs_diff[feature_subordinate]); } } END_SECTION END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/SignalToNoiseEstimatorMeanIterative_test.cpp
.cpp
3,084
107
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow $ // $Authors: $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> #include <OpenMS/FORMAT/DTAFile.h> /////////////////////////// #include <OpenMS/PROCESSING/NOISEESTIMATION/SignalToNoiseEstimatorMeanIterative.h> /////////////////////////// using namespace OpenMS; using namespace std; // #define DEBUG_TEST // #undef DEBUG_TEST START_TEST(SignalToNoiseEstimatorMeanIterative, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// SignalToNoiseEstimatorMeanIterative< >* ptr = nullptr; SignalToNoiseEstimatorMeanIterative< >* nullPointer = nullptr; START_SECTION((SignalToNoiseEstimatorMeanIterative())) ptr = new SignalToNoiseEstimatorMeanIterative<>; TEST_NOT_EQUAL(ptr, nullPointer) SignalToNoiseEstimatorMeanIterative<> sne; END_SECTION START_SECTION((SignalToNoiseEstimatorMeanIterative& operator=(const SignalToNoiseEstimatorMeanIterative &source))) MSSpectrum raw_data; SignalToNoiseEstimatorMeanIterative<> sne; sne.init(raw_data); SignalToNoiseEstimatorMeanIterative<> sne2 = sne; NOT_TESTABLE END_SECTION START_SECTION((SignalToNoiseEstimatorMeanIterative(const SignalToNoiseEstimatorMeanIterative &source))) MSSpectrum raw_data; SignalToNoiseEstimatorMeanIterative<> sne; sne.init(raw_data); SignalToNoiseEstimatorMeanIterative<> sne2(sne); NOT_TESTABLE END_SECTION START_SECTION((virtual ~SignalToNoiseEstimatorMeanIterative())) delete ptr; END_SECTION START_SECTION([EXTRA](virtual void init(const Container& c))) TOLERANCE_ABSOLUTE(0.5) MSSpectrum raw_data; MSSpectrum::const_iterator it; DTAFile dta_file; dta_file.load(OPENMS_GET_TEST_DATA_PATH("SignalToNoiseEstimator_test.dta"), raw_data); SignalToNoiseEstimatorMeanIterative<> sne; Param p; p.setValue("win_len", 40.1); p.setValue("noise_for_empty_window", 2.0); p.setValue("min_required_elements", 10); sne.setParameters(p); sne.init(raw_data); MSSpectrum stn_data; #ifdef DEBUG_TEST MSSpectrum stn_data__; #endif dta_file.load(OPENMS_GET_TEST_DATA_PATH("SignalToNoiseEstimatorMeanIterative_test.out"), stn_data); int i = 0; for (it=raw_data.begin();it!=raw_data.end(); ++it) { TEST_REAL_SIMILAR (stn_data[i].getIntensity(), sne.getSignalToNoise(i)); #ifdef DEBUG_TEST Peak1D peak = (*it); peak.setIntensity(stn_data[i].getIntensity() / sne.getSignalToNoise(it)); stn_data__.push_back(peak); #endif ++i; } #ifdef DEBUG_TEST dta_file.store(OPENMS_GET_TEST_DATA_PATH("SignalToNoiseEstimatorMeanIterative_test.debug"), stn_data__); #endif END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/CVTermListInterface_test.cpp
.cpp
12,958
333
// 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 $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> #include <map> /////////////////////////// #include <OpenMS/METADATA/CVTermListInterface.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(CVTermListInterface, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// CVTermListInterface* ptr = nullptr; CVTermListInterface* nullPointer = nullptr; START_SECTION(CVTermListInterface()) { ptr = new CVTermListInterface(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(virtual ~CVTermListInterface()) { delete ptr; } END_SECTION START_SECTION((bool operator==(const CVTermListInterface &cv_term_list) const )) { CVTermListInterface cv_term_list, cv_term_list2; TEST_TRUE(cv_term_list == cv_term_list2) cv_term_list.setMetaValue("blubb", "blubber"); TEST_EQUAL(cv_term_list == cv_term_list2, false) cv_term_list2.setMetaValue("blubb", "blubber"); TEST_TRUE(cv_term_list == cv_term_list2) CVTerm::Unit unit("my_unit_accession", "my_unit_name", "my_unit_ontology_name"); CVTerm cv_term("my_accession", "my_name", "my_cv_identifier_ref", "3.0", unit); cv_term_list.addCVTerm(cv_term); TEST_EQUAL(cv_term_list == cv_term_list2, false) cv_term_list2.addCVTerm(cv_term); TEST_TRUE(cv_term_list == cv_term_list2) } END_SECTION START_SECTION((bool operator!=(const CVTermListInterface &cv_term_list) const )) { CVTermListInterface cv_term_list, cv_term_list2; TEST_TRUE(cv_term_list == cv_term_list2) cv_term_list.setMetaValue("blubb", "blubber"); TEST_EQUAL(cv_term_list == cv_term_list2, false) cv_term_list2.setMetaValue("blubb", "blubber"); TEST_TRUE(cv_term_list == cv_term_list2) CVTerm::Unit unit("my_unit_accession", "my_unit_name", "my_unit_ontology_name"); CVTerm cv_term("my_accession", "my_name", "my_cv_identifier_ref", "3.0", unit); cv_term_list.addCVTerm(cv_term); TEST_EQUAL(cv_term_list == cv_term_list2, false) cv_term_list2.addCVTerm(cv_term); TEST_TRUE(cv_term_list == cv_term_list2) } END_SECTION START_SECTION((bool hasCVTerm(const String &accession) const )) { CVTerm::Unit unit("my_unit_accession", "my_unit_name", "my_unit_ontology_name"); CVTerm cv_term("my_accession", "my_name", "my_cv_identifier_ref", "3.0", unit); CVTermListInterface cv_term_list; TEST_EQUAL(cv_term_list.hasCVTerm("my_accession"), false) cv_term_list.addCVTerm(cv_term); TEST_EQUAL(cv_term_list.hasCVTerm("my_accession"), true) } END_SECTION /* START_SECTION((bool checkCVTerms(const CVMappingRule &rule, const ControlledVocabulary &cv) const )) { } END_SECTION */ START_SECTION((void setCVTerms(const std::vector< CVTerm > &terms))) { CVTerm::Unit unit("my_unit_accession", "my_unit_name", "my_unit_ontology_name"); CVTerm cv_term("my_accession", "my_name", "my_cv_identifier_ref", "3.0", unit); CVTerm cv_term2("my_accession2", "my_name2", "my_cv_identifier_ref2", "4.0", unit); CVTermListInterface cv_term_list; vector<CVTerm> cv_terms; cv_terms.push_back(cv_term); cv_terms.push_back(cv_term2); cv_term_list.setCVTerms(cv_terms); TEST_EQUAL(cv_term_list.hasCVTerm("my_accession"), true); TEST_EQUAL(cv_term_list.hasCVTerm("my_accession2"), true); } END_SECTION START_SECTION((const Map<String, std::vector<CVTerm> >& getCVTerms() const )) { CVTerm::Unit unit("my_unit_accession", "my_unit_name", "my_unit_ontology_name"); CVTerm cv_term("my_accession", "my_name", "my_cv_identifier_ref", "3.0", unit); CVTerm cv_term2("my_accession2", "my_name2", "my_cv_identifier_ref2", "4.0", unit); CVTermListInterface cv_term_list; TEST_EQUAL(cv_term_list.getCVTerms().size(), 0); // test empty one CVTermListInterface cv_term_list2; TEST_EQUAL(cv_term_list2.getCVTerms().size(), 0); // test empty one vector<CVTerm> cv_terms; cv_terms.push_back(cv_term); cv_terms.push_back(cv_term2); cv_term_list.setCVTerms(cv_terms); const auto& t = cv_term_list.getCVTerms(); TEST_EQUAL(t.size(), 2); TEST_EQUAL(t.find("my_accession") != t.end(), true); TEST_EQUAL(t.find("my_accession2") != t.end(), true); } END_SECTION START_SECTION((void addCVTerm(const CVTerm &term))) { CVTerm::Unit unit("my_unit_accession", "my_unit_name", "my_unit_ontology_name"); CVTerm cv_term("my_accession", "my_name", "my_cv_identifier_ref", "3.0", unit); CVTermListInterface cv_term_list; TEST_EQUAL(cv_term_list.hasCVTerm("my_accession"), false) cv_term_list.addCVTerm(cv_term); TEST_EQUAL(cv_term_list.hasCVTerm("my_accession"), true) } END_SECTION START_SECTION((void replaceCVTerm(const CVTerm &cv_term))) { CVTerm::Unit unit("my_unit_accession", "my_unit_name", "my_unit_ontology_name"); CVTerm cv_term("my_accession", "my_name", "my_cv_identifier_ref", "3.0", unit); CVTermListInterface cv_term_list; TEST_EQUAL(cv_term_list.hasCVTerm("my_accession"), false) cv_term_list.replaceCVTerm(cv_term); TEST_EQUAL(cv_term_list.hasCVTerm("my_accession"), true) TEST_EQUAL(cv_term_list.getCVTerms().at("my_accession").size(), 1) TEST_EQUAL(cv_term_list.getCVTerms().at("my_accession")[0].getValue(), "3.0") CVTerm cv_term2("my_accession", "my_name", "my_cv_identifier_ref", "2.0", unit); cv_term_list.replaceCVTerm(cv_term2); TEST_EQUAL(cv_term_list.hasCVTerm("my_accession"), true) TEST_EQUAL(cv_term_list.getCVTerms().at("my_accession").size(), 1) TEST_EQUAL(cv_term_list.getCVTerms().at("my_accession")[0].getValue(), "2.0") } END_SECTION START_SECTION((void replaceCVTerms(const std::vector<CVTerm> &cv_terms))) { CVTerm::Unit unit("my_unit_accession", "my_unit_name", "my_unit_ontology_name"); CVTerm cv_term("my_accession", "my_name", "my_cv_identifier_ref", "3.0", unit); CVTerm cv_term2("my_accession", "my_name", "my_cv_identifier_ref", "2.0", unit); std::vector<CVTerm> tmp; tmp.push_back(cv_term); tmp.push_back(cv_term2); CVTermListInterface cv_term_list; TEST_EQUAL(cv_term_list.hasCVTerm("my_accession"), false) cv_term_list.replaceCVTerms(tmp, "my_accession"); TEST_EQUAL(cv_term_list.hasCVTerm("my_accession"), true) TEST_EQUAL(cv_term_list.getCVTerms().at("my_accession").size(), 2) TEST_EQUAL(cv_term_list.getCVTerms().at("my_accession")[0].getValue(), "3.0") TEST_EQUAL(cv_term_list.getCVTerms().at("my_accession")[1].getValue(), "2.0") cv_term_list.replaceCVTerm(cv_term2); TEST_EQUAL(cv_term_list.hasCVTerm("my_accession"), true) TEST_EQUAL(cv_term_list.getCVTerms().at("my_accession").size(), 1) TEST_EQUAL(cv_term_list.getCVTerms().at("my_accession")[0].getValue(), "2.0") } END_SECTION START_SECTION((void replaceCVTerms(const Map<String, vector<CVTerm> >& cv_term_map))) { CVTerm::Unit unit("my_unit_accession", "my_unit_name", "my_unit_ontology_name"); CVTerm cv_term("my_accession", "my_name", "my_cv_identifier_ref", "3.0", unit); CVTerm cv_term2("my_accession2", "my_name", "my_cv_identifier_ref", "2.0", unit); std::vector<CVTerm> tmp; tmp.push_back(cv_term); std::vector<CVTerm> tmp2; tmp2.push_back(cv_term2); std::map<String, std::vector<CVTerm> >new_terms; new_terms["my_accession2"] = tmp2; TEST_EQUAL(new_terms.find("my_accession2") != new_terms.end(), true); // create CVTermListInterface with old "my_accession" CVTermListInterface cv_term_list; TEST_EQUAL(cv_term_list.hasCVTerm("my_accession"), false) cv_term_list.replaceCVTerms(tmp, "my_accession"); TEST_EQUAL(cv_term_list.hasCVTerm("my_accession"), true) TEST_EQUAL(cv_term_list.getCVTerms().at("my_accession").size(), 1) // replace the terms, delete "my_accession" and introduce "my_accession2" cv_term_list.replaceCVTerms(new_terms); TEST_EQUAL(cv_term_list.hasCVTerm("my_accession"), false) TEST_EQUAL(cv_term_list.hasCVTerm("my_accession2"), true) TEST_EQUAL(cv_term_list.getCVTerms().at("my_accession2").size(), 1) TEST_EQUAL(cv_term_list.getCVTerms().at("my_accession2")[0].getValue(), "2.0") } END_SECTION /* START_SECTION(([EXTRA] bool checkCVTerms(const ControlledVocabulary &cv) const )) { // [Term] // id: MS:1000132 // name: percent of base peak // def: "The magnitude of a peak or measurement element expressed in terms of the percentage of the magnitude of the base peak intensity." [PSI:MS] // xref: value-type:xsd\:float "The allowed value-type for this CV term." // is_a: MS:1000043 ! intensity unit CVTerm::Unit unit("MS:1000043", "intensity unit", "MS"); CVTerm cv_term("MS:1000132", "percent of base peak", "MS", "3.0", unit); CVTermListInterface cv_term_list; TEST_EQUAL(cv_term_list.hasCVTerm("my_accession"), false) cv_term_list.addCVTerm(cv_term); TEST_EQUAL(cv_term_list.hasCVTerm("my_accession"), true) ControlledVocabulary cv; cv.loadFromOBO("MS", "CV/psi-ms.obo"); TEST_EQUAL(cv_term_list.checkCVTerms(cv), true) CVTerm cv_term2("MS:1000132", "percent of base peaks wrong", "MS", "3.0", unit); cv_term_list.addCVTerm(cv_term2); TEST_EQUAL(cv_term_list.checkCVTerms(cv), false) } END_SECTION START_SECTION(([EXTRA] void correctCVTermNames())) { CVTerm::Unit unit("MS:1000043", "intensity unit", "MS"); CVTerm cv_term("MS:1000132", "percent of base peak", "MS", "3.0", unit); CVTermListInterface cv_term_list; TEST_EQUAL(cv_term_list.hasCVTerm("my_accession"), false) cv_term_list.addCVTerm(cv_term); TEST_EQUAL(cv_term_list.hasCVTerm("my_accession"), true) ControlledVocabulary cv; cv.loadFromOBO("MS", "CV/psi-ms.obo"); TEST_EQUAL(cv_term_list.checkCVTerms(cv), true) CVTerm cv_term2("MS:1000132", "percent of base peaks wrong", "MS", "3.0", unit); cv_term_list.addCVTerm(cv_term2); TEST_EQUAL(cv_term_list.checkCVTerms(cv), false) cv_term_list.correctCVTermNames(); TEST_EQUAL(cv_term_list.checkCVTerms(cv), true) } END_SECTION */ START_SECTION((CVTermListInterface(const CVTermListInterface &rhs))) { CVTermListInterface cv_term_list; cv_term_list.setMetaValue("blubb", "blubber"); CVTermListInterface cv_term_list2(cv_term_list); TEST_TRUE(cv_term_list == cv_term_list2) CVTerm::Unit unit("my_unit_accession", "my_unit_name", "my_unit_ontology_name"); CVTerm cv_term("my_accession", "my_name", "my_cv_identifier_ref", "3.0", unit); cv_term_list.addCVTerm(cv_term); CVTermListInterface cv_term_list3(cv_term_list); TEST_TRUE(cv_term_list == cv_term_list3) } END_SECTION ///////////////////////////////////////////////////////////// // Copy constructor, move constructor, assignment operator, move assignment operator, equality START_SECTION((CVTermListInterface& operator=(const CVTermListInterface &rhs))) { CVTermListInterface cv_term_list; cv_term_list.setMetaValue("blubb", "blubber"); CVTermListInterface cv_term_list2; cv_term_list2 = cv_term_list; TEST_TRUE(cv_term_list == cv_term_list2) CVTerm::Unit unit("my_unit_accession", "my_unit_name", "my_unit_ontology_name"); CVTerm cv_term("my_accession", "my_name", "my_cv_identifier_ref", "3.0", unit); cv_term_list.addCVTerm(cv_term); CVTermListInterface cv_term_list3; cv_term_list3 = cv_term_list; TEST_TRUE(cv_term_list == cv_term_list3) } END_SECTION START_SECTION((CVTermListInterface(CVTermListInterface &&rhs) noexcept)) { // Ensure that CVTermListInterface has a no-except move constructor (otherwise // std::vector is inefficient and will copy instead of move). TEST_EQUAL(noexcept(CVTermListInterface(std::declval<CVTermListInterface&&>())), true) CVTermListInterface cv_term_list; cv_term_list.setMetaValue("blubb2", "blubbe"); CVTermListInterface orig = cv_term_list; CVTermListInterface cv_term_list2(std::move(cv_term_list)); TEST_TRUE(orig == cv_term_list2) CVTerm::Unit unit("my_unit_accession", "my_unit_name", "my_unit_ontology_name"); CVTerm cv_term("my_accession", "my_name", "my_cv_identifier_ref", "3.0", unit); cv_term_list2.addCVTerm(cv_term); orig = cv_term_list2; CVTermListInterface cv_term_list3(std::move(cv_term_list2)); TEST_TRUE(orig == cv_term_list3) TEST_EQUAL(cv_term_list3.getCVTerms().size(), 1) } END_SECTION START_SECTION((bool empty() const)) { CVTerm::Unit unit("MS:1000043", "intensity unit", "MS"); CVTerm cv_term("MS:1000132", "percent of base peak", "MS", "3.0", unit); CVTermListInterface cv_term_list; TEST_EQUAL(cv_term_list.empty(), true) TEST_EQUAL(cv_term_list.hasCVTerm("my_accession"), false) cv_term_list.addCVTerm(cv_term); TEST_EQUAL(cv_term_list.hasCVTerm("MS:1000132"), true) TEST_EQUAL(cv_term_list.empty(), false) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/Product_test.cpp
.cpp
5,342
195
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Marc Sturm $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/METADATA/Product.h> /////////////////////////// #include <unordered_set> #include <unordered_map> using namespace OpenMS; using namespace std; START_TEST(Product, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// Product* ptr = nullptr; Product* nullPointer = nullptr; START_SECTION((Product())) ptr = new Product(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((~Product())) delete ptr; END_SECTION START_SECTION((double getMZ() const )) Product tmp; TEST_EQUAL(tmp.getMZ(),0); END_SECTION START_SECTION((void setMZ(double mz))) Product tmp; tmp.setMZ(47.11); TEST_REAL_SIMILAR(tmp.getMZ(),47.11); END_SECTION START_SECTION((double getIsolationWindowUpperOffset() const )) Product tmp; TEST_REAL_SIMILAR(tmp.getIsolationWindowUpperOffset(), 0); END_SECTION START_SECTION((void setIsolationWindowUpperOffset(double bound))) Product tmp; tmp.setIsolationWindowUpperOffset(22.7); TEST_REAL_SIMILAR(tmp.getIsolationWindowUpperOffset(), 22.7); END_SECTION START_SECTION((double getIsolationWindowLowerOffset() const )) Product tmp; TEST_REAL_SIMILAR(tmp.getIsolationWindowLowerOffset(), 0); END_SECTION START_SECTION((void setIsolationWindowLowerOffset(double bound))) Product tmp; tmp.setIsolationWindowLowerOffset(22.8); TEST_REAL_SIMILAR(tmp.getIsolationWindowLowerOffset(), 22.8); END_SECTION START_SECTION((Product(const Product& source))) Product tmp; tmp.setMZ(47.11); tmp.setIsolationWindowUpperOffset(22.7); tmp.setIsolationWindowLowerOffset(22.8); tmp.setMetaValue("label",String("label")); Product tmp2(tmp); TEST_EQUAL((String)(tmp2.getMetaValue("label")), "label"); TEST_REAL_SIMILAR(tmp2.getIsolationWindowUpperOffset(), 22.7); TEST_REAL_SIMILAR(tmp2.getIsolationWindowLowerOffset(), 22.8); TEST_REAL_SIMILAR(tmp2.getMZ(),47.11); END_SECTION START_SECTION((Product& operator= (const Product& source))) Product tmp; tmp.setMZ(47.11); tmp.setIsolationWindowUpperOffset(22.7); tmp.setIsolationWindowLowerOffset(22.8); tmp.setMetaValue("label",String("label")); //normal assignment Product tmp2; tmp2 = tmp; TEST_EQUAL((String)(tmp2.getMetaValue("label")), "label"); TEST_REAL_SIMILAR(tmp2.getIsolationWindowUpperOffset(), 22.7); TEST_REAL_SIMILAR(tmp2.getIsolationWindowLowerOffset(), 22.8); TEST_REAL_SIMILAR(tmp2.getMZ(),47.11); //assignment of empty object tmp2 = Product(); TEST_EQUAL(tmp2.getMetaValue("label").isEmpty(), true); TEST_REAL_SIMILAR(tmp2.getIsolationWindowUpperOffset(), 0.0); TEST_REAL_SIMILAR(tmp2.getIsolationWindowLowerOffset(), 0.0); TEST_REAL_SIMILAR(tmp2.getMZ(),0.0); END_SECTION START_SECTION((bool operator== (const Product& rhs) const)) Product tmp,tmp2; TEST_TRUE(tmp == tmp2); tmp2.setMZ(47.11); TEST_EQUAL(tmp==tmp2, false); tmp2 = tmp; tmp.setIsolationWindowUpperOffset(22.7); TEST_EQUAL(tmp==tmp2, false); tmp2 = tmp; tmp.setIsolationWindowLowerOffset(22.8); TEST_EQUAL(tmp==tmp2, false); tmp2 = tmp; tmp.setMetaValue("label",String("label")); TEST_EQUAL(tmp==tmp2, false); END_SECTION START_SECTION((bool operator!= (const Product& rhs) const)) Product tmp,tmp2; TEST_EQUAL(tmp!=tmp2, false); tmp2.setMZ(47.11); TEST_FALSE(tmp == tmp2); tmp2 = tmp; tmp2 = tmp; tmp.setIsolationWindowUpperOffset(22.7); TEST_FALSE(tmp == tmp2); tmp2 = tmp; tmp2 = tmp; tmp.setIsolationWindowLowerOffset(22.8); TEST_FALSE(tmp == tmp2); tmp2 = tmp; tmp.setMetaValue("label",String("label")); TEST_FALSE(tmp == tmp2); END_SECTION START_SECTION(([EXTRA] std::hash<Product>)) { // Test that equal products have equal hashes Product p1; p1.setMZ(100.5); p1.setIsolationWindowLowerOffset(10.0); p1.setIsolationWindowUpperOffset(20.0); Product p2; p2.setMZ(100.5); p2.setIsolationWindowLowerOffset(10.0); p2.setIsolationWindowUpperOffset(20.0); TEST_EQUAL(std::hash<Product>{}(p1), std::hash<Product>{}(p2)) // Test that different products have different hashes (not guaranteed, but highly likely) Product p3; p3.setMZ(200.5); p3.setIsolationWindowLowerOffset(10.0); p3.setIsolationWindowUpperOffset(20.0); TEST_NOT_EQUAL(std::hash<Product>{}(p1), std::hash<Product>{}(p3)) // Test use in unordered_set std::unordered_set<Product> product_set; product_set.insert(p1); product_set.insert(p2); // duplicate, should not increase size product_set.insert(p3); TEST_EQUAL(product_set.size(), 2) // Test use in unordered_map std::unordered_map<Product, std::string> product_map; product_map[p1] = "first"; product_map[p3] = "third"; TEST_EQUAL(product_map[p2], "first") // p2 equals p1 TEST_EQUAL(product_map.size(), 2) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/AccurateMassSearchEngine_test.cpp
.cpp
15,376
417
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg$ // $Authors: Erhan Kenar, Chris Bielow $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/ANALYSIS/ID/AccurateMassSearchEngine.h> #include <OpenMS/CONCEPT/FuzzyStringComparator.h> #include <OpenMS/CONCEPT/Constants.h> #include <OpenMS/FORMAT/ConsensusXMLFile.h> #include <OpenMS/FORMAT/FeatureXMLFile.h> #include <OpenMS/FORMAT/MzTab.h> #include <OpenMS/FORMAT/MzTabFile.h> #include <OpenMS/FORMAT/MzTabMFile.h> #include <OpenMS/KERNEL/Feature.h> #include <OpenMS/KERNEL/ConsensusFeature.h> #include <OpenMS/KERNEL/FeatureMap.h> #include <OpenMS/KERNEL/ConsensusMap.h> #include <OpenMS/KERNEL/MSSpectrum.h> #include <OpenMS/KERNEL/MSExperiment.h> #include <OpenMS/METADATA/ID/IdentificationDataConverter.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(AccurateMassSearchEngine, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// AccurateMassSearchEngine* ptr = nullptr; AccurateMassSearchEngine* null_ptr = nullptr; START_SECTION(AccurateMassSearchEngine()) { ptr = new AccurateMassSearchEngine(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(virtual ~AccurateMassSearchEngine()) { delete ptr; } END_SECTION START_SECTION([EXTRA]AdductInfo) { EmpiricalFormula ef_empty; // make sure an empty formula has no weight (we rely on that in AdductInfo's getMZ() and getNeutralMass() TEST_EQUAL(ef_empty.getMonoWeight(), 0) // now we test if converting from neutral mass to m/z and back recovers the input value using different adducts { // testing M;-2 // intrinsic doubly negative charge AdductInfo ai("TEST_INTRINSIC", ef_empty, -2, 1); double neutral_mass=1000; // some mass... double mz = ai.getMZ(neutral_mass); double neutral_mass_recon = ai.getNeutralMass(mz); TEST_REAL_SIMILAR(neutral_mass, neutral_mass_recon); } { // testing M+Na+H;+2 EmpiricalFormula simpleAdduct("HNa"); AdductInfo ai("TEST_WITHADDUCT", simpleAdduct, 2, 1); double neutral_mass=1000; // some mass... double mz = ai.getMZ(neutral_mass); double neutral_mass_recon = ai.getNeutralMass(mz); TEST_REAL_SIMILAR(neutral_mass, neutral_mass_recon); } } END_SECTION Param ams_param; ams_param.setValue("db:mapping", std::vector<std::string>{OPENMS_GET_TEST_DATA_PATH("reducedHMDBMapping.tsv")}); ams_param.setValue("db:struct", std::vector<std::string>{OPENMS_GET_TEST_DATA_PATH("reducedHMDB2StructMapping.tsv")}); ams_param.setValue("keep_unidentified_masses", "true"); ams_param.setValue("mzTab:exportIsotopeIntensities", "true"); AccurateMassSearchEngine ams; ams.setParameters(ams_param); START_SECTION(void init()) NOT_TESTABLE // tested below END_SECTION START_SECTION((void queryByMZ(const double& observed_mz, const Int& observed_charge, const String& ion_mode, std::vector<AccurateMassSearchResult>& results) const)) { std::vector<AccurateMassSearchResult> hmdb_results_pos; // test 'ams' not initialized TEST_EXCEPTION(Exception::IllegalArgument, ams.queryByMZ(1234, 1, "positive", hmdb_results_pos)); ams.init(); // test invalid scan polarity TEST_EXCEPTION(Exception::InvalidParameter, ams.queryByMZ(1234, 1, "this_is_an_invalid_ionmode", hmdb_results_pos)); // test the actual query { Param ams_param_tmp = ams_param; ams_param_tmp.setValue("mass_error_value", 17.0); ams.setParameters(ams_param_tmp); ams.init(); // -- positive mode // expected hit: C17H11N5 with neutral mass ~285.101445377 double m = EmpiricalFormula("C17H11N5").getMonoWeight(); double mz = m / 1 + EmpiricalFormula("Na").getMonoWeight() - Constants::ELECTRON_MASS_U; // assume M+Na;+1 as charge std::cout << "mz query mass:" << mz << "\n\n"; // we'll get some other hits as well... String id_list_pos[] = {"C10H17N3O6S", "C15H16O7", "C14H14N2OS2", "C16H15NO4", "C17H11N5" /* this one we want! */, "C10H14NO6P", "C14H12O4", "C7H6O2"}; //{"C10H17N3O6S", "C15H16O7", "C14H14N2OS2", "C16H15NO4", "C17H11N5", "C10H14NO6P", "C14H12O4", "C7H6O2"}; // 290.05475446 C14H14N2OS2 HMDB:HMDB38641 missing Size id_list_pos_length(sizeof(id_list_pos)/sizeof(id_list_pos[0])); ams.queryByMZ(mz, 1, "positive", hmdb_results_pos); ams.setParameters(ams_param); // reset to default 5ppm ams.init(); TEST_EQUAL(hmdb_results_pos.size(), id_list_pos_length) ABORT_IF(hmdb_results_pos.size() != id_list_pos_length) for (Size i = 0; i < id_list_pos_length; ++i) { TEST_STRING_EQUAL(hmdb_results_pos[i].getFormulaString(), id_list_pos[i]) std::cout << hmdb_results_pos[i] << std::endl; } TEST_EQUAL(hmdb_results_pos[4].getFormulaString(), "C17H11N5"); // correct hit? TEST_REAL_SIMILAR(hmdb_results_pos[4].getQueryMass(), m); // was the mass correctly reconstructed internally? TEST_REAL_SIMILAR(abs(hmdb_results_pos[4].getMZErrorPPM()), 0.0); // ppm error within float precision? } // -- negative mode // expected hit: C17H20N2S with neutral mass ~284.13472 { std::vector<AccurateMassSearchResult> hmdb_results_neg; double m = EmpiricalFormula("C17H20N2S").getMonoWeight(); double mz = m / 3 - Constants::PROTON_MASS_U; // assume M-3H;-3 as charge // manual check: // double mass_recovered = mz * 3 - EmpiricalFormula("H-3").getMonoWeight() - Constants::ELECTRON_MASS_U*3; ams.queryByMZ(mz, 3, "negative", hmdb_results_neg); ABORT_IF(hmdb_results_neg.size() != 1) std::cout << hmdb_results_neg[0] << std::endl; TEST_EQUAL(hmdb_results_neg[0].getFormulaString(), "C17H20N2S"); // correct hit? TEST_REAL_SIMILAR(hmdb_results_neg[0].getQueryMass(), m); // was the mass correctly reconstructed internally? TEST_EQUAL(abs(hmdb_results_neg[0].getMZErrorPPM()) < 0.0002, true); // ppm error within float precision? .. should be ~0.0001576.. } } END_SECTION AccurateMassSearchEngine ams_feat_test; ams_feat_test.setParameters(ams_param); ams_feat_test.init(); String feat_query_pos[] = {"C23H45NO4", "C20H37NO3", "C22H41NO"}; START_SECTION((void queryByFeature(const Feature& feature, const Size& feature_index, const String& ion_mode, std::vector<AccurateMassSearchResult>& results) const)) { Feature test_feat; test_feat.setRT(300.0); test_feat.setMZ(399.33486); test_feat.setIntensity(100.0); test_feat.setMetaValue(Constants::UserParam::NUM_OF_MASSTRACES, 3); test_feat.setCharge(1.0); vector<double> masstrace_intenstiy = {100.0, 26.1, 4.0}; test_feat.setMetaValue("masstrace_intensity", masstrace_intenstiy); //test_feat.setMetaValue("masstrace_intensity_0", 100.0); //test_feat.setMetaValue("masstrace_intensity_1", 26.1); //test_feat.setMetaValue("masstrace_intensity_2", 4.0); std::vector<AccurateMassSearchResult> results; // invalid scan_polarity TEST_EXCEPTION(Exception::InvalidParameter, ams_feat_test.queryByFeature(test_feat, 0, "invalid_scan_polatority", results)); // actual test ams_feat_test.queryByFeature(test_feat, 0, "positive", results); TEST_EQUAL(results.size(), 3) for (Size i = 0; i < results.size(); ++i) { TEST_REAL_SIMILAR(results[i].getObservedRT(), 300.0) TEST_REAL_SIMILAR(results[i].getObservedIntensity(), 100.0) } Size feat_query_size(sizeof(feat_query_pos)/sizeof(feat_query_pos[0])); ABORT_IF(results.size() != feat_query_size) for (Size i = 0; i < feat_query_size; ++i) { TEST_STRING_EQUAL(results[i].getFormulaString(), feat_query_pos[i]) } } END_SECTION START_SECTION((void queryByConsensusFeature(const ConsensusFeature& cfeat, const Size& cf_index, const Size& number_of_maps, const String& ion_mode, std::vector<AccurateMassSearchResult>& results) const)) { ConsensusFeature cons_feat; cons_feat.setRT(300.0); cons_feat.setMZ(399.33486); cons_feat.setIntensity(100.0); cons_feat.setCharge(1.0); FeatureHandle fh1, fh2, fh3; fh1.setRT(300.0); fh1.setMZ(399.33485); fh1.setIntensity(100.0); fh1.setCharge(1.0); fh1.setMapIndex(0); fh2.setRT(310.0); fh2.setMZ(399.33486); fh2.setIntensity(300.0); fh2.setCharge(1.0); fh2.setMapIndex(1); fh3.setRT(290.0); fh3.setMZ(399.33487); fh3.setIntensity(500.0); fh3.setCharge(1.0); fh3.setMapIndex(2); cons_feat.insert(fh1); cons_feat.insert(fh2); cons_feat.insert(fh3); cons_feat.computeConsensus(); std::vector<AccurateMassSearchResult> results; TEST_EXCEPTION(Exception::InvalidParameter, ams_feat_test.queryByConsensusFeature(cons_feat, 0, 3, "blabla", results)); // invalid scan_polarity ams_feat_test.queryByConsensusFeature(cons_feat, 0, 3, "positive", results); TEST_EQUAL(results.size(), 3) for (Size i = 0; i < results.size(); ++i) { TEST_REAL_SIMILAR(results[i].getObservedRT(), 300.0) TEST_REAL_SIMILAR(results[i].getObservedIntensity(), 0.0) } // std::cout << cons_feat.getMZ() << " " << results.size() << std::endl; for (Size i = 0; i < results.size(); ++i) { std::vector<double> indiv_ints = results[i].getIndividualIntensities(); TEST_EQUAL(indiv_ints.size(), 3) ABORT_IF(indiv_ints.size() != 3) TEST_REAL_SIMILAR(indiv_ints[0], fh1.getIntensity()); TEST_REAL_SIMILAR(indiv_ints[1], fh2.getIntensity()); TEST_REAL_SIMILAR(indiv_ints[2], fh3.getIntensity()); } Size feat_query_size(sizeof(feat_query_pos)/sizeof(feat_query_pos[0])); ABORT_IF(results.size() != feat_query_size) for (Size i = 0; i < feat_query_size; ++i) { TEST_STRING_EQUAL(results[i].getFormulaString(), feat_query_pos[i]) } } END_SECTION FuzzyStringComparator fsc; // fsc.setAcceptableAbsolute((3.04011223650013 - 3.04011223637974)*1.1); // 1.3242891228060217e-10 // also Linux may give slightly different results depending on optimization level (O0 vs O1) // note that the default value for TEST_REAL_SIMILAR is 1e-5, see ./source/CONCEPT/ClassTest.cpp fsc.setAcceptableAbsolute(1e-8); StringList sl; sl.push_back("xml-stylesheet"); sl.push_back("IdentificationRun id=\"PI_0\" date="); sl.push_back("software[1]"); sl.push_back("database[1]-uri"); fsc.setWhitelist(sl); START_SECTION((void run(FeatureMap&, MzTab&) const)) { FeatureMap exp_fm; FeatureXMLFile().load(OPENMS_GET_TEST_DATA_PATH("AccurateMassSearchEngine_input1.featureXML"), exp_fm); { MzTab test_mztab; ams_feat_test.run(exp_fm, test_mztab); // test annotation of input String tmp_file; NEW_TMP_FILE(tmp_file); FeatureXMLFile ff; ff.store(tmp_file, exp_fm); TEST_EQUAL(fsc.compareFiles(tmp_file, OPENMS_GET_TEST_DATA_PATH("AccurateMassSearchEngine_output1.featureXML")), true); String tmp_mztab_file; NEW_TMP_FILE(tmp_mztab_file); MzTabFile().store(tmp_mztab_file, test_mztab); TEST_EQUAL(fsc.compareFiles(tmp_mztab_file, OPENMS_GET_TEST_DATA_PATH("AccurateMassSearchEngine_output1_featureXML.mzTab")), true); // test use of adduct information Param ams_param_tmp = ams_param; ams_param_tmp.setValue("use_feature_adducts", "true"); AccurateMassSearchEngine ams_feat_test2; ams_feat_test2.setParameters(ams_param_tmp); ams_feat_test2.init(); FeatureMap exp_fm2; FeatureXMLFile().load(OPENMS_GET_TEST_DATA_PATH("AccurateMassSearchEngine_input1.featureXML"), exp_fm2); MzTab test_mztab2; ams_feat_test2.run(exp_fm2, test_mztab2); String tmp_mztab_file2; NEW_TMP_FILE(tmp_mztab_file2); MzTabFile().store(tmp_mztab_file2, test_mztab2); TEST_EQUAL(fsc.compareFiles(tmp_mztab_file2, OPENMS_GET_TEST_DATA_PATH("AccurateMassSearchEngine_output2_featureXML.mzTab")), true); } } END_SECTION START_SECTION((void run(FeatureMap&, MzTabM&) const)) { FeatureMap exp_fm; FeatureXMLFile().load(OPENMS_GET_TEST_DATA_PATH("AccurateMassSearchEngine_input1.featureXML"), exp_fm); { MzTabM test_mztabm; ams_feat_test.run(exp_fm, test_mztabm); String tmp_mztabm_file; NEW_TMP_FILE(tmp_mztabm_file); MzTabMFile().store(tmp_mztabm_file, test_mztabm); TEST_EQUAL(fsc.compareFiles(tmp_mztabm_file, OPENMS_GET_TEST_DATA_PATH("AccurateMassSearchEngine_output1_mztabm_featureXML.mzTab")), true); // test use of adduct information Param ams_param_tmp = ams_param; ams_param_tmp.setValue("use_feature_adducts", "true"); AccurateMassSearchEngine ams_feat_test2; ams_feat_test2.setParameters(ams_param_tmp); ams_feat_test2.init(); FeatureMap exp_fm2; FeatureXMLFile().load(OPENMS_GET_TEST_DATA_PATH("AccurateMassSearchEngine_input1.featureXML"), exp_fm2); MzTabM test_mztabm2; ams_feat_test2.run(exp_fm2, test_mztabm2); String tmp_mztabm_file2; NEW_TMP_FILE(tmp_mztabm_file2); MzTabMFile().store(tmp_mztabm_file2, test_mztabm2); TEST_EQUAL(fsc.compareFiles(tmp_mztabm_file2, OPENMS_GET_TEST_DATA_PATH("AccurateMassSearchEngine_output2_mztabm_featureXML.mzTab")), true); } } END_SECTION START_SECTION((void run(ConsensusMap&, MzTab&) const)) ConsensusMap exp_cm; ConsensusXMLFile().load(OPENMS_GET_TEST_DATA_PATH("AccurateMassSearchEngine_input1.consensusXML"), exp_cm); MzTab test_mztab2; ams_feat_test.run(exp_cm, test_mztab2); // test annotation of input String tmp_file; NEW_TMP_FILE(tmp_file); ConsensusXMLFile ff; ff.store(tmp_file, exp_cm); TEST_EQUAL(fsc.compareFiles(tmp_file, OPENMS_GET_TEST_DATA_PATH("AccurateMassSearchEngine_output1.consensusXML")), true); String tmp_mztab_file; NEW_TMP_FILE(tmp_mztab_file); MzTabFile().store(tmp_mztab_file, test_mztab2); TEST_EQUAL(fsc.compareFiles(tmp_mztab_file, OPENMS_GET_TEST_DATA_PATH("AccurateMassSearchEngine_output1_consensusXML.mzTab")), true); END_SECTION START_SECTION([EXTRA] template <typename MAPTYPE> void resolveAutoMode_(const MAPTYPE& map)) FeatureMap exp_fm; FeatureXMLFile().load(OPENMS_GET_TEST_DATA_PATH("AccurateMassSearchEngine_input1.featureXML"), exp_fm); FeatureMap fm_p = exp_fm; AccurateMassSearchEngine ams; MzTab mzt; Param p; p.setValue("ionization_mode","auto"); p.setValue("db:mapping", std::vector<std::string>{OPENMS_GET_TEST_DATA_PATH("reducedHMDBMapping.tsv")}); p.setValue("db:struct", std::vector<std::string>{OPENMS_GET_TEST_DATA_PATH("reducedHMDB2StructMapping.tsv")}); ams.setParameters(p); ams.init(); TEST_EXCEPTION(Exception::InvalidParameter, ams.run(fm_p, mzt)); // 'fm_p' has no scan_polarity meta value for (auto& f : fm_p) { f.setMetaValue("scan_polarity", "something;somethingelse"); } TEST_EXCEPTION(Exception::InvalidParameter, ams.run(fm_p, mzt)); // 'fm_p' scan_polarity meta value wrong for (auto& f : fm_p) { f.setMetaValue("scan_polarity", "positive"); } ams.run(fm_p, mzt); for (auto& f : fm_p) { f.setMetaValue("scan_polarity", "negative"); } ams.run(fm_p, mzt); END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/CompleteLinkage_test.cpp
.cpp
3,560
130
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Mathias Walzer$ // $Authors: $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/ML/CLUSTERING/CompleteLinkage.h> #include <OpenMS/ML/CLUSTERING/ClusterAnalyzer.h> #include <OpenMS/DATASTRUCTURES/DistanceMatrix.h> #include <vector> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(CompleteLinkage, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// CompleteLinkage* ptr = nullptr; CompleteLinkage* nullPointer = nullptr; START_SECTION(CompleteLinkage()) { ptr = new CompleteLinkage(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(~CompleteLinkage()) { delete ptr; } END_SECTION ptr = new CompleteLinkage(); START_SECTION((CompleteLinkage(const CompleteLinkage &source))) { CompleteLinkage copy(*ptr); } END_SECTION START_SECTION((CompleteLinkage& operator=(const CompleteLinkage &source))) { CompleteLinkage copy; copy = *ptr; } END_SECTION START_SECTION((void operator()(DistanceMatrix< float > &original_distance, std::vector<BinaryTreeNode>& cluster_tree, const float threshold=1) const)) { DistanceMatrix<float> matrix(6,666); matrix.setValue(1,0,0.5f); matrix.setValue(2,0,0.8f); matrix.setValue(2,1,0.3f); matrix.setValue(3,0,0.6f); matrix.setValue(3,1,0.8f); matrix.setValue(3,2,0.8f); matrix.setValue(4,0,0.8f); matrix.setValue(4,1,0.8f); matrix.setValue(4,2,0.8f); matrix.setValue(4,3,0.4f); matrix.setValue(5,0,0.7f); matrix.setValue(5,1,0.8f); matrix.setValue(5,2,0.8f); matrix.setValue(5,3,0.8f); matrix.setValue(5,4,0.8f); DistanceMatrix<float> matrix2(matrix); vector< BinaryTreeNode > result; vector< BinaryTreeNode > tree; //~ tree.push_back(BinaryTreeNode(1,2,0.3f)); //~ tree.push_back(BinaryTreeNode(2,3,0.4f)); //~ tree.push_back(BinaryTreeNode(0,3,0.7f)); //~ tree.push_back(BinaryTreeNode(0,1,0.8f)); //~ tree.push_back(BinaryTreeNode(0,1,0.8f)); tree.push_back(BinaryTreeNode(1,2,0.3f)); tree.push_back(BinaryTreeNode(3,4,0.4f)); tree.push_back(BinaryTreeNode(0,5,0.7f)); tree.push_back(BinaryTreeNode(0,1,0.8f)); tree.push_back(BinaryTreeNode(0,3,0.8f)); (*ptr)(matrix,result); TEST_EQUAL(tree.size(), result.size()); for (Size i = 0; i < result.size(); ++i) { TEST_EQUAL(tree[i].left_child, result[i].left_child); TEST_EQUAL(tree[i].right_child, result[i].right_child); TOLERANCE_ABSOLUTE(0.0001); TEST_REAL_SIMILAR(tree[i].distance, result[i].distance); } float th(0.7f); tree.pop_back(); tree.pop_back(); tree.pop_back(); tree.push_back(BinaryTreeNode(0,1,-1.0f)); tree.push_back(BinaryTreeNode(0,3,-1.0f)); tree.push_back(BinaryTreeNode(0,5,-1.0f)); result.clear(); (*ptr)(matrix2,result,th); TEST_EQUAL(tree.size(), result.size()); for (Size i = 0; i < result.size(); ++i) { TOLERANCE_ABSOLUTE(0.0001); TEST_EQUAL(tree[i].left_child, result[i].left_child); TEST_EQUAL(tree[i].right_child, result[i].right_child); TEST_REAL_SIMILAR(tree[i].distance, result[i].distance); } } END_SECTION delete ptr; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/SVOutStream_test.cpp
.cpp
5,125
179
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hendrik Weisser $ // $Authors: Hendrik Weisser $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/FORMAT/SVOutStream.h> #include <sstream> using namespace OpenMS; using namespace std; /////////////////////////// START_TEST(SVOutStream, "$Id$") ///////////////////////////////////////////////////////////// SVOutStream* sv_ptr = nullptr; SVOutStream* sv_nullPointer = nullptr; START_SECTION((SVOutStream(std::ostream& out, const String& sep="\t", const String& replacement="_", String::QuotingMethod quoting=String::DOUBLE))) { stringstream strstr; sv_ptr = new SVOutStream(strstr); TEST_NOT_EQUAL(sv_ptr, sv_nullPointer); } END_SECTION START_SECTION(([EXTRA] ~SVOutStream())) { delete sv_ptr; } END_SECTION START_SECTION((template <typename T> SVOutStream& operator<<(const T& value))) { stringstream strstr; SVOutStream out(strstr, ","); out << 123 << 3.14 << -1.23e45 << nl; out << 456 << endl; // different cases for Unix/Windows: TEST_EQUAL((strstr.str() == "123,3.14,-1.23e+45\n456\n") || (strstr.str() == "123,3.14,-1.23e+045\n456\n") || (strstr.str() == "123,3.14,-1.23e45\n456\n"), true) std::cout << strstr.str() << std::endl; } { stringstream strstr; SVOutStream out(strstr, "_/_"); out << 123 << 3.14 << -1.23e45 << endl; out << 456 << nl; // different cases for Unix/Windows: TEST_EQUAL((strstr.str() == "123_/_3.14_/_-1.23e+45\n456\n") || (strstr.str() == "123_/_3.14_/_-1.23e45\n456\n") || (strstr.str() == "123_/_3.14_/_-1.23e+045\n456\n"), true); } END_SECTION START_SECTION((SVOutStream& operator<<(String str))) { stringstream strstr; SVOutStream out(strstr, ",", "_", String::NONE); out << String("a") << string("bc") << "d,f" << nl; out << String("g\"i\"k") << 'l' << endl; TEST_EQUAL(strstr.str(), "a,bc,d_f\ng\"i\"k,l\n"); } { stringstream strstr; SVOutStream out(strstr, ",", "_", String::ESCAPE); out << string("a") << "bc" << String("d,f") << nl; out << "g\"i\"k" << 'l' << endl; TEST_EQUAL(strstr.str(), "\"a\",\"bc\",\"d,f\"\n\"g\\\"i\\\"k\",\"l\"\n"); } { stringstream strstr; SVOutStream out(strstr, ",", "_", String::DOUBLE); out << "a" << String("bc") << string("d,f") << nl; out << string("g\"i\"k") << 'l' << endl; TEST_EQUAL(strstr.str(), "\"a\",\"bc\",\"d,f\"\n\"g\"\"i\"\"k\",\"l\"\n"); } { stringstream strstr; SVOutStream out(strstr, "; ", ",_", String::NONE); out << String("a") << "bc" << string("d; f") << nl; out << "g\"i\"k" << 'l' << endl; TEST_EQUAL(strstr.str(), "a; bc; d,_f\ng\"i\"k; l\n"); } END_SECTION START_SECTION((SVOutStream& operator<<(const std::string& str))) { NOT_TESTABLE // tested with "operator<<(String)" } END_SECTION START_SECTION((SVOutStream& operator<<(const char* c_str))) { NOT_TESTABLE // tested with "operator<<(String)" } END_SECTION START_SECTION((SVOutStream& operator<<(const char c))) { NOT_TESTABLE // tested with "operator<<(String)" } END_SECTION START_SECTION((SVOutStream& operator<<(std::ostream& (*fp)(std::ostream&)))) { stringstream strstr; SVOutStream out(strstr, ",", "_", String::ESCAPE); out << endl << 123 << endl << "bla"; TEST_EQUAL(strstr.str(), "\n123\n\"bla\""); } END_SECTION START_SECTION((SVOutStream& operator<<(enum Newline))) { stringstream strstr; SVOutStream out(strstr, ",", "_", String::ESCAPE); out << nl << 123 << nl << "bla"; TEST_EQUAL(strstr.str(), "\n123\n\"bla\""); } END_SECTION START_SECTION((SVOutStream& write(const String& str))) { stringstream strstr; SVOutStream out(strstr, ",", "_", String::ESCAPE); out << "bla" << 123 << nl; out.write("#This, is, a, comment\n"); out << 4.56 << "test" << endl; TEST_EQUAL(strstr.str(), "\"bla\",123\n#This, is, a, comment\n4.56,\"test\"\n"); } END_SECTION START_SECTION((bool modifyStrings(bool modify))) { stringstream strstr; SVOutStream out(strstr, ","); out << "test"; bool result = out.modifyStrings(false); // "true" by default TEST_EQUAL(result, true); out << "bla"; result = out.modifyStrings(true); TEST_EQUAL(result, false); out << "laber" << endl; TEST_EQUAL(strstr.str(), "\"test\",bla,\"laber\"\n"); } END_SECTION START_SECTION((template <typename NumericT> SVOutStream& writeValueOrNan(NumericT thing))) { stringstream strstr; SVOutStream out(strstr, ","); out.writeValueOrNan(123); out.writeValueOrNan(3.14); out << nl; out.writeValueOrNan(456); out.writeValueOrNan(std::numeric_limits<double>::quiet_NaN()); out << nl; out.writeValueOrNan(std::numeric_limits<double>::infinity()); out.writeValueOrNan(-std::numeric_limits<double>::infinity()); out << endl; TEST_EQUAL(strstr.str(), "123,3.14\n456,nan\ninf,-inf\n"); } END_SECTION END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/FeatureFinderAlgorithmPicked_test.cpp
.cpp
3,234
95
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Marc Sturm $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> #include <OpenMS/CONCEPT/Constants.h> /////////////////////////// #include <OpenMS/FEATUREFINDER/FeatureFinderAlgorithmPicked.h> /////////////////////////// #include <OpenMS/MATH/MathFunctions.h> #include <OpenMS/FORMAT/MzMLFile.h> #include <OpenMS/FORMAT/ParamXMLFile.h> START_TEST(FeatureFinderAlgorithmPicked, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace OpenMS::Math; using namespace std; typedef FeatureFinderAlgorithmPicked FFPP; FFPP* ptr = nullptr; FFPP* nullPointer = nullptr; START_SECTION((FeatureFinderAlgorithmPicked())) ptr = new FFPP; TEST_NOT_EQUAL(ptr,nullPointer) END_SECTION START_SECTION((~FeatureFinderAlgorithmPicked())) delete ptr; END_SECTION START_SECTION((virtual void run())) //input and output PeakMap input; MzMLFile mzml_file; mzml_file.getOptions().addMSLevel(1); mzml_file.load(OPENMS_GET_TEST_DATA_PATH("FeatureFinderAlgorithmPicked.mzML"),input); input.updateRanges(); FeatureMap output; //parameters Param param; ParamXMLFile paramFile; paramFile.load(OPENMS_GET_TEST_DATA_PATH("FeatureFinderAlgorithmPicked.ini"), param); param = param.copy("FeatureFinder:1:algorithm:", true); FFPP ffpp; ffpp.run(input, output, param, FeatureMap()); TEST_EQUAL(output.size(), 8); // test some of the metavalue number_of_datapoints TEST_EQUAL(output[0].getMetaValue(Constants::UserParam::NUM_OF_DATAPOINTS), 88); TEST_EQUAL(output[3].getMetaValue(Constants::UserParam::NUM_OF_DATAPOINTS), 71); TEST_EQUAL(output[7].getMetaValue(Constants::UserParam::NUM_OF_DATAPOINTS), 47); TOLERANCE_ABSOLUTE(0.001); TEST_REAL_SIMILAR(output[0].getOverallQuality(), 0.8826); TEST_REAL_SIMILAR(output[1].getOverallQuality(), 0.8680); TEST_REAL_SIMILAR(output[2].getOverallQuality(), 0.9077); TEST_REAL_SIMILAR(output[3].getOverallQuality(), 0.9270); TEST_REAL_SIMILAR(output[4].getOverallQuality(), 0.9398); TEST_REAL_SIMILAR(output[5].getOverallQuality(), 0.9098); TEST_REAL_SIMILAR(output[6].getOverallQuality(), 0.9403); TEST_REAL_SIMILAR(output[7].getOverallQuality(), 0.9245); TOLERANCE_ABSOLUTE(20.0); TEST_REAL_SIMILAR(output[0].getIntensity(), 51366.2); TEST_REAL_SIMILAR(output[1].getIntensity(), 44767.6); TEST_REAL_SIMILAR(output[2].getIntensity(), 34731.1); TEST_REAL_SIMILAR(output[3].getIntensity(), 19494.2); TEST_REAL_SIMILAR(output[4].getIntensity(), 12570.2); TEST_REAL_SIMILAR(output[5].getIntensity(), 8532.26); TEST_REAL_SIMILAR(output[6].getIntensity(), 7318.62); TEST_REAL_SIMILAR(output[7].getIntensity(), 5038.81); END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MQEvidenceExporter_test.cpp
.cpp
3,643
94
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow$ // $Authors: Valentin Noske, Vincent Musch$ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/FORMAT/ConsensusXMLFile.h> #include <OpenMS/FORMAT/FeatureXMLFile.h> #include <OpenMS/QC/MQEvidenceExporter.h> #include <OpenMS/SYSTEM/File.h> #include <OpenMS/KERNEL/MSExperiment.h> #include <OpenMS/FORMAT/FASTAFile.h> #include <map> #include <OpenMS/test_config.h> /////////////////////////// /////////////////////////// START_TEST(MQEvidence, "$ID$") using namespace OpenMS; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// File::TempDir dir; const String path = dir.getPath(); START_SECTION(MQEvidence()) { MQEvidence *ptr = nullptr; MQEvidence *null_ptr = nullptr; ptr = new MQEvidence(path); TEST_NOT_EQUAL(ptr, null_ptr); delete ptr; } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// START_SECTION((void exportFeatureMap( const OpenMS::FeatureMap& feature_map, const OpenMS::ConsensusMap& cmap, const OpenMS::MSExperiment& exp, const std::map<String, String>& fasta_map))) { { //FASTA-HANDELING std::vector<FASTAFile::FASTAEntry> fasta_info; std::map<String, String> fasta_map; FASTAFile().load(OPENMS_GET_TEST_DATA_PATH("FASTAContainer_test.fasta"), fasta_info); //map the identifier to the description so that we can access the description via the cmap-identifier for(const auto& entry : fasta_info) { fasta_map.emplace(entry.identifier, entry.description); } MQEvidence evd(path); PeakMap exp; ConsensusMap cmap_one; ConsensusXMLFile().load(OPENMS_GET_TEST_DATA_PATH("MQEvidence_1.consensusXML"), cmap_one); ConsensusMap cmap_two; ConsensusXMLFile().load(OPENMS_GET_TEST_DATA_PATH("MQEvidence_2.consensusXML"), cmap_two); FeatureMap fmap_one; FeatureXMLFile().load(OPENMS_GET_TEST_DATA_PATH("MQEvidence_1.featureXML"), fmap_one); evd.exportFeatureMap(fmap_one, cmap_two, exp, fasta_map); FeatureMap fmap_two; FeatureXMLFile().load(OPENMS_GET_TEST_DATA_PATH("MQEvidence_2.featureXML"), fmap_two); evd.exportFeatureMap(fmap_two, cmap_two, exp, fasta_map); FeatureMap fmap_three; FeatureXMLFile().load(OPENMS_GET_TEST_DATA_PATH("MQEvidence_3.featureXML"), fmap_three); evd.exportFeatureMap(fmap_three, cmap_two, exp, fasta_map); FeatureMap fmap_four; FeatureXMLFile().load(OPENMS_GET_TEST_DATA_PATH("MQEvidence_4.featureXML"), fmap_four); evd.exportFeatureMap(fmap_four, cmap_one, exp, fasta_map); FeatureMap fmap_five; FeatureXMLFile().load(OPENMS_GET_TEST_DATA_PATH("MQEvidence_5.featureXML"), fmap_five); evd.exportFeatureMap(fmap_five, cmap_one, exp, fasta_map); FeatureMap fmap_six; FeatureXMLFile().load(OPENMS_GET_TEST_DATA_PATH("MQEvidence_6.featureXML"), fmap_six); evd.exportFeatureMap(fmap_six, cmap_one, exp, fasta_map); } String filename = path + "/evidence.txt"; TEST_FILE_SIMILAR(filename.c_str(), OPENMS_GET_TEST_DATA_PATH("MQEvidence_result.txt")); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/Instrument_test.cpp
.cpp
9,724
336
// 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 $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/METADATA/Instrument.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(Instrument, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// Instrument* ptr = nullptr; Instrument* nullPointer = nullptr; START_SECTION(Instrument()) ptr = new Instrument(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION(~Instrument()) delete ptr; END_SECTION START_SECTION(const std::vector<IonDetector>& getIonDetectors() const) Instrument tmp; TEST_EQUAL(tmp.getIonDetectors().size(),0) END_SECTION START_SECTION(const std::vector<IonSource>& getIonSources() const) Instrument tmp; TEST_EQUAL(tmp.getIonSources().size(),0) END_SECTION START_SECTION(const String& getCustomizations() const) Instrument tmp; TEST_EQUAL(tmp.getCustomizations(),""); END_SECTION START_SECTION(const String& getModel() const) Instrument tmp; TEST_EQUAL(tmp.getModel(),""); END_SECTION START_SECTION(const String& getName() const) Instrument tmp; TEST_EQUAL(tmp.getName(),""); END_SECTION START_SECTION(const String& getVendor() const) Instrument tmp; TEST_EQUAL(tmp.getVendor(),""); END_SECTION START_SECTION(const std::vector<MassAnalyzer>& getMassAnalyzers() const) Instrument tmp; TEST_EQUAL(tmp.getMassAnalyzers().size(),0); END_SECTION START_SECTION(const Software& getSoftware() const) Instrument tmp; TEST_STRING_EQUAL(tmp.getSoftware().getName(),""); END_SECTION START_SECTION(IonOpticsType getIonOptics() const) Instrument tmp; TEST_EQUAL(tmp.getIonOptics(),Instrument::IonOpticsType::UNKNOWN); END_SECTION START_SECTION(void setIonOptics(IonOpticsType ion_optics)) Instrument tmp; tmp.setIonOptics(Instrument::IonOpticsType::REFLECTRON); TEST_EQUAL(tmp.getIonOptics(),Instrument::IonOpticsType::REFLECTRON); END_SECTION START_SECTION(void setCustomizations(const String& customizations)) Instrument tmp; tmp.setCustomizations("Customizations"); TEST_EQUAL(tmp.getCustomizations(),"Customizations"); END_SECTION START_SECTION(void setIonDetectors(const std::vector<IonDetector>& ion_detectors)) Instrument tmp; std::vector<IonDetector> dummy; dummy.resize(1); tmp.setIonDetectors(dummy); TEST_EQUAL(tmp.getIonDetectors().size(),1); END_SECTION START_SECTION(void setIonSources(const std::vector<IonSource>& ion_sources)) Instrument tmp; std::vector<IonSource> dummy; dummy.resize(1); tmp.setIonSources(dummy); TEST_EQUAL(tmp.getIonSources().size(),1); END_SECTION START_SECTION(void setMassAnalyzers(const std::vector<MassAnalyzer>& mass_analyzers)) Instrument tmp; MassAnalyzer dummy; dummy.setScanTime(47.11); vector<MassAnalyzer> dummy2; dummy2.push_back(dummy); dummy.setScanTime(47.12); dummy2.push_back(dummy); tmp.setMassAnalyzers(dummy2); TEST_EQUAL(tmp.getMassAnalyzers().size(),2); TEST_REAL_SIMILAR(tmp.getMassAnalyzers()[0].getScanTime(),47.11); TEST_REAL_SIMILAR(tmp.getMassAnalyzers()[1].getScanTime(),47.12); END_SECTION START_SECTION(void setModel(const String& model)) Instrument tmp; tmp.setModel("Model"); TEST_EQUAL(tmp.getModel(),"Model"); END_SECTION START_SECTION(void setName(const String& name)) Instrument tmp; tmp.setName("Name"); TEST_EQUAL(tmp.getName(),"Name"); END_SECTION START_SECTION(void setVendor(const String& vendor)) Instrument tmp; tmp.setVendor("Vendor"); TEST_EQUAL(tmp.getVendor(),"Vendor"); END_SECTION START_SECTION(void setSoftware(const Software& software)) Instrument tmp; Software s; s.setName("sn"); tmp.setSoftware(s); TEST_STRING_EQUAL(tmp.getSoftware().getName(),"sn"); END_SECTION START_SECTION(std::vector<IonDetector>& getIonDetectors()) Instrument tmp; tmp.getIonDetectors().resize(1); TEST_EQUAL(tmp.getIonDetectors().size(),1); END_SECTION START_SECTION(std::vector<IonSource>& getIonSources()) Instrument tmp; tmp.getIonSources().resize(1); TEST_EQUAL(tmp.getIonSources().size(),1); END_SECTION START_SECTION(std::vector<MassAnalyzer>& getMassAnalyzers()) Instrument tmp; tmp.getMassAnalyzers().resize(2); tmp.getMassAnalyzers()[0].setScanTime(47.11); tmp.getMassAnalyzers()[1].setScanTime(47.12); TEST_EQUAL(tmp.getMassAnalyzers().size(),2); TEST_REAL_SIMILAR(tmp.getMassAnalyzers()[0].getScanTime(),47.11); TEST_REAL_SIMILAR(tmp.getMassAnalyzers()[1].getScanTime(),47.12); END_SECTION START_SECTION(Software& getSoftware()) Instrument tmp; tmp.getSoftware().setName("sn"); TEST_STRING_EQUAL(tmp.getSoftware().getName(),"sn"); END_SECTION START_SECTION(Instrument(const Instrument& source)) Instrument tmp; tmp.getMassAnalyzers().resize(1); tmp.getMassAnalyzers()[0].setScanTime(47.11); tmp.getIonSources().resize(1); tmp.getIonDetectors().resize(1); tmp.setModel("Model"); tmp.setName("Name"); tmp.setVendor("Vendor"); tmp.setMetaValue("label",String("label")); tmp.getSoftware().setName("sn"); tmp.setIonOptics(Instrument::IonOpticsType::REFLECTRON); Instrument tmp2(tmp); TEST_EQUAL((String)(tmp2.getMetaValue("label")), "label"); TEST_EQUAL(tmp2.getName(),"Name"); TEST_EQUAL(tmp2.getModel(),"Model"); TEST_EQUAL(tmp2.getVendor(),"Vendor"); TEST_EQUAL(tmp2.getIonDetectors().size(),1); TEST_EQUAL(tmp2.getIonSources().size(),1); TEST_EQUAL(tmp2.getMassAnalyzers().size(),1); TEST_REAL_SIMILAR(tmp2.getMassAnalyzers()[0].getScanTime(),47.11); TEST_EQUAL(tmp2.getSoftware().getName(),"sn"); TEST_EQUAL(tmp2.getIonOptics(),Instrument::IonOpticsType::REFLECTRON); END_SECTION START_SECTION(Instrument& operator= (const Instrument& source)) Instrument tmp; tmp.getMassAnalyzers().resize(1); tmp.getMassAnalyzers()[0].setScanTime(47.11); tmp.getIonSources().resize(1); tmp.getIonDetectors().resize(1); tmp.setModel("Model"); tmp.setName("Name"); tmp.setVendor("Vendor"); tmp.setMetaValue("label",String("label")); tmp.getSoftware().setName("sn"); tmp.setIonOptics(Instrument::IonOpticsType::REFLECTRON); Instrument tmp2; tmp2 = tmp; TEST_EQUAL((String)(tmp2.getMetaValue("label")), "label"); TEST_EQUAL(tmp2.getName(),"Name"); TEST_EQUAL(tmp2.getModel(),"Model"); TEST_EQUAL(tmp2.getVendor(),"Vendor"); TEST_EQUAL(tmp2.getIonDetectors().size(),1); TEST_EQUAL(tmp2.getIonSources().size(),1); TEST_EQUAL(tmp2.getMassAnalyzers().size(),1); TEST_REAL_SIMILAR(tmp2.getMassAnalyzers()[0].getScanTime(),47.11); TEST_EQUAL(tmp2.getSoftware().getName(),"sn"); TEST_EQUAL(tmp2.getIonOptics(),Instrument::IonOpticsType::REFLECTRON); tmp2 = Instrument(); TEST_EQUAL(tmp2.getMetaValue("label").isEmpty(), true); TEST_EQUAL(tmp2.getName(),""); TEST_EQUAL(tmp2.getModel(),""); TEST_EQUAL(tmp2.getVendor(),""); TEST_EQUAL(tmp2.getIonDetectors().size(),0); TEST_EQUAL(tmp2.getIonSources().size(),0); TEST_EQUAL(tmp2.getMassAnalyzers().size(),0); TEST_EQUAL(tmp2.getSoftware().getName(),""); TEST_EQUAL(tmp2.getIonOptics(),Instrument::IonOpticsType::UNKNOWN); END_SECTION START_SECTION(bool operator== (const Instrument& rhs) const) Instrument edit,empty; TEST_EQUAL(edit==empty,true); edit.getMassAnalyzers().resize(1); TEST_EQUAL(edit==empty,false); edit = empty; edit.getIonSources().resize(1); TEST_EQUAL(edit==empty,false); edit = empty; edit.getIonDetectors().resize(1); TEST_EQUAL(edit==empty,false); edit = empty; edit.setModel("Model"); TEST_EQUAL(edit==empty,false); edit = empty; edit.setName("Name"); TEST_EQUAL(edit==empty,false); edit = empty; edit.getSoftware().setName("sn"); TEST_EQUAL(edit==empty,false); edit = empty; edit.setVendor("Vendor"); TEST_EQUAL(edit==empty,false); edit = empty; edit.setIonOptics(Instrument::IonOpticsType::REFLECTRON); TEST_EQUAL(edit==empty,false); edit = empty; edit.setMetaValue("label",String("label")); TEST_EQUAL(edit==empty,false); END_SECTION START_SECTION(bool operator!= (const Instrument& rhs) const) Instrument edit,empty; TEST_EQUAL(edit!=empty,false); edit.getMassAnalyzers().resize(1); TEST_EQUAL(edit!=empty,true); edit = empty; edit.getIonSources().resize(1); TEST_EQUAL(edit!=empty,true); edit = empty; edit.getIonDetectors().resize(1); TEST_EQUAL(edit!=empty,true); edit = empty; edit.setModel("Model"); TEST_EQUAL(edit!=empty,true); edit = empty; edit.setName("Name"); TEST_EQUAL(edit!=empty,true); edit = empty; edit.setVendor("Vendor"); TEST_EQUAL(edit!=empty,true); edit = empty; edit.getSoftware().setName("sn"); TEST_EQUAL(edit!=empty,true); edit = empty; edit.setIonOptics(Instrument::IonOpticsType::REFLECTRON); TEST_EQUAL(edit!=empty,true) edit = empty; edit.setMetaValue("label",String("label")); TEST_EQUAL(edit!=empty,true); END_SECTION START_SECTION((static StringList getAllNamesOfIonOpticsType())) StringList names = Instrument::getAllNamesOfIonOpticsType(); TEST_EQUAL(names.size(), static_cast<size_t>(Instrument::IonOpticsType::SIZE_OF_IONOPTICSTYPE)); TEST_EQUAL(names[static_cast<size_t>(Instrument::IonOpticsType::REFLECTRON)], "reflectron"); END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/PeakPickerMobilogram_test.cpp
.cpp
4,328
89
// Copyright (c) 2002-present, The OpenMS Team -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Justin Sing $ // $Authors: Justin Sing $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> #include <boost/assign/std/vector.hpp> #include <OpenMS/ANALYSIS/OPENSWATH/PeakPickerMobilogram.h> using namespace OpenMS; using namespace std; typedef Mobilogram RichPeakMobilogram; RichPeakMobilogram get_mobilogram(int i) { static const double im_data1[] = {0.93734956, 0.93835497, 0.9393905, 0.9404265, 0.9414631, 0.9425003, 0.9435083, 0.9445466, 0.9455854, 0.94662476, 0.947635, 0.94867545, 0.9496867, 0.95072824, 0.95177037, 0.9527832, 0.9538264, 0.95484036, 0.9558847, 0.9568997, 0.9579451, 0.9589612, 0.96000767, 0.9610248, 0.96207243, 0.96309066, 0.9641094, 0.96515864, 0.9661785, 0.96719885, 0.96824974, 0.9692712, 0.9702931, 0.97131556, 0.9723687, 0.97339225, 0.9744164, 0.975441, 0.9764661, 0.977522, 0.9785482, 0.979575, 0.98060226, 0.98163015, 0.9826585, 0.9836874, 0.98471683, 0.9857468, 0.9867773, 0.98780835, 0.98883986, 0.989872, 0.9909046, 0.9919378, 0.99297154, 0.99397534, 0.99501014, 0.9960454, 0.9970813, 0.9981177, 1.0125301}; static const double int_data1[] = {341.995757, 200.000741, 325.0076900000001, 79.002655, 227.00538, 487.00108, 576.0032550000001, 526.996605, 715.9864020000001, 778.010235, 686.003534, 548.0023570000001, 481.00395999999995, 547.00563, 950.006949, 1453.9987189999997, 831.026847, 1839.009966, 2306.021277, 2588.9953999999993, 2126.0273610000004, 3254.0281579999996, 3961.0108749999995, 4708.020719000002, 4991.072095, 5230.084562000001, 6559.103413000001, 6486.9137040000005, 9512.035332, 14461.755780000001, 16570.804681, 19887.687351000004, 22368.220470000004, 31683.985819, 37679.199531000006, 46487.67955, 48958.673168000016, 52820.41709300001, 58070.474128999995, 57655.34146700001, 58849.449743000005, 56964.34470800001, 56100.919934, 48964.276839, 43019.251419, 39263.106511000005, 28199.275315000003, 25018.205981999996, 20248.883416, 14727.949587000001, 10372.823519, 6309.068338999999, 5370.119231000001, 2253.037892, 2025.998686, 868.9924269999999, 209.0077, 44.99693, 317.999914, 57.00195, 78.0025}; RichPeakMobilogram mobilogram; for (int k = 0; k < 60; k++) { MobilityPeak1D peak; if (i == 0) { peak.setPos(im_data1[k]); peak.setIntensity(int_data1[k]); } mobilogram.push_back(peak); } return mobilogram; } START_TEST(PeakPickerMobilogram, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// PeakPickerMobilogram* ptr = nullptr; PeakPickerMobilogram* nullPointer = nullptr; START_SECTION(PeakPickerMobilogram()) { ptr = new PeakPickerMobilogram(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(~PeakPickerMobilogram()) { delete ptr; } END_SECTION START_SECTION(void pickMobilogram(const RichPeakMobilogram& mobilogram, RichPeakMobilogram& picked_mobilogram)) { RichPeakMobilogram mobilogram, picked_mobilogram, smoothed_mobilogram; mobilogram = get_mobilogram(0); PeakPickerMobilogram picker; Param picker_param = picker.getParameters(); picker_param.setValue("method", "corrected"); picker_param.setValue("use_gauss", "false"); picker.setParameters(picker_param); picker.pickMobilogram(mobilogram, picked_mobilogram, smoothed_mobilogram); TEST_REAL_SIMILAR(picked_mobilogram[0].getIntensity(), 58956.1); TEST_REAL_SIMILAR(picked_mobilogram[0].getPos(), 0.978364); TEST_REAL_SIMILAR(picked_mobilogram.getFloatDataArrays()[PeakPickerMobilogram::IDX_ABUNDANCE][0], 884145); // IntegratedIntensity TEST_REAL_SIMILAR(picked_mobilogram.getFloatDataArrays()[PeakPickerMobilogram::IDX_LEFTBORDER][0], 0.948675); // leftWidth TEST_REAL_SIMILAR(picked_mobilogram.getFloatDataArrays()[PeakPickerMobilogram::IDX_RIGHTBORDER][0], 0.997081); // rightWidth } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/DecoyGenerator_test.cpp
.cpp
4,757
108
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Timo Sachsenberg $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/CHEMISTRY/AASequence.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/CHEMISTRY/DecoyGenerator.h> /////////////////////////// START_TEST(DecoyGenerator, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace std; DecoyGenerator* dg = nullptr; DecoyGenerator* nullPointer = nullptr; START_SECTION((DecoyGenerator())) { dg = new DecoyGenerator(); TEST_NOT_EQUAL(dg, nullPointer) } END_SECTION START_SECTION((~DecoyGenerator())) { delete dg; } END_SECTION dg = new DecoyGenerator(); dg->setSeed(4711); START_SECTION((AASequence reverseProtein(const AASequence& protein))) TEST_EQUAL(dg->reverseProtein(AASequence::fromString("PRTEINE")).toString(), "ENIETRP") END_SECTION START_SECTION((AASequence reversePeptides(const AASequence& protein, const String& protease))) TEST_EQUAL(dg->reversePeptides(AASequence::fromString("TESTPEPTIDE"), "Trypsin").toString(),"EDITPEPTSET") TEST_EQUAL(dg->reversePeptides(AASequence::fromString("TESTRPEPTRIDE"), "Trypsin/P").toString(),"TSETRTPEPREDI") TEST_EQUAL(dg->reversePeptides(AASequence::fromString("TESTRPEPTRIDE"), "Trypsin").toString(),"TPEPRTSETREDI") END_SECTION START_SECTION((AASequence shufflePeptides(const AASequence& aas, const String& protease, const int max_atempts, int seed))) // 1. no cutting site (full peptide is shuffled to minimize sequence identity) TEST_EQUAL(dg->shufflePeptides(AASequence::fromString("TESTPEPTIDE"), "Trypsin").toString(),"DIESETEPTTP") // 2. cutting site after "TESTR", "RPEPTR" and "IDE" (each peptide is shuffled to minimize sequence identity) TEST_EQUAL(dg->shufflePeptides(AASequence::fromString("TESTRPEPTRIDE"), "Trypsin/P").toString(),"ETTSRTPEPRIED") // 3. cutting site after "TESTRPEPTR", "IDE" (each peptide is shuffled to minimize sequence identity) TEST_EQUAL(dg->shufflePeptides(AASequence::fromString("TESTRPEPTRIDE"), "Trypsin").toString(), "SPERTETTPRIED") END_SECTION START_SECTION((std::vector<AASequence> shuffle(const AASequence& protein, const String& protease, int decoy_factor))) // Uses shufflePeptides with fixed seed (4711) for each peptide // Returns a vector with decoy_factor entries, each containing a complete shuffled protein // 1. no cutting site (full peptide is shuffled to minimize sequence identity) auto result1 = dg->shuffle(AASequence::fromString("TESTPEPTIDE"), "Trypsin"); TEST_EQUAL(result1.size(), 1) TEST_EQUAL(result1[0].toString(),"DIESETEPTTP") // 2. cutting site after "TESTR", "RPEPTR" and "IDE" (each peptide is shuffled to minimize sequence identity) auto result2 = dg->shuffle(AASequence::fromString("TESTRPEPTRIDE"), "Trypsin/P"); TEST_EQUAL(result2.size(), 1) TEST_EQUAL(result2[0].toString(),"ETTSRTPRPEDIE") // 3. cutting site after "TESTRPEPTR", "IDE" (each peptide is shuffled to minimize sequence identity) auto result3 = dg->shuffle(AASequence::fromString("TESTRPEPTRIDE"), "Trypsin"); TEST_EQUAL(result3.size(), 1) TEST_EQUAL(result3[0].toString(), "ETEPTSRRTPDIE") // 4. decoy_factor=2 should generate 2 complete decoy proteins in the vector // Each variant gets a fresh DecoyGenerator with seed 4711, producing different shuffles auto result4 = dg->shuffle(AASequence::fromString("TESTPEPTIDE"), "Trypsin", 2); TEST_EQUAL(result4.size(), 2) TEST_EQUAL(result4[0].toString(), "DIESETEPTTP") TEST_EQUAL(result4[1].toString(), "PTEPIDEETTS") // 5. Top-down use-case: no protease cleavage (entire protein shuffled as one peptide) auto result5 = dg->shuffle(AASequence::fromString("LONGERPROTEINSEQUENCEFORTOPDOWN"), "no cleavage"); TEST_EQUAL(result5.size(), 1) TEST_EQUAL(result5[0].toString(), "UPTECWLFREONNNORNOOEOESQEIDRGPT") // 6. Top-down with decoy_factor=2 (two different shuffled proteins in vector) auto result6 = dg->shuffle(AASequence::fromString("LONGERPROTEINSEQUENCEFORTOPDOWN"), "no cleavage", 2); TEST_EQUAL(result6.size(), 2) TEST_EQUAL(result6[0].toString(), "UPTECWLFREONNNORNOOEOESQEIDRGPT") TEST_EQUAL(result6[1].toString(), "FEIRPNEEDOROERNNCNETQGLOWOOPTUS") END_SECTION delete dg; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/PeakIndex_test.cpp
.cpp
4,289
191
// 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 $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/KERNEL/StandardTypes.h> #include <OpenMS/KERNEL/PeakIndex.h> #include <OpenMS/KERNEL/FeatureMap.h> #include <OpenMS/KERNEL/ConsensusMap.h> #include <OpenMS/KERNEL/MSExperiment.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(PeakIndex, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// PeakIndex* ptr = nullptr; PeakIndex* nullPointer = nullptr; START_SECTION((PeakIndex())) { ptr = new PeakIndex(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION((~PeakIndex())) { delete ptr; } END_SECTION START_SECTION((PeakIndex(Size peak))) { PeakIndex i(17); TEST_EQUAL(i.peak,17) } END_SECTION START_SECTION((PeakIndex(Size spectrum, Size peak))) { PeakIndex i(5,17); TEST_EQUAL(i.peak,17) TEST_EQUAL(i.spectrum,5) } END_SECTION START_SECTION((bool isValid() const)) { PeakIndex i; TEST_EQUAL(i.isValid(),false) i.peak = 5; i.spectrum = 17; TEST_EQUAL(i.isValid(),true) } END_SECTION START_SECTION((void clear())) { PeakIndex i(5,17); TEST_EQUAL(i.isValid(),true) i.clear(); TEST_EQUAL(i.isValid(),false) TEST_NOT_EQUAL(i.peak,17) TEST_NOT_EQUAL(i.spectrum,5) } END_SECTION START_SECTION((bool operator==(const PeakIndex &rhs) const)) { PeakIndex i1, i2; TEST_TRUE(i1 == i2) i1.peak = 1; TEST_EQUAL(i1==i2, false) i2.peak = 1; TEST_TRUE(i1 == i2) i1.spectrum = 2; TEST_EQUAL(i1==i2, false) i2.spectrum = 2; TEST_TRUE(i1 == i2) } END_SECTION START_SECTION((bool operator!=(const PeakIndex &rhs) const)) { PeakIndex i1, i2; TEST_EQUAL(i1!=i2, false) i1.peak = 1; TEST_FALSE(i1 == i2) i2.peak = 1; TEST_EQUAL(i1!=i2, false) i1.spectrum = 2; TEST_FALSE(i1 == i2) i2.spectrum = 2; TEST_EQUAL(i1!=i2, false) } END_SECTION FeatureMap map; map.resize(5); map[0].setMZ(1); map[1].setMZ(2); map[2].setMZ(3); map[3].setMZ(4); map[4].setMZ(5); ConsensusMap c_map; c_map.resize(5); c_map[0].setMZ(1.1); c_map[1].setMZ(2.1); c_map[2].setMZ(3.1); c_map[3].setMZ(4.1); c_map[4].setMZ(5.1); START_SECTION((template <typename FeatureMapType> const FeatureMapType::value_type& getFeature(const FeatureMapType &map) const )) { PeakIndex i; TEST_PRECONDITION_VIOLATED(i.getFeature(map)) i.peak = 4; TEST_REAL_SIMILAR(i.getFeature(map).getMZ(),5.0) TEST_REAL_SIMILAR(i.getFeature(c_map).getMZ(),5.1) i.peak = 0; TEST_REAL_SIMILAR(i.getFeature(map).getMZ(),1.0) TEST_REAL_SIMILAR(i.getFeature(c_map).getMZ(),1.1) i.peak = 5; TEST_PRECONDITION_VIOLATED(i.getFeature(map)) } END_SECTION PeakMap exp; exp.resize(3); exp[0].setRT(1); exp[0].resize(15); exp[1].setRT(2); exp[2].setRT(3); exp[2].resize(3); exp[2][0].setMZ(1.0); exp[2][1].setMZ(2.0); exp[2][2].setMZ(3.0); START_SECTION((template <typename PeakMapType> const PeakMapType::SpectrumType& getSpectrum(const PeakMapType &map) const )) { PeakIndex i; TEST_PRECONDITION_VIOLATED(i.getSpectrum(exp)) i.spectrum = 0; TEST_REAL_SIMILAR(i.getSpectrum(exp).getRT(),1.0) i.spectrum = 2; TEST_REAL_SIMILAR(i.getSpectrum(exp).getRT(),3.0) i.spectrum = 3; TEST_PRECONDITION_VIOLATED(i.getSpectrum(exp)) } END_SECTION START_SECTION((template <typename PeakMapType> const PeakMapType::PeakType& getPeak(const PeakMapType &map) const )) { PeakIndex i; TEST_PRECONDITION_VIOLATED(i.getPeak(exp)) i.peak = 0; i.spectrum = 0; TEST_REAL_SIMILAR(i.getPeak(exp).getMZ(),0.0) i.peak = 0; i.spectrum = 2; TEST_REAL_SIMILAR(i.getPeak(exp).getMZ(),1.0) i.peak = 2; TEST_REAL_SIMILAR(i.getPeak(exp).getMZ(),3.0) i.peak = 16; TEST_PRECONDITION_VIOLATED(i.getPeak(exp)) i.peak = 0; i.spectrum = 3; TEST_PRECONDITION_VIOLATED(i.getPeak(exp)) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ChromatogramExtractorAlgorithm_test.cpp
.cpp
21,953
534
// 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 $ // -------------------------------------------------------------------------- #include <OpenMS/ANALYSIS/OPENSWATH/ChromatogramExtractorAlgorithm.h> #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/CONCEPT/Constants.h> #include <OpenMS/test_config.h> #include <OpenMS/FORMAT/MzMLFile.h> #include <OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/SimpleOpenMSSpectraAccessFactory.h> using namespace OpenMS; using namespace std; void find_max_helper(const OpenSwath::ChromatogramPtr& chrom, double &max_value, double &foundat) { max_value = -1; foundat = -1; for(Size i = 0; i < chrom->getTimeArray()->data.size(); i++) { double rt = chrom->getTimeArray()->data[i]; double in = chrom->getIntensityArray()->data[i]; if(in > max_value) { max_value = in; foundat = rt; } } } START_TEST(ChromatogramExtractorAlgorithm, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// ChromatogramExtractorAlgorithm* ptr = nullptr; ChromatogramExtractorAlgorithm* nullPointer = nullptr; START_SECTION(ChromatogramExtractorAlgorithm()) { ptr = new ChromatogramExtractorAlgorithm(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(~ChromatogramExtractorAlgorithm()) { delete ptr; } END_SECTION START_SECTION(void extractChromatograms(const OpenSwath::SpectrumAccessPtr input, std::vector< OpenSwath::ChromatogramPtr > &output, std::vector< ExtractionCoordinates >& extraction_coordinates, double mz_extraction_window, bool ppm, String filter)) { double extract_window = 0.05; std::shared_ptr<PeakMap > exp(new PeakMap); MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("ChromatogramExtractor_input.mzML"), *exp); OpenSwath::SpectrumAccessPtr expptr = SimpleOpenMSSpectraFactory::getSpectrumAccessOpenMSPtr(exp); /////////////////////////////////////////////////////////////////////////// ChromatogramExtractorAlgorithm extractor; std::vector< ChromatogramExtractorAlgorithm::ExtractionCoordinates > coordinates; std::vector< OpenSwath::ChromatogramPtr > out_exp; for (int i = 0; i < 3; i++) { OpenSwath::ChromatogramPtr s(new OpenSwath::Chromatogram); out_exp.push_back(s); } { ChromatogramExtractorAlgorithm::ExtractionCoordinates coord; coord.mz = 618.31; coord.rt_start = 0; coord.rt_end = -1; coord.id = "tr1"; coordinates.push_back(coord); coord.mz = 628.45; coord.rt_start = 0; coord.rt_end = -1; coord.id = "tr2"; coordinates.push_back(coord); coord.mz = 654.38; coord.rt_start = 0; coord.rt_end = -1; coord.id = "tr3"; coordinates.push_back(coord); } extractor.extractChromatograms(expptr, out_exp, coordinates, extract_window, false, -1, "tophat"); OpenSwath::ChromatogramPtr chrom = out_exp[0]; TEST_EQUAL(chrom->getTimeArray()->data.size(), 59); TEST_EQUAL(chrom->getIntensityArray()->data.size(), 59); // we sort/reorder int firstchromat = 1; int secondchromat = 2; int thirdchromat = 0; double max_value = -1; double foundat = -1; find_max_helper(out_exp[firstchromat], max_value, foundat); TEST_REAL_SIMILAR(max_value, 169.792); TEST_REAL_SIMILAR(foundat, 3120.26); find_max_helper(out_exp[secondchromat], max_value, foundat); TEST_REAL_SIMILAR(max_value, 577.33); TEST_REAL_SIMILAR(foundat, 3120.26); find_max_helper(out_exp[thirdchromat], max_value, foundat); TEST_REAL_SIMILAR(max_value, 35.593); TEST_REAL_SIMILAR(foundat, 3055.16); // there is no ion mobility, so this should not work TEST_EXCEPTION(Exception::IllegalArgument, extractor.extractChromatograms(expptr, out_exp, coordinates, extract_window, false, 1, "tophat")) } END_SECTION START_SECTION([EXTRA] void extractChromatograms(const OpenSwath::SpectrumAccessPtr input, std::vector< OpenSwath::ChromatogramPtr > &output, std::vector< ExtractionCoordinates >& extraction_coordinates, double mz_extraction_window, bool ppm, String filter)) { typedef OpenMS::DataArrays::FloatDataArray FloatDataArray; double extract_window = 0.10; std::shared_ptr<PeakMap > exp(new PeakMap); // MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("ChromatogramExtractor_input.mzML"), *exp); for (int i = 0; i < 4; i++) { MSSpectrum s; s.setRT(i); FloatDataArray fda; for (int k = 0; k < 10; k++) { Peak1D p; p.setMZ(618.3 + k * 0.01); p.setIntensity(100 * i + k *2); s.push_back(p); fda.push_back(100 + k *10); } for (int k = 0; k < 10; k++) { Peak1D p; p.setMZ(628.4 + k * 0.01); p.setIntensity(100 * i + k*2); s.push_back(p); fda.push_back(100 + k *10); std::cout << " ion mobility " << 100 + k*10 << " : " << p << std::endl; } fda.setName(Constants::UserParam::ION_MOBILITY); s.getFloatDataArrays().push_back(fda); exp->addSpectrum(s); } OpenSwath::SpectrumAccessPtr expptr = SimpleOpenMSSpectraFactory::getSpectrumAccessOpenMSPtr(exp); /////////////////////////////////////////////////////////////////////////// ChromatogramExtractorAlgorithm extractor; std::vector< ChromatogramExtractorAlgorithm::ExtractionCoordinates > coordinates; { ChromatogramExtractorAlgorithm::ExtractionCoordinates coord; coord.mz = 618.31; coord.rt_start = 0; coord.rt_end = -1; coord.id = "tr1"; coord.ion_mobility = 120; coordinates.push_back(coord); coord.mz = 628.45; coord.rt_start = 0; coord.rt_end = -1; coord.id = "tr2"; coord.ion_mobility = 170; coordinates.push_back(coord); } // no IM window { std::vector< OpenSwath::ChromatogramPtr > out_exp; for (int i = 0; i < 2; i++) { OpenSwath::ChromatogramPtr s(new OpenSwath::Chromatogram); out_exp.push_back(s); } extractor.extractChromatograms(expptr, out_exp, coordinates, extract_window, false, -1, "tophat"); OpenSwath::ChromatogramPtr chrom = out_exp[0]; TEST_EQUAL(chrom->getTimeArray()->data.size(), 4); TEST_EQUAL(chrom->getIntensityArray()->data.size(), 4); double max_value = -1; double foundat = -1; find_max_helper(out_exp[0], max_value, foundat); TEST_REAL_SIMILAR(max_value, 1830) TEST_REAL_SIMILAR(foundat, 3) find_max_helper(out_exp[1], max_value, foundat); TEST_REAL_SIMILAR(max_value, 2790) TEST_REAL_SIMILAR(foundat, 3) } // small IM window { std::vector< OpenSwath::ChromatogramPtr > out_exp; for (int i = 0; i < 2; i++) { OpenSwath::ChromatogramPtr s(new OpenSwath::Chromatogram); out_exp.push_back(s); } extractor.extractChromatograms(expptr, out_exp, coordinates, extract_window, false, 15, "tophat"); OpenSwath::ChromatogramPtr chrom = out_exp[0]; TEST_EQUAL(chrom->getTimeArray()->data.size(), 4); TEST_EQUAL(chrom->getIntensityArray()->data.size(), 4); double max_value = -1; double foundat = -1; find_max_helper(out_exp[0], max_value, foundat); TEST_REAL_SIMILAR(max_value, 304) TEST_REAL_SIMILAR(foundat, 3) find_max_helper(out_exp[1], max_value, foundat); TEST_REAL_SIMILAR(max_value, 314) TEST_REAL_SIMILAR(foundat, 3) } // larger IM window { std::vector< OpenSwath::ChromatogramPtr > out_exp; for (int i = 0; i < 2; i++) { OpenSwath::ChromatogramPtr s(new OpenSwath::Chromatogram); out_exp.push_back(s); } extractor.extractChromatograms(expptr, out_exp, coordinates, extract_window, false, 30, "tophat"); OpenSwath::ChromatogramPtr chrom = out_exp[0]; TEST_EQUAL(chrom->getTimeArray()->data.size(), 4); TEST_EQUAL(chrom->getIntensityArray()->data.size(), 4); double max_value = -1; double foundat = -1; find_max_helper(out_exp[0], max_value, foundat); TEST_REAL_SIMILAR(max_value, 303 + 304 + 305) TEST_REAL_SIMILAR(foundat, 3) find_max_helper(out_exp[1], max_value, foundat); TEST_REAL_SIMILAR(max_value, 313 + 314 + 315) TEST_REAL_SIMILAR(foundat, 3) } } END_SECTION /////////////////////////////////////////////////////////////////////////// /// Private functions /////////////////////////////////////////////////////////////////////////// // mz_a = [400+0.01*i for i in range(20)] // int_a = [0 + i*100.0 for i in range(10)] + [900 - i*100.0 for i in range(10)] // im_a = [100+0.01*i +100*(i%2) for i in range(20)] // zip_a = [ (a,b,c) for a,b,c in zip(mz_a, int_a, im_a) ] static const double mz_arr[] = { 400.0 , 400.01, 400.02, 400.03, 400.04, 400.05, 400.06, 400.07, 400.08, 400.09, 400.1 , 400.11, 400.12, 400.13, 400.14, 400.15, 400.16, 400.17, 400.18, 400.19, // additional values 450.0, 500.0, }; static const double int_arr[] = { 8.0 , 100.0, 200.0, 300.0, 400.0, 500.0, 600.0, 700.0, 800.0, 900.0, 900.0, 800.0, 700.0, 600.0, 500.0, 400.0, 300.0, 200.0, 100.0, 0.0, // additional values 10.0, 10.0, }; static const double im_arr[] = { 100.0, 200.01, 100.02, 200.03, 100.04, 200.05, 100.06, 200.07, 100.08, 200.09, 100.1, 200.11, 100.12, 200.13, 100.14, 200.15, 100.16, 200.17, 100.18, 200.19, // additional values 300.1, 300.2 }; START_SECTION(void extract_value_tophat(const std::vector< double >::const_iterator &mz_start, std::vector< double >::const_iterator &mz_it, const std::vector< double >::const_iterator &mz_end, std::vector< double >::const_iterator &int_it, const double &mz, double &integrated_intensity, const double &mz_extraction_window, bool ppm)) { std::vector<double> mz (mz_arr, mz_arr + sizeof(mz_arr) / sizeof(mz_arr[0]) ); std::vector<double> intensities (int_arr, int_arr + sizeof(int_arr) / sizeof(int_arr[0]) ); // convert the data into a spectrum MSSpectrum spectrum; for(Size i=0; i<mz.size(); ++i) { Peak1D peak; peak.setMZ(mz[i]); peak.setIntensity(intensities[i]); spectrum.push_back(peak); } std::vector<double>::const_iterator mz_start = mz.begin(); std::vector<double>::const_iterator mz_it_end = mz.end(); std::vector<double>::const_iterator mz_it = mz.begin(); std::vector<double>::const_iterator int_it = intensities.begin(); double integrated_intensity = 0; double extract_window = 0.2; // +/- 0.1 // If we use monotonically increasing m/z values then everything should work fine ChromatogramExtractorAlgorithm extractor; // test the zero first value extractor.extract_value_tophat(mz_start, mz_it, mz_it_end, int_it, 399.805, integrated_intensity, extract_window, false); TEST_REAL_SIMILAR(integrated_intensity, 0.0); // test very first data point extractor.extract_value_tophat(mz_start, mz_it, mz_it_end, int_it, 399.91, integrated_intensity, extract_window, false); TEST_REAL_SIMILAR(integrated_intensity, 108.0); extractor.extract_value_tophat(mz_start, mz_it, mz_it_end, int_it, 400.0, integrated_intensity, extract_window, false); // print(sum([0 + i*100.0 for i in range(10)] + 8) ) TEST_REAL_SIMILAR( integrated_intensity, 4508.0); extractor.extract_value_tophat(mz_start, mz_it, mz_it_end, int_it, 400.05, integrated_intensity, extract_window, false); //print(sum([0 + i*100.0 for i in range(10)]) + sum([900 - i*100.0 for i in range(6)]) ) TEST_REAL_SIMILAR( integrated_intensity, 8400.0); extractor.extract_value_tophat(mz_start, mz_it, mz_it_end, int_it, 400.1, integrated_intensity, extract_window, false); //print(sum([0 + i*100.0 for i in range(10)]) + sum([900 - i*100.0 for i in range(10)]) ) TEST_REAL_SIMILAR( integrated_intensity, 9000.0); TEST_EQUAL((int)integrated_intensity, 9000); extractor.extract_value_tophat(mz_start, mz_it, mz_it_end, int_it, 400.28, integrated_intensity, extract_window, false); TEST_REAL_SIMILAR( integrated_intensity,100.0); // test the very last value extractor.extract_value_tophat(mz_start, mz_it, mz_it_end, int_it, 500.0, integrated_intensity, extract_window, false); TEST_REAL_SIMILAR( integrated_intensity, 10.0); // this is to document the situation of using m/z values that are not monotonically increasing: // --> it might not give the correct result (9000) if we try to extract 400.1 AFTER 500.0 extractor.extract_value_tophat(mz_start, mz_it, mz_it_end, int_it, 400.1, integrated_intensity, extract_window, false); TEST_NOT_EQUAL((int)integrated_intensity,9000); /// use ppm extraction windows // mz_it = mz.begin(); int_it = intensities.begin(); integrated_intensity = 0; extract_window = 500; // 500 ppm == 0.2 Da @ 400 m/z extractor.extract_value_tophat(mz_start, mz_it, mz_it_end, int_it, 399.89, integrated_intensity, extract_window, true); TEST_REAL_SIMILAR( integrated_intensity, 0.0); // below 400, 500ppm is below 0.2 Da... extractor.extract_value_tophat(mz_start, mz_it, mz_it_end, int_it, 399.91, integrated_intensity, extract_window, true); TEST_REAL_SIMILAR( integrated_intensity, 8.0); // very first value extractor.extract_value_tophat(mz_start, mz_it, mz_it_end, int_it, 399.92, integrated_intensity, extract_window, true); TEST_REAL_SIMILAR( integrated_intensity,108.0); extractor.extract_value_tophat(mz_start, mz_it, mz_it_end, int_it, 400.0, integrated_intensity, extract_window, true); TEST_REAL_SIMILAR( integrated_intensity,4508.0); extractor.extract_value_tophat(mz_start, mz_it, mz_it_end, int_it, 400.05, integrated_intensity, extract_window, true); TEST_REAL_SIMILAR( integrated_intensity,8400.0); extractor.extract_value_tophat(mz_start, mz_it, mz_it_end, int_it, 400.1, integrated_intensity, extract_window, true); TEST_REAL_SIMILAR( integrated_intensity,9000.0); } END_SECTION START_SECTION([EXTRA IM]void extract_value_tophat(const std::vector< double >::const_iterator &mz_start, std::vector< double >::const_iterator &mz_it, const std::vector< double >::const_iterator &mz_end, std::vector< double >::const_iterator &int_it, const double &mz, double &integrated_intensity, const double &mz_extraction_window, bool ppm)) { std::vector<double> mz (mz_arr, mz_arr + sizeof(mz_arr) / sizeof(mz_arr[0]) ); std::vector<double> intensities (int_arr, int_arr + sizeof(int_arr) / sizeof(int_arr[0]) ); std::vector<double> ion_mobility (im_arr, im_arr + sizeof(im_arr) / sizeof(im_arr[0]) ); // convert the data into a spectrum MSSpectrum spectrum; for(Size i=0; i<mz.size(); ++i) { Peak1D peak; peak.setMZ(mz[i]); peak.setIntensity(intensities[i]); spectrum.push_back(peak); } std::vector<double>::const_iterator mz_start = mz.begin(); std::vector<double>::const_iterator mz_it_end = mz.end(); std::vector<double>::const_iterator mz_it = mz.begin(); std::vector<double>::const_iterator int_it = intensities.begin(); std::vector<double>::const_iterator im_it = ion_mobility.begin(); double integrated_intensity = 0; double extract_window = 0.2; // +/- 0.1 double im_extract_window = 0.3; // +/- 0.15 // If we use monotonically increasing m/z values then everything should work fine ChromatogramExtractorAlgorithm extractor; // extractor.extract_value_tophat(mz_start, mz_it, mz_it_end, int_it, im_it, 399.805, 100, integrated_intensity, extract_window, im_extract_window, false); // test the zero first value extractor.extract_value_tophat(mz_start, mz_it, mz_it_end, int_it, im_it, 399.805, 100, integrated_intensity, extract_window, im_extract_window, false); TEST_REAL_SIMILAR(integrated_intensity, 0.0); // test very first data point extractor.extract_value_tophat(mz_start, mz_it, mz_it_end, int_it, im_it, 399.91, 100, integrated_intensity, extract_window, im_extract_window, false); TEST_REAL_SIMILAR(integrated_intensity, 8.0); extractor.extract_value_tophat(mz_start, mz_it, mz_it_end, int_it, im_it, 400.0, 100, integrated_intensity, extract_window, im_extract_window, false); // sum([i for m,i,im in zip_a if im < 100.15 and m < 400.1]) + 8 TEST_REAL_SIMILAR( integrated_intensity, 2008.0); extractor.extract_value_tophat(mz_start, mz_it, mz_it_end, int_it, im_it, 400.05, 100, integrated_intensity, extract_window, im_extract_window, false); // sum([i for m,i,im in zip_a if im < 100.15 and m < 400.15]) TEST_REAL_SIMILAR( integrated_intensity, 4100.0); extractor.extract_value_tophat(mz_start, mz_it, mz_it_end, int_it, im_it, 400.1, 100, integrated_intensity, extract_window, im_extract_window, false); // sum([i for m,i,im in zip_a if im < 100.15 and m < 400.2]) TEST_REAL_SIMILAR( integrated_intensity, 4100.0); TEST_EQUAL((int)integrated_intensity, 4100); extractor.extract_value_tophat(mz_start, mz_it, mz_it_end, int_it, im_it, 400.28, 100, integrated_intensity, extract_window, im_extract_window, false); TEST_REAL_SIMILAR( integrated_intensity, 0.0); extractor.extract_value_tophat(mz_start, mz_it, mz_it_end, int_it, im_it, 400.28, 200, integrated_intensity, extract_window, im_extract_window, false); TEST_REAL_SIMILAR( integrated_intensity, 0.0); extractor.extract_value_tophat(mz_start, mz_it, mz_it_end, int_it, im_it, 400.28, 200.1, integrated_intensity, extract_window, im_extract_window, false); TEST_REAL_SIMILAR( integrated_intensity, 0.0); // test the very last value extractor.extract_value_tophat(mz_start, mz_it, mz_it_end, int_it, im_it, 500.0, 300.0, integrated_intensity, extract_window, im_extract_window, false); TEST_REAL_SIMILAR( integrated_intensity, 0.0); extractor.extract_value_tophat(mz_start, mz_it, mz_it_end, int_it, im_it, 500.0, 300.1, integrated_intensity, extract_window, im_extract_window, false); TEST_REAL_SIMILAR( integrated_intensity, 10.0); // this is to document the situation of using m/z values that are not monotonically increasing: // --> it might not give the correct result (9000) if we try to extract 400.1 AFTER 500.0 extractor.extract_value_tophat(mz_start, mz_it, mz_it_end, int_it, im_it, 400.1, 100, integrated_intensity, extract_window, im_extract_window, false); TEST_NOT_EQUAL((int)integrated_intensity, 9000); } END_SECTION START_SECTION([EXTRA]void extract_value_tophat(const std::vector< double >::const_iterator &mz_start, std::vector< double >::const_iterator &mz_it, const std::vector< double >::const_iterator &mz_end, std::vector< double >::const_iterator &int_it, const double &mz, double &integrated_intensity, const double &mz_extraction_window, bool ppm)) { std::vector<double> mz (mz_arr, mz_arr + sizeof(mz_arr) / sizeof(mz_arr[0]) ); std::vector<double> intensities (int_arr, int_arr + sizeof(int_arr) / sizeof(int_arr[0]) ); std::vector<double>::const_iterator mz_start = mz.begin(); std::vector<double>::const_iterator mz_it_end = mz.end(); std::vector<double>::const_iterator mz_it = mz.begin(); std::vector<double>::const_iterator int_it = intensities.begin(); double integrated_intensity = 0; double extract_window = 0.2; // +/- 0.1 // If we use monotonically increasing m/z values then everything should work fine ChromatogramExtractorAlgorithm extractor; // test the zero first value extractor.extract_value_tophat(mz_start, mz_it, mz_it_end, int_it, 399.805, integrated_intensity, extract_window, false); TEST_REAL_SIMILAR(integrated_intensity, 0.0); // test very first data point extractor.extract_value_tophat(mz_start, mz_it, mz_it_end, int_it, 400.0001, integrated_intensity, 0.001, false); TEST_REAL_SIMILAR(integrated_intensity, 8.0); } END_SECTION START_SECTION([EXTRA]void extract_value_tophat(const std::vector< double >::const_iterator &mz_start, std::vector< double >::const_iterator &mz_it, const std::vector< double >::const_iterator &mz_end, std::vector< double >::const_iterator &int_it, const double &mz, double &integrated_intensity, const double &mz_extraction_window, bool ppm)) { std::vector<double> mz (mz_arr, mz_arr + sizeof(mz_arr) / sizeof(mz_arr[0]) ); std::vector<double> intensities (int_arr, int_arr + sizeof(int_arr) / sizeof(int_arr[0]) ); std::vector<double> ion_mobility (im_arr, im_arr + sizeof(im_arr) / sizeof(im_arr[0]) ); std::vector<double>::const_iterator mz_start = mz.begin(); std::vector<double>::const_iterator mz_it_end = mz.end(); std::vector<double>::const_iterator mz_it = mz.begin(); std::vector<double>::const_iterator int_it = intensities.begin(); std::vector<double>::const_iterator im_it = ion_mobility.begin(); double integrated_intensity = 0; double extract_window = 0.2; // +/- 0.1 double im_extract_window = 0.3; // +/- 0.15 // If we use monotonically increasing m/z values then everything should work fine ChromatogramExtractorAlgorithm extractor; // test the zero first value extractor.extract_value_tophat(mz_start, mz_it, mz_it_end, int_it, im_it, 399.805, 100, integrated_intensity, extract_window, im_extract_window, false); TEST_REAL_SIMILAR(integrated_intensity, 0.0); // test very first data point extractor.extract_value_tophat(mz_start, mz_it, mz_it_end, int_it, im_it, 400.0001, 100, integrated_intensity, 0.001, im_extract_window, false); TEST_REAL_SIMILAR(integrated_intensity, 8.0); } END_SECTION START_SECTION( [ChromatogramExtractorAlgorithm::ExtractionCoordinates] static bool SortExtractionCoordinatesByMZ(const ChromatogramExtractorAlgorithm::ExtractionCoordinates &left, const ChromatogramExtractorAlgorithm::ExtractionCoordinates &right)) { NOT_TESTABLE } END_SECTION START_SECTION([ChromatogramExtractorAlgorithm::ExtractionCoordinates] static bool SortExtractionCoordinatesReverseByMZ(const ChromatogramExtractorAlgorithm::ExtractionCoordinates &left, const ChromatogramExtractorAlgorithm::ExtractionCoordinates &right)) { NOT_TESTABLE } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MathFunctions_test.cpp
.cpp
7,613
222
// 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 $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/MATH/MathFunctions.h> /////////////////////////// using namespace OpenMS; using namespace std; using namespace OpenMS::Math; START_TEST(MathFunctions, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// START_SECTION((double log_binomial_coef(unsigned n, unsigned k))) { // Test normal cases TEST_REAL_SIMILAR(Math::log_binomial_coef(10, 5), 5.5294); TEST_REAL_SIMILAR(Math::log_binomial_coef(20, 10), 12.12679); // Test edge cases TEST_REAL_SIMILAR(Math::log_binomial_coef(5, 0), 0.0); TEST_REAL_SIMILAR(Math::log_binomial_coef(5, 5), 0.0); // Test symmetry property TEST_REAL_SIMILAR(Math::log_binomial_coef(10, 3), Math::log_binomial_coef(10, 7)); // Test invalid input TEST_EXCEPTION(std::invalid_argument, Math::log_binomial_coef(5, 6)); } END_SECTION START_SECTION((double log_sum_exp(double x, double y))) { // Test normal cases TEST_REAL_SIMILAR(Math::log_sum_exp(1.0, 2.0), 2.31326169); TEST_REAL_SIMILAR(Math::log_sum_exp(10.0, 10.0), 10.6931472); // Test with one very small value (should be close to the larger value) TEST_REAL_SIMILAR(Math::log_sum_exp(100.0, 0.0), 100.0); TEST_REAL_SIMILAR(Math::log_sum_exp(0.0, 100.0), 100.0); // Test with negative infinity double neg_inf = -std::numeric_limits<double>::infinity(); TEST_REAL_SIMILAR(Math::log_sum_exp(neg_inf, 5.0), 5.0); TEST_REAL_SIMILAR(Math::log_sum_exp(5.0, neg_inf), 5.0); } END_SECTION START_SECTION((ceilDecimal)) { TEST_REAL_SIMILAR(ceilDecimal(12345.671,-2),12345.68) TEST_REAL_SIMILAR(ceilDecimal(12345.67,-1),12345.7) TEST_REAL_SIMILAR(ceilDecimal(12345.67,0),12346.0) TEST_REAL_SIMILAR(ceilDecimal(12345.67,1),12350.0) TEST_REAL_SIMILAR(ceilDecimal(12345.67,2),12400.0) } END_SECTION START_SECTION((roundDecimal)) { TEST_REAL_SIMILAR(roundDecimal(12345.671,-2),12345.67) TEST_REAL_SIMILAR(roundDecimal(12345.67,-1),12345.7) TEST_REAL_SIMILAR(roundDecimal(12345.67,0),12346.0) TEST_REAL_SIMILAR(roundDecimal(12345.67,1),12350.0) TEST_REAL_SIMILAR(roundDecimal(12345.67,2),12300.0) } END_SECTION START_SECTION((intervalTransformation)) { TEST_REAL_SIMILAR(intervalTransformation(0.5,0.0,1.0,0.0,600.0),300.0) TEST_REAL_SIMILAR(intervalTransformation(0.5,0.25,1.0,0.0,600.0),200.0) TEST_REAL_SIMILAR(intervalTransformation(0.5,0.0,0.75,0.0,600.0),400.0) TEST_REAL_SIMILAR(intervalTransformation(0.5,0.0,1.0,150.0,600.0),375.0) TEST_REAL_SIMILAR(intervalTransformation(0.5,0.0,1.0,0.0,450.0),225.0) } END_SECTION START_SECTION((linear2log)) { TEST_REAL_SIMILAR(linear2log(0.0),0.0) TEST_REAL_SIMILAR(linear2log(9.0),1.0) TEST_REAL_SIMILAR(linear2log(99.0),2.0) TEST_REAL_SIMILAR(linear2log(999.0),3.0) } END_SECTION START_SECTION((log2linear)) { TEST_REAL_SIMILAR(log2linear(0.0),0.0) TEST_REAL_SIMILAR(log2linear(1.0),9.0) TEST_REAL_SIMILAR(log2linear(2.0),99.0) TEST_REAL_SIMILAR(log2linear(3.0),999.0) } END_SECTION START_SECTION((isOdd)) { TEST_TRUE(!isOdd(0)) TEST_TRUE(isOdd(1)) TEST_TRUE(!isOdd(2)) TEST_TRUE(isOdd(3)) } END_SECTION START_SECTION((template <typename T> T round (T x))) { float f_down=14.49f; // expected 14 float f_up = 14.50f; // expected 15 double d_up = -999.49; // expected -999 double d_down = -675.77; // expected -676 TEST_REAL_SIMILAR(Math::round(f_down), 14.0) TEST_REAL_SIMILAR(Math::round(f_up), 15.0) TEST_REAL_SIMILAR(Math::round(d_up), -999) TEST_REAL_SIMILAR(Math::round(d_down), -676) } END_SECTION START_SECTION(template<typename T> T roundTo(const T value, int digits)) { TEST_REAL_SIMILAR(roundTo(3.14159265, 2), 3.14) TEST_REAL_SIMILAR(roundTo(1234.9, -2), 1200) TEST_REAL_SIMILAR(roundTo(1234.9, 0), 1235) TEST_REAL_SIMILAR(roundTo(1234.9, -1), 1230) TEST_REAL_SIMILAR(roundTo(1234.9, -3), 1000) } END_SECTION START_SECTION(template<typename T> double percentOf(T value, T total, int digits)) { TEST_REAL_SIMILAR(percentOf(1.0 / 3, 1.0, 2), 33.33) TEST_REAL_SIMILAR(percentOf(1.0 / 3, 1.0, 3), 33.333) TEST_REAL_SIMILAR(percentOf(1.0 / 3, 1.0, 4), 33.3333) TEST_REAL_SIMILAR(percentOf(166.6666, 1000.0, 1), 16.7) TEST_EXCEPTION(Exception::InvalidValue, percentOf(-1.0, 1000.0, 2)) TEST_EXCEPTION(Exception::InvalidValue, percentOf(1.0, -1000.0, 2)) } END_SECTION START_SECTION((bool approximatelyEqual(double a, double b, double tol))) { TEST_TRUE(approximatelyEqual(1.1, 1.1002, 0.1)) TEST_TRUE(approximatelyEqual(1.1, 1.1002, 0.01)) TEST_TRUE(approximatelyEqual(1.1, 1.1002, 0.001)) TEST_FALSE(approximatelyEqual(1.1, 1.1002, 0.0001)) } END_SECTION START_SECTION((template <typename T> T getPPM(T mz_obs, T mz_ref))) { TEST_REAL_SIMILAR(getPPM(1001.0, 1000.0), 1000.0) // == 1 / 1000 * 1e6 TEST_REAL_SIMILAR(getPPM( 999.0, 1000.0), -1000.0) // == -1 / 1000 * 1e6 } END_SECTION START_SECTION((template <typename T> T getPPMAbs(T mz_obs, T mz_ref))) { TEST_REAL_SIMILAR(getPPMAbs(1001.0, 1000.0), 1000.0) // == abs(1 / 1000 * 1e6) TEST_REAL_SIMILAR(getPPMAbs( 999.0, 1000.0), 1000.0) // == abs(-1 / 1000 * 1e6) } END_SECTION START_SECTION((pair<double, double> getTolWindow(double val, double tol, bool ppm))) { TEST_REAL_SIMILAR(getTolWindow(1000, 10, true).first, 999.99) TEST_REAL_SIMILAR(getTolWindow(1000, 10, true).second, 1000.0100001) TEST_REAL_SIMILAR(getTolWindow(1000, 10, false).first, 990) TEST_REAL_SIMILAR(getTolWindow(1000, 10, false).second, 1010) TEST_REAL_SIMILAR(getTolWindow(500, 5, true).first, 499.9975) TEST_REAL_SIMILAR(getTolWindow(500, 5, true).second, 500.0025000125) } END_SECTION START_SECTION((double binomial_cdf_complement(unsigned N, unsigned n, double p))) { // Test normal cases TEST_REAL_SIMILAR(Math::binomial_cdf_complement(10, 5, 0.5), 0.623046875); TEST_REAL_SIMILAR(Math::binomial_cdf_complement(20, 10, 0.4), 0.24466); // Test edge cases TEST_REAL_SIMILAR(Math::binomial_cdf_complement(10, 0, 0.3), 1.0); TEST_REAL_SIMILAR(Math::binomial_cdf_complement(10, 10, 0.7), 0.0282475249); // Test with p = 0 and p = 1 TEST_REAL_SIMILAR(Math::binomial_cdf_complement(10, 0, 0.0), 1.0); TEST_REAL_SIMILAR(Math::binomial_cdf_complement(10, 1, 0.0), 0.0); TEST_REAL_SIMILAR(Math::binomial_cdf_complement(10, 0, 1.0), 1.0); TEST_REAL_SIMILAR(Math::binomial_cdf_complement(10, 10, 1.0), 1.0); // Test invalid inputs TEST_EXCEPTION(std::invalid_argument, Math::binomial_cdf_complement(10, 11, 0.5)); TEST_EXCEPTION(std::invalid_argument, Math::binomial_cdf_complement(10, 5, -0.1)); TEST_EXCEPTION(std::invalid_argument, Math::binomial_cdf_complement(10, 5, 1.1)); // Test the function used in AScore // This is similar to the test in AScore_test.cpp for computeCumulativeScoreTest_ TEST_REAL_SIMILAR(Math::binomial_cdf_complement(1, 1, 0.1), 0.1); TEST_REAL_SIMILAR(Math::binomial_cdf_complement(3, 1, 0.1), 0.271); // Test with larger values TEST_REAL_SIMILAR(Math::binomial_cdf_complement(100, 60, 0.5), 0.02844); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/DateTime_test.cpp
.cpp
7,822
331
// 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 $ // -------------------------------------------------------------------------- // #include <OpenMS/CONCEPT/ClassTest.h> /////////////////////////// #include <OpenMS/DATASTRUCTURES/DateTime.h> #include <OpenMS/DATASTRUCTURES/String.h> #include <iostream> #include <vector> using namespace OpenMS; using namespace std; /////////////////////////// START_TEST(DateTime, "$Id$") ///////////////////////////////////////////////////////////// DateTime* ptr = nullptr; DateTime* nullPointer = nullptr; START_SECTION((DateTime())) { ptr = new DateTime(); TEST_NOT_EQUAL(ptr, nullPointer) delete ptr; } END_SECTION START_SECTION((~DateTime())) { ptr = new DateTime(); delete ptr; } END_SECTION ///////////////////////////////////////////////////////////// // Copy constructor, move constructor, assignment operator, move assignment operator, equality START_SECTION((DateTime(const DateTime& date))) { DateTime date1; DateTime date2; DateTime date3; date1.set("2006-12-12 11:59:59"); date2 = DateTime(date1); TEST_TRUE(date1 == date2) } END_SECTION START_SECTION((DateTime(const DateTime&& date))) { // Ensure that DateTime has a no-except move constructor (otherwise // std::vector is inefficient and will copy instead of move). TEST_EQUAL(noexcept(DateTime(std::declval<DateTime&&>())), true) DateTime date1; DateTime date2; DateTime date3; date1.set("2006-12-12 11:59:59"); date2 = DateTime(std::move(date1)); TEST_EQUAL(date2.get(), "2006-12-12 11:59:59") } END_SECTION START_SECTION((DateTime& operator= (const DateTime& source))) { DateTime date, date2; date.set("2006-12-12 11:59:59"); TEST_EQUAL(date==date2,false); date2 = date; TEST_EQUAL(date==date2,true); } END_SECTION START_SECTION((DateTime& operator= (DateTime&& source))) { DateTime date, date2; date.set("2006-12-12 11:59:59"); TEST_EQUAL(date==date2,false); date2 = std::move(date); TEST_EQUAL(date2.get(), "2006-12-12 11:59:59") } END_SECTION START_SECTION((void clear())) { DateTime date1; DateTime date2; date1.set("2006-12-12 11:59:59"); date1.clear(); TEST_TRUE(date1 == date2) TEST_EQUAL(date1.isNull(), true) } END_SECTION START_SECTION((String get() const)) { DateTime date_time; date_time.set("1999-11-24 14:24:31"); TEST_EQUAL(date_time.get(),"1999-11-24 14:24:31") } END_SECTION START_SECTION((void get(UInt& month, UInt& day, UInt& year, UInt& hour, UInt& minute, UInt& second) const)) { DateTime date; UInt month; UInt day; UInt year; UInt hour; UInt minute; UInt second; date.set("2006-12-14 11:59:58"); date.get(month, day, year, hour, minute, second); TEST_EQUAL(month, 12) TEST_EQUAL(day, 14) TEST_EQUAL(year, 2006) TEST_EQUAL(hour, 11) TEST_EQUAL(minute, 59) TEST_EQUAL(second, 58) } END_SECTION START_SECTION((void getDate(UInt& month, UInt& day, UInt& year) const)) { DateTime date; UInt month; UInt day; UInt year; date.set("2006-12-14 21:12:02"); date.getDate(month, day, year); TEST_EQUAL(month, 12) TEST_EQUAL(day, 14) TEST_EQUAL(year, 2006) } END_SECTION START_SECTION((String getDate() const)) { DateTime date; date.set("2006-12-14 21:12:02"); TEST_STRING_EQUAL(date.getDate(), String("2006-12-14")) } END_SECTION START_SECTION((void getTime(UInt& hour, UInt& minute, UInt& second) const)) { DateTime date; UInt hour; UInt minute; UInt second; date.set("2006-12-14 11:59:58"); date.getTime(hour, minute, second); TEST_EQUAL(hour, 11) TEST_EQUAL(minute, 59) TEST_EQUAL(second, 58) } END_SECTION START_SECTION((String getTime() const)) { DateTime date; date.set("2006-12-14 11:59:58"); TEST_STRING_EQUAL(date.getTime(), "11:59:58") } END_SECTION START_SECTION((void set(UInt month, UInt day, UInt year, UInt hour, UInt minute, UInt second))) { DateTime date; UInt month = 12; UInt day = 14; UInt year = 2006; UInt hour = 11; UInt minute = 59; UInt second = 58; date.set(month, day, year, hour, minute, second); date.get(month, day, year, hour, minute, second); TEST_EQUAL(month, 12) TEST_EQUAL(day, 14) TEST_EQUAL(year, 2006) TEST_EQUAL(hour, 11) TEST_EQUAL(minute, 59) TEST_EQUAL(second, 58) } END_SECTION START_SECTION((void set(const String &date))) { DateTime date_time; date_time.set("1999-11-24 14:24:31"); TEST_EQUAL(date_time.get(), "1999-11-24 14:24:31") date_time.set("01.02.2000 14:24:32"); TEST_EQUAL(date_time.get(), "2000-02-01 14:24:32") date_time.set("01/02/2000 14:24:32"); TEST_EQUAL(date_time.get(), "2000-01-02 14:24:32") date_time.set("2005-11-13T10:58:57"); TEST_EQUAL(date_time.get(), "2005-11-13 10:58:57") date_time.set("2008-11-13 10:59:57"); TEST_EQUAL(date_time.get(), "2008-11-13 10:59:57") date_time.set("2006-12-14Z"); TEST_EQUAL(date_time.get(), "2006-12-14 00:00:00") date_time.set("2006-12-14+11:00"); TEST_EQUAL(date_time.get(), "2006-12-14 11:00:00") // test if get is able to ignore the +02:00 timezone part / with and without milliseconds // this test is due to #209 date_time.set("2011-08-05T15:32:07.468+02:00"); TEST_EQUAL(date_time.get(), "2011-08-05 15:32:07") date_time.set("2011-08-05T15:32:07+02:00"); TEST_EQUAL(date_time.get(), "2011-08-05 15:32:07") TEST_EXCEPTION(Exception::ParseError, date_time.set("2006ff-12-14+11:00")) TEST_EXCEPTION(Exception::ParseError, date_time.set("2006-12-14-11:00")) TEST_EXCEPTION(Exception::ParseError, date_time.set("2006-12-14Z11:00")) TEST_EXCEPTION(Exception::ParseError, date_time.set("-2006-12-14Z11:00")) } END_SECTION START_SECTION((void setDate(UInt month, UInt day, UInt year))) { DateTime date; UInt month = 12; UInt day = 14; UInt year = 2006; date.setDate(month, day, year); date.getDate(month, day, year); TEST_EQUAL(month, 12) TEST_EQUAL(day, 14) TEST_EQUAL(year, 2006) } END_SECTION START_SECTION((void setDate(const String &date))) { DateTime date; UInt month; UInt day; UInt year; date.set("2006-12-14 11:59:58"); date.getDate(month, day, year); TEST_EQUAL(month, 12) TEST_EQUAL(day, 14) TEST_EQUAL(year, 2006) } END_SECTION START_SECTION((void setTime(UInt hour, UInt minute, UInt second))) { DateTime date; UInt hour; UInt minute; UInt second; date.setTime(11, 59, 58); date.getTime(hour, minute, second); TEST_EQUAL(hour, 11) TEST_EQUAL(minute, 59) TEST_EQUAL(second, 58) } END_SECTION START_SECTION((void setTime(const String &date))) { DateTime date; UInt hour; UInt minute; UInt second; date.setTime("11:59:58"); date.getTime(hour, minute, second); TEST_EQUAL(hour, 11) TEST_EQUAL(minute, 59) TEST_EQUAL(second, 58) } END_SECTION START_SECTION(([EXTRA] Three digit year should get leading zero according to Qt 4.4.3 documentation )) { // This is a regression test. Leave it here even if the issue gets hacked away in DateTime. DateTime one_moment_in_time; one_moment_in_time.set(5,4,666,3,2,1); // this behaviour is not critical and does not work on Qt 4.3 machines // so the leading zero is not checked! (who really needs dates before the year 1000 in this library?) TEST_EQUAL(one_moment_in_time.get().hasSubstring("666-05-04 03:02:01"), true); } END_SECTION START_SECTION((static DateTime now())) { TEST_EQUAL(DateTime::now().isValid(), true) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/TransformationModelInterpolated_test.cpp
.cpp
5,884
177
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: $ // $Authors: Hendrik Weisser, Stephan Aiche $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/ANALYSIS/MAPMATCHING/TransformationModel.h> #include <OpenMS/ANALYSIS/MAPMATCHING/TransformationModelInterpolated.h> #include <OpenMS/FORMAT/CsvFile.h> /////////////////////////// START_TEST(TransformationModelInterpolated, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace std; TransformationModelInterpolated* ptr = nullptr; TransformationModelInterpolated* nullPointer = nullptr; TransformationModel::DataPoints dummy_data; dummy_data.push_back(make_pair(0.0, 1.0)); dummy_data.push_back(make_pair(0.5, 4.0)); dummy_data.push_back(make_pair(1.0, 2.0)); dummy_data.push_back(make_pair(1.0, 4.0)); START_SECTION((TransformationModelInterpolated(const DataPoints &data, const Param &params))) { ptr = new TransformationModelInterpolated(dummy_data, Param()); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION((~TransformationModelInterpolated())) { delete ptr; } END_SECTION START_SECTION((double evaluate(double value) const)) { // NOTE: This test ensure first of all the compatibility of the interpolation // to the original GSL based implementation of TransformationModelInterpolated /* load data generated by gsl interpolation */ CsvFile data_points(OPENMS_GET_TEST_DATA_PATH("TransformationModelInterpolated_base_data.txt"), '\t'); TransformationModel::DataPoints base_data; for (Size i = 0; i < data_points.rowCount(); ++i) { StringList sl; if (data_points.getRow(i, sl)) { base_data.push_back(make_pair(sl[0].toDouble(), sl[1].toDouble())); } } // create interpolations Param p_linear; TransformationModelInterpolated::getDefaultParameters(p_linear); p_linear.setValue("interpolation_type", "linear"); TransformationModelInterpolated linear_interpolation(base_data, p_linear); Param p_cspline; TransformationModelInterpolated::getDefaultParameters(p_cspline); p_cspline.setValue("interpolation_type", "cspline"); TransformationModelInterpolated cspline_interpolation(base_data, p_cspline); Param p_akima; TransformationModelInterpolated::getDefaultParameters(p_akima); p_akima.setValue("interpolation_type", "akima"); TransformationModelInterpolated akima_interpolation(base_data, p_akima); // read gsl results CsvFile gsl_results(OPENMS_GET_TEST_DATA_PATH("TransformationModelInterpolated_gsl_data.txt"), '\t'); std::vector<double> gsl_target_points; std::vector<double> gsl_cspline; std::vector<double> gsl_linear; std::vector<double> gsl_akima; for (Size i = 0; i < gsl_results.rowCount(); ++i) { StringList sl; if (gsl_results.getRow(i, sl)) { gsl_target_points.push_back(sl[0].toDouble()); gsl_linear.push_back(sl[1].toDouble()); gsl_akima.push_back(sl[2].toDouble()); gsl_cspline.push_back(sl[3].toDouble()); } } // test the interpolation for (size_t i = 0; i < gsl_target_points.size(); ++i) { const double x = gsl_target_points[i]; TEST_REAL_SIMILAR(linear_interpolation.evaluate(x), gsl_linear[i]) TEST_REAL_SIMILAR(cspline_interpolation.evaluate(x), gsl_cspline[i]) TEST_REAL_SIMILAR(akima_interpolation.evaluate(x), gsl_akima[i]) } } END_SECTION START_SECTION(([EXTRA] TransformationModelInterpolated::evaluate() beyond the actual borders)) { Param p; TransformationModelInterpolated::getDefaultParameters(p); TransformationModelInterpolated tr(dummy_data, p); TEST_REAL_SIMILAR(tr.evaluate(0.0), 1.0); TEST_REAL_SIMILAR(tr.evaluate(0.5), 4.0); TEST_REAL_SIMILAR(tr.evaluate(1.0), 3.0); // using default value, two-point-linear { // Without changing parameters, extrapolation is linear and independent of // the actual interpolation beyond the borders TransformationModelInterpolated tr(dummy_data, Param()); // see TransformationModelLinear_test TEST_REAL_SIMILAR(tr.evaluate(-0.5), 0.0); TEST_REAL_SIMILAR(tr.evaluate(1.5), 4.0); } { TransformationModelInterpolated::getDefaultParameters(p); p.setValue("extrapolation_type", "two-point-linear"); TransformationModelInterpolated tr(dummy_data, p); TEST_REAL_SIMILAR(tr.evaluate(-0.5), 0.0); // slope of 2 TEST_REAL_SIMILAR(tr.evaluate(1.5), 4.0); // slope of 2 } { TransformationModelInterpolated::getDefaultParameters(p); p.setValue("extrapolation_type", "four-point-linear"); TransformationModelInterpolated tr(dummy_data, p); TEST_REAL_SIMILAR(tr.evaluate(-0.5), -2.0); // slope of 6 TEST_REAL_SIMILAR(tr.evaluate(1.5), 2.0); // slope of -2 } { TransformationModelInterpolated::getDefaultParameters(p); p.setValue("extrapolation_type", "global-linear"); TransformationModelInterpolated tr(dummy_data, p); TEST_REAL_SIMILAR(tr.evaluate(-0.5), 0.909091); // 1.727 + 1.636 * -0.5 TEST_REAL_SIMILAR(tr.evaluate(1.5), 4.1818182); // 1.727 + 1.636 * 1.5 } } END_SECTION START_SECTION((static void getDefaultParameters(Param & params))) { Param p; TransformationModelInterpolated::getDefaultParameters(p); TEST_EQUAL(!p.empty(), true) TEST_EQUAL(p.getValue("interpolation_type"), "cspline") TEST_EQUAL(p.getValue("extrapolation_type"), "two-point-linear") } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/NLargest_test.cpp
.cpp
4,930
170
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Mathias Walzer $ // $Authors: Andreas Bertsch $ // -------------------------------------------------------------------------- // #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/PROCESSING/FILTERING/NLargest.h> #include <OpenMS/KERNEL/StandardTypes.h> #include <OpenMS/FORMAT/DTAFile.h> using namespace OpenMS; using namespace std; /////////////////////////// START_TEST(NLargest, "$Id$") ///////////////////////////////////////////////////////////// NLargest* e_ptr = nullptr; NLargest* e_nullPointer = nullptr; START_SECTION((NLargest())) e_ptr = new NLargest; TEST_NOT_EQUAL(e_ptr, e_nullPointer) END_SECTION START_SECTION(NLargest(UInt n)) NLargest filter(10); TEST_EQUAL((UInt)filter.getParameters().getValue("n"), 10) END_SECTION START_SECTION((~NLargest())) delete e_ptr; END_SECTION e_ptr = new NLargest(); START_SECTION((NLargest(const NLargest& source))) NLargest copy(*e_ptr); TEST_EQUAL(copy.getParameters(), e_ptr->getParameters()) TEST_EQUAL(copy.getName(), e_ptr->getName()) END_SECTION START_SECTION((NLargest& operator=(const NLargest& source))) NLargest copy; copy = *e_ptr; TEST_EQUAL(copy.getParameters(), e_ptr->getParameters()) TEST_EQUAL(copy.getName(), e_ptr->getName()) END_SECTION START_SECTION((template<typename SpectrumType> void filterSpectrum(SpectrumType& spectrum))) DTAFile dta_file; PeakSpectrum spec; dta_file.load(OPENMS_GET_TEST_DATA_PATH("Transformers_tests.dta"), spec); TEST_EQUAL(spec.size(), 121) Param p(e_ptr->getParameters()); p.setValue("n", 10); e_ptr->setParameters(p); e_ptr->filterSpectrum(spec); TEST_EQUAL(spec.size(), 10) END_SECTION START_SECTION((void filterPeakMap(PeakMap& exp))) delete e_ptr; e_ptr = new NLargest(); DTAFile dta_file; PeakSpectrum spec; dta_file.load(OPENMS_GET_TEST_DATA_PATH("Transformers_tests.dta"), spec); PeakMap pm; pm.addSpectrum(spec); TEST_EQUAL(pm.begin()->size(), 121) Param p(e_ptr->getParameters()); p.setValue("n", 10); e_ptr->setParameters(p); e_ptr->filterPeakMap(pm); TEST_EQUAL(pm.begin()->size(), 10) END_SECTION START_SECTION((void filterPeakSpectrum(PeakSpectrum& spectrum))) delete e_ptr; e_ptr = new NLargest(); DTAFile dta_file; PeakSpectrum spec; dta_file.load(OPENMS_GET_TEST_DATA_PATH("Transformers_tests.dta"), spec); TEST_EQUAL(spec.size(), 121) Param p(e_ptr->getParameters()); p.setValue("n", 10); e_ptr->setParameters(p); e_ptr->filterPeakSpectrum(spec); TEST_EQUAL(spec.size(), 10) PeakSpectrum s_da; s_da.getIntegerDataArrays().resize(1); s_da.getStringDataArrays().resize(1); // create a "triangle" shape with apex at i=50 for (Size i = 0; i != 50; ++i) { s_da.push_back(Peak1D(i, i + 0.1)); s_da.getIntegerDataArrays()[0].push_back(i); s_da.getStringDataArrays()[0].push_back("up"); } for (int i = 50; i != 100; ++i) { s_da.push_back(Peak1D(i, (100 - i) + 0.2)); s_da.getIntegerDataArrays()[0].push_back(i); s_da.getStringDataArrays()[0].push_back("down"); } e_ptr->filterPeakSpectrum(s_da); /* int mz DA_int DA_string 50.2 50 50 down 49.2 51 51 down 49.1 49 49 up 48.2 52 52 down 48.1 48 48 up 47.2 53 53 down 47.1 47 47 up 46.2 54 54 down 46.1 46 46 up 45.2 55 55 down */ TEST_EQUAL(s_da.size(), 10) TEST_EQUAL(s_da[0].getIntensity(), 50.2) TEST_EQUAL(s_da[1].getIntensity(), 49.2) TEST_EQUAL(s_da[2].getIntensity(), 49.1) TEST_EQUAL(s_da.getIntegerDataArrays()[0][0], 50) TEST_EQUAL(s_da.getIntegerDataArrays()[0][1], 51) TEST_EQUAL(s_da.getIntegerDataArrays()[0][2], 49) TEST_EQUAL(s_da.getStringDataArrays()[0][0], "down") TEST_EQUAL(s_da.getStringDataArrays()[0][1], "down") TEST_EQUAL(s_da.getStringDataArrays()[0][2], "up") TEST_EQUAL(s_da[7].getIntensity(), 46.2) TEST_EQUAL(s_da[8].getIntensity(), 46.1) TEST_EQUAL(s_da[9].getIntensity(), 45.2) TEST_EQUAL(s_da.getIntegerDataArrays()[0][7], 54) TEST_EQUAL(s_da.getIntegerDataArrays()[0][8], 46) TEST_EQUAL(s_da.getIntegerDataArrays()[0][9], 55) TEST_EQUAL(s_da.getStringDataArrays()[0][7], "down") TEST_EQUAL(s_da.getStringDataArrays()[0][8], "up") TEST_EQUAL(s_da.getStringDataArrays()[0][9], "down") // debug code // for (Size i = 0; i != s_da.size(); ++i) // { // cout << "int:" << s_da[i].getIntensity() << " mz:" << s_da[i].getMZ() << "\t" << s_da.getIntegerDataArrays()[0][i] << "\t" << s_da.getStringDataArrays()[0][i] << endl; // } END_SECTION delete e_ptr; ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/IDMergerAlgorithm_test.cpp
.cpp
7,902
202
// 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 $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/ANALYSIS/ID/IDMergerAlgorithm.h> #include <OpenMS/METADATA/PeptideIdentification.h> #include <OpenMS/FORMAT/IdXMLFile.h> #include <OpenMS/SYSTEM/StopWatch.h> #include <OpenMS/test_config.h> using namespace OpenMS; using namespace std; START_TEST(IDMergerAlgorithm, "$Id$") START_SECTION(insertRun()) { ProteinIdentification pr1; pr1.setIdentifier("PR1"); pr1.setPrimaryMSRunPath({"f1r1.mzML","f2r1.mzML"}); pr1.getHits().emplace_back(0,1,"A",""); pr1.getHits().emplace_back(0,1,"B",""); pr1.getHits().emplace_back(0,1,"C",""); ProteinIdentification pr2; pr2.setIdentifier("PR2"); pr2.setPrimaryMSRunPath({"f1r2.mzML","f2r2.mzML"}); pr2.getHits().emplace_back(0,1,"A",""); pr2.getHits().emplace_back(0,1,"D",""); pr2.getHits().emplace_back(0,1,"E",""); ProteinIdentification pr3; pr3.setIdentifier("PR3"); pr3.setPrimaryMSRunPath({"f1r3.mzML","f2r3.mzML"}); pr3.getHits().emplace_back(0,1,"D",""); pr3.getHits().emplace_back(0,1,"E",""); pr3.getHits().emplace_back(0,1,"F",""); pr3.getHits().emplace_back(0,1,"G",""); ProteinIdentification pr4; //empty pr4.setIdentifier("PR4"); pr4.setPrimaryMSRunPath({"control.mzML"}); PeptideHit ph0{0,1,1,AASequence::fromString("AA")}; ph0.addPeptideEvidence(PeptideEvidence{"A",1,3,'A','A'}); ph0.addPeptideEvidence(PeptideEvidence{"B",1,3,'A','A'}); PeptideHit ph1{0,1,1,AASequence::fromString("AAA")}; ph1.addPeptideEvidence(PeptideEvidence{"A",1,4,'A','A'}); PeptideHit ph11{0,1,1,AASequence::fromString("AAC")}; ph11.addPeptideEvidence(PeptideEvidence{"C",1,4,'A','A'}); PeptideHit ph2{0,1,1,AASequence::fromString("AAAA")}; ph2.addPeptideEvidence(PeptideEvidence{"D",1,5,'A','A'}); ph2.addPeptideEvidence(PeptideEvidence{"E",1,5,'A','A'}); PeptideHit ph3{0,1,1,AASequence::fromString("AAAAA")}; ph3.addPeptideEvidence(PeptideEvidence{"D",1,6,'A','A'}); ph3.addPeptideEvidence(PeptideEvidence{"E",1,6,'A','A'}); PeptideHit ph4{0,1,1,AASequence::fromString("AAAAAA")}; ph4.addPeptideEvidence(PeptideEvidence{"F",1,7,'A','A'}); // ph5 same pep sequence but different proteins -> this actually means that there was an error or a different // protein database was used or something was filtered. But we cannot recover it here during merging. // you need to re-index. We can think about warning but this requires additional checks & datastructures. PeptideHit ph5{0.1,1,1,AASequence::fromString("AAA")}; ph5.addPeptideEvidence(PeptideEvidence{"F",1,4,'A','A'}); PeptideIdentification pe1; pe1.setIdentifier("PR1"); pe1.getHits().push_back(ph0); pe1.setMetaValue(Constants::UserParam::ID_MERGE_INDEX,0); PeptideIdentification pe2; pe2.setIdentifier("PR1"); pe2.getHits().push_back(ph1); pe2.getHits().push_back(ph11); pe2.setMetaValue(Constants::UserParam::ID_MERGE_INDEX,0); PeptideIdentification pe3; pe3.setIdentifier("PR2"); pe3.getHits().push_back(ph0); // how to handle accessions that are not in the corresponding list of proteins? //currently ignore and add nonetheless. pe3.setMetaValue(Constants::UserParam::ID_MERGE_INDEX,0); PeptideIdentification pe4; pe4.setIdentifier("PR2"); pe4.getHits().push_back(ph2); pe4.getHits().push_back(ph3); pe4.setMetaValue(Constants::UserParam::ID_MERGE_INDEX,1); PeptideIdentification pe5; pe5.setIdentifier("PR3"); pe5.getHits().push_back(ph2); pe5.setMetaValue(Constants::UserParam::ID_MERGE_INDEX,0); PeptideIdentification pe6; pe6.setIdentifier("PR3"); pe6.getHits().push_back(ph3); pe6.setMetaValue(Constants::UserParam::ID_MERGE_INDEX,1); PeptideIdentification pe7; pe7.setIdentifier("PR3"); pe7.getHits().push_back(ph4); pe7.setMetaValue(Constants::UserParam::ID_MERGE_INDEX,0); PeptideIdentification pe8; pe8.setIdentifier("PR3"); pe8.getHits().push_back(ph5); pe8.setMetaValue(Constants::UserParam::ID_MERGE_INDEX,0); //can happen if second file had no IDs PeptideIdentification pe9; pe9.setIdentifier("PR5"); // non-existent run: this will be ignored pe9.getHits().push_back(ph5); pe9.setMetaValue(Constants::UserParam::ID_MERGE_INDEX,564); PeptideIdentificationList pes{pe1,pe2,pe3,pe4,pe5,pe6,pe7,pe8,pe9}; vector<ProteinIdentification> prs{pr1,pr2,pr3,pr4}; IDMergerAlgorithm ima("mymerge"); ima.insertRuns(prs, pes); ProteinIdentification prres; PeptideIdentificationList peres; ima.returnResultsAndClear(prres,peres); TEST_EQUAL(pes.size(), 9) TEST_EQUAL(peres.size(), 8) TEST_EQUAL(prres.getHits().size(), 7) StringList toFill; prres.getPrimaryMSRunPath(toFill); TEST_EQUAL(toFill.size(), 7) TEST_EQUAL(static_cast<int>(peres[2].getMetaValue(Constants::UserParam::ID_MERGE_INDEX)), 2) } END_SECTION START_SECTION(insertRun()) { IdXMLFile f; vector<ProteinIdentification> pr1; PeptideIdentificationList pe1; f.load(OPENMS_GET_TEST_DATA_PATH("newIDMergerTest1.idXML"),pr1,pe1); Size pe1size = pe1.size(); vector<ProteinIdentification> pr2; PeptideIdentificationList pe2; f.load(OPENMS_GET_TEST_DATA_PATH("newIDMergerTest2.idXML"),pr2,pe2); Size pe2size = pe2.size(); IDMergerAlgorithm ima("mymerge"); ima.insertRuns(std::move(pr1), std::move(pe1)); ima.insertRuns(std::move(pr2), std::move(pe2)); TEST_EXCEPTION(Exception::MissingInformation, ima.insertRuns({ProteinIdentification{}}, {PeptideIdentification{}})) ProteinIdentification prres; PeptideIdentificationList peres; ima.returnResultsAndClear(prres,peres); TEST_EQUAL(prres.getHits().size(),6) TEST_EQUAL(peres.size(),pe1size + pe2size) TEST_EQUAL(pr1.size(),0) TEST_EQUAL(pr2.size(),0) TEST_EQUAL(pe1.size(),0) TEST_EQUAL(pe2.size(),0) TEST_EQUAL(prres.getIdentifier().hasPrefix("mymerge"), true) StringList toFill; prres.getPrimaryMSRunPath(toFill); TEST_EQUAL(toFill.size(), 2) } END_SECTION START_SECTION(check search setting consistency) { IdXMLFile f; vector<ProteinIdentification> pr1; PeptideIdentificationList pe1; f.load(OPENMS_GET_TEST_DATA_PATH("newIDMergerTest1.idXML"),pr1,pe1); vector<ProteinIdentification> pr2; PeptideIdentificationList pe2; f.load(OPENMS_GET_TEST_DATA_PATH("newIDMergerTest2.idXML"),pr2,pe2); // fail with different db filename pr2[0].getSearchParameters().db = "baz"; IDMergerAlgorithm ima("mymerge"); ima.insertRuns(std::move(pr1), std::move(pe1)); TEST_EXCEPTION(Exception::MissingInformation,ima.insertRuns(pr2, pe2)) // check windows path with correct filename String fn = "C:\\foo\\s_pyo_sf370_potato_human_target_decoy_with_contaminants.fasta"; pr2[0].getSearchParameters().db = fn; ima.insertRuns(std::move(pr2), std::move(pe2)); ProteinIdentification prres; PeptideIdentificationList peres; ima.returnResultsAndClear(prres,peres); TEST_EQUAL(prres.getHits().size(),6) } END_SECTION END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ConsensusIDAlgorithmRanks_test.cpp
.cpp
4,138
136
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hendrik Weisser $ // $Authors: Marc Sturm, Andreas Bertsch, Sven Nahnsen, Hendrik Weisser $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/ANALYSIS/ID/ConsensusIDAlgorithmRanks.h> using namespace OpenMS; using namespace std; /////////////////////////// START_TEST(ConsensusIDAlgorithmRanks, "$Id$") ///////////////////////////////////////////////////////////// ConsensusIDAlgorithm* ptr = nullptr; ConsensusIDAlgorithm* null_pointer = nullptr; START_SECTION(ConsensusIDAlgorithmRanks()) { ptr = new ConsensusIDAlgorithmRanks(); TEST_NOT_EQUAL(ptr, null_pointer); } END_SECTION START_SECTION(~ConsensusIDAlgorithmRanks()) { delete(ptr); } END_SECTION // create 3 ID runs: PeptideIdentification temp; temp.setScoreType("Posterior Error Probability"); temp.setHigherScoreBetter(false); PeptideIdentificationList ids(3, temp); vector<PeptideHit> hits; // the first ID has 5 hits hits.resize(5); hits[0].setSequence(AASequence::fromString("A")); hits[0].setScore(0.1); hits[1].setSequence(AASequence::fromString("B")); hits[1].setScore(0.2); hits[2].setSequence(AASequence::fromString("C")); hits[2].setScore(0.3); hits[3].setSequence(AASequence::fromString("D")); hits[3].setScore(0.4); hits[4].setSequence(AASequence::fromString("E")); hits[4].setScore(0.5); ids[0].setHits(hits); // the second ID has 3 hits hits.resize(3); hits[0].setSequence(AASequence::fromString("C")); hits[0].setScore(0.2); hits[1].setSequence(AASequence::fromString("A")); hits[1].setScore(0.4); hits[2].setSequence(AASequence::fromString("B")); hits[2].setScore(0.6); ids[1].setHits(hits); // the third ID has 10 hits hits.resize(10); hits[0].setSequence(AASequence::fromString("F")); hits[0].setScore(0.0); hits[1].setSequence(AASequence::fromString("C")); hits[1].setScore(0.1); hits[2].setSequence(AASequence::fromString("G")); hits[2].setScore(0.2); hits[3].setSequence(AASequence::fromString("D")); hits[3].setScore(0.3); hits[4].setSequence(AASequence::fromString("B")); hits[4].setScore(0.4); hits[5].setSequence(AASequence::fromString("E")); hits[5].setScore(0.5); hits[6].setSequence(AASequence::fromString("H")); hits[6].setScore(0.6); hits[7].setSequence(AASequence::fromString("I")); hits[7].setScore(0.7); hits[8].setSequence(AASequence::fromString("J")); hits[8].setScore(0.8); hits[9].setSequence(AASequence::fromString("K")); hits[9].setScore(0.9); ids[2].setHits(hits); START_SECTION(void apply(PeptideIdentificationList& ids)) { TOLERANCE_ABSOLUTE(0.01) ConsensusIDAlgorithmRanks consensus; // define parameters: Param param; param.setValue("filter:considered_hits", 5); consensus.setParameters(param); // apply: map<String,String> empty; PeptideIdentificationList f = ids; consensus.apply(f, empty); TEST_EQUAL(f.size(), 1); hits = f[0].getHits(); TEST_EQUAL(hits.size(), 7); TEST_EQUAL(hits[0].getSequence(), AASequence::fromString("C")); TEST_REAL_SIMILAR(hits[0].getScore(), 0.8); TEST_EQUAL(hits[1].getSequence(), AASequence::fromString("A")); TEST_REAL_SIMILAR(hits[1].getScore(), 0.6); TEST_EQUAL(hits[2].getSequence(), AASequence::fromString("B")); TEST_REAL_SIMILAR(hits[2].getScore(), 0.5333); TEST_EQUAL(hits[3].getSequence(), AASequence::fromString("F")); TEST_REAL_SIMILAR(hits[3].getScore(), 0.33333); TEST_EQUAL(hits[4].getSequence(), AASequence::fromString("D")); TEST_REAL_SIMILAR(hits[4].getScore(), 0.26666); TEST_EQUAL(hits[5].getSequence(), AASequence::fromString("G")); TEST_REAL_SIMILAR(hits[5].getScore(), 0.2); TEST_EQUAL(hits[6].getSequence(), AASequence::fromString("E")); TEST_REAL_SIMILAR(hits[6].getScore(), 0.06666); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ZlibCompression_test.cpp
.cpp
7,132
167
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Hannes Roest $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/FORMAT/ZlibCompression.h> /////////////////////////// #define MULTI_LINE_STRING(...) #__VA_ARGS__ START_TEST(ZlibCompression, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; ZlibCompression* zlib_ptr = nullptr; START_SECTION((ZlibCompression())) zlib_ptr = new ZlibCompression(); END_SECTION START_SECTION((~ZlibCompression())) delete zlib_ptr; END_SECTION char const * toCompress = "AAAAAAAAAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"; char const * toCompress2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; char const * toCompress3 = "Freude, schoner Gotterfunken, Tochter aus Elysium, Wir betreten feuertrunken, Himmlische, dein Heiligtum!"; std::string raw_data(toCompress); std::string raw_data2(toCompress2); std::string raw_data3(toCompress3); std::string raw_data4 = MULTI_LINE_STRING( <spectrum index="2" id="index=2" defaultArrayLength="15"> <binaryDataArrayList count="2"> <binaryDataArray encodedLength="160" > <cvParam cvRef="MS" accession="MS:1000523" name="64-bit float" value=""/> <cvParam cvRef="MS" accession="MS:1000576" name="no compression" value=""/> <binary>AAAAAAAAAAAAAAAAAADwPwAAAAAAAABAAAAAAAAACEAAAAAAAAAQQAAAAAAAABRAAAAAAAAAGEAAAAAAAAAcQAAAAAAAACBAAAAAAAAAIkAAAAAAAAAkQAAAAAAAACZAAAAAAAAAKEAAAAAAAAAqQAAAAAAAACxA</binary> </binaryDataArray> <binaryDataArray encodedLength="160" > <cvParam cvRef="MS" accession="MS:1000523" name="64-bit float" value=""/> <cvParam cvRef="MS" accession="MS:1000576" name="no compression" value=""/> <cvParam cvRef="MS" accession="MS:1000515" name="intensity array" value="" unitAccession="MS:1000131" unitName="number of detector counts" unitCvRef="MS"/> <binary>AAAAAAAALkAAAAAAAAAsQAAAAAAAACpAAAAAAAAAKEAAAAAAAAAmQAAAAAAAACRAAAAAAAAAIkAAAAAAAAAgQAAAAAAAABxAAAAAAAAAGEAAAAAAAAAUQAAAAAAAABBAAAAAAAAACEAAAAAAAAAAQAAAAAAAAPA/</binary> </binaryDataArray> </binaryDataArrayList> </spectrum> ); START_SECTION((static void compressString(std::string& raw_data, std::string& compressed_data))) { std::string compressed_data; // Because implementations of zlib and alternatives differ, we just test if // the compressed data requires less space. ZlibCompression::compressString(raw_data, compressed_data); TEST_EQUAL(raw_data.size(), 58) TEST_TRUE(compressed_data.size() < raw_data.size()) ZlibCompression::compressString(raw_data2, compressed_data); TEST_EQUAL(raw_data2.size(), 64) TEST_TRUE(compressed_data.size() >= raw_data2.size()) ZlibCompression::compressString(raw_data3, compressed_data); TEST_EQUAL(raw_data3.size(), 105) TEST_TRUE(compressed_data.size() < raw_data3.size()) ZlibCompression::compressString(raw_data4, compressed_data); TEST_EQUAL(raw_data4.size(), 1052) TEST_TRUE(compressed_data.size() < raw_data4.size()) } END_SECTION START_SECTION((static void uncompressString(const void* compressed_data, size_t nr_bytes, std::string& raw_data, size_t output_size))) { std::string compressed_data; std::string uncompressed_data; ZlibCompression::compressString(raw_data, compressed_data); ZlibCompression::uncompressString(compressed_data, uncompressed_data, raw_data.size()); TEST_EQUAL(raw_data.size(), 58) TEST_TRUE(compressed_data.size() < raw_data.size()) TEST_EQUAL(uncompressed_data.size(), 58) TEST_TRUE(uncompressed_data == raw_data) ZlibCompression::compressString(raw_data2, compressed_data); ZlibCompression::uncompressString(compressed_data, uncompressed_data, raw_data2.size()); TEST_EQUAL(raw_data2.size(), 64) TEST_TRUE(compressed_data.size() >= raw_data2.size()) // difficult to compress... TEST_EQUAL(uncompressed_data.size(), 64) TEST_TRUE(uncompressed_data == raw_data2) ZlibCompression::compressString(raw_data3, compressed_data); ZlibCompression::uncompressString(compressed_data, uncompressed_data, raw_data3.size()); TEST_EQUAL(raw_data3.size(), 105) TEST_TRUE(compressed_data.size() < raw_data3.size()) TEST_EQUAL(uncompressed_data.size(), 105) TEST_TRUE(uncompressed_data == raw_data3) ZlibCompression::compressString(raw_data4, compressed_data); ZlibCompression::uncompressString(compressed_data, uncompressed_data, raw_data4.size()); TEST_EQUAL(raw_data4.size(), 1052) TEST_TRUE(compressed_data.size() < raw_data4.size()) TEST_EQUAL(uncompressed_data.size(), 1052) TEST_TRUE(uncompressed_data == raw_data4) //////////////// // Exceptions // //////////////// ZlibCompression::compressString(raw_data, compressed_data); // Invalid output_size TEST_EXCEPTION(Exception::InvalidValue, ZlibCompression::uncompressString(compressed_data, uncompressed_data, 10);) // Truncated data TEST_EXCEPTION(Exception::InternalToolError, ZlibCompression::uncompressData(&compressed_data[0], compressed_data.size()-10, uncompressed_data, raw_data.size());) } END_SECTION START_SECTION((static void uncompressString(const void * compressed_data, size_t nr_bytes, std::string& raw_data))) { String compressed_data; String uncompressed_data; ZlibCompression::compressString(raw_data, compressed_data); ZlibCompression::uncompressString(compressed_data, uncompressed_data); TEST_EQUAL(raw_data.size(), 58) TEST_TRUE(compressed_data.size() < raw_data.size()) TEST_EQUAL(uncompressed_data.size(), 58) TEST_TRUE(uncompressed_data == raw_data) ZlibCompression::compressString(raw_data2, compressed_data); ZlibCompression::uncompressString(compressed_data, uncompressed_data); TEST_EQUAL(raw_data2.size(), 64) TEST_TRUE(compressed_data.size() >= raw_data2.size()) // "ABCD..." string is difficult to compress TEST_EQUAL(uncompressed_data.size(), 64) TEST_TRUE(uncompressed_data == raw_data2) ZlibCompression::compressString(raw_data3, compressed_data); ZlibCompression::uncompressString(compressed_data, uncompressed_data); TEST_EQUAL(raw_data3.size(), 105) TEST_TRUE(compressed_data.size() < raw_data3.size()) TEST_EQUAL(uncompressed_data.size(), 105) TEST_TRUE(uncompressed_data == raw_data3) ZlibCompression::compressString(raw_data4, compressed_data); ZlibCompression::uncompressString(compressed_data, uncompressed_data); TEST_EQUAL(raw_data4.size(), 1052) TEST_TRUE(compressed_data.size() < raw_data4.size()) TEST_EQUAL(uncompressed_data.size(), 1052) TEST_TRUE(uncompressed_data == raw_data4) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/OnDiscMSExperiment_test.cpp
.cpp
18,618
506
// 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 $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/KERNEL/OnDiscMSExperiment.h> #include <OpenMS/FORMAT/OPTIONS/PeakFileOptions.h> /////////////////////////// START_TEST(OnDiscMSExperiment, "$Id$"); ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace std; OnDiscPeakMap* ptr = nullptr; OnDiscPeakMap* nullPointer = nullptr; START_SECTION((OnDiscMSExperiment())) { ptr = new OnDiscPeakMap(); TEST_NOT_EQUAL(ptr, nullPointer); } END_SECTION START_SECTION((~OnDiscMSExperiment())) { delete ptr; } END_SECTION START_SECTION((OnDiscMSExperiment(const OnDiscMSExperiment& filename))) { OnDiscPeakMap tmp; tmp.openFile(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML")); OnDiscPeakMap tmp2(tmp); TEST_EQUAL(tmp2.getExperimentalSettings()->getInstrument().getName(), tmp.getExperimentalSettings()->getInstrument().getName() ) TEST_EQUAL(tmp2.getExperimentalSettings()->getInstrument().getVendor(), tmp.getExperimentalSettings()->getInstrument().getVendor() ) TEST_EQUAL(tmp2.getExperimentalSettings()->getInstrument().getModel(), tmp.getExperimentalSettings()->getInstrument().getModel() ) TEST_EQUAL(tmp2.getExperimentalSettings()->getInstrument().getMassAnalyzers().size(), tmp.getExperimentalSettings()->getInstrument().getMassAnalyzers().size() ) TEST_EQUAL(tmp2.size(),tmp.size()); } END_SECTION // START_SECTION((OnDiscMSExperiment(const String& filename))) // { // OnDiscPeakMap tmp(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML")); // TEST_EQUAL(tmp.size(), 2); // } // END_SECTION START_SECTION((bool operator== (const OnDiscMSExperiment& rhs) const)) { OnDiscPeakMap tmp; tmp.openFile(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML")); OnDiscPeakMap tmp2; tmp2.openFile(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML"), true); OnDiscPeakMap same; same.openFile(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML")); OnDiscPeakMap failed; failed.openFile(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML")); TEST_TRUE(tmp == same); TEST_EQUAL(tmp2==same, false); TEST_TRUE(tmp2 == tmp2); TEST_EQUAL((*tmp.getExperimentalSettings())==(*same.getExperimentalSettings()), true); TEST_EQUAL(tmp==failed, false); } END_SECTION START_SECTION((bool operator!= (const OnDiscMSExperiment& rhs) const)) { OnDiscPeakMap tmp; tmp.openFile(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML")); OnDiscPeakMap tmp2; tmp2.openFile(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML"), true); OnDiscPeakMap same; same.openFile(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML")); OnDiscPeakMap failed; failed.openFile(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML")); TEST_EQUAL(tmp!=same, false); TEST_FALSE(tmp2 == same); TEST_FALSE(tmp == failed); } END_SECTION START_SECTION(( bool openFile(const String& filename, bool skipMetaData = false) )) { OnDiscPeakMap tmp; OnDiscPeakMap same; OnDiscPeakMap failed; bool res; res = tmp.openFile(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML")); TEST_EQUAL(res, true) res = tmp.openFile(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML"), true); TEST_EQUAL(res, true) res = same.openFile(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML")); TEST_EQUAL(res, true) res = same.openFile(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML"), true); TEST_EQUAL(res, true) res = failed.openFile(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML")); TEST_EQUAL(res, false) res = failed.openFile(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML"), true); TEST_EQUAL(res, false) } END_SECTION START_SECTION((bool isSortedByRT() const)) { OnDiscPeakMap tmp; tmp.openFile(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML")); TEST_EQUAL(tmp.isSortedByRT(), true); } END_SECTION START_SECTION((Size size() const)) { OnDiscPeakMap tmp; tmp.openFile(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML")); OnDiscPeakMap tmp2; tmp2.openFile(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML"), true); OnDiscPeakMap failed; failed.openFile(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML")); TEST_EQUAL(tmp.size(), 2); TEST_EQUAL(tmp2.size(), 2); TEST_EQUAL(failed.size(), 0); } END_SECTION START_SECTION((bool empty() const)) { OnDiscPeakMap tmp; tmp.openFile(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML")); OnDiscPeakMap tmp2; tmp2.openFile(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML"), true); OnDiscPeakMap failed; failed.openFile(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML")); TEST_EQUAL(tmp.empty(), false); TEST_EQUAL(tmp2.empty(), false); TEST_EQUAL(failed.empty(), true); } END_SECTION START_SECTION((Size getNrSpectra() const)) { OnDiscPeakMap tmp; tmp.openFile(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML")); OnDiscPeakMap tmp2; tmp2.openFile(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML"), true); OnDiscPeakMap failed; failed.openFile(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML")); TEST_EQUAL(tmp.getNrSpectra(), 2); TEST_EQUAL(tmp2.getNrSpectra(), 2); TEST_EQUAL(failed.getNrSpectra(), 0); } END_SECTION START_SECTION((Size getNrChromatograms() const)) { OnDiscPeakMap tmp; tmp.openFile(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML")); OnDiscPeakMap tmp2; tmp2.openFile(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML"), true); OnDiscPeakMap failed; failed.openFile(OPENMS_GET_TEST_DATA_PATH("MzMLFile_1.mzML")); TEST_EQUAL(tmp.getNrChromatograms(), 1); TEST_EQUAL(tmp2.getNrChromatograms(), 1); TEST_EQUAL(failed.getNrChromatograms(), 0); } END_SECTION START_SECTION((std::shared_ptr<const ExperimentalSettings> getExperimentalSettings() const)) { OnDiscPeakMap tmp; tmp.openFile(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML")); OnDiscPeakMap tmp2; tmp2.openFile(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML"), true); std::shared_ptr<const ExperimentalSettings> settings = tmp.getExperimentalSettings(); TEST_EQUAL(settings->getInstrument().getName(), "LTQ FT") TEST_EQUAL(settings->getInstrument().getMassAnalyzers().size(), 1) settings = tmp2.getExperimentalSettings(); TEST_TRUE(settings == nullptr) } END_SECTION START_SECTION((MSSpectrum operator[] (Size n) const)) { OnDiscPeakMap tmp; tmp.openFile(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML")); TEST_EQUAL(tmp.empty(), false); MSSpectrum s = tmp[0]; TEST_EQUAL(s.empty(), false); TEST_EQUAL(s.size(), 19914); OnDiscPeakMap tmp2; tmp2.openFile(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML"), true); TEST_EQUAL(tmp2.empty(), false); s = tmp2[0]; TEST_EQUAL(s.empty(), false); TEST_EQUAL(s.size(), 19914); } END_SECTION START_SECTION((MSSpectrum getSpectrum(Size id))) { OnDiscPeakMap tmp; tmp.openFile(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML")); TEST_EQUAL(tmp.empty(), false); MSSpectrum s = tmp.getSpectrum(0); TEST_EQUAL(s.empty(), false); TEST_EQUAL(s.size(), 19914); OnDiscPeakMap tmp2; tmp2.openFile(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML"), true); TEST_EQUAL(tmp2.empty(), false); MSSpectrum s2 = tmp2.getSpectrum(0); TEST_EQUAL(s2.empty(), false); TEST_EQUAL(s2.size(), 19914); MSSpectrum s3 = tmp2.getSpectrum(1); TEST_EQUAL(s3.empty(), false); TEST_EQUAL(s3.size(), 19800); } END_SECTION START_SECTION(OpenMS::Interfaces::SpectrumPtr getSpectrumById(Size id)) { OnDiscPeakMap tmp; tmp.openFile(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML")); TEST_EQUAL(tmp.empty(), false); OpenMS::Interfaces::SpectrumPtr s = tmp.getSpectrumById(0); TEST_EQUAL(s->getMZArray()->data.empty(), false); TEST_EQUAL(s->getMZArray()->data.size(), 19914); TEST_EQUAL(s->getIntensityArray()->data.empty(), false); TEST_EQUAL(s->getIntensityArray()->data.size(), 19914); OnDiscPeakMap tmp2; tmp2.openFile(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML"), true); TEST_EQUAL(tmp2.empty(), false); s = tmp2.getSpectrumById(0); TEST_EQUAL(s->getMZArray()->data.empty(), false); TEST_EQUAL(s->getMZArray()->data.size(), 19914); TEST_EQUAL(s->getIntensityArray()->data.empty(), false); TEST_EQUAL(s->getIntensityArray()->data.size(), 19914); } END_SECTION START_SECTION((MSChromatogram getChromatogram(Size id))) { OnDiscPeakMap tmp; tmp.openFile(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML")); TEST_EQUAL(tmp.getNrChromatograms(), 1); TEST_EQUAL(tmp.empty(), false); MSChromatogram c = tmp.getChromatogram(0); TEST_EQUAL(c.empty(), false); TEST_EQUAL(c.size(), 48); OnDiscPeakMap tmp2; tmp2.openFile(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML"), true); TEST_EQUAL(tmp2.getNrChromatograms(), 1); TEST_EQUAL(tmp2.empty(), false); c = tmp2.getChromatogram(0); TEST_EQUAL(c.empty(), false); TEST_EQUAL(c.size(), 48); } END_SECTION START_SECTION(OpenMS::Interfaces::ChromatogramPtr getChromatogramById(Size id)) { OnDiscPeakMap tmp; tmp.openFile(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML")); TEST_EQUAL(tmp.empty(), false); OpenMS::Interfaces::ChromatogramPtr s = tmp.getChromatogramById(0); TEST_EQUAL(s->getTimeArray()->data.empty(), false); TEST_EQUAL(s->getTimeArray()->data.size(), 48); TEST_EQUAL(s->getIntensityArray()->data.empty(), false); TEST_EQUAL(s->getIntensityArray()->data.size(), 48); OnDiscPeakMap tmp2; tmp2.openFile(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML"), true); TEST_EQUAL(tmp2.empty(), false); s = tmp2.getChromatogramById(0); TEST_EQUAL(s->getTimeArray()->data.empty(), false); TEST_EQUAL(s->getTimeArray()->data.size(), 48); TEST_EQUAL(s->getIntensityArray()->data.empty(), false); TEST_EQUAL(s->getIntensityArray()->data.size(), 48); } END_SECTION START_SECTION(MSChromatogram getChromatogramByNativeId(const std::string& id)) { OnDiscPeakMap tmp; tmp.openFile(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML")); TEST_EQUAL(tmp.empty(), false); OpenMS::MSChromatogram s = tmp.getChromatogramByNativeId("TIC"); TEST_EQUAL(s.empty(), false); TEST_EQUAL(s.size(), 48); TEST_EXCEPTION(Exception::IllegalArgument, tmp.getChromatogramByNativeId("TIK")) OnDiscPeakMap tmp2; tmp2.openFile(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML"), true); TEST_EQUAL(tmp2.empty(), false); s = tmp2.getChromatogramByNativeId("TIC"); TEST_EQUAL(s.empty(), false); TEST_EQUAL(s.size(), 48); TEST_EXCEPTION(Exception::IllegalArgument, tmp2.getChromatogramByNativeId("TIK")) } END_SECTION START_SECTION(MSMSSpectrum getSpectrumByNativeId(const std::string& id)) { OnDiscPeakMap tmp; tmp.openFile(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML")); TEST_EQUAL(tmp.empty(), false); OpenMS::MSSpectrum s = tmp.getSpectrumByNativeId("controllerType=0 controllerNumber=1 scan=1"); TEST_EQUAL(s.empty(), false); TEST_EQUAL(s.size(), 19914); s = tmp.getSpectrumByNativeId("controllerType=0 controllerNumber=1 scan=2"); TEST_EQUAL(s.empty(), false); TEST_EQUAL(s.size(), 19800); TEST_EXCEPTION(Exception::IllegalArgument, tmp.getSpectrumByNativeId("TIK")) OnDiscPeakMap tmp2; tmp2.openFile(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML"), true); TEST_EQUAL(tmp2.empty(), false); s = tmp2.getSpectrumByNativeId("controllerType=0 controllerNumber=1 scan=1"); TEST_EQUAL(s.empty(), false); TEST_EQUAL(s.size(), 19914); TEST_EXCEPTION(Exception::IllegalArgument, tmp2.getSpectrumByNativeId("TIK")) } END_SECTION START_SECTION((PeakFileOptions& getOptions())) { OnDiscPeakMap tmp; PeakFileOptions& options = tmp.getOptions(); TEST_EQUAL(options.hasMZRange(), false); TEST_EQUAL(options.hasRTRange(), false); TEST_EQUAL(options.hasIntensityRange(), false); // Test that modifications persist options.setMZRange(DRange<1>(400.0, 600.0)); TEST_EQUAL(tmp.getOptions().hasMZRange(), true); TEST_REAL_SIMILAR(tmp.getOptions().getMZRange().minPosition()[0], 400.0); TEST_REAL_SIMILAR(tmp.getOptions().getMZRange().maxPosition()[0], 600.0); } END_SECTION START_SECTION((const PeakFileOptions& getOptions() const)) { OnDiscPeakMap tmp; tmp.getOptions().setMZRange(DRange<1>(400.0, 600.0)); const OnDiscPeakMap& const_tmp = tmp; const PeakFileOptions& options = const_tmp.getOptions(); TEST_EQUAL(options.hasMZRange(), true); TEST_REAL_SIMILAR(options.getMZRange().minPosition()[0], 400.0); } END_SECTION START_SECTION((void setOptions(const PeakFileOptions& options))) { OnDiscPeakMap tmp; PeakFileOptions options; options.setMZRange(DRange<1>(400.0, 600.0)); options.setIntensityRange(DRange<1>(100.0, 1000.0)); tmp.setOptions(options); TEST_EQUAL(tmp.getOptions().hasMZRange(), true); TEST_EQUAL(tmp.getOptions().hasIntensityRange(), true); TEST_REAL_SIMILAR(tmp.getOptions().getMZRange().minPosition()[0], 400.0); TEST_REAL_SIMILAR(tmp.getOptions().getIntensityRange().minPosition()[0], 100.0); } END_SECTION START_SECTION(([EXTRA] Test m/z range filtering on getSpectrum)) { OnDiscPeakMap tmp; tmp.openFile(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML")); // Get unfiltered spectrum first MSSpectrum s_unfiltered = tmp.getSpectrum(0); TEST_EQUAL(s_unfiltered.size(), 19914); // Now set m/z range filter and verify filtering works tmp.getOptions().setMZRange(DRange<1>(400.0, 600.0)); MSSpectrum s_filtered = tmp.getSpectrum(0); // Filtered spectrum should be smaller TEST_EQUAL(s_filtered.size() < s_unfiltered.size(), true); TEST_EQUAL(s_filtered.size() > 0, true); // All peaks should be within range for (const auto& peak : s_filtered) { TEST_EQUAL(peak.getMZ() >= 400.0, true); TEST_EQUAL(peak.getMZ() <= 600.0, true); } } END_SECTION START_SECTION(([EXTRA] Test intensity range filtering on getSpectrum)) { OnDiscPeakMap tmp; tmp.openFile(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML")); // Get unfiltered spectrum first MSSpectrum s_unfiltered = tmp.getSpectrum(0); Size unfiltered_size = s_unfiltered.size(); // Set intensity range filter tmp.getOptions().setIntensityRange(DRange<1>(1000.0, 1000000.0)); MSSpectrum s_filtered = tmp.getSpectrum(0); // Filtered spectrum should be smaller (fewer peaks above 1000 intensity) TEST_EQUAL(s_filtered.size() < unfiltered_size, true); // All peaks should be within intensity range for (const auto& peak : s_filtered) { TEST_EQUAL(peak.getIntensity() >= 1000.0, true); TEST_EQUAL(peak.getIntensity() <= 1000000.0, true); } } END_SECTION START_SECTION(([EXTRA] Test copy constructor copies options)) { OnDiscPeakMap tmp; tmp.getOptions().setMZRange(DRange<1>(400.0, 600.0)); tmp.openFile(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML")); OnDiscPeakMap tmp2(tmp); TEST_EQUAL(tmp2.getOptions().hasMZRange(), true); TEST_REAL_SIMILAR(tmp2.getOptions().getMZRange().minPosition()[0], 400.0); TEST_REAL_SIMILAR(tmp2.getOptions().getMZRange().maxPosition()[0], 600.0); } END_SECTION START_SECTION(([EXTRA] Test RT range filter skips loading peak data)) { OnDiscPeakMap tmp; tmp.openFile(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML")); // Get first spectrum to know its RT MSSpectrum s1 = tmp.getSpectrum(0); double rt = s1.getRT(); TEST_EQUAL(s1.size(), 19914); // has peaks // Now set RT range that excludes this spectrum tmp.getOptions().setRTRange(DRange<1>(rt + 1000, rt + 2000)); MSSpectrum s2 = tmp.getSpectrum(0); // Spectrum should have metadata but no peaks (filtered out, peaks not loaded) TEST_EQUAL(s2.empty(), true); // no peaks loaded TEST_REAL_SIMILAR(s2.getRT(), rt); // but metadata is preserved } END_SECTION START_SECTION(([EXTRA] Test MS level filter skips loading peak data)) { OnDiscPeakMap tmp; tmp.openFile(OPENMS_GET_TEST_DATA_PATH("IndexedmzMLFile_1.mzML")); // Get first spectrum info MSSpectrum s1 = tmp.getSpectrum(0); int ms_level = s1.getMSLevel(); TEST_EQUAL(s1.size(), 19914); // has peaks // Set MS level filter to exclude this spectrum's level std::vector<Int> levels; levels.push_back(ms_level + 1); // filter for a different MS level tmp.getOptions().setMSLevels(levels); MSSpectrum s2 = tmp.getSpectrum(0); // Spectrum should have metadata but no peaks (filtered out, peaks not loaded) TEST_EQUAL(s2.empty(), true); // no peaks loaded TEST_EQUAL(s2.getMSLevel(), ms_level); // but metadata is preserved } END_SECTION START_SECTION(([EXTRA] Test precursor m/z range filter skips loading peak data for MS2)) { OnDiscPeakMap tmp; tmp.openFile(OPENMS_GET_TEST_DATA_PATH("MzMLFile_4_indexed.mzML")); // File has 4 spectra: MS1 (index 0), MS2 (index 1 with precursor m/z 5.55), MS1 (index 2), MS1 (index 3) // Get MS2 spectrum (index 1) without filter MSSpectrum s1 = tmp.getSpectrum(1); TEST_EQUAL(s1.getMSLevel(), 2); Size unfiltered_size = s1.size(); TEST_EQUAL(unfiltered_size > 0, true); // Should have peaks // Get precursor m/z for verification TEST_EQUAL(s1.getPrecursors().empty(), false); double precursor_mz = s1.getPrecursors()[0].getMZ(); TEST_REAL_SIMILAR(precursor_mz, 5.55); // Verify expected precursor m/z // Set precursor m/z range that excludes this spectrum (range: 10.0 - 20.0) tmp.getOptions().setPrecursorMZRange(DRange<1>(10.0, 20.0)); MSSpectrum s2 = tmp.getSpectrum(1); // Spectrum should have metadata but no peaks (filtered out by precursor m/z) TEST_EQUAL(s2.empty(), true); // no peaks loaded TEST_EQUAL(s2.getMSLevel(), 2); // but metadata is preserved TEST_EQUAL(s2.getPrecursors().empty(), false); // precursor info is preserved // Set precursor m/z range that includes this spectrum (range: 5.0 - 6.0) tmp.getOptions().setPrecursorMZRange(DRange<1>(5.0, 6.0)); MSSpectrum s3 = tmp.getSpectrum(1); // Spectrum should have peaks (passes precursor m/z filter) TEST_EQUAL(s3.size(), unfiltered_size); // peaks loaded TEST_EQUAL(s3.getMSLevel(), 2); // MS1 spectra (index 0, 2, 3) should not be affected by precursor m/z filter MSSpectrum s_ms1 = tmp.getSpectrum(0); TEST_EQUAL(s_ms1.getMSLevel(), 1); TEST_EQUAL(s_ms1.size() > 0, true); // MS1 should still have peaks despite precursor filter } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/PepXMLFile_test.cpp
.cpp
21,934
502
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow, Hendrik Weisser $ // $Authors: Chris Bielow, Hendrik Weisser $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/FORMAT/PepXMLFile.h> #include <OpenMS/FORMAT/IdXMLFile.h> //ONLY used for checking if pepxml transformation produced a reusable id file /////////////////////////// #include <OpenMS/KERNEL/MSSpectrum.h> #include <OpenMS/KERNEL/MSExperiment.h> #include <OpenMS/CONCEPT/FuzzyStringComparator.h> #include <OpenMS/FORMAT/MzMLFile.h> #include <OpenMS/DATASTRUCTURES/ListUtilsIO.h> using namespace OpenMS; using namespace std; START_TEST(PepXMLFile, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// PepXMLFile * ptr = nullptr; PepXMLFile* nullPointer = nullptr; PepXMLFile file; START_SECTION(PepXMLFile()) ptr = new PepXMLFile(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION(~PepXMLFile()) delete ptr; END_SECTION START_SECTION(void load(const String& filename, std::vector<ProteinIdentification>& proteins, PeptideIdentificationList& peptides, const String& experiment_name, SpectrumMetaDataLookup& lookup)) { vector<ProteinIdentification> proteins; PeptideIdentificationList peptides; String pep_file = OPENMS_GET_TEST_DATA_PATH("PepXMLFile_test.pepxml"); String mz_file = OPENMS_GET_TEST_DATA_PATH("PepXMLFile_test.mzML"); String exp_name = "PepXMLFile_test"; PeakMap experiment; MzMLFile().load(mz_file, experiment); SpectrumMetaDataLookup lookup; lookup.readSpectra(experiment.getSpectra()); file.load(pep_file, proteins, peptides, exp_name, lookup); TEST_EQUAL(peptides.size(), 18); TEST_EQUAL(proteins.size(), 2); PeptideIdentification first = peptides[0]; TEST_REAL_SIMILAR(first.getRT(), 1.3653); TEST_REAL_SIMILAR(first.getMZ(), 538.605); // more checks below } END_SECTION START_SECTION(void load(const String& filename, std::vector<ProteinIdentification>& proteins, PeptideIdentificationList& peptides, const String& experiment_name = "")) { vector<ProteinIdentification> proteins; PeptideIdentificationList peptides; // file contains results from two search runs: String filename = OPENMS_GET_TEST_DATA_PATH("PepXMLFile_test.pepxml"); String exp_name = "PepXMLFile_test"; file.load(filename, proteins, peptides, exp_name); // peptide IDs: TEST_EQUAL(peptides.size(), 18); PeptideIdentification first = peptides.front(), last = peptides.back(); bool accu_result = true; // to avoid spamming TEST_EQUAL's in the "for" loop for (Size i = 1; i < 9; ++i) // should be the same for all peptides from the first search run: { accu_result &= (first.getIdentifier() == peptides[i].getIdentifier()); accu_result &= (first.getScoreType() == peptides[i].getScoreType()); accu_result &= (first.isHigherScoreBetter() == peptides[i].isHigherScoreBetter()); accu_result &= (first.getSignificanceThreshold() == peptides[i].getSignificanceThreshold()); } TEST_EQUAL(accu_result, true); TEST_REAL_SIMILAR(first.getRT(), 1.3653); // RT of MS2 spectrum TEST_REAL_SIMILAR(first.getMZ(), 538.605); // recomputed TEST_EQUAL(first.getHits().size(), 1); PeptideHit pep_hit = first.getHits()[0]; TEST_EQUAL(pep_hit.getSequence().toString(), ".(Glu->pyro-Glu)ELNKEMAAEKAKAAAG"); TEST_EQUAL(pep_hit.getSequence().toUnmodifiedString(), "ELNKEMAAEKAKAAAG"); TEST_EQUAL(pep_hit.getRank(), 0); // no use checking score, because implementation may still change TEST_EQUAL(pep_hit.getCharge(), 3); vector<PeptideEvidence> pes = pep_hit.getPeptideEvidences(); TEST_EQUAL(pes.size(), 3); TEST_EQUAL(pes[0].getProteinAccession(), "ddb000449223"); TEST_EQUAL(pes[0].getAABefore(), 'R'); TEST_EQUAL(pes[0].getAAAfter(), 'E'); TEST_EQUAL(first.getHits()[0].getSequence().isModified(), true); TEST_EQUAL(first.getHits()[0].getSequence().hasNTerminalModification(), true); TEST_EQUAL(first.getHits()[0].getSequence().hasCTerminalModification(), false); TEST_EQUAL(peptides[1].getHits()[0].getSequence().isModified(), true); TEST_EQUAL(peptides[1].getHits()[0].getSequence().hasNTerminalModification(), true); TEST_EQUAL(peptides[1].getHits()[0].getSequence().hasCTerminalModification(), false); TEST_EQUAL(peptides[5].getHits()[0].getSequence().isModified(), true); TEST_EQUAL(peptides[5].getHits()[0].getSequence().hasNTerminalModification(), false); TEST_EQUAL(peptides[5].getHits()[0].getSequence().hasCTerminalModification(), false); // cursory check of a peptide ID from the second search run: pep_hit = last.getHits()[0]; TEST_EQUAL(pep_hit.getSequence().toString(), "EISPDTTLLDLQNNDISELR"); // protein ID: TEST_EQUAL(proteins.size(), 2); TEST_EQUAL(proteins[0].getIdentifier(), first.getIdentifier()); TEST_EQUAL(proteins[1].getIdentifier(), last.getIdentifier()); TEST_NOT_EQUAL(proteins[0].getIdentifier(), ""); TEST_NOT_EQUAL(proteins[1].getIdentifier(), ""); TEST_NOT_EQUAL(proteins[0].getIdentifier(), proteins[1].getIdentifier()); TEST_EQUAL(proteins[0].getSearchEngine(), "X! Tandem (k-score)"); TEST_EQUAL(proteins[1].getSearchEngine(), "SEQUEST"); vector<ProteinHit> prot_hits = proteins[0].getHits(); TEST_EQUAL(prot_hits.size(), 20); StringList accessions_string; for (std::vector<ProteinHit>::iterator it = prot_hits.begin(); it != prot_hits.end(); ++it) { accessions_string << it->getAccession(); } // check a sample of the IDs that should be present: TEST_EQUAL(ListUtils::contains(accessions_string, "ddb000449223"), true); TEST_EQUAL(ListUtils::contains(accessions_string, "ddb000626346"), true); TEST_EQUAL(ListUtils::contains(accessions_string, "rev000409159"), true); // search parameters: ProteinIdentification::SearchParameters params = proteins[0].getSearchParameters(); TEST_EQUAL(params.db, "./current.fasta"); TEST_EQUAL(params.mass_type, ProteinIdentification::PeakMassType::MONOISOTOPIC); TEST_EQUAL(params.digestion_enzyme.getName(), "Trypsin"); vector<String> fix_mods(params.fixed_modifications), var_mods(params.variable_modifications); TEST_EQUAL(fix_mods.size(), 1) TEST_EQUAL(var_mods.size(), 12) TEST_EQUAL(var_mods[0], "Ammonia-loss (N-term C)") TEST_EQUAL(var_mods[1], "Glu->pyro-Glu (N-term E)") TEST_EQUAL(var_mods[2], "Oxidation (M)") TEST_EQUAL(var_mods[3], "Gln->pyro-Glu (N-term Q)") TEST_EQUAL(var_mods[4], "M[1.0]") TEST_EQUAL(var_mods[5], ".n[2.0]") TEST_EQUAL(var_mods[6], ".c[2.0]") TEST_EQUAL(var_mods[7], ".n[2.5]") TEST_EQUAL(var_mods[8], ".n[2.5]") TEST_EQUAL(var_mods[9], ".n[-2.5]") TEST_EQUAL(var_mods[10], ".n[2.5]") TEST_EQUAL(var_mods[11], ".c[3.4]") /* TODO Probably would be nicer to have the following as fullID for readability * (with the other notation you can't see if it has AA restrictions or if it is protein term) * Actually, I am not sure if you get problems, when you later search by fullID and * erroneously find the another modification with different AA specificity! * We could still use the above notation when writing it to a sequence in * bracket notation TEST_EQUAL(var_mods[4], "+1 (M)") TEST_EQUAL(var_mods[5], "+2 (N-term M)") TEST_EQUAL(var_mods[6], "+2 (Protein C-term L)") TEST_EQUAL(var_mods[7], "+2.5 (N-term)") TEST_EQUAL(var_mods[8], "+2.5 (Protein N-term)") TEST_EQUAL(var_mods[9], "-2.5 (N-term)") TEST_EQUAL(var_mods[10], "+2.5 (Protein N-term)") TEST_EQUAL(var_mods[11], "+3.4 (Protein C-term)") */ // wrong "experiment_name" produces an exception: TEST_EXCEPTION(Exception::ParseError, file.load(filename, proteins, peptides, "abcxyz")); // throw an exception if the pepXML file does not exist: TEST_EXCEPTION(Exception::FileNotFound, file.load("this_file_does_not_exist_but_should_be_a_pepXML_file.pepXML", proteins, peptides, exp_name)); } END_SECTION START_SECTION([EXTRA] void load(const String& filename, std::vector<ProteinIdentification>& proteins, PeptideIdentificationList& peptides, const String& experiment_name = "")) { vector<ProteinIdentification> proteins; PeptideIdentificationList peptides; // file contains results from two search runs: String filename = OPENMS_GET_TEST_DATA_PATH("PepXMLFile_test_extended.pepxml"); String exp_name = "PepXMLFile_test"; file.keepNativeSpectrumName(true); file.load(filename, proteins, peptides, exp_name); // peptide IDs: TEST_EQUAL(peptides.size(), 2); PeptideIdentification first = peptides.front(), last = peptides.back(); TEST_EQUAL(first.getRT(), 1.3653); // RT of MS2 spectrum TEST_REAL_SIMILAR(first.getMZ(), 538.605); // recomputed TEST_EQUAL(first.getHits().size(), 1); TEST_EQUAL(last.getRT(), 488.652); // RT of MS2 spectrum TEST_REAL_SIMILAR(last.getMZ(), 585.3166250319); // recomputed TEST_EQUAL(last.getHits().size(), 1); TEST_EQUAL(last.metaValueExists("swath_assay"), true); TEST_EQUAL(last.metaValueExists("status"), true); TEST_EQUAL(last.metaValueExists("pepxml_spectrum_name"), true); TEST_EQUAL(last.getExperimentLabel().empty(), false); TEST_EQUAL(last.getMetaValue("swath_assay"), "EIVLTQSPGTL2:9"); TEST_EQUAL(last.getMetaValue("status"), "target"); TEST_EQUAL(last.getMetaValue("pepxml_spectrum_name"), "hroest_K120718_SM_OGE10_010_IDA.02552.02552.2"); TEST_EQUAL(last.getExperimentLabel(), "urine"); PeptideHit pep_hit = last.getHits()[0]; TEST_EQUAL(pep_hit.getSequence().toString(), "VVITAPGGNDVK"); TEST_EQUAL(pep_hit.getSequence().toUnmodifiedString(), "VVITAPGGNDVK"); TEST_EQUAL(pep_hit.getRank(), 0); TEST_EQUAL(pep_hit.getCharge(), 2); // check the analysis scores TEST_EQUAL(pep_hit.getAnalysisResults().size(), 2); PeptideHit::PepXMLAnalysisResult a = pep_hit.getAnalysisResults()[0]; TEST_EQUAL(a.score_type, "peptideprophet"); TEST_REAL_SIMILAR(a.main_score, 0.0660); TEST_EQUAL(a.sub_scores.find("fval") != a.sub_scores.end(), true); TEST_EQUAL(a.sub_scores.find("ntt") != a.sub_scores.end(), true); TEST_EQUAL(a.sub_scores.find("empir_irt") != a.sub_scores.end(), true); TEST_EQUAL(a.sub_scores.find("swath_window") != a.sub_scores.end(), true); TEST_REAL_SIMILAR(a.sub_scores.find("fval")->second, 0.7114); TEST_REAL_SIMILAR(a.sub_scores.find("ntt")->second, 2); TEST_REAL_SIMILAR(a.sub_scores.find("empir_irt")->second, 79.79); TEST_REAL_SIMILAR(a.sub_scores.find("swath_window")->second, 9); // <analysis_result analysis="peptideprophet"> // <peptideprophet_result probability="0.0660" all_ntt_prob="(0.0000,0.0000,0.0660)"> // <search_score_summary> // <parameter name="fval" value="0.7114"/> // <parameter name="ntt" value="2"/> // <parameter name="nmc" value="0"/> // <parameter name="massd" value="-0.027"/> // <parameter name="isomassd" value="0"/> // <parameter name="empir_irt" value="79.79"/> // <parameter name="empir_irt_bin" value="53"/> // <parameter name="swath_window" value="9"/> // <parameter name="alt_swath" value="-1"/> // </search_score_summary> // </peptideprophet_result> // </analysis_result> // <analysis_result analysis="interprophet"> // <interprophet_result probability="0.93814" all_ntt_prob="(0,0,0.93814)"> // <search_score_summary> // <parameter name="nss" value="0"/> // <parameter name="nrs" value="10.2137"/> // <parameter name="nse" value="0"/> // <parameter name="nsi" value="0.9793"/> // <parameter name="nsm" value="0"/> // </search_score_summary> // </interprophet_result> // </analysis_result> a = pep_hit.getAnalysisResults()[1]; TEST_EQUAL(a.score_type, "interprophet"); TEST_REAL_SIMILAR(a.main_score, 0.93814); TEST_EQUAL(a.sub_scores.find("fval") == a.sub_scores.end(), true); TEST_EQUAL(a.sub_scores.find("nss") != a.sub_scores.end(), true); TEST_REAL_SIMILAR(a.sub_scores.find("nrs")->second, 10.2137); // wrong "experiment_name" produces an exception: TEST_EXCEPTION(Exception::ParseError, file.load(filename, proteins, peptides, "abcxyz")); // throw an exception if the pepXML file does not exist: TEST_EXCEPTION(Exception::FileNotFound, file.load("this_file_does_not_exist_but_should_be_a_pepXML_file.pepXML", proteins, peptides, exp_name)); } END_SECTION START_SECTION(void store(const String& filename, std::vector<ProteinIdentification>& protein_ids, PeptideIdentificationList& peptide_ids, const String& mz_file = "", const String& mz_name = "", bool peptideprophet_analyzed = false)) { vector<ProteinIdentification> proteins; PeptideIdentificationList peptides; String filename = OPENMS_GET_TEST_DATA_PATH("PepXMLFile_test_store.pepxml"); PepXMLFile().load(filename, proteins, peptides); // Test PeptideProphet-analyzed pepxml. String cm_file_out; NEW_TMP_FILE(cm_file_out); PepXMLFile().store(cm_file_out, proteins, peptides, "", "test", true); FuzzyStringComparator fsc; fsc.setAcceptableAbsolute(1e-7); fsc.setAcceptableRelative(1.0 + 1e-7); // fsc.setWhitelist (ListUtils::create<String>("base_name, local_path, <spectrum_query ")); String filename_out = OPENMS_GET_TEST_DATA_PATH("PepXMLFile_test_out.pepxml"); TEST_EQUAL(fsc.compareFiles(cm_file_out.c_str(), filename_out.c_str()), true) // Test raw_pepxml storage. String cm_file_out_1; NEW_TMP_FILE(cm_file_out_1); PepXMLFile().store(cm_file_out_1, proteins, peptides, "", "test", false); FuzzyStringComparator fsc_1; fsc_1.setAcceptableAbsolute(1e-7); fsc_1.setAcceptableRelative(1.0 + 1e-7); // fsc_1.setWhitelist(ListUtils::create<String>("base_name, local_path, <spectrum_query ")); String filename_out_1 = OPENMS_GET_TEST_DATA_PATH("PepXMLFile_test_out_1.pepxml"); TEST_EQUAL(fsc_1.compareFiles(cm_file_out_1.c_str(), filename_out_1.c_str()), true) } END_SECTION START_SECTION([EXTRA] void store(const String& filename, std::vector<ProteinIdentification>& protein_ids, PeptideIdentificationList& peptide_ids, const String& mz_file = "", const String& mz_name = "", bool peptideprophet_analyzed = false)) { { vector<ProteinIdentification> proteins; PeptideIdentificationList peptides; // file contains results from two search runs: String filename = OPENMS_GET_TEST_DATA_PATH("PepXMLFile_test_extended.pepxml"); String exp_name = "PepXMLFile_test"; PepXMLFile file; file.keepNativeSpectrumName(true); file.load(filename, proteins, peptides, exp_name); TEST_EQUAL(peptides.size(), 2); PeptideIdentification first = peptides.front(), last = peptides.back(); TEST_REAL_SIMILAR(first.getMZ(), 538.605); // recomputed TEST_REAL_SIMILAR(last.getMZ(), 585.3166250319); // recomputed // Now try to store the file again ... String cm_file_out; NEW_TMP_FILE(cm_file_out); file.store(cm_file_out, proteins, peptides, "", exp_name, false); // peptideprophet_analyzed = false is important! // And read it back in again vector<ProteinIdentification> proteins_new; PeptideIdentificationList peptides_new; file.load(cm_file_out, proteins_new, peptides_new, exp_name); TEST_EQUAL(proteins.size(), proteins_new.size()) TEST_EQUAL(peptides.size(), peptides_new.size()) // peptide IDs: TEST_EQUAL(peptides_new.size(), 2); first = peptides_new.front(); last = peptides_new.back(); TEST_EQUAL(first.getRT(), 1.3653); // RT of MS2 spectrum TEST_REAL_SIMILAR(first.getMZ(), 538.6159248633); // recomputed TEST_EQUAL(first.getHits().size(), 1); TEST_EQUAL(last.getRT(), 488.652); // RT of MS2 spectrum TEST_REAL_SIMILAR(last.getMZ(), 585.3304219355); // recomputed TEST_EQUAL(last.getHits().size(), 1); PeptideHit pep_hit = last.getHits()[0]; TEST_EQUAL(pep_hit.getSequence().toString(), "VVITAPGGNDVK"); TEST_EQUAL(pep_hit.getSequence().toUnmodifiedString(), "VVITAPGGNDVK"); TEST_EQUAL(pep_hit.getRank(), 0); TEST_EQUAL(pep_hit.getCharge(), 2); // test extra attributes (correctly read and written) TEST_EQUAL(last.metaValueExists("swath_assay"), true); TEST_EQUAL(last.metaValueExists("status"), true); TEST_EQUAL(last.metaValueExists("pepxml_spectrum_name"), true); TEST_EQUAL(last.getExperimentLabel().empty(), false); TEST_EQUAL(last.getMetaValue("swath_assay"), "EIVLTQSPGTL2:9"); TEST_EQUAL(last.getMetaValue("status"), "target"); TEST_EQUAL(last.getMetaValue("pepxml_spectrum_name"), "hroest_K120718_SM_OGE10_010_IDA.02552.02552.22"); TEST_EQUAL(last.getMetaValue("pepxml_spectrum_name") == "hroest_K120718_SM_OGE10_010_IDA.02552.02552.22", true); TEST_EQUAL(last.getExperimentLabel(), "urine"); // check the analysis scores TEST_EQUAL(pep_hit.getAnalysisResults().size(), 2); PeptideHit::PepXMLAnalysisResult a = pep_hit.getAnalysisResults()[0]; TEST_EQUAL(a.score_type, "peptideprophet"); TEST_REAL_SIMILAR(a.main_score, 0.0660); TEST_EQUAL(a.sub_scores.find("fval") != a.sub_scores.end(), true); TEST_EQUAL(a.sub_scores.find("ntt") != a.sub_scores.end(), true); TEST_EQUAL(a.sub_scores.find("empir_irt") != a.sub_scores.end(), true); TEST_EQUAL(a.sub_scores.find("swath_window") != a.sub_scores.end(), true); TEST_REAL_SIMILAR(a.sub_scores.find("fval")->second, 0.7114); TEST_REAL_SIMILAR(a.sub_scores.find("ntt")->second, 2); TEST_REAL_SIMILAR(a.sub_scores.find("empir_irt")->second, 79.79); TEST_REAL_SIMILAR(a.sub_scores.find("swath_window")->second, 9); } // test keep native spectrum name = false { vector<ProteinIdentification> proteins; PeptideIdentificationList peptides; String filename = OPENMS_GET_TEST_DATA_PATH("PepXMLFile_test_extended.pepxml"); String exp_name = "PepXMLFile_test"; PepXMLFile file; file.keepNativeSpectrumName(false); file.load(filename, proteins, peptides, exp_name); // Now try to store the file again ... String cm_file_out; NEW_TMP_FILE(cm_file_out); file.store(cm_file_out, proteins, peptides, "", exp_name, false); // peptideprophet_analyzed = false is important! // And read it back in again vector<ProteinIdentification> proteins_new; PeptideIdentificationList peptides_new; file.load(cm_file_out, proteins_new, peptides_new, exp_name); // peptide IDs: PeptideIdentification last = peptides.back(); // now this should be fales TEST_EQUAL(last.getMetaValue("pepxml_spectrum_name") != "hroest_K120718_SM_OGE10_010_IDA.02552.02552.22", true); } } END_SECTION // store PepXML with mzML file information START_SECTION(void store(const String& filename, std::vector<ProteinIdentification>& protein_ids, PeptideIdentificationList& peptide_ids, const String& mz_file = "PepXMLFile_test.mzML", const String& mz_name = "", bool peptideprophet_analyzed = false)) { vector<ProteinIdentification> proteins; PeptideIdentificationList peptides; String mzML_filename = OPENMS_GET_TEST_DATA_PATH("PepXMLFile_test.mzML"); String filename = OPENMS_GET_TEST_DATA_PATH("PepXMLFile_test_store.pepxml"); PepXMLFile().load(filename, proteins, peptides); // Test PeptideProphet-analyzed pepxml. String cm_file_out; NEW_TMP_FILE(cm_file_out); PepXMLFile().store(cm_file_out, proteins, peptides, mzML_filename, "test", true); FuzzyStringComparator fsc; fsc.setAcceptableAbsolute(1e-7); fsc.setAcceptableRelative(1.0 + 1e-7); // fsc.setWhitelist (ListUtils::create<String>("base_name, local_path, <spectrum_query ")); String filename_out = OPENMS_GET_TEST_DATA_PATH("PepXMLFile_test_out_mzML.pepxml"); TEST_EQUAL(fsc.compareFiles(cm_file_out.c_str(), filename_out.c_str()), true) } END_SECTION START_SECTION(void keepNativeSpectrumName(bool keep) ) { // tested above in the [EXTRA] store as we store / load once with // keepNativeSpectrumName and once without NOT_TESTABLE } END_SECTION START_SECTION(([EXTRA] checking pepxml transformation to reusable identifications)) // PepXMLFile file; // shadow vector<ProteinIdentification> proteins, reread_proteins; PeptideIdentificationList peptides, reread_peptides; String filename = OPENMS_GET_TEST_DATA_PATH("PepXMLFile_test_store.pepxml"); PepXMLFile().load(filename, proteins, peptides); // Test PeptideProphet-analyzed pepxml. String cm_file_out; NEW_TMP_FILE(cm_file_out); IdXMLFile().store(cm_file_out, proteins, peptides); IdXMLFile().load(cm_file_out, reread_proteins, reread_peptides); ProteinIdentification::SearchParameters params = proteins[0].getSearchParameters(); ProteinIdentification::SearchParameters reread_params = reread_proteins[0].getSearchParameters(); TEST_EQUAL(params.db, reread_params.db); TEST_EQUAL(params.mass_type, reread_params.mass_type); vector<String> fix_mods(params.fixed_modifications), var_mods(params.variable_modifications); vector<String> reread_fix_mods(reread_params.fixed_modifications), reread_var_mods(reread_params.variable_modifications); TEST_EQUAL(fix_mods.size(), reread_fix_mods.size()) TEST_EQUAL(var_mods.size(), reread_var_mods.size()) TEST_EQUAL(find(fix_mods.begin(), fix_mods.end(), reread_fix_mods[0]) != fix_mods.end(), true) TEST_EQUAL(find(fix_mods.begin(), fix_mods.end(), "Carbamidomethyl (C)") != fix_mods.end(), true) for (size_t i = 0; i < reread_var_mods.size(); ++i) { TEST_EQUAL(find(var_mods.begin(), var_mods.end(), reread_var_mods[i]) != var_mods.end(), true) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ProteaseDigestion_test.cpp
.cpp
43,865
717
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow $ // $Authors: Marc Sturm, Chris Bielow, Jeremi Maciejewski $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/CHEMISTRY/ProteaseDigestion.h> #include <vector> #include <algorithm> using namespace OpenMS; using namespace std; /////////////////////////// START_TEST(ProteaseDigestion, "$Id$") ///////////////////////////////////////////////////////////// ProteaseDigestion* pd_ptr = nullptr; ProteaseDigestion* pd_null = nullptr; START_SECTION(([EXTRA] ProteaseDigestion())) pd_ptr = new ProteaseDigestion; TEST_NOT_EQUAL(pd_ptr, pd_null) END_SECTION START_SECTION([EXTRA] ~ProteaseDigestion()) delete pd_ptr; END_SECTION START_SECTION(([EXTRA] ProteaseDigestion(const ProteaseDigestion& rhs))) ProteaseDigestion pd; pd.setMissedCleavages(1234); pd.setEnzyme("no cleavage"); pd.setSpecificity(EnzymaticDigestion::SPEC_SEMI); ProteaseDigestion pd2(pd); TEST_EQUAL(pd.getMissedCleavages(), pd2.getMissedCleavages()); TEST_EQUAL(pd.getEnzymeName(), pd2.getEnzymeName()); TEST_EQUAL(pd.getSpecificity(), pd2.getSpecificity()); END_SECTION START_SECTION(([EXTRA] ProteaseDigestion& operator=(const ProteaseDigestion& rhs))) ProteaseDigestion pd; pd.setMissedCleavages(1234); pd.setEnzyme("no cleavage"); pd.setSpecificity(EnzymaticDigestion::SPEC_SEMI); ProteaseDigestion pd2; pd2 = pd; TEST_EQUAL(pd.getMissedCleavages(), pd2.getMissedCleavages()); TEST_EQUAL(pd.getEnzymeName(), pd2.getEnzymeName()); TEST_EQUAL(pd.getSpecificity(), pd2.getSpecificity()); END_SECTION START_SECTION((void setEnzyme(const String& enzyme_name))) ProteaseDigestion pd; pd.setEnzyme("Trypsin"); TEST_EQUAL(pd.getEnzymeName(), "Trypsin"); pd.setEnzyme("Trypsin/P"); TEST_EQUAL(pd.getEnzymeName(), "Trypsin/P"); END_SECTION START_SECTION((Size peptideCount(const AASequence& protein))) ProteaseDigestion pd; for (int i = 0; i < 2; ++i) // common cases for Trypsin and Trypsin_P { if (i == 0) { pd.setEnzyme("Trypsin"); } else if (i == 1) { pd.setEnzyme("Trypsin/P"); } pd.setMissedCleavages(0); TEST_EQUAL(pd.peptideCount(AASequence::fromString("ACDE")), 1) TEST_EQUAL(pd.peptideCount(AASequence::fromString("ACKDE")), 2) TEST_EQUAL(pd.peptideCount(AASequence::fromString("ACRDE")), 2) TEST_EQUAL(pd.peptideCount(AASequence::fromString("ARCRDRE")), 4) TEST_EQUAL(pd.peptideCount(AASequence::fromString("RKR")), 3) pd.setMissedCleavages(1); TEST_EQUAL(pd.peptideCount(AASequence::fromString("ACDE")), 1) TEST_EQUAL(pd.peptideCount(AASequence::fromString("ACRDE")), 3) TEST_EQUAL(pd.peptideCount(AASequence::fromString("ARCDRE")), 5) TEST_EQUAL(pd.peptideCount(AASequence::fromString("RKR")), 5) pd.setMissedCleavages(3); TEST_EQUAL(pd.peptideCount(AASequence::fromString("ACDE")), 1) TEST_EQUAL(pd.peptideCount(AASequence::fromString("ACRDE")), 3) TEST_EQUAL(pd.peptideCount(AASequence::fromString("ARCDRE")), 6) TEST_EQUAL(pd.peptideCount(AASequence::fromString("RKR")), 6) } // special cases: pd.setMissedCleavages(0); pd.setEnzyme("Trypsin"); TEST_EQUAL(pd.peptideCount(AASequence::fromString("ACKPDE")), 1) TEST_EQUAL(pd.peptideCount(AASequence::fromString("ACRPDE")), 1) TEST_EQUAL(pd.peptideCount(AASequence::fromString("ACKPDERA")), 2) TEST_EQUAL(pd.peptideCount(AASequence::fromString("ACRPDEKA")), 2) pd.setEnzyme("Trypsin/P"); TEST_EQUAL(pd.peptideCount(AASequence::fromString("ACKPDE")), 2) TEST_EQUAL(pd.peptideCount(AASequence::fromString("ACRPDE")), 2) TEST_EQUAL(pd.peptideCount(AASequence::fromString("ACKPDERA")), 3) TEST_EQUAL(pd.peptideCount(AASequence::fromString("ACRPDEKA")), 3) END_SECTION START_SECTION((Size digest(const AASequence& protein, std::vector<AASequence>& output, Size min_length = 1, Size max_length = 0) const)) ProteaseDigestion pd; vector<AASequence> out; pd.digest(AASequence::fromString("ACDE"), out); TEST_EQUAL(out.size(), 1) TEST_EQUAL(out[0].toString(), "ACDE") pd.digest(AASequence::fromString("ACKDE"), out); TEST_EQUAL(out.size(), 2) TEST_EQUAL(out[0].toString(), "ACK") TEST_EQUAL(out[1].toString(), "DE") pd.digest(AASequence::fromString("ACRDE"), out); TEST_EQUAL(out.size(), 2) TEST_EQUAL(out[0].toString(), "ACR") TEST_EQUAL(out[1].toString(), "DE") pd.digest(AASequence::fromString("ACKPDE"), out); TEST_EQUAL(out.size(), 1) TEST_EQUAL(out[0].toString(), "ACKPDE") pd.digest(AASequence::fromString("ACRPDE"), out); TEST_EQUAL(out.size(), 1) TEST_EQUAL(out[0].toString(), "ACRPDE") pd.digest(AASequence::fromString("ARCRDRE"), out); TEST_EQUAL(out.size(), 4) TEST_EQUAL(out[0].toString(), "AR") TEST_EQUAL(out[1].toString(), "CR") TEST_EQUAL(out[2].toString(), "DR") TEST_EQUAL(out[3].toString(), "E") pd.digest(AASequence::fromString("RKR"), out); TEST_EQUAL(out.size(), 3) TEST_EQUAL(out[0].toString(), "R") TEST_EQUAL(out[1].toString(), "K") TEST_EQUAL(out[2].toString(), "R") pd.setMissedCleavages(1); pd.digest(AASequence::fromString("ACDE"), out); TEST_EQUAL(out.size(), 1) TEST_EQUAL(out[0].toString(), "ACDE") pd.digest(AASequence::fromString("ACRDE"), out); TEST_EQUAL(out.size(), 3) TEST_EQUAL(out[0].toString(), "ACR") TEST_EQUAL(out[1].toString(), "DE") TEST_EQUAL(out[2].toString(), "ACRDE") pd.digest(AASequence::fromString("ARCDRE"), out); TEST_EQUAL(out.size(), 5) TEST_EQUAL(out[0].toString(), "AR") TEST_EQUAL(out[1].toString(), "CDR") TEST_EQUAL(out[2].toString(), "E") TEST_EQUAL(out[3].toString(), "ARCDR") TEST_EQUAL(out[4].toString(), "CDRE") Size discarded = pd.digest(AASequence::fromString("ARCDRE"), out, 3, 4); TEST_EQUAL(out.size(), 2) TEST_EQUAL(out[0].toString(), "CDR") TEST_EQUAL(out[1].toString(), "CDRE") TEST_EQUAL(discarded, 3) pd.digest(AASequence::fromString("RKR"), out); TEST_EQUAL(out.size(), 5) TEST_EQUAL(out[0].toString(), "R") TEST_EQUAL(out[1].toString(), "K") TEST_EQUAL(out[2].toString(), "R") TEST_EQUAL(out[3].toString(), "RK") TEST_EQUAL(out[4].toString(), "KR") pd.digest(AASequence::fromString("(ICPL:2H(4))ARCDRE"), out); TEST_EQUAL(out.size(), 5) TEST_EQUAL(out[0].toString(), ".(ICPL:2H(4))AR") TEST_EQUAL(out[1].toString(), "CDR") TEST_EQUAL(out[2].toString(), "E") TEST_EQUAL(out[3].toString(), ".(ICPL:2H(4))ARCDR") TEST_EQUAL(out[4].toString(), "CDRE") pd.digest(AASequence::fromString("ARCDRE.(Amidated)"), out); TEST_EQUAL(out.size(), 5) TEST_EQUAL(out[0].toString(), "AR") TEST_EQUAL(out[1].toString(), "CDR") TEST_EQUAL(out[2].toString(), "E.(Amidated)") TEST_EQUAL(out[3].toString(), "ARCDR") TEST_EQUAL(out[4].toString(), "CDRE.(Amidated)") discarded = pd.digest(AASequence::fromString("ARCDRE.(Amidated)"), out, 3, 4); TEST_EQUAL(out.size(), 2) TEST_EQUAL(out[0].toString(), "CDR") TEST_EQUAL(out[1].toString(), "CDRE.(Amidated)") TEST_EQUAL(discarded, 3) // ------------------------ // Trypsin/P // ------------------------ pd.setMissedCleavages(0); pd.setEnzyme("Trypsin/P"); pd.digest(AASequence::fromString("ACKPDE"), out); TEST_EQUAL(out.size(), 2) TEST_EQUAL(out[0].toString(), "ACK") TEST_EQUAL(out[1].toString(), "PDE") pd.digest(AASequence::fromString("ACRPDE"), out); TEST_EQUAL(out.size(), 2) TEST_EQUAL(out[0].toString(), "ACR") TEST_EQUAL(out[1].toString(), "PDE") // ------------------------ // unspecific cleavage // ------------------------ pd.setEnzyme("unspecific cleavage"); pd.digest(AASequence::fromString("ABCDEFGHIJ"), out); TEST_EQUAL(out.size(), 11*10/2) pd.digest(AASequence::fromString("ABC"), out); TEST_EQUAL(out.size(), 4*3/2) // ------------------------ // semi-specific digestion // ------------------------ pd.setSpecificity(pd.SPEC_SEMI); // Lambda to allow searching 'out' with std::find_if() std::string ref = ""; auto compare_aa = [&ref](const AASequence& seq) -> bool { return seq.toUnmodifiedString() == ref; }; // Make sure unspecific cleavage still works pd.setEnzyme("unspecific cleavage"); pd.digest(AASequence::fromString("ABCDEFGHIJ"), out); TEST_EQUAL(out.size(), 11*10/2); pd.digest(AASequence::fromString("ABC"), out); TEST_EQUAL(out.size(), 4*3/2); pd.setEnzyme("Trypsin/P"); pd.digest(AASequence::fromString("AGLRMHP"), out); // AGLR, MHP, GLR, MH, LR, M, R, AGL, HP, AG, P, A TEST_EQUAL(out.size(), 12); // Assumes output is sorted as: fully-specific -> missed clv -> semi-specific // Are fully-specific variants still here? TEST_EQUAL(out[0].toString(), "AGLR"); TEST_EQUAL(out[1].toString(), "MHP"); // Are there semi-specific variants? ref = "AGL"; TEST_TRUE(std::find_if(out.begin(),out.end(),compare_aa) != out.end()); ref = "HP"; TEST_TRUE(std::find_if(out.begin(),out.end(),compare_aa) != out.end()); // Make sure cleavage sites are iterated over in right order. // (forward for N-terminus cleavage, backwards for C-terminus cleavage) ref = "GLRMHP"; TEST_FALSE(std::find_if(out.begin(),out.end(),compare_aa) != out.end()); ref = "AGLRMH"; TEST_FALSE(std::find_if(out.begin(),out.end(),compare_aa) != out.end()); // Test if it works with missed cleavages pd.setMissedCleavages(2); pd.digest(AASequence::fromString("AGLRMHPQGHKWYV"), out); ref = "AGLRMHPQGHKW"; TEST_TRUE(std::find_if(out.begin(),out.end(),compare_aa) != out.end()); ref = "GHKWYV"; TEST_TRUE(std::find_if(out.begin(),out.end(),compare_aa) != out.end()); ref = "A"; TEST_TRUE(std::find_if(out.begin(),out.end(),compare_aa) != out.end()); // Test if it works with protein without internal cleavage sites pd.setMissedCleavages(1); pd.digest(AASequence::fromString("AHLW"), out); TEST_EQUAL(out.size(), 7); // AHLW, HLW, AHL, LW, AH, W, A // Test if min_size and max_size apply to semi-specific products discarded = pd.digest(AASequence::fromString("AGLRMHP"), out, 2); TEST_EQUAL(discarded, 4); // A, R, P, M pd.digest(AASequence::fromString("AGLRMHPQGHKWYV"), out, 3, 10); ref = "AG"; TEST_FALSE(std::find_if(out.begin(),out.end(),compare_aa) != out.end()); ref = "AGLRMHPQGHKW"; TEST_FALSE(std::find_if(out.begin(),out.end(),compare_aa) != out.end()); // ------------------------ // Exceptions // ------------------------ pd.setSpecificity(pd.SIZE_OF_SPECIFICITY); TEST_EXCEPTION_WITH_MESSAGE(Exception::InvalidValue, pd.digest(AASequence::fromString("ABCDEF"), out), "the value '10' was used but is not valid; Specificity value set on current ProteaseDigestion object is not supported by ProteaseDigestion::digest()."); END_SECTION START_SECTION((bool isValidProduct(const String& protein, int pep_pos, int pep_length, bool ignore_missed_cleavages, bool allow_nterm_protein_cleavage, bool allow_random_asp_pro_cleavage))) NOT_TESTABLE // tested by overload below END_SECTION START_SECTION((bool isValidProduct(const AASequence& protein, int pep_pos, int pep_length, bool ignore_missed_cleavages, bool allow_nterm_protein_cleavage, bool allow_random_asp_pro_cleavage))) ProteaseDigestion pd; pd.setEnzyme("Trypsin"); pd.setSpecificity(EnzymaticDigestion::SPEC_FULL); // require both sides AASequence prot = AASequence::fromString("ABCDEFGKABCRAAAKAARPBBBB"); TEST_EQUAL(pd.isValidProduct(prot, 100, 3), false); // invalid position TEST_EQUAL(pd.isValidProduct(prot, 10, 300), false); // invalid length TEST_EQUAL(pd.isValidProduct(prot, 10, 0), false); // invalid size TEST_EQUAL(pd.isValidProduct(AASequence::fromString(""), 10, 0), false); // invalid size TEST_EQUAL(pd.isValidProduct(prot, 0, 3), false); // invalid N-term TEST_EQUAL(pd.isValidProduct(prot, 0, 8), true); // valid N-term TEST_EQUAL(pd.isValidProduct(prot, 8, 4), true); // valid fully-tryptic TEST_EQUAL(pd.isValidProduct(prot, 8, 8), true); // valid fully-tryptic TEST_EQUAL(pd.isValidProduct(prot, 0, 19), false); // invalid C-term - followed by proline TEST_EQUAL(pd.isValidProduct(prot, 8, 3), false); // invalid C-term TEST_EQUAL(pd.isValidProduct(prot, 3, 6), false); // invalid C+N-term TEST_EQUAL(pd.isValidProduct(prot, 1, 7), false); // invalid N-term TEST_EQUAL(pd.isValidProduct(prot, 0, prot.size()), true); // the whole thing prot = AASequence::fromString("MBCDEFGKABCRAAAKAA"); // starts with Met - we assume the cleaved form without Met occurs in vivo TEST_EQUAL(pd.isValidProduct(prot, 1, 7, true, true), true); // valid N-term (since protein starts with Met) TEST_EQUAL(pd.isValidProduct(prot, 2, 6, true, true), true); // valid N-term (since protein starts with Met and second AA maybe cleaved in XTandem) TEST_EQUAL(pd.isValidProduct(prot, 1, 7, true, false), false); // invalid N-term (since Met cleavage is not allowed.) TEST_EQUAL(pd.isValidProduct(prot, 2, 6, true, false), false); // invalid N-term (since Met cleavage is not allowed.) TEST_EQUAL(pd.isValidProduct(prot, 0, prot.size()), true); // the whole thing //################################################ // same as above, just with other specificity pd.setSpecificity(EnzymaticDigestion::SPEC_SEMI); // require one special cleavage site prot = AASequence::fromString("ABCDEFGKABCRAAAKAARPBBBB"); TEST_EQUAL(pd.isValidProduct(prot, 100, 3), false); // invalid position TEST_EQUAL(pd.isValidProduct(prot, 10, 300), false); // invalid length TEST_EQUAL(pd.isValidProduct(prot, 10, 0), false); // invalid size TEST_EQUAL(pd.isValidProduct(AASequence::fromString(""), 10, 0), false); // invalid size TEST_EQUAL(pd.isValidProduct(prot, 0, 3), true); // invalid N-term TEST_EQUAL(pd.isValidProduct(prot, 0, 8), true); // valid N-term TEST_EQUAL(pd.isValidProduct(prot, 8, 4), true); // valid fully-tryptic TEST_EQUAL(pd.isValidProduct(prot, 8, 8), true); // valid fully-tryptic TEST_EQUAL(pd.isValidProduct(prot, 0, 19), true); // invalid C-term - followed by proline TEST_EQUAL(pd.isValidProduct(prot, 8, 3), true); // invalid C-term TEST_EQUAL(pd.isValidProduct(prot, 3, 6), false); // invalid C+N-term TEST_EQUAL(pd.isValidProduct(prot, 1, 7), true); // invalid N-term TEST_EQUAL(pd.isValidProduct(prot, 0, prot.size()), true); // the whole thing prot = AASequence::fromString("MBCDEFGKABCRAAAKAA"); // starts with Met - we assume the cleaved form without Met occurs in vivo TEST_EQUAL(pd.isValidProduct(prot, 1, 7, true, true), true); // valid N-term (since protein starts with Met) TEST_EQUAL(pd.isValidProduct(prot, 2, 6, true, true), true); // valid N-term (since protein starts with Met and second AA maybe cleaved in XTandem) TEST_EQUAL(pd.isValidProduct(prot, 1, 7, true, false), true); // invalid N-term (since Met cleavage is not allowed.) TEST_EQUAL(pd.isValidProduct(prot, 2, 6, true, false), true); // invalid N-term (since Met cleavage is not allowed.) TEST_EQUAL(pd.isValidProduct(prot, 0, prot.size()), true); // the whole thing //################################################ // same as above, just with other specificity pd.setSpecificity(EnzymaticDigestion::SPEC_NONE); // require no special cleavage site prot = AASequence::fromString("ABCDEFGKABCRAAAKAARPBBBB"); TEST_EQUAL(pd.isValidProduct(prot, 100, 3), false); // invalid position TEST_EQUAL(pd.isValidProduct(prot, 10, 300), false); // invalid length TEST_EQUAL(pd.isValidProduct(prot, 10, 0), false); // invalid size TEST_EQUAL(pd.isValidProduct(AASequence::fromString(""), 10, 0), false); // invalid size TEST_EQUAL(pd.isValidProduct(prot, 0, 3), true); // invalid N-term TEST_EQUAL(pd.isValidProduct(prot, 0, 8), true); // valid N-term TEST_EQUAL(pd.isValidProduct(prot, 8, 4), true); // valid fully-tryptic TEST_EQUAL(pd.isValidProduct(prot, 8, 8), true); // valid fully-tryptic TEST_EQUAL(pd.isValidProduct(prot, 0, 19), true); // invalid C-term - followed by proline TEST_EQUAL(pd.isValidProduct(prot, 8, 3), true); // invalid C-term TEST_EQUAL(pd.isValidProduct(prot, 3, 6), true); // invalid C+N-term TEST_EQUAL(pd.isValidProduct(prot, 1, 7), true); // invalid N-term TEST_EQUAL(pd.isValidProduct(prot, 0, prot.size()), true); // the whole thing // ------------------------ // Trypsin/P // ------------------------ pd.setEnzyme("Trypsin/P"); pd.setSpecificity(EnzymaticDigestion::SPEC_FULL); // require both sides prot = AASequence::fromString("ABCDEFGKABCRAAAKAARPBBBB"); TEST_EQUAL(pd.isValidProduct(prot, 100, 3), false); // invalid position TEST_EQUAL(pd.isValidProduct(prot, 10, 300), false); // invalid length TEST_EQUAL(pd.isValidProduct(prot, 10, 0), false); // invalid size TEST_EQUAL(pd.isValidProduct(AASequence::fromString(""), 10, 0), false); // invalid size TEST_EQUAL(pd.isValidProduct(prot, 0, 3), false); // invalid N-term TEST_EQUAL(pd.isValidProduct(prot, 0, 8), true); // valid N-term TEST_EQUAL(pd.isValidProduct(prot, 8, 4), true); // valid fully-tryptic TEST_EQUAL(pd.isValidProduct(prot, 8, 8), true); // valid fully-tryptic TEST_EQUAL(pd.isValidProduct(prot, 0, 19), true); // valid C-term - followed by proline TEST_EQUAL(pd.isValidProduct(prot, 8, 3), false); // invalid C-term TEST_EQUAL(pd.isValidProduct(prot, 3, 6), false); // invalid C+N-term TEST_EQUAL(pd.isValidProduct(prot, 1, 7), false); // invalid N-term TEST_EQUAL(pd.isValidProduct(prot, 0, prot.size()), true); // the whole thing prot = AASequence::fromString("MBCDEFGKABCRAAAKAA"); // starts with Met - we assume the cleaved form without Met occurs in vivo TEST_EQUAL(pd.isValidProduct(prot, 1, 7, true, true), true); // valid N-term (since protein starts with Met) TEST_EQUAL(pd.isValidProduct(prot, 1, 7), false); // invalid N-term (since Met cleavage is not allowpd.) TEST_EQUAL(pd.isValidProduct(prot, 0, prot.size()), true); // the whole thing // test with different missed cleavages when this is not ignored (ignore_missed_cleavages = false) // |8 |12 |16|19 prot = AASequence::fromString("ABCDEFGKABCRAAAKAARPBBBB"); // 4 cleavages at {(0),8,12,16,19} pd.setMissedCleavages(0); // redundant, by default zero, should be zero TEST_EQUAL(pd.isValidProduct(prot, 8, 4, false, false), true); // valid fully-tryptic TEST_EQUAL(pd.isValidProduct(prot, 8, 8, false, false), false); // invalid, fully-tryptic but with a missing cleavage pd.setMissedCleavages(1); TEST_EQUAL(pd.isValidProduct(prot, 8, 8, false, false), true); // valid, fully-tryptic with 1 missing cleavage (allow) TEST_EQUAL(pd.isValidProduct(prot, 8, 11, false, false), false);// invalid, fully-tryptic but with 2 missing cleavages pd.setMissedCleavages(2); TEST_EQUAL(pd.isValidProduct(prot, 8, 11, false, false), true); // valid, fully-tryptic with 2 missing cleavages TEST_EQUAL(pd.isValidProduct(prot, 0, 24, true, false), true); // boundary case, length of protein (no checking of MCs) TEST_EQUAL(pd.isValidProduct(prot, 0, 24, false, false), false);// boundary case, this exceeds missing cleavages TEST_EQUAL(pd.isValidProduct(prot, 0, 19, false, false), false);// start-boundary case, 2 allowed, 3 required pd.setMissedCleavages(3); TEST_EQUAL(pd.isValidProduct(prot, 0, 24, false, false), false);// boundary case, invalid: 3 allowed, 4 required TEST_EQUAL(pd.isValidProduct(prot, 0, 19, false, false), true); // start-boundary case, 3 allowed, 3 required pd.setMissedCleavages(4); // maximum cleavages for this peptide TEST_EQUAL(pd.isValidProduct(prot, 0, 24, false, false), true); // boundary case, accepted: 4 allowed, 4 required TEST_EQUAL(pd.isValidProduct(prot, 0, 19, false, false), true); // start-boundary case, 4 allowed, 3 required pd.setMissedCleavages(5); // allow even more ... TEST_EQUAL(pd.isValidProduct(prot, 0, 24, false, false), true); // boundary case, accepted: 5 allowed, 4 required pd.setMissedCleavages(0); // set back to default //################################################ // same as above, just with other specificity pd.setSpecificity(EnzymaticDigestion::SPEC_SEMI); // require one special cleavage site prot = AASequence::fromString("ABCDEFGKABCRAAAKAARPBBBB"); TEST_EQUAL(pd.isValidProduct(prot, 100, 3), false); // invalid position TEST_EQUAL(pd.isValidProduct(prot, 10, 300), false); // invalid length TEST_EQUAL(pd.isValidProduct(prot, 10, 0), false); // invalid size TEST_EQUAL(pd.isValidProduct(AASequence::fromString(""), 10, 0), false); // invalid size TEST_EQUAL(pd.isValidProduct(prot, 0, 3), true); // invalid N-term TEST_EQUAL(pd.isValidProduct(prot, 0, 8), true); // valid N-term TEST_EQUAL(pd.isValidProduct(prot, 8, 4), true); // valid fully-tryptic TEST_EQUAL(pd.isValidProduct(prot, 8, 8), true); // valid fully-tryptic TEST_EQUAL(pd.isValidProduct(prot, 0, 19), true); // valid C-term - followed by proline TEST_EQUAL(pd.isValidProduct(prot, 8, 3), true); // invalid C-term TEST_EQUAL(pd.isValidProduct(prot, 3, 6), false); // invalid C+N-term TEST_EQUAL(pd.isValidProduct(prot, 1, 7), true); // invalid N-term valid C-term TEST_EQUAL(pd.isValidProduct(prot, 0, prot.size()), true); // the whole thing prot = AASequence::fromString("MBCDEFGKABCRAAAKAA"); // starts with Met - we assume the cleaved form without Met occurs in vivo TEST_EQUAL(pd.isValidProduct(prot, 1, 7, true, true), true); // valid N-term (since protein starts with Met) TEST_EQUAL(pd.isValidProduct(prot, 1, 7, true, false), true); // invalid N-term (since Met cleavage is not allowpd.) TEST_EQUAL(pd.isValidProduct(prot, 0, prot.size()), true); // the whole thing // test with different missed cleavages when this is not ignored (ignore_missed_cleavages = false) // |8 |12 |16|19 prot = AASequence::fromString("ABCDEFGKABCRAAAKAARPBBBB"); // 4 cleavages at {(0),8,12,16,19} pd.setMissedCleavages(0); // redundant, by default zero, should be zero TEST_EQUAL(pd.isValidProduct(prot, 8, 3, false, false), true); // valid semi-tryptic TEST_EQUAL(pd.isValidProduct(prot, 8, 5, false, false), false); // invalid, semi-tryptic but with a missing cleavage pd.setMissedCleavages(1); TEST_EQUAL(pd.isValidProduct(prot, 8, 5, false, false), true); // valid, semi-tryptic with 1 missing cleavage (allow) TEST_EQUAL(pd.isValidProduct(prot, 8, 10, false, false), false);// invalid, semi-tryptic but with 2 missing cleavages pd.setMissedCleavages(2); TEST_EQUAL(pd.isValidProduct(prot, 8, 10, false, false), true); // valid, semi-tryptic with 2 missing cleavages TEST_EQUAL(pd.isValidProduct(prot, 0, 24, true, false), true); // boundary case, length of protein (no checking of MCs) TEST_EQUAL(pd.isValidProduct(prot, 0, 24, false, false), false);// boundary case, this exceeds missing cleavages TEST_EQUAL(pd.isValidProduct(prot, 0, 18, false, false), false);// start-boundary case, 2 allowed, 3 required pd.setMissedCleavages(3); TEST_EQUAL(pd.isValidProduct(prot, 0, 24, false, false), false);// boundary case, invalid: 3 allowed, 4 required TEST_EQUAL(pd.isValidProduct(prot, 0, 18, false, false), true); // start-boundary case, 3 allowed, 3 required pd.setMissedCleavages(4); // maximum cleavages for this peptide TEST_EQUAL(pd.isValidProduct(prot, 0, 24, false, false), true); // boundary case, accepted: 4 allowed, 4 required TEST_EQUAL(pd.isValidProduct(prot, 0, 18, false, false), true); // start-boundary case, 4 allowed, 3 required pd.setMissedCleavages(5); // allow even more ... TEST_EQUAL(pd.isValidProduct(prot, 0, 24, false, false), true); // boundary case, accepted: 5 allowed, 4 required pd.setMissedCleavages(0); // set back to default //################################################ // same as above, just with other specificity pd.setSpecificity(EnzymaticDigestion::SPEC_NONE); // require no special cleavage site prot = AASequence::fromString("ABCDEFGKABCRAAAKAARPBBBB"); TEST_EQUAL(pd.isValidProduct(prot, 100, 3), false); // invalid position TEST_EQUAL(pd.isValidProduct(prot, 10, 300), false); // invalid length TEST_EQUAL(pd.isValidProduct(prot, 10, 0), false); // invalid size TEST_EQUAL(pd.isValidProduct(AASequence::fromString(""), 10, 0), false); // invalid size TEST_EQUAL(pd.isValidProduct(prot, 0, 3), true); // invalid N-term TEST_EQUAL(pd.isValidProduct(prot, 0, 8), true); // valid N-term TEST_EQUAL(pd.isValidProduct(prot, 8, 4), true); // valid fully-tryptic TEST_EQUAL(pd.isValidProduct(prot, 8, 8), true); // valid fully-tryptic TEST_EQUAL(pd.isValidProduct(prot, 0, 19), true); // valid C-term - followed by proline TEST_EQUAL(pd.isValidProduct(prot, 8, 3), true); // invalid C-term TEST_EQUAL(pd.isValidProduct(prot, 3, 6), true); // invalid C+N-term TEST_EQUAL(pd.isValidProduct(prot, 1, 7), true); // invalid N-term TEST_EQUAL(pd.isValidProduct(prot, 0, prot.size()), true); // the whole thing // test with different missed cleavages when this is not ignored (ignore_missed_cleavages = false) // |8 |12 |16|19 prot = AASequence::fromString("ABCDEFGKABCRAAAKAARPBBBB"); // 4 cleavages at {(0),8,12,16,19} pd.setMissedCleavages(0); // redundant, by default zero, should be zero TEST_EQUAL(pd.isValidProduct(prot, 9, 2, false, false), true); // valid not-tryptic TEST_EQUAL(pd.isValidProduct(prot, 9, 5, false, false), false); // invalid, not-tryptic but with a missing cleavage pd.setMissedCleavages(1); TEST_EQUAL(pd.isValidProduct(prot, 9, 5, false, false), true); // valid, not-tryptic with 1 missing cleavage (allow) TEST_EQUAL(pd.isValidProduct(prot, 9, 9, false, false), false); // invalid, semi-tryptic but with 2 missing cleavages pd.setMissedCleavages(2); TEST_EQUAL(pd.isValidProduct(prot, 9, 9, false, false), true); // valid, semi-tryptic with 2 missing cleavages TEST_EQUAL(pd.isValidProduct(prot, 0, 24, true, false), true); // boundary case, length of protein (no checking of MCs) TEST_EQUAL(pd.isValidProduct(prot, 0, 24, false, false), false);// boundary case, this exceeds missing cleavages pd.setMissedCleavages(3); TEST_EQUAL(pd.isValidProduct(prot, 0, 24, false, false), false);// boundary case, invalid: 3 allowed, 4 required pd.setMissedCleavages(4); // maximum cleavages for this peptide TEST_EQUAL(pd.isValidProduct(prot, 0, 24, false, false), true); // boundary case, accepted: 4 allowed, 4 required pd.setMissedCleavages(5); // allow even more ... TEST_EQUAL(pd.isValidProduct(prot, 0, 24, false, false), true); // boundary case, accepted: 5 allowed, 4 required pd.setMissedCleavages(0); // set back to default // tests with random Asp-Pro Cleavages pd.setSpecificity(EnzymaticDigestion::SPEC_SEMI); // |6* |11|14*|18 |22|25 |29* |34* prot = AASequence::fromString("MCABCDPEFGKACDPBCRAAAKAARPBBDPBBCDP"); // 4 real cleavages at {(0),11,18,22,25} pd.setMissedCleavages(0); // redundant, by default zero, should be zero TEST_EQUAL(pd.isValidProduct(prot, 0, 2), true); // valid N-term TEST_EQUAL(pd.isValidProduct(prot, 1, 2, true, true), true); // valid N-term, M cleavage TEST_EQUAL(pd.isValidProduct(prot, 2, 2, true, true), true); // valid N-term, MC cleavage TEST_EQUAL(pd.isValidProduct(prot, 3, 2, true, true), false); // invalid N- and C-term TEST_EQUAL(pd.isValidProduct(prot, 6, 3, true, true, true), true); // valid N-term (random D|P cleavage) TEST_EQUAL(pd.isValidProduct(prot, 6, 3, true, true, false), false); // invalid C- and N-term (random D|P cleavage not allowed) TEST_EQUAL(pd.isValidProduct(prot, 6, 5, true, true, true), true); // valid fully-tryptic (N-term random D|P) TEST_EQUAL(pd.isValidProduct(prot, 6, 6, true, true, true), true); // valid N-term (random D|P) TEST_EQUAL(pd.isValidProduct(prot, 29, 4, true, true, true), true); // valid fully-tryptic (N-term random D|P) TEST_EQUAL(pd.isValidProduct(prot, 0, prot.size()), true); // the whole thing TEST_EQUAL(pd.isValidProduct(prot, 1, prot.size()-1, true), true); // valid C-term (end), M cleavage not allowed TEST_EQUAL(pd.isValidProduct(prot, 2, prot.size()-2, true), true); // valid C-term (end), MC cleavage not allowed TEST_EQUAL(pd.isValidProduct(prot, 1, prot.size()-1, true, true), true); // valid C- and N-term (end, start M cleavage) TEST_EQUAL(pd.isValidProduct(prot, 2, prot.size()-2, true, true), true); // valid C- and N-term (end, start MC cleavage) TEST_EQUAL(pd.isValidProduct(prot, 6, 6, false, false, true), false); // valid N-term (D|P), one real cleavage site skipped (11) TEST_EQUAL(pd.isValidProduct(prot, 6, 8, false, false, true), false); // valid termini (both D|P), one real cleavage site skipped (11) TEST_EQUAL(pd.isValidProduct(prot, 6, 10, false, false, true), false); // valid N-term (D|P), skipped real cleavage (11) and D|P (14) TEST_EQUAL(pd.isValidProduct(prot, 6, 12, false, false, true), false); // valid termini (D|P, real), skipped real cleavage (11) and D|P (14) TEST_EQUAL(pd.isValidProduct(prot, 11, 4, false, false, true), true); // valid N-term (real), one D|P cleavage site skipped (14) TEST_EQUAL(pd.isValidProduct(prot, 11, 7, false, false, true), true); // valid termini (both real), one D|P cleavage site skipped (14) TEST_EQUAL(pd.isValidProduct(prot, 18, 16, false, false, true), false); // valid termini (real, D|P), two real cleavage sites skipped (22,25), one D|P (29) TEST_EQUAL(pd.isValidProduct(prot, 18, 17, false, false, true), false); // valid termini (real, end), two real cleavage sites skipped (22,25), two D|P (35) pd.setMissedCleavages(1); TEST_EQUAL(pd.isValidProduct(prot, 6, 6, false, false, true), true); // valid N-term (D|P), one real cleavage site skipped (11) TEST_EQUAL(pd.isValidProduct(prot, 6, 8, false, false, true), true); // valid termini (both D|P), one real cleavage site skipped (11) TEST_EQUAL(pd.isValidProduct(prot, 6, 10, false, false, true), true); // valid N-term (D|P), skipped real cleavage (11) and D|P (14) TEST_EQUAL(pd.isValidProduct(prot, 6, 12, false, false, true), true); // valid termini (D|P, real), skipped real cleavage (11) and D|P (14) TEST_EQUAL(pd.isValidProduct(prot, 11, 4, false, false, true), true); // valid N-term (real), one D|P cleavage site skipped (14) TEST_EQUAL(pd.isValidProduct(prot, 11, 7, false, false, true), true); // valid termini (both real), one D|P cleavage site skipped (14) TEST_EQUAL(pd.isValidProduct(prot, 18, 16, false, false, true), false); // valid termini (real, D|P), two real cleavage sites skipped (22,25), one D|P (29) TEST_EQUAL(pd.isValidProduct(prot, 18, 17, false, false, true), false); // valid termini (real, end), two real cleavage sites skipped (22,25), two D|P (35) pd.setMissedCleavages(2); TEST_EQUAL(pd.isValidProduct(prot, 6, 6, false, false, true), true); // valid N-term (D|P), one real cleavage site skipped (11) TEST_EQUAL(pd.isValidProduct(prot, 6, 8, false, false, true), true); // valid termini (both D|P), one real cleavage site skipped (11) TEST_EQUAL(pd.isValidProduct(prot, 6, 10, false, false, true), true); // valid N-term (D|P), skipped real cleavage (11) and D|P (14) TEST_EQUAL(pd.isValidProduct(prot, 6, 12, false, false, true), true); // valid termini (D|P, real), skipped real cleavage (11) and D|P (14) TEST_EQUAL(pd.isValidProduct(prot, 11, 4, false, false, true), true); // valid N-term (real), one D|P cleavage site skipped (14) TEST_EQUAL(pd.isValidProduct(prot, 11, 7, false, false, true), true); // valid termini (both real), one D|P cleavage site skipped (14) TEST_EQUAL(pd.isValidProduct(prot, 18, 16, false, false, true), true); // valid termini (real, D|P), two real cleavage sites skipped (22,25), one D|P (29) TEST_EQUAL(pd.isValidProduct(prot, 18, 17, false, false, true), true); // valid termini (real, end), two real cleavage sites skipped (22,25), two D|P (35) // more than needed pd.setMissedCleavages(3); TEST_EQUAL(pd.isValidProduct(prot, 6, 6, false, false, true), true); // valid N-term (D|P), one real cleavage site skipped (11) TEST_EQUAL(pd.isValidProduct(prot, 6, 8, false, false, true), true); // valid termini (both D|P), one real cleavage site skipped (11) TEST_EQUAL(pd.isValidProduct(prot, 6, 10, false, false, true), true); // valid N-term (D|P), skipped real cleavage (11) and D|P (14) TEST_EQUAL(pd.isValidProduct(prot, 6, 12, false, false, true), true); // valid termini (D|P, real), skipped real cleavage (11) and D|P (14) TEST_EQUAL(pd.isValidProduct(prot, 11, 4, false, false, true), true); // valid N-term (real), one D|P cleavage site skipped (14) TEST_EQUAL(pd.isValidProduct(prot, 11, 7, false, false, true), true); // valid termini (both real), one D|P cleavage site skipped (14) TEST_EQUAL(pd.isValidProduct(prot, 18, 16, false, false, true), true); // valid termini (real, D|P), two real cleavage sites skipped (22,25), one D|P (29) TEST_EQUAL(pd.isValidProduct(prot, 18, 17, false, false, true), true); // valid termini (real, end), two real cleavage sites skipped (22,25), two D|P (35) // ------------------------ // glutamyl endopeptidase (since it cleaves after D as the random XTandem cleavage) // ------------------------ pd.setEnzyme("glutamyl endopeptidase"); pd.setSpecificity(EnzymaticDigestion::SPEC_SEMI); // |6* |11|14*|18 |22|25 |29* |34* prot = AASequence::fromString("MCABCDPLFGKACDPHCRAAAKAARPHHDPHHCDP"); // 4 real cleavages at {(0),11,18,22,25} pd.setMissedCleavages(0); // redundant, by default zero, should be zero TEST_EQUAL(pd.isValidProduct(prot, 6, 8, true, true, true), true); // valid C and N-term TEST_EQUAL(pd.isValidProduct(prot, 6, 8, true, true, false), true); // valid C and N-term TEST_EQUAL(pd.isValidProduct(prot, 6, 5, true, true, true), true); // valid N-term TEST_EQUAL(pd.isValidProduct(prot, 6, 5, true, true, false), true); // valid N-term TEST_EQUAL(pd.isValidProduct(prot, 6, 23, true, true, true), true); // valid C and N-term (but 1 missed, ignored) TEST_EQUAL(pd.isValidProduct(prot, 6, 23, true, true, false), true); // valid C and N-term (but 1 missed, ignored) TEST_EQUAL(pd.isValidProduct(prot, 6, 28, true, true, true), true); // valid C and N-term (but 2 missed, ignored) TEST_EQUAL(pd.isValidProduct(prot, 6, 28, true, true, false), true); // valid C and N-term (but 2 missed, ignored) TEST_EQUAL(pd.isValidProduct(prot, 6, 23, false, true, true), false); // valid C and N-term (but 1 missed) TEST_EQUAL(pd.isValidProduct(prot, 6, 23, false, true, false), false); // valid C and N-term (but 1 missed) TEST_EQUAL(pd.isValidProduct(prot, 6, 28, false, true, true), false); // valid C and N-term (but 2 missed) TEST_EQUAL(pd.isValidProduct(prot, 6, 28, false, true, false), false); // valid C and N-term (but 2 missed) TEST_EQUAL(pd.isValidProduct(prot, 0, prot.size()), true); // valid N-term start, C-term end (3 missed, ignored) TEST_EQUAL(pd.isValidProduct(prot, 1, prot.size()-1, true), true); // valid C-term end (3 missed, ignored) TEST_EQUAL(pd.isValidProduct(prot, 2, prot.size()-2, true), true); // valid C-term end (3 missed, ignored) TEST_EQUAL(pd.isValidProduct(prot, 0, prot.size(), false), false); // valid N-term start, C-term end (but 3 missed) TEST_EQUAL(pd.isValidProduct(prot, 1, prot.size()-1, false), false); // valid C-term end (but 3 missed) TEST_EQUAL(pd.isValidProduct(prot, 2, prot.size()-2, false), false); // valid C-term end (but 3 missed) pd.setMissedCleavages(1); TEST_EQUAL(pd.isValidProduct(prot, 6, 8, false, true, true), true); // valid C and N-term TEST_EQUAL(pd.isValidProduct(prot, 6, 8, false, true, false), true); // valid C and N-term TEST_EQUAL(pd.isValidProduct(prot, 6, 5, false, true, true), true); // valid N-term TEST_EQUAL(pd.isValidProduct(prot, 6, 5, false, true, false), true); // valid N-term TEST_EQUAL(pd.isValidProduct(prot, 6, 23, false, true, true), true); // valid C and N-term (but 1 missed) TEST_EQUAL(pd.isValidProduct(prot, 6, 23, false, true, false), true); // valid C and N-term (but 1 missed) TEST_EQUAL(pd.isValidProduct(prot, 6, 28, false, true, true), false); // valid C and N-term (but 2 missed) TEST_EQUAL(pd.isValidProduct(prot, 6, 28, false, true, false), false); // valid C and N-term (but 2 missed) pd.setMissedCleavages(2); TEST_EQUAL(pd.isValidProduct(prot, 6, 8, false, true, true), true); // valid C and N-term TEST_EQUAL(pd.isValidProduct(prot, 6, 8, false, true, false), true); // valid C and N-term TEST_EQUAL(pd.isValidProduct(prot, 6, 5, false, true, true), true); // valid N-term TEST_EQUAL(pd.isValidProduct(prot, 6, 5, false, true, false), true); // valid N-term TEST_EQUAL(pd.isValidProduct(prot, 6, 23, false, true, true), true); // valid C and N-term (but 1 missed) TEST_EQUAL(pd.isValidProduct(prot, 6, 23, false, true, false), true); // valid C and N-term (but 1 missed) TEST_EQUAL(pd.isValidProduct(prot, 6, 28, false, true, true), true); // valid C and N-term (but 2 missed) TEST_EQUAL(pd.isValidProduct(prot, 6, 28, false, true, false), true); // valid C and N-term (but 2 missed) // more than needed pd.setMissedCleavages(3); TEST_EQUAL(pd.isValidProduct(prot, 6, 8, false, true, true), true); // valid C and N-term TEST_EQUAL(pd.isValidProduct(prot, 6, 8, false, true, false), true); // valid C and N-term TEST_EQUAL(pd.isValidProduct(prot, 6, 5, false, true, true), true); // valid N-term TEST_EQUAL(pd.isValidProduct(prot, 6, 5, false, true, false), true); // valid N-term TEST_EQUAL(pd.isValidProduct(prot, 6, 23, false, true, true), true); // valid C and N-term (but 1 missed) TEST_EQUAL(pd.isValidProduct(prot, 6, 23, false, true, false), true); // valid C and N-term (but 1 missed) TEST_EQUAL(pd.isValidProduct(prot, 6, 28, false, true, true), true); // valid C and N-term (but 2 missed) TEST_EQUAL(pd.isValidProduct(prot, 6, 28, false, true, false), true); // valid C and N-term (but 2 missed) /// no cleavage: pd.setEnzyme("no cleavage"); pd.setSpecificity(EnzymaticDigestion::SPEC_FULL); // require both sides prot = AASequence::fromString("MADPDE"); // something which start with 'M' to test nterm prot cleavage TEST_EQUAL(pd.isValidProduct(prot, 100, 3), false); // invalid position TEST_EQUAL(pd.isValidProduct(prot, 1, 300), false); // invalid length TEST_EQUAL(pd.isValidProduct(prot, 3, 0), false); // invalid size const bool with_nterm_prot_cleavage = true; const bool no_nterm_prot_cleavage = false; const bool with_rnd_asppro_cleavage = true; const bool no_rnd_asppro_cleavage = false; TEST_EQUAL(pd.isValidProduct(prot, 0, 6, true, with_nterm_prot_cleavage), true); TEST_EQUAL(pd.isValidProduct(prot, 0, 6, true, no_nterm_prot_cleavage), true); TEST_EQUAL(pd.isValidProduct(prot, 1, 5, true, with_nterm_prot_cleavage), true); TEST_EQUAL(pd.isValidProduct(prot, 1, 5, true, no_nterm_prot_cleavage), false); TEST_EQUAL(pd.isValidProduct(prot, 0, 5, true, with_nterm_prot_cleavage), false); TEST_EQUAL(pd.isValidProduct(prot, 0, 5, true, no_nterm_prot_cleavage), false); // asppro_cleavage should make no difference TEST_EQUAL(pd.isValidProduct(prot, 0, 6, true, with_nterm_prot_cleavage, with_rnd_asppro_cleavage), true); TEST_EQUAL(pd.isValidProduct(prot, 0, 6, true, no_nterm_prot_cleavage, no_rnd_asppro_cleavage), true); TEST_EQUAL(pd.isValidProduct(prot, 1, 5, true, with_nterm_prot_cleavage, with_rnd_asppro_cleavage), true); TEST_EQUAL(pd.isValidProduct(prot, 1, 5, true, no_nterm_prot_cleavage, no_rnd_asppro_cleavage), false); TEST_EQUAL(pd.isValidProduct(prot, 0, 5, true, with_nterm_prot_cleavage, with_rnd_asppro_cleavage), false); TEST_EQUAL(pd.isValidProduct(prot, 0, 5, true, no_nterm_prot_cleavage, no_rnd_asppro_cleavage), false); // ... unless we hit one TEST_EQUAL(pd.isValidProduct(prot, 1, 2, true, no_nterm_prot_cleavage, no_rnd_asppro_cleavage), false); TEST_EQUAL(pd.isValidProduct(prot, 0, 3, true, with_nterm_prot_cleavage, with_rnd_asppro_cleavage), true); TEST_EQUAL(pd.isValidProduct(prot, 0, 3, true, no_nterm_prot_cleavage, no_rnd_asppro_cleavage), false); pd.setSpecificity(EnzymaticDigestion::SPEC_SEMI); // require one side prot = AASequence::fromString("MADPDE"); // something which starts with 'M' to test nterm prot cleavage and has a D/P cleavage TEST_EQUAL(pd.isValidProduct(prot, 100, 3), false); // invalid position TEST_EQUAL(pd.isValidProduct(prot, 1, 300), false); // invalid length TEST_EQUAL(pd.isValidProduct(prot, 3, 0), false); // invalid size TEST_EQUAL(pd.isValidProduct(prot, 0, 6, true, with_nterm_prot_cleavage), true); TEST_EQUAL(pd.isValidProduct(prot, 0, 6, true, no_nterm_prot_cleavage), true); TEST_EQUAL(pd.isValidProduct(prot, 1, 5, true, with_nterm_prot_cleavage), true); TEST_EQUAL(pd.isValidProduct(prot, 1, 5, true, no_nterm_prot_cleavage), true); TEST_EQUAL(pd.isValidProduct(prot, 0, 5, true, with_nterm_prot_cleavage), true); TEST_EQUAL(pd.isValidProduct(prot, 0, 5, true, no_nterm_prot_cleavage), true); // asppro_cleavage should make no difference TEST_EQUAL(pd.isValidProduct(prot, 0, 6, true, with_nterm_prot_cleavage, with_rnd_asppro_cleavage), true); TEST_EQUAL(pd.isValidProduct(prot, 0, 6, true, no_nterm_prot_cleavage, no_rnd_asppro_cleavage), true); TEST_EQUAL(pd.isValidProduct(prot, 1, 5, true, with_nterm_prot_cleavage, with_rnd_asppro_cleavage), true); TEST_EQUAL(pd.isValidProduct(prot, 1, 5, true, no_nterm_prot_cleavage, no_rnd_asppro_cleavage), true); TEST_EQUAL(pd.isValidProduct(prot, 0, 5, true, with_nterm_prot_cleavage, with_rnd_asppro_cleavage), true); TEST_EQUAL(pd.isValidProduct(prot, 0, 5, true, no_nterm_prot_cleavage, no_rnd_asppro_cleavage), true); // ... unless we hit one TEST_EQUAL(pd.isValidProduct(prot, 1, 2, true, no_nterm_prot_cleavage, no_rnd_asppro_cleavage), false); TEST_EQUAL(pd.isValidProduct(prot, 1, 2, true, no_nterm_prot_cleavage, with_rnd_asppro_cleavage), true); TEST_EQUAL(pd.isValidProduct(prot, 0, 3, true, with_nterm_prot_cleavage, with_rnd_asppro_cleavage), true); TEST_EQUAL(pd.isValidProduct(prot, 0, 3, true, no_nterm_prot_cleavage, no_rnd_asppro_cleavage), true); END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ConsensusMapNormalizerAlgorithmThreshold_test.cpp
.cpp
1,618
56
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Lars Nilse$ // $Authors: Hendrik Brauer, Oliver Kohlbacher, Johannes Junker$ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/ANALYSIS/MAPMATCHING/ConsensusMapNormalizerAlgorithmThreshold.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(ConsensusMapNormalizerAlgorithmThreshold, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// ConsensusMapNormalizerAlgorithmThreshold* ptr = nullptr; ConsensusMapNormalizerAlgorithmThreshold* nullPointer = nullptr; START_SECTION(ConsensusMapNormalizerAlgorithmThreshold()) { ptr = new ConsensusMapNormalizerAlgorithmThreshold(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(~ConsensusMapNormalizerAlgorithmThreshold()) { delete ptr; } END_SECTION START_SECTION((static std::vector<double> computeCorrelation(const ConsensusMap &map, const double &ratio_threshold))) { NOT_TESTABLE } END_SECTION START_SECTION((static void normalizeMaps(ConsensusMap &map, const std::vector< double > &ratios))) { NOT_TESTABLE } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/PeptideMass_test.cpp
.cpp
2,105
71
// 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 $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/KERNEL/FeatureMap.h> #include <OpenMS/QC/PeptideMass.h> /////////////////////////// START_TEST(PeptideMass, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace std; PeptideMass* ptr = nullptr; PeptideMass* nullPointer = nullptr; START_SECTION(MzCalibration()) ptr = new PeptideMass(); TEST_NOT_EQUAL(ptr, nullPointer); END_SECTION START_SECTION(~PeptideMass()) delete ptr; END_SECTION START_SECTION(void compute(FeatureMap& features)) { Feature f; PeptideIdentification pi; pi.getHits().push_back(PeptideHit(1.0, 1, 3, AASequence::fromString("KKK"))); pi.setMZ(100.0); f.getPeptideIdentifications().push_back(pi); FeatureMap fm; fm.push_back(f); pi.setMZ(200.0); pi.getHits().back().setCharge(2); f.getPeptideIdentifications().back() = pi; fm.push_back(f); PeptideMass fw; fw.compute(fm); TEST_EQUAL(fm[0].getPeptideIdentifications()[0].getHits()[0].getMetaValue("mass"), (100.0 - Constants::PROTON_MASS_U) * 3) TEST_EQUAL(fm[1].getPeptideIdentifications()[0].getHits()[0].getMetaValue("mass"), (200.0 - Constants::PROTON_MASS_U) * 2) } END_SECTION START_SECTION(QCBase::Status requirements() const override) { PeptideMass fw; TEST_EQUAL(fw.requirements() == (QCBase::Status() | QCBase::Requires::POSTFDRFEAT), true); } END_SECTION START_SECTION(const String& getName() const) { TEST_EQUAL(PeptideMass().getName(), "PeptideMass"); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/NuXLModificationsGenerator_test.cpp
.cpp
1,415
51
// Copyright (c) 2002-present, The OpenMS Team -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: $ // $Authors: $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> /////////////////////////// #include <OpenMS/ANALYSIS/NUXL/NuXLModificationsGenerator.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(NuXLModificationsGenerator, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// NuXLModificationsGenerator* ptr = nullptr; NuXLModificationsGenerator* null_ptr = nullptr; START_SECTION(NuXLModificationsGenerator()) { ptr = new NuXLModificationsGenerator(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(~NuXLModificationsGenerator()) { delete ptr; } END_SECTION START_SECTION((static NuXLModificationMassesResult initModificationMassesNA(StringList target_nucleotides, StringList mappings, StringList restrictions, StringList modifications, String sequence_restriction, bool cysteine_adduct, Int max_length=4))) { // TODO } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ModifiedPeptideGenerator_test.cpp
.cpp
14,237
297
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg$ // $Authors: Timo Sachsenberg$ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> #include <OpenMS/CHEMISTRY/ModificationsDB.h> #include <OpenMS/DATASTRUCTURES/ListUtils.h> #include <OpenMS/DATASTRUCTURES/ListUtilsIO.h> #ifdef _OPENMP #include <omp.h> #endif /////////////////////////// #include <OpenMS/CHEMISTRY/ModifiedPeptideGenerator.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(ModifiedPeptideGenerator, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// ModifiedPeptideGenerator* ptr = nullptr; ModifiedPeptideGenerator* null_ptr = nullptr; START_SECTION(ModifiedPeptideGenerator()) { ptr = new ModifiedPeptideGenerator(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(~ModifiedPeptideGenerator()) { delete ptr; } END_SECTION START_SECTION((static void applyFixedModifications(const ModifiedPeptideGenerator::MapToResidueType& fixed_mods, AASequence& peptide))) { // query modification of interest from ModificationsDB StringList modNames; modNames << "Carbamidomethyl (C)"; ModifiedPeptideGenerator::MapToResidueType fixed_mods = ModifiedPeptideGenerator::getModifications(modNames); AASequence seq0 = AASequence::fromString("AAAACAAAA"); // exactly one target site AASequence seq1 = AASequence::fromString("AAAAAAAAA"); // no target site AASequence seq2 = AASequence::fromString("CCCCCCCCC"); // all target sites AASequence seq3 = AASequence::fromString("AAAACAAC(Carbamidomethyl)AAA"); // one of two target sites already modified AASequence seq4 = AASequence::fromString("AAAACAAC(Oxidation)AAA"); // one of two target sites already modified ModifiedPeptideGenerator::applyFixedModifications(fixed_mods, seq0); ModifiedPeptideGenerator::applyFixedModifications(fixed_mods, seq1); ModifiedPeptideGenerator::applyFixedModifications(fixed_mods, seq2); ModifiedPeptideGenerator::applyFixedModifications(fixed_mods, seq3); ModifiedPeptideGenerator::applyFixedModifications(fixed_mods, seq4); TEST_EQUAL(seq0.toString(), "AAAAC(Carbamidomethyl)AAAA"); TEST_EQUAL(seq1.toString(), "AAAAAAAAA"); TEST_EQUAL(seq2.toString(), "C(Carbamidomethyl)C(Carbamidomethyl)C(Carbamidomethyl)C(Carbamidomethyl)C(Carbamidomethyl)C(Carbamidomethyl)C(Carbamidomethyl)C(Carbamidomethyl)C(Carbamidomethyl)"); TEST_EQUAL(seq3.toString(), "AAAAC(Carbamidomethyl)AAC(Carbamidomethyl)AAA"); TEST_EQUAL(seq4.toString(), "AAAAC(Carbamidomethyl)AAC(Oxidation)AAA"); // test terminal modifications modNames.clear(); modNames << "Carbamyl (N-term)"; fixed_mods.val.clear(); fixed_mods = ModifiedPeptideGenerator::getModifications(modNames); seq0 = AASequence::fromString("KAAAAAAAA"); // exactly one target site seq1 = AASequence::fromString("K(Carbamyl)AAAAAAAA"); // ambiguous case: is mod Carbamyl (K) or (N-Term)? ModifiedPeptideGenerator::applyFixedModifications(fixed_mods, seq0); ModifiedPeptideGenerator::applyFixedModifications(fixed_mods, seq1); TEST_EQUAL(seq0.toString(), ".(Carbamyl)KAAAAAAAA"); TEST_EQUAL(seq1.toString(), ".(Carbamyl)K(Carbamyl)AAAAAAAA"); } END_SECTION START_SECTION((static void applyVariableModifications(const ModifiedPeptideGenerator::MapToResidueType& var_mods, const AASequence& peptide, Size max_variable_mods_per_peptide, std::vector< AASequence > &all_modified_peptides, bool keep_unmodified=true))) { // query modification of interest from ModificationsDB StringList modNames; modNames << "Oxidation (M)"; ModifiedPeptideGenerator::MapToResidueType variable_mods = ModifiedPeptideGenerator::getModifications(modNames); vector<AASequence> modified_peptides; // test behavior if sequence empty AASequence seq; ModifiedPeptideGenerator::applyVariableModifications(variable_mods, seq, 1, modified_peptides, false); TEST_EQUAL(modified_peptides.size(), 0); // no generated peptide modified_peptides.clear(); // test behavior if peptide empty seq = AASequence::fromString(""); ModifiedPeptideGenerator::applyVariableModifications(variable_mods, seq, 0, modified_peptides, false); TEST_EQUAL(modified_peptides.size(), 0); // no generated peptide modified_peptides.clear(); ModifiedPeptideGenerator::applyVariableModifications(variable_mods, seq, 1, modified_peptides, false); TEST_EQUAL(modified_peptides.size(), 0); // no generated peptide modified_peptides.clear(); ModifiedPeptideGenerator::applyVariableModifications(variable_mods, seq, 2, modified_peptides, false); TEST_EQUAL(modified_peptides.size(), 0); // no generated peptide modified_peptides.clear(); // test behavior if no target site in sequence seq = AASequence::fromString("AAAAAAAAA"); ModifiedPeptideGenerator::applyVariableModifications(variable_mods, seq, 1, modified_peptides, false); TEST_EQUAL(modified_peptides.size(), 0); // no generated peptide modified_peptides.clear(); // test flag to preserve passed peptide ModifiedPeptideGenerator::applyVariableModifications(variable_mods, seq, 1, modified_peptides, true); TEST_EQUAL(modified_peptides[0], AASequence::fromString("AAAAAAAAA")); // only the original peptide modified_peptides.clear(); // test behavior if one target site in sequence and different number of maximum variable modifications are choosen seq = AASequence::fromString("AAAAMAAAA"); // exactly one target site ModifiedPeptideGenerator::applyVariableModifications(variable_mods, seq, 0, modified_peptides, false); TEST_EQUAL(modified_peptides.size(), 0); // no generated peptide modified_peptides.clear(); ModifiedPeptideGenerator::applyVariableModifications(variable_mods, seq, 1, modified_peptides, false); TEST_EQUAL(modified_peptides.size(), 1); // one generated peptide TEST_EQUAL(modified_peptides[0].toString(), "AAAAM(Oxidation)AAAA"); modified_peptides.clear(); ModifiedPeptideGenerator::applyVariableModifications(variable_mods, seq, 2, modified_peptides, false); TEST_EQUAL(modified_peptides.size(), 1); // also only one generated peptide as there is only one target site TEST_EQUAL(modified_peptides[0].toString(), "AAAAM(Oxidation)AAAA"); modified_peptides.clear(); // test again keeping of the original peptides ModifiedPeptideGenerator::applyVariableModifications(variable_mods, seq, 1, modified_peptides, true); TEST_EQUAL(modified_peptides.size(), 2); // original and modified peptide TEST_EQUAL(modified_peptides[0].toString(), "AAAAMAAAA"); TEST_EQUAL(modified_peptides[1].toString(), "AAAAM(Oxidation)AAAA"); modified_peptides.clear(); // test behavior if two target sites are in peptide and we need some combinatorics // only one additional variable modification seq = AASequence::fromString("AAMAAAMAA"); // two target site ModifiedPeptideGenerator::applyVariableModifications(variable_mods, seq, 1, modified_peptides, false); TEST_EQUAL(modified_peptides.size(), 2); // two modified peptides each modified at a different site TEST_EQUAL(modified_peptides[0].toString(), "AAMAAAM(Oxidation)AA"); TEST_EQUAL(modified_peptides[1].toString(), "AAM(Oxidation)AAAMAA"); modified_peptides.clear(); // up to two variable modifications per peptide ModifiedPeptideGenerator::applyVariableModifications(variable_mods, seq, 2, modified_peptides, false); TEST_EQUAL(modified_peptides.size(), 3); // three modified peptides, 1 modified at first M, 1 modified at second M and both M modified TEST_EQUAL(modified_peptides[0].toString(), "AAMAAAM(Oxidation)AA"); TEST_EQUAL(modified_peptides[1].toString(), "AAM(Oxidation)AAAMAA"); TEST_EQUAL(modified_peptides[2].toString(), "AAM(Oxidation)AAAM(Oxidation)AA"); modified_peptides.clear(); // two different modifications with same target site modNames.clear(); modNames << "Glutathione (C)" << "Carbamidomethyl (C)"; variable_mods.val.clear(); variable_mods = ModifiedPeptideGenerator::getModifications(modNames); seq = AASequence::fromString("ACAACAACA"); // three target sites ModifiedPeptideGenerator::applyVariableModifications(variable_mods, seq, 1, modified_peptides, false); TEST_EQUAL(modified_peptides.size(), 6); // six modified peptides, as both C modifications can occur at all 3 sites std::sort(modified_peptides.begin(), modified_peptides.end(), [](const AASequence & a, const AASequence & b) -> bool { return a.toString() < b.toString(); }); TEST_EQUAL(modified_peptides[0].toString(), "AC(Carbamidomethyl)AACAACA"); TEST_EQUAL(modified_peptides[1].toString(), "AC(Glutathione)AACAACA"); TEST_EQUAL(modified_peptides[2].toString(), "ACAAC(Carbamidomethyl)AACA"); TEST_EQUAL(modified_peptides[3].toString(), "ACAAC(Glutathione)AACA"); TEST_EQUAL(modified_peptides[4].toString(), "ACAACAAC(Carbamidomethyl)A"); modified_peptides.clear(); ModifiedPeptideGenerator::applyVariableModifications(variable_mods, seq, 1, modified_peptides, true); TEST_EQUAL(modified_peptides.size(), 7); // same as above but +1 unmodified peptide modified_peptides.clear(); seq = AASequence::fromString("ACAACAACA"); // three target sites and maximum of three occurrences of the two modifications Glutathione and Carbamidomethyl ModifiedPeptideGenerator::applyVariableModifications(variable_mods, seq, 3, modified_peptides, false); TEST_EQUAL(modified_peptides.size(), 3*3*3-1); // three sites with 3 possibilities (none, Glut., Carb.) each - but we need to subtract (none, none, none). The unmodified peptide modified_peptides.clear(); seq = AASequence::fromString("AAAAC(Carbamidomethyl)AAAA"); // target site already occupied ModifiedPeptideGenerator::applyVariableModifications(variable_mods, seq, 3, modified_peptides, false); TEST_EQUAL(modified_peptides.size(), 0); // no generated peptide as target site was already occupied // three different modifications modNames.clear(); modNames << "Glutathione (C)" << "Carbamidomethyl (C)" << "Oxidation (M)"; variable_mods.val.clear(); variable_mods = ModifiedPeptideGenerator::getModifications(modNames); modified_peptides.clear(); seq = AASequence::fromString("ACMACMACA"); // three target sites (C) and two target sites (M) ModifiedPeptideGenerator::applyVariableModifications(variable_mods, seq, 3, modified_peptides, false); // for exactly one mod: 2*3 + 2 = 8 (two possibilities each for each C sites and 1 for each of the two M sites) // for exactly two mods: 1 (iff two Ox) + 6 * 2 (iff one Ox at two pos.) + (3 choose 2) * 4 (iff no Ox) = 25 // for exactly three mod: 6 (iff two Ox) + ((3 choose2) * 4) * 2 (iff one Ox at two pos.) + 8 (iff no Ox) = 38 TEST_EQUAL(modified_peptides.size(), 8 + 25 + 38); // test terminal modifications modNames.clear(); modNames << "Carbamyl (N-term)" << "Oxidation (M)"; variable_mods.val.clear(); variable_mods = ModifiedPeptideGenerator::getModifications(modNames); modified_peptides.clear(); seq = AASequence::fromString("KAAAAAAAMA"); // exactly one target site ModifiedPeptideGenerator::applyVariableModifications(variable_mods, seq, 2, modified_peptides, true); TEST_EQUAL(modified_peptides.size(), 4); std::sort(modified_peptides.begin(), modified_peptides.end(), [](const AASequence & a, const AASequence & b) -> bool { return a.toString() < b.toString(); }); TEST_EQUAL(modified_peptides[0].toString(), ".(Carbamyl)KAAAAAAAM(Oxidation)A"); TEST_EQUAL(modified_peptides[1].toString(), ".(Carbamyl)KAAAAAAAMA"); TEST_EQUAL(modified_peptides[2].toString(), "KAAAAAAAM(Oxidation)A"); TEST_EQUAL(modified_peptides[3].toString(), "KAAAAAAAMA"); modified_peptides.clear(); seq = AASequence::fromString("K(Carbamyl)AAAAAAAMA"); ModifiedPeptideGenerator::applyVariableModifications(variable_mods, seq, 2, modified_peptides, true); TEST_EQUAL(modified_peptides.size(), 4); std::sort(modified_peptides.begin(), modified_peptides.end(), [](const AASequence & a, const AASequence & b) -> bool { return a.toString() < b.toString(); }); TEST_EQUAL(modified_peptides[0].toString(), ".(Carbamyl)K(Carbamyl)AAAAAAAM(Oxidation)A"); TEST_EQUAL(modified_peptides[1].toString(), ".(Carbamyl)K(Carbamyl)AAAAAAAMA"); TEST_EQUAL(modified_peptides[2].toString(), "K(Carbamyl)AAAAAAAM(Oxidation)A"); TEST_EQUAL(modified_peptides[3].toString(), "K(Carbamyl)AAAAAAAMA"); } END_SECTION START_SECTION([EXTRA] multithreaded example) { // only do this in release, since MP errors are unlikely to occur in Debug mode anyway and it takes 5min to run the test in Debug #ifdef NDEBUG int nr_iterations (1e5); int test = 0; // many modifications vector<String> all_mods = {"Carbamidomethyl (C)", "Oxidation (M)", "Carbamyl (M)", "Phospho (S)", "Phospho (T)", "Carbamyl (T)", "Phospho (Y)", "Carbamyl (K)", "Carbamyl (N-term)"}; ModifiedPeptideGenerator::MapToResidueType variable_mods = ModifiedPeptideGenerator::getModifications(all_mods); const std::string s("ACDEFGHIKLMNPQRSTVWY"); const AASequence seq = AASequence::fromString(s); #pragma omp parallel for reduction (+: test) for (int i = 0; i < nr_iterations; ++i) { vector<AASequence> modified_peptides; modified_peptides.reserve(199); ModifiedPeptideGenerator::applyVariableModifications(variable_mods, seq, 4, modified_peptides, true); test += modified_peptides.size(); } TEST_EQUAL(test, 199 * nr_iterations) #endif } END_SECTION START_SECTION([EXTRA] ModifiedPeptideGenerator::getModifications) { StringList mods; mods << "Pyro-carbamidomethyl (N-term C)" << "Carbamidomethyl (C)" << "Carbamyl (N-term)" << "Deamidated (Protein N-term F)"; auto mod_map = ModifiedPeptideGenerator::getModifications(mods); TEST_EQUAL(mods.size(), mod_map.val.size()); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/FragmentMassError_test.cpp
.cpp
17,009
404
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow $ // $Authors: Swenja Wagner, Patricia Scheil $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/CHEMISTRY/TheoreticalSpectrumGenerator.h> #include <OpenMS/KERNEL/FeatureMap.h> #include <OpenMS/MATH/MathFunctions.h> #include <OpenMS/QC/FragmentMassError.h> ////////////////////////// using namespace OpenMS; // Functions to create input data // create a MSSpectrum with Precursor, MSLevel and RT const MSSpectrum createMSSpectrum(UInt ms_level, double rt, const String& id, Precursor::ActivationMethod precursor_method = Precursor::ActivationMethod::CID) { Precursor precursor; std::set<Precursor::ActivationMethod> am; am.insert(precursor_method); precursor.setActivationMethods(am); MSSpectrum ms_spec; ms_spec.setRT(rt); ms_spec.setMSLevel(ms_level); ms_spec.setPrecursors({precursor}); ms_spec.setNativeID(id); return ms_spec; } // create a PeptideIdentifiaction with a PeptideHit (sequence, charge), rt and mz // default values for sequence PEPTIDE const PeptideIdentification createPeptideIdentification(const String& id, const String& sequence = String("PEPTIDE"), Int charge = 3, double mz = 266) { PeptideHit peptide_hit; peptide_hit.setSequence(AASequence::fromString(sequence)); peptide_hit.setCharge(charge); PeptideIdentification peptide_id; peptide_id.setSpectrumReference( id); peptide_id.setMZ(mz); peptide_id.setHits({peptide_hit}); return peptide_id; } START_TEST(FragmentMassError, "$Id$") FragmentMassError* ptr = nullptr; FragmentMassError* nulpt = nullptr; START_SECTION(FragmentMassError()) { ptr = new FragmentMassError(); TEST_NOT_EQUAL(ptr, nulpt) } END_SECTION START_SECTION(~FragmentMassError()) { delete ptr; } END_SECTION FragmentMassError frag_ma_err; // tests compute function with fmap START_SECTION(void compute(FeatureMap& fmap, const MSExperiment& exp, const std::map<String, UInt64>& map_to_spectrum, const ToleranceUnit tolerance_unit = ToleranceUnit::AUTO, const double tolerance = 20)) { //-------------------------------------------------------------------- // create valid input data //-------------------------------------------------------------------- // FeatureMap FeatureMap fmap; // empty PeptideIdentification PeptideIdentification pep_id_empty; pep_id_empty.setRT(6); // empty Feature Feature feat_empty; // put valid data in fmap fmap.setUnassignedPeptideIdentifications({createPeptideIdentification("XTandem::1", "HIMALAYA", 1, 888), createPeptideIdentification("XTandem::2", "ALABAMA", 2, 264), pep_id_empty}); fmap.push_back(feat_empty); // set ProteinIdentifications ProteinIdentification protId; ProteinIdentification::SearchParameters param; param.fragment_mass_tolerance_ppm = false; param.fragment_mass_tolerance = 0.3; protId.setSearchParameters(param); fmap.setProteinIdentifications({protId}); // MSExperiment MSExperiment exp; // create b- and y-ion spectrum of peptide sequence HIMALAYA with charge 1 // shift every peak by 5 ppm PeakSpectrum ms_spec_2_himalaya = createMSSpectrum(2, 3.7, "XTandem::1"); TheoreticalSpectrumGenerator theo_gen_hi; theo_gen_hi.getSpectrum(ms_spec_2_himalaya, AASequence::fromString("HIMALAYA"), 1, 1); for (Peak1D& peak : ms_spec_2_himalaya) peak.setMZ(Math::ppmToMass(peak.getMZ(), 5.0) + peak.getMZ()); // create c- and z-ion spectrum of peptide sequence ALABAMA with charge 2 // shift every peak by 5 ppm PeakSpectrum ms_spec_2_alabama = createMSSpectrum(2, 2, "XTandem::2", Precursor::ActivationMethod::ECD); TheoreticalSpectrumGenerator theo_gen_al; Param theo_gen_settings_al = theo_gen_al.getParameters(); theo_gen_settings_al.setValue("add_c_ions", "true"); theo_gen_settings_al.setValue("add_z_ions", "true"); theo_gen_settings_al.setValue("add_b_ions", "false"); theo_gen_settings_al.setValue("add_y_ions", "false"); theo_gen_al.setParameters(theo_gen_settings_al); theo_gen_al.getSpectrum(ms_spec_2_alabama, AASequence::fromString("ALABAMA"), 2, 2); for (Peak1D& peak : ms_spec_2_alabama) peak.setMZ(Math::ppmToMass(peak.getMZ(), 5.0) + peak.getMZ()); // empty MSSpectrum MSSpectrum ms_spec_empty; // put valid data in exp exp.setSpectra({ms_spec_empty, ms_spec_2_alabama, ms_spec_2_himalaya}); // map the MSExperiment QCBase::SpectraMap spectra_map(exp); //-------------------------------------------------------------------- // test with valid input - default parameter //-------------------------------------------------------------------- frag_ma_err.compute(fmap, exp, spectra_map); std::vector<FragmentMassError::Statistics> result = frag_ma_err.getResults(); TEST_REAL_SIMILAR(result[0].average_ppm, 5.0) TEST_REAL_SIMILAR(result[0].variance_ppm, 0.0) // offset is constant, i.e. no variance //-------------------------------------------------------------------- // test with valid input - ToleranceUnit PPM //-------------------------------------------------------------------- FragmentMassError frag_ma_err_ppm; frag_ma_err_ppm.compute(fmap, exp, spectra_map, QCBase::ToleranceUnit::PPM, 6); std::vector<FragmentMassError::Statistics> result_ppm = frag_ma_err_ppm.getResults(); TEST_REAL_SIMILAR(result_ppm[0].average_ppm, 5.0) TEST_REAL_SIMILAR(result_ppm[0].variance_ppm, 0.0) // offset is constant, i.e. no variance //-------------------------------------------------------------------- // test with valid input and flags //-------------------------------------------------------------------- FragmentMassError frag_ma_err_flag_da; frag_ma_err_flag_da.compute(fmap, exp, spectra_map, QCBase::ToleranceUnit::DA, 1); std::vector<FragmentMassError::Statistics> result_flag_da = frag_ma_err_flag_da.getResults(); TEST_REAL_SIMILAR(result_flag_da[0].average_ppm, 5.0) TEST_REAL_SIMILAR(result_flag_da[0].variance_ppm, 0.0) // offset is constant, i.e. no variance //-------------------------------------------------------------------- // test with missing toleranceUnit and toleranceValue in featureMap //-------------------------------------------------------------------- // featureMap with missing ProteinIdentifications { FeatureMap fmap_auto = fmap; fmap_auto.getProteinIdentifications().clear(); TEST_EXCEPTION(Exception::MissingInformation, frag_ma_err.compute(fmap_auto, exp, spectra_map, QCBase::ToleranceUnit::AUTO)) } //-------------------------------------------------------------------- // test with no given fragmentation method //-------------------------------------------------------------------- // create MSExperiment with no given fragmentation method exp[0].setPrecursors({}); // falls back to CID spectra_map.calculateMap(exp); frag_ma_err.compute(fmap, exp, spectra_map); TEST_REAL_SIMILAR(frag_ma_err.getResults()[1].average_ppm, 5.0) TEST_REAL_SIMILAR(frag_ma_err.getResults()[1].variance_ppm, 0.0) // offset is constant, i.e. no variance //-------------------------------------------------------------------- // test with matching ms1 spectrum //-------------------------------------------------------------------- // fmap with PeptideIdentification with RT matching to a MS1 Spectrum fmap.setUnassignedPeptideIdentifications({createPeptideIdentification("XTandem::3")}); // set MS1 Spectrum to exp exp.setSpectra({createMSSpectrum(1, 5, "XTandem::3")}); spectra_map.calculateMap(exp); TEST_EXCEPTION(Exception::IllegalArgument, frag_ma_err.compute(fmap, exp, spectra_map)) //-------------------------------------------------------------------- // test with fragmentation method SORI, which is not supported //-------------------------------------------------------------------- // put PeptideIdentification with RT matching to MSSpectrum with fragmentation method SORI to fmap FeatureMap fmap_sori; fmap_sori.setProteinIdentifications({protId}); fmap_sori.setUnassignedPeptideIdentifications({createPeptideIdentification("XTandem::5")}); // MSExperiment with fragmentation method SORI (not supported) exp.setSpectra({createMSSpectrum(2, 7, "XTandem::5", Precursor::ActivationMethod::SORI)}); spectra_map.calculateMap(exp); TEST_EXCEPTION(Exception::InvalidParameter, frag_ma_err.compute(fmap_sori, exp, spectra_map)) //-------------------------------------------------------------------- // test if spectrum has no peaks //-------------------------------------------------------------------- // put PeptideIdentification with RT matching to MSSpectrum with no peaks to fmap fmap.setUnassignedPeptideIdentifications({createPeptideIdentification("XTandem::6")}); // MSExperiment without peaks exp.setSpectra({createMSSpectrum(2, 4, "XTandem::6")}); spectra_map.calculateMap(exp); FragmentMassError frag_ma_err_excp; frag_ma_err_excp.compute(fmap, exp, spectra_map); std::vector<FragmentMassError::Statistics> result_excp; result_excp = frag_ma_err_excp.getResults(); TEST_REAL_SIMILAR(result_excp[0].average_ppm, 0) TEST_REAL_SIMILAR(result_excp[0].variance_ppm, 0) } END_SECTION // tests compute function with pepIDs START_SECTION(void compute(PeptideIdentificationList& pep_ids, const ProteinIdentification::SearchParameters& search_params, const MSExperiment& exp, const QCBase::SpectraMap& map_to_spectrum, ToleranceUnit tolerance_unit = ToleranceUnit::AUTO, double tolerance = 20)); { //-------------------------------------------------------------------- // create valid input data //-------------------------------------------------------------------- // Peptide Identifications PeptideIdentificationList pep_ids; // empty PeptideIdentification PeptideIdentification pep_id_empty; pep_id_empty.setRT(6); // put valid data in fmap pep_ids = {createPeptideIdentification("XTandem::1", "HIMALAYA", 1, 888), createPeptideIdentification("XTandem::2", "ALABAMA", 2, 264), pep_id_empty}; // Search Parameters ProteinIdentification::SearchParameters param; param.fragment_mass_tolerance_ppm = false; param.fragment_mass_tolerance = 0.3; // MSExperiment MSExperiment exp; // create b- and y-ion spectrum of peptide sequence HIMALAYA with charge 1 // shift every peak by 5 ppm PeakSpectrum ms_spec_2_himalaya = createMSSpectrum(2, 3.7, "XTandem::1"); TheoreticalSpectrumGenerator theo_gen_hi; theo_gen_hi.getSpectrum(ms_spec_2_himalaya, AASequence::fromString("HIMALAYA"), 1, 1); for (Peak1D& peak : ms_spec_2_himalaya) peak.setMZ(Math::ppmToMass(peak.getMZ(), 5.0) + peak.getMZ()); // create c- and z-ion spectrum of peptide sequence ALABAMA with charge 2 // shift every peak by 5 ppm PeakSpectrum ms_spec_2_alabama = createMSSpectrum(2, 2, "XTandem::2", Precursor::ActivationMethod::ECD); TheoreticalSpectrumGenerator theo_gen_al; Param theo_gen_settings_al = theo_gen_al.getParameters(); theo_gen_settings_al.setValue("add_c_ions", "true"); theo_gen_settings_al.setValue("add_z_ions", "true"); theo_gen_settings_al.setValue("add_b_ions", "false"); theo_gen_settings_al.setValue("add_y_ions", "false"); theo_gen_al.setParameters(theo_gen_settings_al); theo_gen_al.getSpectrum(ms_spec_2_alabama, AASequence::fromString("ALABAMA"), 2, 2); for (Peak1D& peak : ms_spec_2_alabama) peak.setMZ(Math::ppmToMass(peak.getMZ(), 5.0) + peak.getMZ()); // empty MSSpectrum MSSpectrum ms_spec_empty; // put valid data in exp exp.setSpectra({ms_spec_empty, ms_spec_2_alabama, ms_spec_2_himalaya}); // map the MSExperiment QCBase::SpectraMap spectra_map(exp); //-------------------------------------------------------------------- // test with valid input - default parameter //-------------------------------------------------------------------- frag_ma_err.compute(pep_ids, param, exp, spectra_map); std::vector<FragmentMassError::Statistics> result = frag_ma_err.getResults(); TEST_REAL_SIMILAR(result[0].average_ppm, 5.0) TEST_REAL_SIMILAR(result[0].variance_ppm, 0.0) // offset is constant, i.e. no variance //-------------------------------------------------------------------- // test with valid input - ToleranceUnit PPM //-------------------------------------------------------------------- FragmentMassError frag_ma_err_ppm; frag_ma_err_ppm.compute(pep_ids, param, exp, spectra_map, FragmentMassError::ToleranceUnit::PPM, 6); std::vector<FragmentMassError::Statistics> result_ppm = frag_ma_err_ppm.getResults(); TEST_REAL_SIMILAR(result_ppm[0].average_ppm, 5.0) TEST_REAL_SIMILAR(result_ppm[0].variance_ppm, 0.0) // offset is constant, i.e. no variance //-------------------------------------------------------------------- // test with valid input and flags //-------------------------------------------------------------------- FragmentMassError frag_ma_err_flag_da; frag_ma_err_flag_da.compute(pep_ids, param, exp, spectra_map, FragmentMassError::ToleranceUnit::DA, 1); std::vector<FragmentMassError::Statistics> result_flag_da = frag_ma_err_flag_da.getResults(); TEST_REAL_SIMILAR(result_flag_da[0].average_ppm, 5.0) TEST_REAL_SIMILAR(result_flag_da[0].variance_ppm, 0.0) // offset is constant, i.e. no variance //-------------------------------------------------------------------- // test with missing toleranceUnit and toleranceValue in featureMap //-------------------------------------------------------------------- // Search params without FME info { ProteinIdentification::SearchParameters empty_params; TEST_EXCEPTION(Exception::MissingInformation, frag_ma_err.compute(pep_ids, empty_params, exp, spectra_map, FragmentMassError::ToleranceUnit::AUTO)) } //-------------------------------------------------------------------- // test with no given fragmentation method //-------------------------------------------------------------------- // create MSExperiment with no given fragmentation method exp[0].setPrecursors({}); // falls back to CID spectra_map.calculateMap(exp); frag_ma_err.compute(pep_ids, param, exp, spectra_map); TEST_REAL_SIMILAR(frag_ma_err.getResults()[1].average_ppm, 5.0) TEST_REAL_SIMILAR(frag_ma_err.getResults()[1].variance_ppm, 0.0) // offset is constant, i.e. no variance //-------------------------------------------------------------------- // test with matching ms1 spectrum //-------------------------------------------------------------------- // PeptideIdentification with RT matching to a MS1 Spectrum PeptideIdentificationList ms1_id({createPeptideIdentification("XTandem::3")}); // set MS1 Spectrum to exp exp.setSpectra({createMSSpectrum(1, 5, "XTandem::3")}); spectra_map.calculateMap(exp); TEST_EXCEPTION(Exception::IllegalArgument, frag_ma_err.compute(ms1_id, param, exp, spectra_map)) //-------------------------------------------------------------------- // test with fragmentation method SORI, which is not supported //-------------------------------------------------------------------- // PeptideIdentification with RT matching to MSSpectrum with fragmentation method SORI PeptideIdentificationList sori_id({createPeptideIdentification("XTandem::5")}); // MSExperiment with fragmentation method SORI (not supported) exp.setSpectra({createMSSpectrum(2, 7, "XTandem::5", Precursor::ActivationMethod::SORI)}); spectra_map.calculateMap(exp); TEST_EXCEPTION(Exception::InvalidParameter, frag_ma_err.compute(sori_id, param, exp, spectra_map)) //-------------------------------------------------------------------- // test if spectrum has no peaks //-------------------------------------------------------------------- // PeptideIdentification with RT matching to MSSpectrum with no peaks PeptideIdentificationList no_peaks_id({createPeptideIdentification("XTandem::6")}); // MSExperiment without peaks exp.setSpectra({createMSSpectrum(2, 4, "XTandem::6")}); spectra_map.calculateMap(exp); FragmentMassError frag_ma_err_excp; frag_ma_err_excp.compute(no_peaks_id, param, exp, spectra_map); std::vector<FragmentMassError::Statistics> result_excp; result_excp = frag_ma_err_excp.getResults(); TEST_REAL_SIMILAR(result_excp[0].average_ppm, 0) TEST_REAL_SIMILAR(result_excp[0].variance_ppm, 0) } END_SECTION START_SECTION(const String& getName() const override) {TEST_EQUAL(frag_ma_err.getName(), "FragmentMassError")} END_SECTION START_SECTION(QCBase::Status requirements() const override) { QCBase::Status stat = QCBase::Status() | QCBase::Requires::RAWMZML | QCBase::Requires::POSTFDRFEAT; TEST_EQUAL(frag_ma_err.requirements() == stat, true) } END_SECTION END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/OPXLHelper_test.cpp
.cpp
24,737
503
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Eugen Netz $ // $Authors: Eugen Netz $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/ANALYSIS/XLMS/OPXLHelper.h> #include <OpenMS/ANALYSIS/XLMS/OPXLDataStructs.h> #include <OpenMS/CHEMISTRY/TheoreticalSpectrumGeneratorXLMS.h> #include <OpenMS/CHEMISTRY/TheoreticalSpectrumGenerator.h> #include <OpenMS/ANALYSIS/XLMS/OPXLSpectrumProcessingAlgorithms.h> #include <OpenMS/FORMAT/FASTAFile.h> #include <OpenMS/CHEMISTRY/ProteaseDigestion.h> #include <OpenMS/DATASTRUCTURES/ListUtils.h> #include <OpenMS/FORMAT/IdXMLFile.h> #include <OpenMS/CONCEPT/Constants.h> #include <OpenMS/CHEMISTRY/Tagger.h> #include <QStringList> using namespace OpenMS; START_TEST(OPXLHelper, "$Id$") // loading and building data structures required in several following tests std::vector<FASTAFile::FASTAEntry> fasta_db; FASTAFile file; file.load(OPENMS_GET_TEST_DATA_PATH("FASTAFile_test.fasta"), fasta_db); ProteaseDigestion digestor; String enzyme_name = "Trypsin"; digestor.setEnzyme(enzyme_name); digestor.setMissedCleavages(2); Size min_peptide_length = 5; QStringList q_str_list1; QStringList q_str_list2; q_str_list1 << "Carbamidomethyl (C)" << "Carbamidomethyl (T)"; q_str_list2 << "Oxidation (M)" << "Oxidation (Y)"; StringList fixedModNames = StringListUtils::fromQStringList(q_str_list1); StringList varModNames = StringListUtils::fromQStringList(q_str_list2); const ModifiedPeptideGenerator::MapToResidueType& fixed_modifications = ModifiedPeptideGenerator::getModifications(fixedModNames); const ModifiedPeptideGenerator::MapToResidueType& variable_modifications = ModifiedPeptideGenerator::getModifications(varModNames); QStringList q_str_list3; QStringList q_str_list4; q_str_list3 << "K" << "E"; q_str_list4 << "D" << "E" << "C-term"; StringList cross_link_residue1 = StringListUtils::fromQStringList(q_str_list3); StringList cross_link_residue2 = StringListUtils::fromQStringList(q_str_list4); Size max_variable_mods_per_peptide = 5; START_SECTION(static std::vector<OPXLDataStructs::AASeqWithMass> digestDatabase(std::vector<FASTAFile::FASTAEntry> fasta_db, EnzymaticDigestion digestor, Size min_peptide_length, StringList cross_link_residue1, StringList cross_link_residue2, std::vector<const ResidueModification*> fixed_modifications, std::vector<const ResidueModification*> variable_modifications, Size max_variable_mods_per_peptide)) std::vector<OPXLDataStructs::AASeqWithMass> peptides = OPXLHelper::digestDatabase(fasta_db, digestor, min_peptide_length, cross_link_residue1, cross_link_residue2, fixed_modifications, variable_modifications, max_variable_mods_per_peptide); TEST_EQUAL(peptides.size(), 886) TEST_EQUAL(peptides[5].peptide_mass > 5, true) // not an empty AASequence TEST_EQUAL(peptides[5].peptide_mass, peptides[5].peptide_seq.getMonoWeight()) TEST_EQUAL(peptides[500].peptide_mass > 5, true) // not an empty AASequence TEST_EQUAL(peptides[500].peptide_mass, peptides[500].peptide_seq.getMonoWeight()) TEST_EQUAL(peptides[668].position, OPXLDataStructs::INTERNAL) TEST_EQUAL(peptides[778].position, OPXLDataStructs::N_TERM) END_SECTION // building more data structures required in several following tests std::vector<OPXLDataStructs::AASeqWithMass> peptides = OPXLHelper::digestDatabase(fasta_db, digestor, min_peptide_length, cross_link_residue1, cross_link_residue2, fixed_modifications, variable_modifications, max_variable_mods_per_peptide); std::sort(peptides.begin(), peptides.end(), OPXLDataStructs::AASeqWithMassComparator()); double cross_link_mass = 150.0; double precursor_mass_tolerance = 10; bool precursor_mass_tolerance_unit_ppm = true; std::vector<String> mono_masses; mono_masses.push_back("50.0"); DoubleList cross_link_mass_mono_link = ListUtils::create<double>(mono_masses); std::vector< double > spectrum_precursors; double first_mass = peptides[700].peptide_mass + peptides[800].peptide_mass + cross_link_mass; for (Size i = 0; i < 1000; i++) { spectrum_precursors.push_back(first_mass + (i/4)); } std::sort(spectrum_precursors.begin(), spectrum_precursors.end()); START_SECTION(static std::vector<OPXLDataStructs::XLPrecursor> enumerateCrossLinksAndMasses(const std::vector<OPXLDataStructs::AASeqWithMass>& peptides, double cross_link_mass_light, const DoubleList& cross_link_mass_mono_link, const StringList& cross_link_residue1, const StringList& cross_link_residue2, std::vector< double >& spectrum_precursors, vector< int >& precursor_correction_positions, double precursor_mass_tolerance, bool precursor_mass_tolerance_unit_ppm)) std::cout << std::endl; std::vector< int > spectrum_precursor_correction_positions; std::vector<OPXLDataStructs::XLPrecursor> precursors = OPXLHelper::enumerateCrossLinksAndMasses(peptides, cross_link_mass, cross_link_mass_mono_link, cross_link_residue1, cross_link_residue2, spectrum_precursors, spectrum_precursor_correction_positions, precursor_mass_tolerance, precursor_mass_tolerance_unit_ppm); // std::sort(precursors.begin(), precursors.end(), OPXLDataStructs::XLPrecursorComparator()); TOLERANCE_ABSOLUTE(1e-3) TEST_EQUAL(precursors.size(), 9604) TEST_EQUAL(spectrum_precursor_correction_positions.size(), 9604) // sample about 1/15 of the data, since a lot of precursors are generated for (Size i = 0; i < precursors.size(); i += 2000) { if (precursors[i].beta_index > peptides.size()) { // mono-link TEST_REAL_SIMILAR(peptides[precursors[i].alpha_index].peptide_mass + cross_link_mass_mono_link[0], precursors[i].precursor_mass) } else { // cross-link double computed_precursor = peptides[precursors[i].alpha_index].peptide_mass + peptides[precursors[i].beta_index].peptide_mass + cross_link_mass; TEST_REAL_SIMILAR(computed_precursor, precursors[i].precursor_mass) } } END_SECTION // building more data structures required in the following test std::cout << std::endl; std::vector< int > spectrum_precursor_correction_positions; std::vector<OPXLDataStructs::XLPrecursor> precursors = OPXLHelper::enumerateCrossLinksAndMasses(peptides, cross_link_mass, cross_link_mass_mono_link, cross_link_residue1, cross_link_residue2, spectrum_precursors, spectrum_precursor_correction_positions, precursor_mass_tolerance, precursor_mass_tolerance_unit_ppm); std::sort(precursors.begin(), precursors.end(), OPXLDataStructs::XLPrecursorComparator()); START_SECTION(static std::vector <OPXLDataStructs::ProteinProteinCrossLink> buildCandidates(const std::vector< OPXLDataStructs::XLPrecursor > & candidates, const std::vector< int > precursor_corrections, std::vector< int >& precursor_correction_positions, const std::vector<OPXLDataStructs::AASeqWithMass> & peptide_masses, const StringList & cross_link_residue1, const StringList & cross_link_residue2, double cross_link_mass, const DoubleList & cross_link_mass_mono_link, std::vector< double >& spectrum_precursor_vector, std::vector< double >& allowed_error_vector, String cross_link_name)) double precursor_mass = 11814.50296; double allowed_error = 0.1; String cross_link_name = "MyLinker"; std::vector< OPXLDataStructs::XLPrecursor > filtered_precursors; // determine MS2 precursors that match to the current peptide mass std::vector< OPXLDataStructs::XLPrecursor >::const_iterator low_it; std::vector< OPXLDataStructs::XLPrecursor >::const_iterator up_it; low_it = std::lower_bound(precursors.begin(), precursors.end(), precursor_mass - allowed_error, OPXLDataStructs::XLPrecursorComparator()); up_it = std::upper_bound(precursors.begin(), precursors.end(), precursor_mass + allowed_error, OPXLDataStructs::XLPrecursorComparator()); if (low_it != up_it) // no matching precursor in data { for (; low_it != up_it; ++low_it) { filtered_precursors.push_back(*low_it); } } TEST_EQUAL(precursors.size(), 9604) TEST_EQUAL(filtered_precursors.size(), 32) std::vector< int > precursor_corrections(59, 0); std::vector< int > precursor_correction_positions(59, 0); std::vector< double > spectrum_precursor_vector(1, 0.0); std::vector< double > allowed_error_vector(1, allowed_error); std::vector <OPXLDataStructs::ProteinProteinCrossLink> spectrum_candidates = OPXLHelper::buildCandidates(filtered_precursors, precursor_corrections, precursor_correction_positions, peptides, cross_link_residue1, cross_link_residue2, cross_link_mass, cross_link_mass_mono_link, spectrum_precursor_vector, allowed_error_vector, cross_link_name); TEST_EQUAL(spectrum_candidates.size(), 1152) TEST_EQUAL(spectrum_candidates[50].cross_linker_name, "MyLinker") for (Size i = 0; i < spectrum_candidates.size(); i += 200) { TEST_REAL_SIMILAR(spectrum_candidates[i].alpha->getMonoWeight() + spectrum_candidates[i].beta->getMonoWeight() + spectrum_candidates[i].cross_linker_mass, precursor_mass) } END_SECTION // prepare data for the next three tests PeptideIdentificationList peptide_ids; std::vector< ProteinIdentification > protein_ids; IdXMLFile id_file; // this is an old test file, that can not be easily reproduced anymore, // since it represents an intermediate state of the data structures and is not written out // in this form anymore // But it is very useful to test the functions that change the old structure to the new one id_file.load(OPENMS_GET_TEST_DATA_PATH("OPXLHelper_test.idXML"), protein_ids, peptide_ids); for (auto& id : peptide_ids) //OMS_CODING_TEST_EXCLUDE { for (auto& hit : id.getHits()) //OMS_CODING_TEST_EXCLUDE { hit.removeMetaValue("XL_Protein_position_alpha"); hit.removeMetaValue("XL_Protein_position_beta"); hit.removeMetaValue("xl_target_decoy"); hit.removeMetaValue("accessions_beta"); } } START_SECTION(static void addProteinPositionMetaValues(PeptideIdentificationList & peptide_ids)) // test that the MetaValues were removed for (const auto& id : peptide_ids) { for (const auto& hit : id.getHits()) { TEST_EQUAL(hit.metaValueExists("XL_Protein_position_alpha"), false) TEST_EQUAL(hit.metaValueExists("XL_Protein_position_beta"), false) TEST_EQUAL(hit.metaValueExists("xl_target_decoy"), false) TEST_EQUAL(hit.metaValueExists("accessions_beta"), false) TEST_EQUAL(hit.metaValueExists(Constants::UserParam::OPENPEPXL_XL_POS1_PROT), false) TEST_EQUAL(hit.metaValueExists(Constants::UserParam::OPENPEPXL_XL_POS2_PROT), false) TEST_EQUAL(hit.metaValueExists(Constants::UserParam::OPENPEPXL_TARGET_DECOY_ALPHA), false) TEST_EQUAL(hit.metaValueExists(Constants::UserParam::OPENPEPXL_TARGET_DECOY_BETA), false) TEST_EQUAL(hit.metaValueExists(Constants::UserParam::OPENPEPXL_BETA_ACCESSIONS), false) TEST_EQUAL(hit.metaValueExists(Constants::UserParam::TARGET_DECOY), true) } } // add protein position MetaValues OPXLHelper::addProteinPositionMetaValues(peptide_ids); // check, that they were added to every PeptideHit for (const auto& id : peptide_ids) { const PeptideHit& hit = id.getHits()[0]; TEST_EQUAL(hit.metaValueExists(Constants::UserParam::OPENPEPXL_XL_POS1_PROT), true) TEST_EQUAL(hit.metaValueExists(Constants::UserParam::OPENPEPXL_XL_POS2_PROT), true) TEST_EQUAL(hit.metaValueExists(Constants::UserParam::OPENPEPXL_TARGET_DECOY_ALPHA), false) TEST_EQUAL(hit.metaValueExists(Constants::UserParam::OPENPEPXL_TARGET_DECOY_BETA), false) TEST_EQUAL(hit.metaValueExists(Constants::UserParam::OPENPEPXL_BETA_ACCESSIONS), false) } // a few example values TEST_EQUAL(peptide_ids[1].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_POS1_PROT), "1539") TEST_EQUAL(peptide_ids[1].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_POS2_PROT), "182") TEST_EQUAL(peptide_ids[1].getHits()[1].getMetaValue(Constants::UserParam::OPENPEPXL_XL_POS1_PROT), "1539") TEST_EQUAL(peptide_ids[1].getHits()[1].getMetaValue(Constants::UserParam::OPENPEPXL_XL_POS2_PROT), "182") END_SECTION START_SECTION(static void addXLTargetDecoyMV(PeptideIdentificationList & peptide_ids)) // add xl_target_decoy MetaValue OPXLHelper::addXLTargetDecoyMV(peptide_ids); // check, that they were added to every PeptideHit for (const auto& id : peptide_ids) { const PeptideHit& hit = id.getHits()[0]; TEST_EQUAL(hit.metaValueExists(Constants::UserParam::OPENPEPXL_TARGET_DECOY_ALPHA), true) TEST_EQUAL(hit.metaValueExists(Constants::UserParam::OPENPEPXL_TARGET_DECOY_BETA), true) } // a few example values TEST_EQUAL(peptide_ids[0].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_TARGET_DECOY_ALPHA), "target") TEST_EQUAL(peptide_ids[0].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_TARGET_DECOY_BETA), "-") TEST_EQUAL(peptide_ids[1].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_TARGET_DECOY_ALPHA), "target") TEST_EQUAL(peptide_ids[1].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_TARGET_DECOY_BETA), "target") END_SECTION START_SECTION(static void addBetaAccessions(PeptideIdentificationList & peptide_ids)) // add accessions_beta MV OPXLHelper::addBetaAccessions(peptide_ids); // check, that they were added to every PeptideHit for (const auto& id : peptide_ids) { for (const auto& hit : id.getHits()) { TEST_EQUAL(hit.metaValueExists(Constants::UserParam::OPENPEPXL_BETA_ACCESSIONS), true) } } // a few example values TEST_EQUAL(peptide_ids[0].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_BETA_ACCESSIONS), "-") TEST_EQUAL(peptide_ids[1].getHits()[1].getMetaValue(Constants::UserParam::OPENPEPXL_BETA_ACCESSIONS), "Protein1") END_SECTION START_SECTION(static PeptideIdentificationList combineTopRanksFromPairs(PeptideIdentificationList & peptide_ids, Size number_top_hits)) auto pep_ids = peptide_ids; // all hits are to separate spectra, so everything should be rank 1 for (const auto& id : pep_ids) { for (const auto& hit : id.getHits()) { TEST_EQUAL(hit.getMetaValue(Constants::UserParam::OPENPEPXL_XL_RANK), 1) } } // artificially assign one of the hits to the spectrum of another pep_ids[1].getHits()[0].setMetaValue("spectrum_index", pep_ids[0].getHits()[0].getMetaValue("spectrum_index")); pep_ids[1].getHits()[1].setMetaValue("spectrum_index", pep_ids[0].getHits()[0].getMetaValue("spectrum_index")); pep_ids = OPXLHelper::combineTopRanksFromPairs(pep_ids, 5); // there is one rank 2 now (in peptide_ids[2] now, because the order is not preserved) TEST_EQUAL(pep_ids[2].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_RANK), 2) END_SECTION START_SECTION(static void removeBetaPeptideHits(PeptideIdentificationList & peptide_ids)) OPXLHelper::removeBetaPeptideHits(peptide_ids); TEST_EQUAL(peptide_ids.size(), 3) for (const auto& id : peptide_ids) { TEST_EQUAL(id.getHits().size(), 1) } // a few example values // mono-link TEST_EQUAL(peptide_ids[0].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_POS1_PROT), "2078") TEST_EQUAL(peptide_ids[0].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_POS2_PROT), "-") // cross-link TEST_EQUAL(peptide_ids[1].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_POS1_PROT), "1539") TEST_EQUAL(peptide_ids[1].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_XL_POS2_PROT), "182") TEST_EQUAL(peptide_ids[1].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_BETA_PEPEV_PRE), "K") TEST_EQUAL(peptide_ids[1].getHits()[0].getMetaValue(Constants::UserParam::OPENPEPXL_BETA_PEPEV_END), "189") END_SECTION START_SECTION(static void buildFragmentAnnotations(std::vector<PeptideHit::PeakAnnotation> & frag_annotations, const std::vector< std::pair< Size, Size > > & matching, const PeakSpectrum & theoretical_spectrum, const PeakSpectrum & experiment_spectrum)) TheoreticalSpectrumGeneratorXLMS specGen; Param param = specGen.getParameters(); param.setValue("add_isotopes", "false"); param.setValue("add_metainfo", "true"); param.setValue("add_first_prefix_ion", "false"); param.setValue("add_a_ions", "false"); param.setValue("add_losses", "false"); param.setValue("add_precursor_peaks", "false"); param.setValue("add_k_linked_ions", "false"); specGen.setParameters(param); PeakSpectrum theo_spec, exp_spec; // Theoretical Spec with metainfo AASequence peptedi = AASequence::fromString("PEPTEDI"); specGen.getLinearIonSpectrum(theo_spec, peptedi, 4, true); param.setValue("add_metainfo", "false"); specGen.setParameters(param); // Theoretical Spec without metainfo (Pseudo experimental spectrum) AASequence peptide = AASequence::fromString("PEPTIDE"); specGen.getLinearIonSpectrum(exp_spec, peptide, 3, true); std::vector <std::pair <Size, Size> > alignment; DataArrays::FloatDataArray dummy_array; DataArrays::IntegerDataArray dummy_charge_array; OPXLSpectrumProcessingAlgorithms::getSpectrumAlignmentFastCharge(alignment, 50, true, theo_spec, exp_spec, dummy_charge_array, dummy_charge_array, dummy_array); std::vector<PeptideHit::PeakAnnotation> frag_annotations; // test, that additional annotations are added and do not replace existing ones PeptideHit::PeakAnnotation frag_anno; frag_anno.annotation = "TEST"; frag_anno.charge = 50; frag_anno.mz = 1.0; frag_anno.intensity = 5.0; frag_annotations.push_back(frag_anno); OPXLHelper::buildFragmentAnnotations(frag_annotations, alignment, theo_spec, exp_spec); // number of annotations should be equal to number of aligned peaks (+ 1 for manual "TEST" annotation) TEST_EQUAL(frag_annotations.size(), alignment.size() + 1) TEST_EQUAL(frag_annotations[0].charge, 50) TEST_EQUAL(frag_annotations[0].mz, 1.0) TEST_EQUAL(frag_annotations[0].intensity, 5.0) TEST_EQUAL(frag_annotations[0].annotation, "TEST") TEST_EQUAL(frag_annotations[1].charge, 1) TEST_REAL_SIMILAR(frag_annotations[1].mz, 98.06004) TEST_EQUAL(frag_annotations[1].intensity, 1) TEST_EQUAL(frag_annotations[1].annotation, "[alpha|ci$b1]") TEST_EQUAL(frag_annotations[3].charge, 1) TEST_REAL_SIMILAR(frag_annotations[3].mz, 324.15539) TEST_EQUAL(frag_annotations[3].intensity, 1) TEST_EQUAL(frag_annotations[3].annotation, "[alpha|ci$b3]") END_SECTION START_SECTION(static std::vector <OPXLDataStructs::ProteinProteinCrossLink> OPXLHelper::collectPrecursorCandidates(IntList precursor_correction_steps, double precursor_mass, double precursor_mass_tolerance, bool precursor_mass_tolerance_unit_ppm, std::vector<OPXLDataStructs::AASeqWithMass> filtered_peptide_masses, double cross_link_mass, DoubleList cross_link_mass_mono_link, StringList cross_link_residue1, StringList cross_link_residue2, String cross_link_name, bool use_sequence_tags, std::vector<std::string>& tags)) IntList precursor_correction_steps; precursor_correction_steps.push_back(2); precursor_correction_steps.push_back(1); double precursor_mass = 10668.85060; String cross_link_name = "MyLinker"; precursor_mass_tolerance = 10; std::vector <OPXLDataStructs::ProteinProteinCrossLink> spectrum_candidates = OPXLHelper::collectPrecursorCandidates(precursor_correction_steps, precursor_mass, precursor_mass_tolerance, precursor_mass_tolerance_unit_ppm, peptides, cross_link_mass, cross_link_mass_mono_link, cross_link_residue1, cross_link_residue2, cross_link_name); TEST_EQUAL(spectrum_candidates.size(), 1050) TEST_EQUAL(spectrum_candidates[50].cross_linker_name, "MyLinker") for (Size i = 0; i < spectrum_candidates.size(); i += 100) { TEST_REAL_SIMILAR(spectrum_candidates[i].alpha->getMonoWeight() + spectrum_candidates[i].beta->getMonoWeight() + spectrum_candidates[i].cross_linker_mass, precursor_mass - 1 * Constants::C13C12_MASSDIFF_U) } END_SECTION START_SECTION(static double OPXLHelper::computePrecursorError(OPXLDataStructs::CrossLinkSpectrumMatch csm, double precursor_mz, int precursor_charge)) OPXLDataStructs::ProteinProteinCrossLink ppcl; AASequence alpha = AASequence::fromString("TESTPEPTIDE"); AASequence beta = AASequence::fromString("TESTTESTESTE"); ppcl.alpha = &alpha; ppcl.beta = &beta; ppcl.cross_linker_mass = 150.0; OPXLDataStructs::CrossLinkSpectrumMatch csm; csm.cross_link = ppcl; csm.precursor_correction = 0; double precursor_charge = 3; double precursor_mz = (ppcl.alpha->getMonoWeight() + ppcl.beta->getMonoWeight() + ppcl.cross_linker_mass + precursor_charge * Constants::PROTON_MASS_U) / precursor_charge; double rel_error = OPXLHelper::computePrecursorError(csm, precursor_mz, precursor_charge); TEST_REAL_SIMILAR(rel_error, 0) precursor_mz += 0.05; rel_error = OPXLHelper::computePrecursorError(csm, precursor_mz, precursor_charge); TEST_REAL_SIMILAR(rel_error, 56.21777) END_SECTION START_SECTION(static void OPXLHelper::isoPeakMeans(OPXLDataStructs::CrossLinkSpectrumMatch& csm, DataArrays::IntegerDataArray& num_iso_peaks_array, std::vector< std::pair< Size, Size > >& matched_spec_linear_alpha, std::vector< std::pair< Size, Size > >& matched_spec_linear_beta, std::vector< std::pair< Size, Size > >& matched_spec_xlinks_alpha, std::vector< std::pair< Size, Size > >& matched_spec_xlinks_beta)) DataArrays::IntegerDataArray iso_peaks; iso_peaks.push_back(3); iso_peaks.push_back(5); iso_peaks.push_back(2); iso_peaks.push_back(1); iso_peaks.push_back(1); iso_peaks.push_back(3); iso_peaks.push_back(1); iso_peaks.push_back(3); iso_peaks.push_back(2); std::vector< std::pair< Size, Size > > matched_spec_linear_alpha; matched_spec_linear_alpha.push_back(std::make_pair(1,1)); matched_spec_linear_alpha.push_back(std::make_pair(2,2)); matched_spec_linear_alpha.push_back(std::make_pair(4,3)); matched_spec_linear_alpha.push_back(std::make_pair(6,4)); matched_spec_linear_alpha.push_back(std::make_pair(7,5)); std::vector< std::pair< Size, Size > > matched_spec_linear_beta; std::vector< std::pair< Size, Size > > matched_spec_xlinks_alpha; std::vector< std::pair< Size, Size > > matched_spec_xlinks_beta; matched_spec_xlinks_beta.push_back(std::make_pair(3,1)); matched_spec_xlinks_beta.push_back(std::make_pair(5,2)); matched_spec_xlinks_beta.push_back(std::make_pair(8,3)); matched_spec_xlinks_beta.push_back(std::make_pair(0,4)); OPXLDataStructs::CrossLinkSpectrumMatch csm; OPXLHelper::isoPeakMeans(csm, iso_peaks, matched_spec_linear_alpha, matched_spec_linear_beta, matched_spec_xlinks_alpha, matched_spec_xlinks_beta); TEST_REAL_SIMILAR(csm.num_iso_peaks_mean, 2.3333) TEST_REAL_SIMILAR(csm.num_iso_peaks_mean_linear_alpha, 2.4) TEST_REAL_SIMILAR(csm.num_iso_peaks_mean_linear_beta, 0) TEST_REAL_SIMILAR(csm.num_iso_peaks_mean_xlinks_alpha, 0) TEST_REAL_SIMILAR(csm.num_iso_peaks_mean_xlinks_beta, 2.25) END_SECTION START_SECTION(filterPrecursorsByTags(std::vector <OPXLDataStructs::XLPrecursor>& candidates, std::vector<std::string>& tags)) std::cout << std::endl; std::vector< int > spectrum_precursor_correction_positions; std::vector<OPXLDataStructs::XLPrecursor> precursors = OPXLHelper::enumerateCrossLinksAndMasses(peptides, cross_link_mass, cross_link_mass_mono_link, cross_link_residue1, cross_link_residue2, spectrum_precursors, spectrum_precursor_correction_positions, precursor_mass_tolerance, precursor_mass_tolerance_unit_ppm); // set of tags std::vector<std::string> tags = {"DE", "PP", "FDA", "CIA", "FTC", "ESA", "ISRO", "NASA", "JAXA"}; TEST_EQUAL(precursors.size(), 9604); // filter candidates OPXLHelper::filterPrecursorsByTags(precursors, spectrum_precursor_correction_positions, tags); TEST_EQUAL(precursors.size(), 4372); // // hasSubstring method runtime benchmark: search those 4372 candidates that do not contain the tags many times // // with 30000 iterations: 126.80 sec // std::cout << std::endl; // for (int i = 0; i < 30000; ++i) // { // OPXLHelper::filterPrecursorsByTags(precursors, spectrum_precursor_correction_positions, tags); // } // TEST_EQUAL(precursors.size(), 4372); // // Aho-Corasick method runtime benchmark: search those 4372 candidates that do not contain the tags many times // // with 30000 iterations: Timeout after 1500.10 sec // // with 3000 iterations: 200.92 sec // for (int i = 0; i < 3000; ++i) // { // OPXLHelper::filterPrecursorsByTagTrie(precursors, spectrum_precursor_correction_positions, tags); // } // TEST_EQUAL(precursors.size(), 4372); END_SECTION END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/BasicProteinInferenceAlgorithm_test.cpp
.cpp
10,877
219
// 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 $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/ANALYSIS/ID/BasicProteinInferenceAlgorithm.h> #include <OpenMS/FORMAT/IdXMLFile.h> #include <OpenMS/test_config.h> #include <OpenMS/FORMAT/ConsensusXMLFile.h> using namespace OpenMS; using namespace std; START_TEST(BasicProteinInferenceAlgorithm, "$Id$") START_SECTION(BasicProteinInferenceAlgorithm on Protein Peptide ID) { vector<ProteinIdentification> prots; PeptideIdentificationList peps; IdXMLFile idf; idf.load(OPENMS_GET_TEST_DATA_PATH("newMergerTest_out.idXML"),prots,peps); BasicProteinInferenceAlgorithm bpia; Param p = bpia.getParameters(); p.setValue("min_peptides_per_protein", 0); p.setValue("annotate_indistinguishable_groups", "false"); bpia.setParameters(p); bpia.run(peps, prots); TEST_EQUAL(prots[0].getHits()[0].getScore(), 0.6) TEST_EQUAL(prots[0].getHits()[1].getScore(), 0.6) TEST_EQUAL(prots[0].getHits()[2].getScore(), -std::numeric_limits<double>::infinity()) TEST_EQUAL(prots[0].getHits()[3].getScore(), 0.8) TEST_EQUAL(prots[0].getHits()[4].getScore(), 0.6) TEST_EQUAL(prots[0].getHits()[5].getScore(), 0.9) TEST_EQUAL(prots[0].getHits()[0].getMetaValue("nr_found_peptides"), 1) TEST_EQUAL(prots[0].getHits()[1].getMetaValue("nr_found_peptides"), 1) TEST_EQUAL(prots[0].getHits()[2].getMetaValue("nr_found_peptides"), 0) TEST_EQUAL(prots[0].getHits()[3].getMetaValue("nr_found_peptides"), 2) TEST_EQUAL(prots[0].getHits()[4].getMetaValue("nr_found_peptides"), 1) TEST_EQUAL(prots[0].getHits()[5].getMetaValue("nr_found_peptides"), 1) } END_SECTION START_SECTION(BasicProteinInferenceAlgorithm on Protein Peptide ID without shared peps) { vector<ProteinIdentification> prots; PeptideIdentificationList peps; IdXMLFile idf; idf.load(OPENMS_GET_TEST_DATA_PATH("newMergerTest_out.idXML"),prots,peps); BasicProteinInferenceAlgorithm bpia; Param p = bpia.getParameters(); p.setValue("use_shared_peptides","false"); p.setValue("min_peptides_per_protein", 0); p.setValue("annotate_indistinguishable_groups", "false"); bpia.setParameters(p); bpia.run(peps, prots); TEST_EQUAL(prots[0].getHits()[0].getScore(), -std::numeric_limits<double>::infinity()) TEST_EQUAL(prots[0].getHits()[1].getScore(), -std::numeric_limits<double>::infinity()) TEST_EQUAL(prots[0].getHits()[2].getScore(), -std::numeric_limits<double>::infinity()) TEST_EQUAL(prots[0].getHits()[3].getScore(), 0.8) TEST_EQUAL(prots[0].getHits()[4].getScore(), -std::numeric_limits<double>::infinity()) TEST_EQUAL(prots[0].getHits()[5].getScore(), 0.9) TEST_EQUAL(prots[0].getHits()[0].getMetaValue("nr_found_peptides"), 0) TEST_EQUAL(prots[0].getHits()[1].getMetaValue("nr_found_peptides"), 0) TEST_EQUAL(prots[0].getHits()[2].getMetaValue("nr_found_peptides"), 0) TEST_EQUAL(prots[0].getHits()[3].getMetaValue("nr_found_peptides"), 1) TEST_EQUAL(prots[0].getHits()[4].getMetaValue("nr_found_peptides"), 0) TEST_EQUAL(prots[0].getHits()[5].getMetaValue("nr_found_peptides"), 1) } END_SECTION START_SECTION(BasicProteinInferenceAlgorithm on Protein Peptide ID with grouping) { vector<ProteinIdentification> prots; PeptideIdentificationList peps; IdXMLFile idf; idf.load(OPENMS_GET_TEST_DATA_PATH("newMergerTest_out.idXML"),prots,peps); BasicProteinInferenceAlgorithm bpia; Param p = bpia.getParameters(); p.setValue("min_peptides_per_protein", 0); p.setValue("annotate_indistinguishable_groups", "true"); bpia.setParameters(p); bpia.run(peps, prots); TEST_EQUAL(prots[0].getHits()[0].getScore(), 0.6) TEST_EQUAL(prots[0].getHits()[1].getScore(), 0.6) TEST_EQUAL(prots[0].getHits()[2].getScore(), -std::numeric_limits<double>::infinity()) TEST_EQUAL(prots[0].getHits()[3].getScore(), 0.8) TEST_EQUAL(prots[0].getHits()[4].getScore(), 0.6) TEST_EQUAL(prots[0].getHits()[5].getScore(), 0.9) TEST_EQUAL(prots[0].getIndistinguishableProteins().size(), 4); TEST_EQUAL(prots[0].getIndistinguishableProteins()[0].probability, 0.9); TEST_EQUAL(prots[0].getIndistinguishableProteins()[1].probability, 0.8); TEST_EQUAL(prots[0].getIndistinguishableProteins()[2].probability, 0.6); TEST_EQUAL(prots[0].getIndistinguishableProteins()[3].probability, 0.6); TEST_EQUAL(prots[0].getHits()[0].getMetaValue("nr_found_peptides"), 1) TEST_EQUAL(prots[0].getHits()[1].getMetaValue("nr_found_peptides"), 1) TEST_EQUAL(prots[0].getHits()[2].getMetaValue("nr_found_peptides"), 0) TEST_EQUAL(prots[0].getHits()[3].getMetaValue("nr_found_peptides"), 2) TEST_EQUAL(prots[0].getHits()[4].getMetaValue("nr_found_peptides"), 1) TEST_EQUAL(prots[0].getHits()[5].getMetaValue("nr_found_peptides"), 1) } END_SECTION START_SECTION(BasicProteinInferenceAlgorithm on Protein Peptide ID with grouping plus resolution) { vector<ProteinIdentification> prots; PeptideIdentificationList peps; IdXMLFile idf; idf.load(OPENMS_GET_TEST_DATA_PATH("newMergerTest_out.idXML"),prots,peps); BasicProteinInferenceAlgorithm bpia; Param p = bpia.getParameters(); p.setValue("min_peptides_per_protein", 0); p.setValue("annotate_indistinguishable_groups", "true"); p.setValue("greedy_group_resolution", "true"); bpia.setParameters(p); bpia.run(peps, prots); TEST_EQUAL(prots[0].getHits().size(), 4) TEST_EQUAL(prots[0].getHits()[0].getScore(), 0.6) TEST_EQUAL(prots[0].getHits()[1].getScore(), 0.6) TEST_EQUAL(prots[0].getHits()[2].getScore(), 0.8) TEST_EQUAL(prots[0].getHits()[3].getScore(), 0.9) TEST_EQUAL(prots[0].getHits()[0].getMetaValue("nr_found_peptides"), 1) TEST_EQUAL(prots[0].getHits()[1].getMetaValue("nr_found_peptides"), 1) TEST_EQUAL(prots[0].getHits()[2].getMetaValue("nr_found_peptides"), 2) TEST_EQUAL(prots[0].getHits()[3].getMetaValue("nr_found_peptides"), 1) TEST_EQUAL(prots[0].getIndistinguishableProteins().size(), 3); TEST_EQUAL(prots[0].getIndistinguishableProteins()[0].probability, 0.9); TEST_EQUAL(prots[0].getIndistinguishableProteins()[1].probability, 0.8); TEST_EQUAL(prots[0].getIndistinguishableProteins()[2].probability, 0.6); } END_SECTION START_SECTION(BasicProteinInferenceAlgorithm on Protein Peptide ID with grouping and user score) { vector<ProteinIdentification> prots; PeptideIdentificationList peps; IdXMLFile idf; idf.load(OPENMS_GET_TEST_DATA_PATH("newMergerTest_out.idXML"),prots,peps); BasicProteinInferenceAlgorithm bpia; Param p = bpia.getParameters(); p.setValue("min_peptides_per_protein", 0); p.setValue("annotate_indistinguishable_groups", "true"); p.setValue("score_type", "RAW"); // should use the XTandem score meta value bpia.setParameters(p); TEST_EQUAL(peps[0].getScoreType(), "Posterior Error Probability"); // check if main score is PEP bpia.run(peps, prots); TEST_EQUAL(peps[0].getScoreType(), "Posterior Error Probability"); // check if main score has been reset again to PEP TEST_EQUAL(prots[0].getHits()[0].getScore(), 2.5) TEST_EQUAL(prots[0].getHits()[1].getScore(), 2.5) TEST_EQUAL(prots[0].getHits()[2].getScore(), -std::numeric_limits<double>::infinity()) TEST_EQUAL(prots[0].getHits()[3].getScore(), 5.0) TEST_EQUAL(prots[0].getHits()[4].getScore(), 2.5) TEST_EQUAL(prots[0].getHits()[5].getScore(), 10.0) TEST_EQUAL(prots[0].getIndistinguishableProteins().size(), 4); TEST_EQUAL(prots[0].getIndistinguishableProteins()[0].probability, 10.0); TEST_EQUAL(prots[0].getIndistinguishableProteins()[1].probability, 5.0); TEST_EQUAL(prots[0].getIndistinguishableProteins()[2].probability, 2.5); TEST_EQUAL(prots[0].getIndistinguishableProteins()[3].probability, 2.5); TEST_EQUAL(prots[0].getHits()[0].getMetaValue("nr_found_peptides"), 1) TEST_EQUAL(prots[0].getHits()[1].getMetaValue("nr_found_peptides"), 1) TEST_EQUAL(prots[0].getHits()[2].getMetaValue("nr_found_peptides"), 0) TEST_EQUAL(prots[0].getHits()[3].getMetaValue("nr_found_peptides"), 2) TEST_EQUAL(prots[0].getHits()[4].getMetaValue("nr_found_peptides"), 1) TEST_EQUAL(prots[0].getHits()[5].getMetaValue("nr_found_peptides"), 1) } END_SECTION START_SECTION(BasicProteinInferenceAlgorithm on Protein Peptide ID with grouping plus resolution and user set score type) { vector<ProteinIdentification> prots; PeptideIdentificationList peps; IdXMLFile idf; idf.load(OPENMS_GET_TEST_DATA_PATH("newMergerTest_out.idXML"),prots,peps); BasicProteinInferenceAlgorithm bpia; Param p = bpia.getParameters(); p.setValue("min_peptides_per_protein", 0); p.setValue("annotate_indistinguishable_groups", "true"); p.setValue("greedy_group_resolution", "true"); p.setValue("score_type", "RAW"); // should use the XTandem score meta value bpia.setParameters(p); TEST_EQUAL(peps[0].getScoreType(), "Posterior Error Probability"); // check if main score is PEP bpia.run(peps, prots); TEST_EQUAL(peps[0].getScoreType(), "Posterior Error Probability"); // check if main score has been reset again to PEP TEST_EQUAL(prots[0].getHits().size(), 4) TEST_EQUAL(prots[0].getHits().at(0).getScore(), 2.5) TEST_EQUAL(prots[0].getHits().at(1).getScore(), 2.5) TEST_EQUAL(prots[0].getHits().at(2).getScore(), 5.0) TEST_EQUAL(prots[0].getHits().at(3).getScore(), 10.0) TEST_EQUAL(prots[0].getHits().at(0).getMetaValue("nr_found_peptides"), 1) TEST_EQUAL(prots[0].getHits().at(1).getMetaValue("nr_found_peptides"), 1) TEST_EQUAL(prots[0].getHits().at(2).getMetaValue("nr_found_peptides"), 2) TEST_EQUAL(prots[0].getHits().at(3).getMetaValue("nr_found_peptides"), 1) TEST_EQUAL(prots[0].getIndistinguishableProteins().size(), 3); TEST_EQUAL(prots[0].getIndistinguishableProteins().at(0).probability, 10); TEST_EQUAL(prots[0].getIndistinguishableProteins().at(1).probability, 5.0); TEST_EQUAL(prots[0].getIndistinguishableProteins().at(2).probability, 2.5); } END_SECTION END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MRMBatchFeatureSelector_test.cpp
.cpp
994
29
// 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 $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/ANALYSIS/OPENSWATH/MRMBatchFeatureSelector.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(MRMBatchFeatureSelector, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// // Deleted constructor and destructor ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/GridFeature_test.cpp
.cpp
3,023
120
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hendrik Weisser $ // $Authors: Hendrik Weisser $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/DATASTRUCTURES/GridFeature.h> /////////////////////////// #include <OpenMS/KERNEL/BaseFeature.h> #include <OpenMS/METADATA/PeptideIdentification.h> #include <OpenMS/CHEMISTRY/AASequence.h> START_TEST(GridFeature, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace std; GridFeature* gf_ptr = nullptr; GridFeature* gf_nullPointer = nullptr; START_SECTION((GridFeature(const BaseFeature& feature, Size map_index, Size feature_index))) { BaseFeature bf; gf_ptr = new GridFeature(bf, 0, 0); TEST_NOT_EQUAL(gf_ptr, gf_nullPointer); } END_SECTION START_SECTION((~GridFeature())) { delete gf_ptr; } END_SECTION START_SECTION((const BaseFeature& getFeature() const)) { BaseFeature bf; bf.setRT(1.1); bf.setMZ(2.2); bf.setCharge(3); const BaseFeature bf_const(bf); GridFeature gf(bf_const, 0, 0); TEST_EQUAL(gf.getFeature() == bf_const, true); } END_SECTION START_SECTION((Size getMapIndex() const)) { BaseFeature bf; GridFeature gf(bf, 123, 0); TEST_EQUAL(gf.getMapIndex(), 123); } END_SECTION START_SECTION((Size getFeatureIndex() const)) { BaseFeature bf; GridFeature gf(bf, 0, 123); TEST_EQUAL(gf.getFeatureIndex(), 123); } END_SECTION START_SECTION((Int getID() const)) { BaseFeature bf; GridFeature gf(bf, 0, 123); TEST_EQUAL(gf.getID(), 123); } END_SECTION START_SECTION((const std::set<AASequence>& getAnnotations() const)) { BaseFeature bf; GridFeature gf(bf, 0, 0); TEST_EQUAL(gf.getAnnotations().size(), 0); bf.getPeptideIdentifications().resize(2); PeptideHit hit; hit.setSequence(AASequence::fromString("AAA")); bf.getPeptideIdentifications()[0].insertHit(hit); hit.setSequence(AASequence::fromString("CCC")); bf.getPeptideIdentifications()[1].insertHit(hit); GridFeature gf2(bf, 0, 0); TEST_EQUAL(gf2.getAnnotations().size(), 2); TEST_EQUAL(*(gf2.getAnnotations().begin()), AASequence::fromString("AAA")); TEST_EQUAL(*(gf2.getAnnotations().rbegin()), AASequence::fromString("CCC")); } END_SECTION START_SECTION((double getRT() const)) { BaseFeature bf; bf.setRT(4.56); GridFeature gf(bf, 0, 123); TEST_REAL_SIMILAR(gf.getRT(), 4.56); } END_SECTION START_SECTION((double getMZ() const)) { BaseFeature bf; bf.setMZ(4.56); GridFeature gf(bf, 0, 123); TEST_REAL_SIMILAR(gf.getMZ(), 4.56); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MRMFeatureQCFile_test.cpp
.cpp
25,337
612
// 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 $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> #include <OpenMS/ANALYSIS/OPENSWATH/MRMFeatureQC.h> #include <OpenMS/SYSTEM/File.h> #include <OpenMS/FORMAT/MRMFeatureQCFile.h> using namespace OpenMS; using namespace std; class MRMFeatureQCFile_facade : MRMFeatureQCFile { public: void pushValuesFromLine_( const StringList& line, const std::map<String, Size>& headers, std::vector<MRMFeatureQC::ComponentQCs>& c_qcs ) const { MRMFeatureQCFile::pushValuesFromLine_(line, headers, c_qcs); } void pushValuesFromLine_( const StringList& line, const std::map<String, Size>& headers, std::vector<MRMFeatureQC::ComponentGroupQCs>& cg_qcs ) const { MRMFeatureQCFile::pushValuesFromLine_(line, headers, cg_qcs); } void setPairValue_( const String& key, const String& value, const String& boundary, std::map<String, std::pair<double,double>>& meta_values_qc ) const { MRMFeatureQCFile::setPairValue_(key, value, boundary, meta_values_qc); } Int getCastValue_( const std::map<String, Size>& headers, const StringList& line, const String& header, const Int default_value ) const { return MRMFeatureQCFile::getCastValue_(headers, line, header, default_value); } double getCastValue_( const std::map<String, Size>& headers, const StringList& line, const String& header, const double default_value ) const { return MRMFeatureQCFile::getCastValue_(headers, line, header, default_value); } String getCastValue_( const std::map<String, Size>& headers, const StringList& line, const String& header, const String& default_value ) const { return MRMFeatureQCFile::getCastValue_(headers, line, header, default_value); } }; START_TEST(MRMFeatureQCFile, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// MRMFeatureQCFile* ptr = nullptr; MRMFeatureQCFile* nullPointer = nullptr; START_SECTION(MRMFeatureQCFile()) { ptr = new MRMFeatureQCFile(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(~MRMFeatureQCFile()) { delete ptr; } END_SECTION START_SECTION(void load(const String& filename, MRMFeatureQC& mrmfqc, const bool is_component_group) const) { MRMFeatureQCFile mrmfqcfile; MRMFeatureQC mrmfqc; mrmfqcfile.load(OPENMS_GET_TEST_DATA_PATH("MRMFeatureQCFile_1.csv"), mrmfqc, false); // components file mrmfqcfile.load(OPENMS_GET_TEST_DATA_PATH("MRMFeatureQCFile_2.csv"), mrmfqc, true); // component groups file const std::vector<MRMFeatureQC::ComponentQCs>& c_qcs = mrmfqc.component_qcs; const std::vector<MRMFeatureQC::ComponentGroupQCs>& cg_qcs = mrmfqc.component_group_qcs; TEST_EQUAL(c_qcs[0].component_name, "component1"); TEST_EQUAL(c_qcs[1].component_name, "component2"); TEST_EQUAL(c_qcs[2].component_name, "component3"); TEST_EQUAL(c_qcs[3].component_name, "component4"); // note that the previous line within the file is skipped because component_name is empty TEST_REAL_SIMILAR(c_qcs[0].retention_time_l, 1.0); TEST_REAL_SIMILAR(c_qcs[1].retention_time_l, 3.0); TEST_REAL_SIMILAR(c_qcs[2].retention_time_l, 5.0); TEST_REAL_SIMILAR(c_qcs[3].retention_time_l, 0.0); // default value TEST_REAL_SIMILAR(c_qcs[0].retention_time_u, 2.0); TEST_REAL_SIMILAR(c_qcs[1].retention_time_u, 4.0); TEST_REAL_SIMILAR(c_qcs[2].retention_time_u, 6.0); TEST_REAL_SIMILAR(c_qcs[3].retention_time_u, 1e12); // default value TEST_REAL_SIMILAR(c_qcs[0].intensity_l, 1000.0); TEST_REAL_SIMILAR(c_qcs[1].intensity_l, 2000.0); TEST_REAL_SIMILAR(c_qcs[2].intensity_l, 3000.0); TEST_REAL_SIMILAR(c_qcs[3].intensity_l, 0.0); // default value TEST_REAL_SIMILAR(c_qcs[0].intensity_u, 1000000.0); TEST_REAL_SIMILAR(c_qcs[1].intensity_u, 2000000.0); TEST_REAL_SIMILAR(c_qcs[2].intensity_u, 3000000.0); TEST_REAL_SIMILAR(c_qcs[3].intensity_u, 1e12); // default value TEST_REAL_SIMILAR(c_qcs[0].overall_quality_l, 2.0); TEST_REAL_SIMILAR(c_qcs[1].overall_quality_l, 3.0); TEST_REAL_SIMILAR(c_qcs[2].overall_quality_l, 4.0); TEST_REAL_SIMILAR(c_qcs[3].overall_quality_l, 0.0); // default value TEST_REAL_SIMILAR(c_qcs[0].overall_quality_u, 5.0); TEST_REAL_SIMILAR(c_qcs[1].overall_quality_u, 6.0); TEST_REAL_SIMILAR(c_qcs[2].overall_quality_u, 7.0); TEST_REAL_SIMILAR(c_qcs[3].overall_quality_u, 1e12); // default value TEST_REAL_SIMILAR(c_qcs[0].meta_value_qc.at("peak_apex_int").first, 1000.0); TEST_REAL_SIMILAR(c_qcs[1].meta_value_qc.at("peak_apex_int").first, 2000.0); TEST_REAL_SIMILAR(c_qcs[2].meta_value_qc.at("peak_apex_int").first, 3000.0); TEST_REAL_SIMILAR(c_qcs[3].meta_value_qc.at("peak_apex_int").first, 0.0); // default value TEST_REAL_SIMILAR(c_qcs[0].meta_value_qc.at("peak_apex_int").second, 1000000.0); TEST_REAL_SIMILAR(c_qcs[1].meta_value_qc.at("peak_apex_int").second, 2000000.0); TEST_REAL_SIMILAR(c_qcs[2].meta_value_qc.at("peak_apex_int").second, 3000000.0); TEST_REAL_SIMILAR(c_qcs[3].meta_value_qc.at("peak_apex_int").second, 1e12); // default value TEST_REAL_SIMILAR(c_qcs[0].meta_value_qc.at("sn_score").first, 2.0); TEST_REAL_SIMILAR(c_qcs[1].meta_value_qc.at("sn_score").first, 5.0); TEST_REAL_SIMILAR(c_qcs[2].meta_value_qc.at("sn_score").first, 10.0); TEST_REAL_SIMILAR(c_qcs[3].meta_value_qc.at("sn_score").first, 0.0); // default value TEST_REAL_SIMILAR(c_qcs[0].meta_value_qc.at("sn_score").second, 10.0); TEST_REAL_SIMILAR(c_qcs[1].meta_value_qc.at("sn_score").second, 20.0); TEST_REAL_SIMILAR(c_qcs[2].meta_value_qc.at("sn_score").second, 50.0); TEST_REAL_SIMILAR(c_qcs[3].meta_value_qc.at("sn_score").second, 1e12); // default value TEST_EQUAL(cg_qcs[0].component_group_name, "componentGroup1"); TEST_EQUAL(cg_qcs[1].component_group_name, "componentGroup2"); TEST_EQUAL(cg_qcs[2].component_group_name, "componentGroup3"); TEST_EQUAL(cg_qcs[3].component_group_name, "componentGroup5"); TEST_EQUAL(cg_qcs[0].n_heavy_l, 1); TEST_EQUAL(cg_qcs[2].n_heavy_l, 3); TEST_EQUAL(cg_qcs[0].n_heavy_u, 2); TEST_EQUAL(cg_qcs[2].n_heavy_u, 4); TEST_EQUAL(cg_qcs[0].n_light_l, 3); TEST_EQUAL(cg_qcs[2].n_light_l, 5); TEST_EQUAL(cg_qcs[0].n_light_u, 4); TEST_EQUAL(cg_qcs[2].n_light_u, 6); TEST_EQUAL(cg_qcs[0].n_detecting_l, 5); TEST_EQUAL(cg_qcs[2].n_detecting_l, 7); TEST_EQUAL(cg_qcs[0].n_detecting_u, 6); TEST_EQUAL(cg_qcs[2].n_detecting_u, 8); TEST_EQUAL(cg_qcs[0].n_quantifying_l, 7); TEST_EQUAL(cg_qcs[2].n_quantifying_l, 9); TEST_EQUAL(cg_qcs[0].n_quantifying_u, 8); TEST_EQUAL(cg_qcs[2].n_quantifying_u, 10); TEST_EQUAL(cg_qcs[0].n_identifying_l, 9); TEST_EQUAL(cg_qcs[2].n_identifying_l, 11); TEST_EQUAL(cg_qcs[0].n_identifying_u, 10); TEST_EQUAL(cg_qcs[2].n_identifying_u, 12); TEST_EQUAL(cg_qcs[0].n_transitions_l, 11); TEST_EQUAL(cg_qcs[2].n_transitions_l, 13); TEST_EQUAL(cg_qcs[0].n_transitions_u, 12); TEST_EQUAL(cg_qcs[2].n_transitions_u, 14); TEST_EQUAL(cg_qcs[0].ion_ratio_pair_name_1, "component1"); TEST_EQUAL(cg_qcs[2].ion_ratio_pair_name_1, "component5"); TEST_EQUAL(cg_qcs[0].ion_ratio_pair_name_2, "component2"); TEST_EQUAL(cg_qcs[2].ion_ratio_pair_name_2, "component6"); TEST_REAL_SIMILAR(cg_qcs[0].ion_ratio_l, 0.5); TEST_REAL_SIMILAR(cg_qcs[2].ion_ratio_l, 2.5); TEST_REAL_SIMILAR(cg_qcs[0].ion_ratio_u, 0.6); TEST_REAL_SIMILAR(cg_qcs[2].ion_ratio_u, 2.6); TEST_EQUAL(cg_qcs[0].ion_ratio_feature_name, "feature1"); TEST_EQUAL(cg_qcs[2].ion_ratio_feature_name, "feature3"); TEST_REAL_SIMILAR(cg_qcs[0].retention_time_l, 1.0); TEST_REAL_SIMILAR(cg_qcs[1].retention_time_l, 2.0); TEST_REAL_SIMILAR(cg_qcs[2].retention_time_l, 3.0); TEST_REAL_SIMILAR(cg_qcs[0].retention_time_u, 2.0); TEST_REAL_SIMILAR(cg_qcs[1].retention_time_u, 3.0); TEST_REAL_SIMILAR(cg_qcs[2].retention_time_u, 4.0); TEST_REAL_SIMILAR(cg_qcs[0].intensity_l, 1000.0); TEST_REAL_SIMILAR(cg_qcs[1].intensity_l, 1001.0); TEST_REAL_SIMILAR(cg_qcs[2].intensity_l, 1002.0); TEST_REAL_SIMILAR(cg_qcs[0].intensity_u, 1000000.0); TEST_REAL_SIMILAR(cg_qcs[1].intensity_u, 1000001.0); TEST_REAL_SIMILAR(cg_qcs[2].intensity_u, 1000002.0); TEST_REAL_SIMILAR(cg_qcs[0].overall_quality_l, 2.0); TEST_REAL_SIMILAR(cg_qcs[1].overall_quality_l, 3.0); TEST_REAL_SIMILAR(cg_qcs[2].overall_quality_l, 4.0); TEST_REAL_SIMILAR(cg_qcs[0].overall_quality_u, 5.0); TEST_REAL_SIMILAR(cg_qcs[1].overall_quality_u, 6.0); TEST_REAL_SIMILAR(cg_qcs[2].overall_quality_u, 7.0); TEST_REAL_SIMILAR(cg_qcs[0].meta_value_qc.at("peak_apex_int").first, 1000.0); TEST_REAL_SIMILAR(cg_qcs[2].meta_value_qc.at("peak_apex_int").first, 1002.0); TEST_REAL_SIMILAR(cg_qcs[0].meta_value_qc.at("peak_apex_int").second, 1000000.0); TEST_REAL_SIMILAR(cg_qcs[2].meta_value_qc.at("peak_apex_int").second, 1000002.0); TEST_REAL_SIMILAR(cg_qcs[0].meta_value_qc.at("sn_score").first, 2.0); TEST_REAL_SIMILAR(cg_qcs[2].meta_value_qc.at("sn_score").first, 10.0); TEST_REAL_SIMILAR(cg_qcs[0].meta_value_qc.at("sn_score").second, 10.0); TEST_REAL_SIMILAR(cg_qcs[2].meta_value_qc.at("sn_score").second, 50.0); TEST_EQUAL(cg_qcs[3].component_group_name, "componentGroup5"); TEST_EQUAL(cg_qcs[3].n_heavy_l, 0); TEST_EQUAL(cg_qcs[3].n_heavy_u, 100); TEST_EQUAL(cg_qcs[3].n_light_l, 0); TEST_EQUAL(cg_qcs[3].n_light_u, 100); TEST_EQUAL(cg_qcs[3].n_detecting_l, 0); TEST_EQUAL(cg_qcs[3].n_detecting_u, 100); TEST_EQUAL(cg_qcs[3].n_quantifying_l, 0); TEST_EQUAL(cg_qcs[3].n_quantifying_u, 100); TEST_EQUAL(cg_qcs[3].n_identifying_l, 0); TEST_EQUAL(cg_qcs[3].n_identifying_u, 100); TEST_EQUAL(cg_qcs[3].n_transitions_l, 0); TEST_EQUAL(cg_qcs[3].n_transitions_u, 100); TEST_EQUAL(cg_qcs[3].ion_ratio_pair_name_1, ""); TEST_EQUAL(cg_qcs[3].ion_ratio_pair_name_2, ""); TEST_REAL_SIMILAR(cg_qcs[3].ion_ratio_l, 0.0); TEST_REAL_SIMILAR(cg_qcs[3].ion_ratio_u, 1e12); TEST_EQUAL(cg_qcs[3].ion_ratio_feature_name, ""); TEST_REAL_SIMILAR(cg_qcs[3].retention_time_l, 0.0); TEST_REAL_SIMILAR(cg_qcs[3].retention_time_u, 1e12); TEST_REAL_SIMILAR(cg_qcs[3].intensity_l, 0.0); TEST_REAL_SIMILAR(cg_qcs[3].intensity_u, 1e12); TEST_REAL_SIMILAR(cg_qcs[3].overall_quality_l, 0.0); TEST_REAL_SIMILAR(cg_qcs[3].overall_quality_u, 1e12); TEST_REAL_SIMILAR(cg_qcs[3].meta_value_qc.at("peak_apex_int").first, 0.0); TEST_REAL_SIMILAR(cg_qcs[3].meta_value_qc.at("peak_apex_int").second, 1e12); TEST_REAL_SIMILAR(cg_qcs[3].meta_value_qc.at("sn_score").first, 0.0); TEST_REAL_SIMILAR(cg_qcs[3].meta_value_qc.at("sn_score").second, 1e12); } END_SECTION START_SECTION(void store(const String& filename, MRMFeatureQC& mrmfqc, const bool is_component_group)) { MRMFeatureQCFile mrmfqcfile; MRMFeatureQC mrmfqc, mrmfqc_test; String file_comp = File::getTemporaryFile(); String file_comp_group = File::getTemporaryFile(); mrmfqcfile.store(file_comp, mrmfqc, false); // empty components file mrmfqcfile.store(file_comp_group, mrmfqc, true); // empty component groups file mrmfqcfile.load(OPENMS_GET_TEST_DATA_PATH("MRMFeatureQCFile_1.csv"), mrmfqc, false); // components file mrmfqcfile.load(OPENMS_GET_TEST_DATA_PATH("MRMFeatureQCFile_2.csv"), mrmfqc, true); // component groups file mrmfqcfile.store(file_comp, mrmfqc, false); // components file mrmfqcfile.store(file_comp_group, mrmfqc, true); // component groups file mrmfqcfile.load(file_comp, mrmfqc_test, false); // components file mrmfqcfile.load(file_comp_group, mrmfqc_test, true); // component groups file TEST_EQUAL(mrmfqc.component_qcs.size(), mrmfqc_test.component_qcs.size()); for (size_t i = 0; i < mrmfqc.component_qcs.size(); ++i) { TEST_EQUAL(mrmfqc.component_qcs.at(i) == mrmfqc_test.component_qcs.at(i), true); } TEST_EQUAL(mrmfqc.component_group_qcs.size(), mrmfqc_test.component_group_qcs.size()); for (size_t i = 0; i < mrmfqc.component_group_qcs.size(); ++i) { TEST_EQUAL(mrmfqc.component_group_qcs.at(i) == mrmfqc_test.component_group_qcs.at(i), true); } } END_SECTION START_SECTION(void pushValuesFromLine_( const StringList& line, const std::map<String, Size>& headers, std::vector<MRMFeatureQC::ComponentQCs>& c_qcs ) const) { const std::map<String, Size> headers { {"component_name", 0}, {"retention_time_l", 1}, {"retention_time_u", 2}, {"intensity_l", 3}, {"intensity_u", 4}, {"overall_quality_l", 5}, {"overall_quality_u", 6}, {"metaValue_peak_apex_int_l", 7}, {"metaValue_peak_apex_int_u", 8}, {"metaValue_sn_score_l", 9}, {"metaValue_sn_score_u", 10} }; const std::vector<String> sl1 { // all info are present "component1", "0.1", "0.2", "0.3", "0.4", "0.5", "0.6", "0.7", "0.8", "0.9", "1.0" }; const std::vector<String> sl2 { // component_name is empty "", "0.1", "0.2", "0.3", "0.4", "0.5", "0.6", "0.7", "0.8", "0.9", "1.0" }; const std::vector<String> sl3 { // testing defaults "component3", "", "", "", "", "", "", "", "", "", "" }; MRMFeatureQCFile_facade mrmfqcfile_f; std::vector<MRMFeatureQC::ComponentQCs> c_qcs; mrmfqcfile_f.pushValuesFromLine_(sl1, headers, c_qcs); TEST_EQUAL(c_qcs.size(), 1); TEST_EQUAL(c_qcs[0].component_name, "component1"); TEST_REAL_SIMILAR(c_qcs[0].retention_time_l, 0.1); TEST_REAL_SIMILAR(c_qcs[0].retention_time_u, 0.2); TEST_REAL_SIMILAR(c_qcs[0].intensity_l, 0.3); TEST_REAL_SIMILAR(c_qcs[0].intensity_u, 0.4); TEST_REAL_SIMILAR(c_qcs[0].overall_quality_l, 0.5); TEST_REAL_SIMILAR(c_qcs[0].overall_quality_u, 0.6); TEST_REAL_SIMILAR(c_qcs[0].meta_value_qc["peak_apex_int"].first, 0.7); TEST_REAL_SIMILAR(c_qcs[0].meta_value_qc["peak_apex_int"].second, 0.8); TEST_REAL_SIMILAR(c_qcs[0].meta_value_qc["sn_score"].first, 0.9); TEST_REAL_SIMILAR(c_qcs[0].meta_value_qc["sn_score"].second, 1.0); mrmfqcfile_f.pushValuesFromLine_(sl2, headers, c_qcs); TEST_EQUAL(c_qcs.size(), 1); mrmfqcfile_f.pushValuesFromLine_(sl3, headers, c_qcs); TEST_EQUAL(c_qcs.size(), 2); TEST_EQUAL(c_qcs[1].component_name, "component3"); TEST_REAL_SIMILAR(c_qcs[1].retention_time_l, 0.0); TEST_REAL_SIMILAR(c_qcs[1].retention_time_u, 1e12); TEST_REAL_SIMILAR(c_qcs[1].intensity_l, 0.0); TEST_REAL_SIMILAR(c_qcs[1].intensity_u, 1e12); TEST_REAL_SIMILAR(c_qcs[1].overall_quality_l, 0.0); TEST_REAL_SIMILAR(c_qcs[1].overall_quality_u, 1e12); TEST_REAL_SIMILAR(c_qcs[1].meta_value_qc["peak_apex_int"].first, 0.0); TEST_REAL_SIMILAR(c_qcs[1].meta_value_qc["peak_apex_int"].second, 1e12); TEST_REAL_SIMILAR(c_qcs[1].meta_value_qc["sn_score"].first, 0.0); TEST_REAL_SIMILAR(c_qcs[1].meta_value_qc["sn_score"].second, 1e12); } END_SECTION START_SECTION(void pushValuesFromLine_( const StringList& line, const std::map<String, Size>& headers, std::vector<MRMFeatureQC::ComponentGroupQCs>& cg_qcs ) const) { const std::map<String, Size> headers { {"component_group_name", 0}, {"n_heavy_l", 1}, {"n_heavy_u", 2}, {"n_light_l", 3}, {"n_light_u", 4}, {"n_detecting_l", 5}, {"n_detecting_u", 6}, {"n_quantifying_l", 7}, {"n_quantifying_u", 8}, {"n_identifying_l", 9}, {"n_identifying_u", 10}, {"n_transitions_l", 11}, {"n_transitions_u", 12}, {"ion_ratio_pair_name_1", 13}, {"ion_ratio_pair_name_2", 14}, {"ion_ratio_l", 15}, {"ion_ratio_u", 16}, {"ion_ratio_feature_name", 17}, {"retention_time_l", 18}, {"retention_time_u", 19}, {"intensity_l", 20}, {"intensity_u", 21}, {"overall_quality_l", 22}, {"overall_quality_u", 23}, {"metaValue_peak_apex_int_l", 24}, {"metaValue_peak_apex_int_u", 25}, {"metaValue_sn_score_l", 26}, {"metaValue_sn_score_u", 27} }; const std::vector<String> sl1 { // all info are present "component_group_1", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "ionRatioPairName1", "ionRatioPairName2", "1.1", "1.2", "ionRatioFeatureName", "0.1", "0.2", "0.3", "0.4", "0.5", "0.6", "0.7", "0.8", "0.9", "1.0" }; const std::vector<String> sl2 { // component_name is empty "", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "ionRatioPairName1", "ionRatioPairName2", "1.1", "1.2", "ionRatioFeatureName", "0.1", "0.2", "0.3", "0.4", "0.5", "0.6", "0.7", "0.8", "0.9", "1.0" }; const std::vector<String> sl3 { // testing defaults "component_group_3", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "" }; MRMFeatureQCFile_facade mrmfqcfile_f; std::vector<MRMFeatureQC::ComponentGroupQCs> cg_qcs; mrmfqcfile_f.pushValuesFromLine_(sl1, headers, cg_qcs); TEST_EQUAL(cg_qcs.size(), 1); TEST_EQUAL(cg_qcs[0].component_group_name, "component_group_1"); TEST_EQUAL(cg_qcs[0].n_heavy_l, 1); TEST_EQUAL(cg_qcs[0].n_heavy_u, 2); TEST_EQUAL(cg_qcs[0].n_light_l, 3); TEST_EQUAL(cg_qcs[0].n_light_u, 4); TEST_EQUAL(cg_qcs[0].n_detecting_l, 5); TEST_EQUAL(cg_qcs[0].n_detecting_u, 6); TEST_EQUAL(cg_qcs[0].n_quantifying_l, 7); TEST_EQUAL(cg_qcs[0].n_quantifying_u, 8); TEST_EQUAL(cg_qcs[0].n_identifying_l, 9); TEST_EQUAL(cg_qcs[0].n_identifying_u, 10); TEST_EQUAL(cg_qcs[0].n_transitions_l, 11); TEST_EQUAL(cg_qcs[0].n_transitions_u, 12); TEST_EQUAL(cg_qcs[0].ion_ratio_pair_name_1, "ionRatioPairName1"); TEST_EQUAL(cg_qcs[0].ion_ratio_pair_name_2, "ionRatioPairName2"); TEST_REAL_SIMILAR(cg_qcs[0].ion_ratio_l, 1.1); TEST_REAL_SIMILAR(cg_qcs[0].ion_ratio_u, 1.2); TEST_EQUAL(cg_qcs[0].ion_ratio_feature_name, "ionRatioFeatureName"); TEST_REAL_SIMILAR(cg_qcs[0].retention_time_l, 0.1); TEST_REAL_SIMILAR(cg_qcs[0].retention_time_u, 0.2); TEST_REAL_SIMILAR(cg_qcs[0].intensity_l, 0.3); TEST_REAL_SIMILAR(cg_qcs[0].intensity_u, 0.4); TEST_REAL_SIMILAR(cg_qcs[0].overall_quality_l, 0.5); TEST_REAL_SIMILAR(cg_qcs[0].overall_quality_u, 0.6); TEST_REAL_SIMILAR(cg_qcs[0].meta_value_qc["peak_apex_int"].first, 0.7); TEST_REAL_SIMILAR(cg_qcs[0].meta_value_qc["peak_apex_int"].second, 0.8); TEST_REAL_SIMILAR(cg_qcs[0].meta_value_qc["sn_score"].first, 0.9); TEST_REAL_SIMILAR(cg_qcs[0].meta_value_qc["sn_score"].second, 1.0); mrmfqcfile_f.pushValuesFromLine_(sl2, headers, cg_qcs); TEST_EQUAL(cg_qcs.size(), 1); mrmfqcfile_f.pushValuesFromLine_(sl3, headers, cg_qcs); TEST_EQUAL(cg_qcs.size(), 2); TEST_EQUAL(cg_qcs[1].component_group_name, "component_group_3"); TEST_EQUAL(cg_qcs[1].n_heavy_l, 0); TEST_EQUAL(cg_qcs[1].n_heavy_u, 100); TEST_EQUAL(cg_qcs[1].n_light_l, 0); TEST_EQUAL(cg_qcs[1].n_light_u, 100); TEST_EQUAL(cg_qcs[1].n_detecting_l, 0); TEST_EQUAL(cg_qcs[1].n_detecting_u, 100); TEST_EQUAL(cg_qcs[1].n_quantifying_l, 0); TEST_EQUAL(cg_qcs[1].n_quantifying_u, 100); TEST_EQUAL(cg_qcs[1].n_identifying_l, 0); TEST_EQUAL(cg_qcs[1].n_identifying_u, 100); TEST_EQUAL(cg_qcs[1].n_transitions_l, 0); TEST_EQUAL(cg_qcs[1].n_transitions_u, 100); TEST_EQUAL(cg_qcs[1].ion_ratio_pair_name_1, ""); TEST_EQUAL(cg_qcs[1].ion_ratio_pair_name_2, ""); TEST_REAL_SIMILAR(cg_qcs[1].ion_ratio_l, 0.0); TEST_REAL_SIMILAR(cg_qcs[1].ion_ratio_u, 1e12); TEST_EQUAL(cg_qcs[1].ion_ratio_feature_name, ""); TEST_REAL_SIMILAR(cg_qcs[1].retention_time_l, 0.0); TEST_REAL_SIMILAR(cg_qcs[1].retention_time_u, 1e12); TEST_REAL_SIMILAR(cg_qcs[1].intensity_l, 0.0); TEST_REAL_SIMILAR(cg_qcs[1].intensity_u, 1e12); TEST_REAL_SIMILAR(cg_qcs[1].overall_quality_l, 0.0); TEST_REAL_SIMILAR(cg_qcs[1].overall_quality_u, 1e12); TEST_REAL_SIMILAR(cg_qcs[1].meta_value_qc["peak_apex_int"].first, 0.0); TEST_REAL_SIMILAR(cg_qcs[1].meta_value_qc["peak_apex_int"].second, 1e12); TEST_REAL_SIMILAR(cg_qcs[1].meta_value_qc["sn_score"].first, 0.0); TEST_REAL_SIMILAR(cg_qcs[1].meta_value_qc["sn_score"].second, 1e12); } END_SECTION START_SECTION(void setPairValue_( const String& key, const String& value, const String& boundary, std::map<String, std::pair<double,double>>& meta_values_qc ) const) { std::map<String, std::pair<double,double>> metavalues; MRMFeatureQCFile_facade mrmfqcfile_f; mrmfqcfile_f.setPairValue_("meta1", "0.123", "u", metavalues); // first pair (initializing the upper bound) TEST_EQUAL(metavalues.size(), 1); TEST_REAL_SIMILAR(metavalues["meta1"].first, 0.0); // default lower bound value TEST_REAL_SIMILAR(metavalues["meta1"].second, 0.123); mrmfqcfile_f.setPairValue_("meta1", "0.456", "l", metavalues); // overwrite the lower bound value TEST_EQUAL(metavalues.size(), 1); // the size of the map doesn't change TEST_REAL_SIMILAR(metavalues["meta1"].first, 0.456); TEST_REAL_SIMILAR(metavalues["meta1"].second, 0.123); mrmfqcfile_f.setPairValue_("meta1", "0.789", "u", metavalues); // overwrite the upper bound value TEST_EQUAL(metavalues.size(), 1); TEST_REAL_SIMILAR(metavalues["meta1"].first, 0.456); TEST_REAL_SIMILAR(metavalues["meta1"].second, 0.789); mrmfqcfile_f.setPairValue_("meta2", "0.111", "l", metavalues); // create another pair (initializing the lower bound) TEST_EQUAL(metavalues.size(), 2); // the size of the map changes TEST_REAL_SIMILAR(metavalues["meta2"].first, 0.111); TEST_REAL_SIMILAR(metavalues["meta2"].second, 1e12); // default upper bound value mrmfqcfile_f.setPairValue_("meta3", "0.222", "u", metavalues); // just another pair TEST_EQUAL(metavalues.size(), 3); TEST_REAL_SIMILAR(metavalues["meta3"].first, 0.0); TEST_REAL_SIMILAR(metavalues["meta3"].second, 0.222); } END_SECTION START_SECTION(Int getCastValue_( const std::map<String, Size>& headers, const StringList& line, const String& header, const Int default_value ) const) { MRMFeatureQCFile_facade mrmfqcfile_f; const std::map<String, Size> headers { {"component_group_name", 0}, {"n_heavy_l", 1}, {"n_heavy_u", 2} }; const StringList line1 {"componentgroup1", "2", "3"}; // all info are present const StringList line2 {"componentgroup2", "", "3"}; // some info is missing TEST_EQUAL(mrmfqcfile_f.getCastValue_(headers, line1, "n_heavy_l", 3), 2) // info is found, converted and returned TEST_EQUAL(mrmfqcfile_f.getCastValue_(headers, line1, "n_light_l", 4), 4) // the requested column is not present in the headers, default value is returned TEST_EQUAL(mrmfqcfile_f.getCastValue_(headers, line2, "n_heavy_l", 5), 5) // the requested column is present in the headers, but the value is empty. Default value is returned } END_SECTION START_SECTION(double getCastValue_( const std::map<String, Size>& headers, const StringList& line, const String& header, const double default_value ) const) { MRMFeatureQCFile_facade mrmfqcfile_f; const std::map<String, Size> headers { {"component_name", 0}, {"retention_time_l", 1}, {"retention_time_u", 2} }; const StringList line1 {"component1", "1.2", "1.3"}; // all info are present const StringList line2 {"component2", "", "1.3"}; // some info is missing TEST_EQUAL(mrmfqcfile_f.getCastValue_(headers, line1, "retention_time_l", 3.1), 1.2) // info is found, converted and returned TEST_EQUAL(mrmfqcfile_f.getCastValue_(headers, line1, "intensity_l", 4.1), 4.1) // the requested column is not present in the headers, default value is returned TEST_EQUAL(mrmfqcfile_f.getCastValue_(headers, line2, "retention_time_l", 5.1), 5.1) // the requested column is present in the headers, but the value is empty. Default value is returned } END_SECTION START_SECTION(String getCastValue_( const std::map<String, Size>& headers, const StringList& line, const String& header, const String& default_value ) const) { MRMFeatureQCFile_facade mrmfqcfile_f; const std::map<String, Size> headers { {"component_name", 0}, {"ion_ratio_feature_name", 1} }; const StringList line1 {"component1", "name1"}; // all info are present const StringList line2 {"component2", ""}; // some info is missing TEST_EQUAL(mrmfqcfile_f.getCastValue_(headers, line1, "ion_ratio_feature_name", "name30"), "name1") // info is found, converted and returned TEST_EQUAL(mrmfqcfile_f.getCastValue_(headers, line1, "intensity_l", "name30"), "name30") // the requested column is not present in the headers, default value is returned TEST_EQUAL(mrmfqcfile_f.getCastValue_(headers, line2, "ion_ratio_feature_name", "name30"), "name30") // the requested column is present in the headers, but the value is empty. Default value is returned } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/PeptideAndProteinQuant_test.cpp
.cpp
14,731
380
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hendrik Weisser $ // $Authors: Hendrik Weisser $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> #include <OpenMS/FORMAT/ConsensusXMLFile.h> #include <OpenMS/FORMAT/FeatureXMLFile.h> #include <OpenMS/FORMAT/IdXMLFile.h> #include <OpenMS/ANALYSIS/QUANTITATION/PeptideAndProteinQuant.h> #include <OpenMS/METADATA/ExperimentalDesign.h> using namespace OpenMS; using namespace std; START_TEST(PeptideAndProteinQuant, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// PeptideAndProteinQuant* ptr = nullptr; PeptideAndProteinQuant* nullPointer = nullptr; START_SECTION((PeptideAndProteinQuant())) ptr = new PeptideAndProteinQuant(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((virtual ~PeptideAndProteinQuant())) delete ptr; END_SECTION PeptideAndProteinQuant quantifier_features; PeptideAndProteinQuant quantifier_consensus; PeptideAndProteinQuant quantifier_identifications; Param params; params.setValue("top:include_all", "true"); quantifier_features.setParameters(params); quantifier_consensus.setParameters(params); quantifier_identifications.setParameters(params); START_SECTION((void readQuantData(FeatureMap& features, ExperimentalDesign& ed))) { FeatureMap features; FeatureXMLFile().load(OPENMS_GET_TEST_DATA_PATH("ProteinQuantifier_input.featureXML"), features); ExperimentalDesign design = ExperimentalDesign::fromFeatureMap(features); TEST_EQUAL(quantifier_features.getPeptideResults().empty(), true); quantifier_features.readQuantData(features, design); quantifier_features.quantifyPeptides(); TEST_EQUAL(quantifier_features.getPeptideResults().empty(), false); } END_SECTION START_SECTION((void readQuantData(ConsensusMap& consensus, ExperimentalDesign& ed))) { ConsensusMap consensus; ConsensusXMLFile().load(OPENMS_GET_TEST_DATA_PATH("ProteinQuantifier_input.consensusXML"), consensus); TEST_EQUAL(quantifier_consensus.getPeptideResults().empty(), true); ExperimentalDesign design = ExperimentalDesign::fromConsensusMap(consensus); quantifier_consensus.readQuantData(consensus, design); quantifier_consensus.quantifyPeptides(); TEST_EQUAL(quantifier_consensus.getPeptideResults().empty(), false); } END_SECTION START_SECTION((void readQuantData(vector<ProteinIdentification>& proteins, PeptideIdentificationList& peptides, ExperimentalDesign& ed))) { vector<ProteinIdentification> proteins; PeptideIdentificationList peptides; IdXMLFile().load(OPENMS_GET_TEST_DATA_PATH("ProteinQuantifier_input.idXML"), proteins, peptides); TEST_EQUAL(quantifier_identifications.getPeptideResults().empty(), true); ExperimentalDesign design = ExperimentalDesign::fromIdentifications(proteins); quantifier_identifications.readQuantData(proteins, peptides, design); quantifier_identifications.quantifyPeptides(); TEST_EQUAL(quantifier_identifications.getPeptideResults().empty(), false); } END_SECTION START_SECTION((void quantifyPeptides(const PeptideIdentificationList& peptides = PeptideIdentificationList()))) { NOT_TESTABLE // tested together with the "readQuantData" methods } END_SECTION START_SECTION((void quantifyProteins(const ProteinIdentification& proteins = ProteinIdentification()))) { TEST_EQUAL(quantifier_features.getProteinResults().empty(), true); quantifier_features.quantifyProteins(); TEST_EQUAL(quantifier_features.getProteinResults().empty(), false); TEST_EQUAL(quantifier_consensus.getProteinResults().empty(), true); quantifier_consensus.quantifyProteins(); TEST_EQUAL(quantifier_consensus.getProteinResults().empty(), false); TEST_EQUAL(quantifier_identifications.getProteinResults().empty(), true); quantifier_identifications.quantifyProteins(); TEST_EQUAL(quantifier_identifications.getProteinResults().empty(), false); } END_SECTION START_SECTION((const Statistics& getStatistics())) { PeptideAndProteinQuant::Statistics stats; stats = quantifier_features.getStatistics(); TEST_EQUAL(stats.n_samples, 1); TEST_EQUAL(stats.quant_proteins, 2); TEST_EQUAL(stats.too_few_peptides, 1); TEST_EQUAL(stats.quant_peptides, 5); TEST_EQUAL(stats.total_peptides, 7); TEST_EQUAL(stats.quant_features, 7); TEST_EQUAL(stats.total_features, 8); TEST_EQUAL(stats.blank_features, 0); TEST_EQUAL(stats.ambig_features, 1); stats = quantifier_consensus.getStatistics(); TEST_EQUAL(stats.n_samples, 3); TEST_EQUAL(stats.quant_proteins, 1); TEST_EQUAL(stats.too_few_peptides, 0); TEST_EQUAL(stats.quant_peptides, 4); TEST_EQUAL(stats.total_peptides, 4); TEST_EQUAL(stats.quant_features, 9); TEST_EQUAL(stats.total_features, 9); TEST_EQUAL(stats.blank_features, 0); TEST_EQUAL(stats.ambig_features, 0); stats = quantifier_identifications.getStatistics(); TEST_EQUAL(stats.n_samples, 2); TEST_EQUAL(stats.quant_proteins, 10); TEST_EQUAL(stats.too_few_peptides, 10); TEST_EQUAL(stats.quant_peptides, 13); // one decoy peptide is not quantified TEST_EQUAL(stats.total_peptides, 14); TEST_EQUAL(stats.quant_features, 17); // feature with a decoy peptide is not quantified TEST_EQUAL(stats.total_features, 18); TEST_EQUAL(stats.blank_features, 0); TEST_EQUAL(stats.ambig_features, 0); } END_SECTION START_SECTION((const PeptideQuant& getPeptideResults())) { PeptideAndProteinQuant::PeptideQuant pep_quant; PeptideAndProteinQuant::PeptideData pep_data; pep_quant = quantifier_features.getPeptideResults(); TEST_EQUAL(pep_quant.size(), 7); pep_data = pep_quant[AASequence::fromString("AAAAA")]; TEST_EQUAL(pep_data.abundances.size(), 1); TEST_EQUAL(pep_data.abundances[1].size(), 1); TEST_EQUAL(pep_data.total_abundances.size(), 1); TEST_REAL_SIMILAR(pep_data.total_abundances[0], 3333); TEST_EQUAL(pep_data.accessions.size(), 1); TEST_EQUAL(pep_data.psm_count, 2); pep_data = pep_quant[AASequence::fromString("CCCCC")]; TEST_EQUAL(pep_data.abundances.size(), 1); // one fraction TEST_EQUAL(pep_data.abundances[1].size(), 1); // one file auto& map_file_to_charges = *pep_data.abundances[1].begin(); TEST_EQUAL(map_file_to_charges.second.size(), 2); // two charges TEST_EQUAL(pep_data.total_abundances.size(), 1); TEST_REAL_SIMILAR(pep_data.total_abundances[0], 7777); TEST_EQUAL(pep_data.accessions.size(), 1); TEST_EQUAL(pep_data.psm_count, 2); pep_data = pep_quant[AASequence::fromString("EEEEE")]; TEST_EQUAL(pep_data.abundances.size(), 0); // it is the second best hit, so it will not be counted TEST_EQUAL(pep_data.total_abundances.size(), 0); TEST_EQUAL(pep_data.accessions.size(), 1); TEST_EQUAL(pep_data.psm_count, 1); pep_data = pep_quant[AASequence::fromString("GGGGG")]; TEST_EQUAL(pep_data.abundances.size(), 1); // one fraction TEST_EQUAL(pep_data.abundances[1].size(), 1); // one file TEST_EQUAL((*pep_data.abundances[1].begin()).second.size(), 1); // two charges TEST_EQUAL(pep_data.total_abundances.size(), 1); TEST_REAL_SIMILAR(pep_data.total_abundances[0], 7777); TEST_EQUAL(pep_data.accessions.size(), 2); TEST_EQUAL(pep_data.psm_count, 1); pep_quant = quantifier_consensus.getPeptideResults(); TEST_EQUAL(pep_quant.size(), 4); pep_data = pep_quant[AASequence::fromString("AAAK")]; TEST_EQUAL(pep_data.abundances.size(), 1); // one fraction TEST_EQUAL(pep_data.abundances[1].size(), 2); // two files TEST_EQUAL((*pep_data.abundances[1].begin()).second.size(), 1); // one charge TEST_EQUAL(pep_data.total_abundances.size(), 2); TEST_REAL_SIMILAR(pep_data.total_abundances[0], 1000); TEST_REAL_SIMILAR(pep_data.total_abundances[2], 1000); TEST_EQUAL(pep_data.accessions.size(), 1); TEST_EQUAL(pep_data.psm_count, 1); pep_data = pep_quant[AASequence::fromString("CCCK")]; TEST_EQUAL(pep_data.abundances.size(), 1); // one fraction TEST_EQUAL(pep_data.abundances[1].size(), 2); // two files TEST_EQUAL((*pep_data.abundances[1].begin()).second.size(), 1); // one charge TEST_EQUAL(pep_data.total_abundances.size(), 2); TEST_REAL_SIMILAR(pep_data.total_abundances[0], 200); TEST_REAL_SIMILAR(pep_data.total_abundances[1], 200); TEST_EQUAL(pep_data.accessions.size(), 1); TEST_EQUAL(pep_data.psm_count, 1); pep_data = pep_quant[AASequence::fromString("EEEK")]; TEST_EQUAL(pep_data.abundances.size(), 1); // one fraction TEST_EQUAL(pep_data.abundances[1].size(), 3); // three files TEST_EQUAL((*pep_data.abundances[1].begin()).second.size(), 1); // one charge TEST_EQUAL(pep_data.total_abundances.size(), 3); TEST_REAL_SIMILAR(pep_data.total_abundances[0], 30); TEST_REAL_SIMILAR(pep_data.total_abundances[1], 30); TEST_REAL_SIMILAR(pep_data.total_abundances[2], 30); TEST_EQUAL(pep_data.accessions.size(), 1); TEST_EQUAL(pep_data.psm_count, 1); pep_data = pep_quant[AASequence::fromString("GGG")]; TEST_EQUAL(pep_data.abundances.size(), 1); // one fraction TEST_EQUAL(pep_data.abundances[1].size(), 2); // two files TEST_EQUAL((*pep_data.abundances[1].begin()).second.size(), 1); // one charge TEST_EQUAL(pep_data.total_abundances.size(), 2); TEST_REAL_SIMILAR(pep_data.total_abundances[0], 4); TEST_REAL_SIMILAR(pep_data.total_abundances[1], 4); TEST_EQUAL(pep_data.accessions.size(), 1); TEST_EQUAL(pep_data.psm_count, 1); } END_SECTION START_SECTION((const ProteinQuant& getProteinResults())) { PeptideAndProteinQuant::ProteinQuant prot_quant; PeptideAndProteinQuant::ProteinData prot_data; prot_quant = quantifier_features.getProteinResults(); TEST_EQUAL(prot_quant.size(), 2); prot_data = prot_quant["Protein0"]; TEST_EQUAL(prot_data.peptide_abundances.size(), 3); TEST_EQUAL(prot_data.total_abundances.size(), 1); TEST_REAL_SIMILAR(prot_data.total_abundances[0], 4711); TEST_EQUAL(prot_data.psm_count, 6); prot_data = prot_quant["Protein1"]; TEST_EQUAL(prot_data.peptide_abundances.size(), 1); TEST_EQUAL(prot_data.total_abundances.size(), 1); TEST_REAL_SIMILAR(prot_data.total_abundances[0], 8888); TEST_EQUAL(prot_data.psm_count, 2); prot_quant = quantifier_consensus.getProteinResults(); TEST_EQUAL(prot_quant.size(), 1); prot_data = prot_quant["Protein"]; TEST_EQUAL(prot_data.peptide_abundances.size(), 4); TEST_EQUAL(prot_data.total_abundances.size(), 3); TEST_REAL_SIMILAR(prot_data.total_abundances[0], 200); TEST_REAL_SIMILAR(prot_data.total_abundances[1], 30); TEST_REAL_SIMILAR(prot_data.total_abundances[2], 515); TEST_EQUAL(prot_data.psm_count, 4); } END_SECTION START_SECTION(([PeptideAndProteinQuant::PeptideData] PeptideData())) { PeptideAndProteinQuant::PeptideData data; TEST_EQUAL(data.abundances.empty(), true); TEST_EQUAL(data.total_abundances.empty(), true); TEST_EQUAL(data.accessions.empty(), true); TEST_EQUAL(data.psm_count, 0); } END_SECTION START_SECTION(([PeptideAndProteinQuant::ProteinData] ProteinData())) { PeptideAndProteinQuant::ProteinData data; TEST_EQUAL(data.peptide_abundances.empty(), true); TEST_EQUAL(data.total_abundances.empty(), true); TEST_EQUAL(data.psm_count, 0); } END_SECTION START_SECTION(([PeptideAndProteinQuant::Statistics] Statistics())) { PeptideAndProteinQuant::Statistics stats; TEST_EQUAL(stats.n_samples, 0); TEST_EQUAL(stats.quant_proteins, 0); TEST_EQUAL(stats.too_few_peptides, 0); TEST_EQUAL(stats.quant_peptides, 0); TEST_EQUAL(stats.total_peptides, 0); TEST_EQUAL(stats.quant_features, 0); TEST_EQUAL(stats.total_features, 0); TEST_EQUAL(stats.blank_features, 0); TEST_EQUAL(stats.ambig_features, 0); } END_SECTION // testing various averaging strategies START_SECTION((const ProteinQuant& getProteinResults())) { FeatureMap f; FeatureXMLFile().load(OPENMS_GET_TEST_DATA_PATH("ProteinQuantifier_input.featureXML"), f); PeptideAndProteinQuant quantifier; PeptideAndProteinQuant::ProteinQuant quant; PeptideAndProteinQuant::ProteinData protein; Param parameters; parameters.setValue("top:N", 0); parameters.setValue("top:aggregate", "median"); quantifier.setParameters(parameters); ExperimentalDesign ed = ExperimentalDesign::fromFeatureMap(f); quantifier.readQuantData(f, ed); quantifier.quantifyPeptides(); quantifier.quantifyProteins(); quant = quantifier.getProteinResults(); protein = quant["Protein0"]; TEST_REAL_SIMILAR(protein.total_abundances[0], 4711); parameters.setValue("top:aggregate", "mean"); quantifier.setParameters(parameters); quantifier.readQuantData(f, ed); quantifier.quantifyPeptides(); quantifier.quantifyProteins(); quant = quantifier.getProteinResults(); protein = quant["Protein0"]; TEST_REAL_SIMILAR(protein.total_abundances[0], 5273.666666); parameters.setValue("top:aggregate", "weighted_mean"); quantifier.setParameters(parameters); quantifier.readQuantData(f, ed); quantifier.quantifyPeptides(); quantifier.quantifyProteins(); quant = quantifier.getProteinResults(); protein = quant["Protein0"]; TEST_REAL_SIMILAR(protein.total_abundances[0], 5927.82624360028); parameters.setValue("top:aggregate", "sum"); quantifier.setParameters(parameters); quantifier.readQuantData(f, ed); quantifier.quantifyPeptides(); quantifier.quantifyProteins(); quant = quantifier.getProteinResults(); protein = quant["Protein0"]; TEST_REAL_SIMILAR(protein.total_abundances[0], 15821); } END_SECTION // iBAQ test START_SECTION((const ProteinQuant& getProteinResults())) { PeptideAndProteinQuant quantifier; PeptideAndProteinQuant::ProteinQuant quant; PeptideAndProteinQuant::ProteinData protein; Param parameters = quantifier.getDefaults(); parameters.setValue("method", "iBAQ"); quantifier.setParameters(parameters); ConsensusMap consensus; ConsensusXMLFile().load(OPENMS_GET_TEST_DATA_PATH("ProteinQuantifier_input.consensusXML"), consensus); ExperimentalDesign ed = ExperimentalDesign::fromConsensusMap(consensus); ProteinIdentification proteins_ = consensus.getProteinIdentifications()[0]; quantifier.readQuantData(consensus, ed); quantifier.quantifyPeptides(); quantifier.quantifyProteins(proteins_); quant = quantifier.getProteinResults(); protein = quant["Protein"]; TEST_REAL_SIMILAR(protein.total_abundances[0], 308.5); TEST_REAL_SIMILAR(protein.total_abundances[1], 58.5); TEST_REAL_SIMILAR(protein.total_abundances[2], 257.5); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MRMDecoy_test.cpp
.cpp
47,409
1,288
// 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, Witold Wolski $ // -------------------------------------------------------------------------- #include <OpenMS/test_config.h> #include <OpenMS/CONCEPT/ClassTest.h> /////////////////////////// #include <OpenMS/ANALYSIS/OPENSWATH/MRMDecoy.h> /////////////////////////// #include <OpenMS/FORMAT/TraMLFile.h> #include <OpenMS/CHEMISTRY/ModificationsDB.h> #include <OpenMS/OPENSWATHALGO/DATAACCESS/TransitionExperiment.h> #include <boost/assign/std/vector.hpp> #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wshadow" #endif using namespace OpenMS; using namespace std; class MRMDecoyHelper : public MRMDecoy { public: OpenMS::TargetedExperiment::Peptide pseudoreversePeptide_helper( const OpenMS::TargetedExperiment::Peptide& peptide) const { return pseudoreversePeptide_(peptide); } OpenMS::TargetedExperiment::Peptide reversePeptide_helper( const OpenMS::TargetedExperiment::Peptide& peptide) const { return reversePeptide_(peptide); } IndexType findFixedResidues_helper(const std::string& sequence) const {return findFixedResidues_(sequence);} IndexType findFixedAndTermResidues_helper(const std::string& sequence) const {return findFixedAndTermResidues_(sequence);} // Helper method to expose protected pseudoreversePeptideLight_ std::pair<std::string, std::vector<OpenSwath::LightModification>> pseudoreversePeptideLight_helper( const std::string& sequence, const std::vector<OpenSwath::LightModification>& modifications) const { return pseudoreversePeptideLight_(sequence, modifications); } // Helper method to expose protected hasCNterminalModsLight_ static bool hasCNterminalModsLight_helper( const std::vector<OpenSwath::LightModification>& modifications, size_t sequence_length, bool checkCterminalAA) { return hasCNterminalModsLight_(modifications, sequence_length, checkCterminalAA); } }; START_TEST(MRMDecoy, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// MRMDecoy * ptr = nullptr; MRMDecoy* nullPointer = nullptr; START_SECTION(MRMDecoy()) { ptr = new MRMDecoy(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(~MRMDecoy()) { delete ptr; } END_SECTION START_SECTION((std::vector<std::pair<std::string::size_type, std::string> > findFixedResidues(std::string sequence))) { MRMDecoyHelper gen; String sequence = "TRESTPEPTIKDE"; MRMDecoy::IndexType tryptic_results = gen.findFixedResidues_helper(sequence); MRMDecoy::IndexType tryptic_expect = {1, 5, 7, 10}; TEST_TRUE(tryptic_results == tryptic_expect) } END_SECTION START_SECTION((std::vector<std::pair<std::string::size_type, std::string> > findFixedAndTermResidues(std::string sequence))) { MRMDecoyHelper gen; String sequence = "TRESTPEPTIKDE"; MRMDecoy::IndexType tryptic_results = gen.findFixedAndTermResidues_helper(sequence); MRMDecoy::IndexType tryptic_expect = {0, 1, 5, 7, 10, 12}; TEST_TRUE(tryptic_results == tryptic_expect) } END_SECTION START_SECTION(OpenMS::TargetedExperiment::Peptide shufflePeptide(OpenMS::TargetedExperiment::Peptide peptide, double identity_threshold, int seed = -1, int max_attempts = 10)) { MRMDecoy gen; OpenMS::TargetedExperiment::Peptide peptide; peptide.sequence = "TESTPEPTIDE"; OpenMS::TargetedExperiment::Peptide::Modification modification; modification.avg_mass_delta = 79.9799; modification.location = 2; modification.mono_mass_delta = 79.966331; peptide.mods.push_back(modification); OpenMS::String expected_sequence = "TIDEPEPSTTE"; OpenMS::Size expected_location = 7; OpenMS::TargetedExperiment::Peptide shuffled = gen.shufflePeptide(peptide, 0.7, 43); TEST_EQUAL(shuffled.sequence, expected_sequence) TEST_EQUAL(shuffled.mods.size(), 1) TEST_EQUAL(shuffled.mods[0].location, expected_location) OpenMS::TargetedExperiment::Peptide shuffleAASequence_target_sequence_11; shuffleAASequence_target_sequence_11.sequence = "TESTPEPTIDE"; OpenMS::TargetedExperiment::Peptide shuffleAASequence_expected_11; shuffleAASequence_expected_11.sequence = "TESTPEPTIDE"; OpenMS::TargetedExperiment::Peptide shuffleAASequence_result_11; shuffleAASequence_result_11 = gen.shufflePeptide(shuffleAASequence_target_sequence_11, 1.1, 42); TEST_EQUAL(shuffleAASequence_result_11.sequence, shuffleAASequence_expected_11.sequence) OpenMS::TargetedExperiment::Peptide shuffleAASequence_target_sequence_07; shuffleAASequence_target_sequence_07.sequence = "TESTPEPTIDE"; OpenMS::TargetedExperiment::Peptide shuffleAASequence_expected_07; shuffleAASequence_expected_07.sequence = "TTETPEPIDSE"; OpenMS::TargetedExperiment::Peptide shuffleAASequence_result_07; shuffleAASequence_result_07 = gen.shufflePeptide(shuffleAASequence_target_sequence_07, 0.7, 42); TEST_EQUAL(shuffleAASequence_result_07.sequence, shuffleAASequence_expected_07.sequence) OpenMS::TargetedExperiment::Peptide shuffleAASequence_target_sequence_09; shuffleAASequence_target_sequence_09.sequence = "TESTPEPTIDE"; OpenMS::TargetedExperiment::Peptide shuffleAASequence_expected_09; shuffleAASequence_expected_09.sequence = "TTETPEPIDSE"; OpenMS::TargetedExperiment::Peptide shuffleAASequence_result_09; shuffleAASequence_result_09 = gen.shufflePeptide(shuffleAASequence_target_sequence_09, 0.9, 42); TEST_EQUAL(shuffleAASequence_result_09.sequence, shuffleAASequence_expected_09.sequence) OpenMS::TargetedExperiment::Peptide shuffleAASequence_target_sequence_01; shuffleAASequence_target_sequence_01.sequence = "TESTPEPTIDE"; OpenMS::TargetedExperiment::Peptide shuffleAASequence_expected_01; shuffleAASequence_expected_01.sequence = "TNGCADQQEAE"; OpenMS::TargetedExperiment::Peptide shuffleAASequence_result_01; shuffleAASequence_result_01 = gen.shufflePeptide(shuffleAASequence_target_sequence_01, 0.2, 42, 10000); TEST_EQUAL(shuffleAASequence_result_01.sequence, shuffleAASequence_expected_01.sequence) OpenMS::TargetedExperiment::Peptide shuffleAASequence_target_sequence_00; shuffleAASequence_target_sequence_00.sequence = "TESTPEPTIDE"; OpenMS::TargetedExperiment::Peptide shuffleAASequence_expected_00; shuffleAASequence_expected_00.sequence = "TEIEPAPTQTE"; OpenMS::TargetedExperiment::Peptide shuffleAASequence_result_00; shuffleAASequence_result_00 = gen.shufflePeptide(shuffleAASequence_target_sequence_00, 0.0, 42, 20); TEST_EQUAL(shuffleAASequence_result_00.sequence, shuffleAASequence_expected_00.sequence) OpenMS::TargetedExperiment::Peptide shuffleAASequence_target_sequence_01b; shuffleAASequence_target_sequence_01b.sequence = "TESTPEPTIDE"; OpenMS::TargetedExperiment::Peptide shuffleAASequence_expected_01b; shuffleAASequence_expected_01b.sequence = "TNGCADQQEAE"; OpenMS::TargetedExperiment::Peptide shuffleAASequence_result_01b; shuffleAASequence_result_01b = gen.shufflePeptide(shuffleAASequence_target_sequence_01b, 0.2, 42, 10000); TEST_EQUAL(shuffleAASequence_result_01b.sequence, shuffleAASequence_expected_01b.sequence) OpenMS::TargetedExperiment::Peptide shuffleAASequence_target_sequence_00b; shuffleAASequence_target_sequence_00b.sequence = "TESTPEPTIDE"; OpenMS::TargetedExperiment::Peptide shuffleAASequence_expected_00b; shuffleAASequence_expected_00b.sequence = "TNDQIADNNEE"; OpenMS::TargetedExperiment::Peptide shuffleAASequence_result_00b; shuffleAASequence_result_00b = gen.shufflePeptide(shuffleAASequence_target_sequence_00b, 0.0, 42, 2000); TEST_EQUAL(shuffleAASequence_result_00b.sequence, shuffleAASequence_expected_00b.sequence) // ensure that C-terminal K and R are preserved { OpenMS::TargetedExperiment::Peptide original_input; original_input.sequence = "TESTPEPTIDEK"; expected_sequence = "TTETPEPEDSIK"; OpenMS::TargetedExperiment::Peptide shuffleAASequence_result_00; shuffled = gen.shufflePeptide(original_input, 0.7, 42, 20); TEST_EQUAL(shuffled.sequence[shuffled.sequence.size() - 1], 'K') TEST_EQUAL(shuffled.sequence, expected_sequence) } // ensure that C-terminal K and R are preserved { OpenMS::TargetedExperiment::Peptide original_input; original_input.sequence = "TESTPEPTIDER"; expected_sequence = "TTETPEPEDSIR"; OpenMS::TargetedExperiment::Peptide shuffleAASequence_result_00; shuffled = gen.shufflePeptide(original_input, 0.7, 42, 20); TEST_EQUAL(shuffled.sequence[shuffled.sequence.size() - 1], 'R') TEST_EQUAL(shuffled.sequence, expected_sequence) } { OpenMS::TargetedExperiment::Peptide original_input; OpenMS::TargetedExperiment::Peptide::Modification mod; // std::vector<TargetedExperiment::Peptide::Modification> mods; std::vector<TargetedExperiment::Peptide::Modification> mods; // original_input.sequence = "EPAHLMSLFGGKPM(UniMod:35)"; original_input.sequence = "EPAHLMSLFGGKPM"; mod.location = 13; // non-C terminal mod.unimod_id = 35; mods.push_back(mod); original_input.mods = mods; expected_sequence = "EPSALMGGHLFKPM"; OpenMS::TargetedExperiment::Peptide shuffleAASequence_result_00; shuffled = gen.shufflePeptide(original_input, 0.7, 42, 20); TEST_EQUAL(shuffled.sequence[shuffled.sequence.size() - 1], 'M') TEST_EQUAL(shuffled.sequence, expected_sequence) TEST_EQUAL(shuffled.mods.size(), 1) TEST_EQUAL(shuffled.mods[0].location, 13) // the second M remained at position 13 } { OpenMS::TargetedExperiment::Peptide original_input; OpenMS::TargetedExperiment::Peptide::Modification mod; // std::vector<TargetedExperiment::Peptide::Modification> mods; std::vector<TargetedExperiment::Peptide::Modification> mods; // original_input.sequence = "EPAHLMSLFGGKPM(UniMod:35)"; original_input.sequence = "EPAHLMSLFGGKPM"; mod.location = 14; // C terminal mod.unimod_id = 35; mods.push_back(mod); original_input.mods = mods; expected_sequence = "EPSALMGGHLFKPM"; OpenMS::TargetedExperiment::Peptide shuffleAASequence_result_00; shuffled = gen.shufflePeptide(original_input, 0.7, 42, 20); TEST_EQUAL(shuffled.sequence[shuffled.sequence.size() - 1], 'M') TEST_EQUAL(shuffled.sequence, expected_sequence) TEST_EQUAL(shuffled.mods.size(), 1) TEST_EQUAL(shuffled.mods[0].location, 14) // Problem: this modification cannot be C terminal any more for F! // TODO: report and fix this } } END_SECTION START_SECTION([EXTRA] shuffle_peptide_with_modifications_and2attempts) { // Regression test for JIRA issue ABL-749 // A peptide with modifications that was shuffled twice did not get its // modifications shuffled as well. MRMDecoy gen; OpenMS::TargetedExperiment::Peptide peptide; peptide.sequence = "GPPSEDGPGVPPPSPR"; OpenMS::TargetedExperiment::Peptide::Modification modification; // modification on the fourth S (counting starts at zero) modification.avg_mass_delta = 79.9799; modification.location = 3; modification.mono_mass_delta = 79.966331; peptide.mods.push_back(modification); // modification on the second to last S modification.avg_mass_delta = 79.9799; modification.location = 13; modification.mono_mass_delta = 79.966331; peptide.mods.push_back(modification); OpenMS::String expected_sequence = "GPPGDSEPGSPPPVPR"; OpenMS::Size expected_location_1 = 9; OpenMS::Size expected_location_2 = 5; OpenMS::TargetedExperiment::Peptide shuffled = gen.shufflePeptide(peptide, 0.7, 130); // the two modifications get switched (the first S now comes after the second S) TEST_EQUAL(shuffled.sequence, expected_sequence) TEST_EQUAL(shuffled.mods.size(), 2) TEST_EQUAL(shuffled.mods[1].location, expected_location_1) TEST_EQUAL(shuffled.mods[0].location, expected_location_2) } END_SECTION START_SECTION([EXTRA] shuffle_peptide_with_terminal_modifications) { // Shuffle a peptide with C/N terminal modifications MRMDecoy gen; AASequence original_sequence = AASequence::fromString("(UniMod:272)TESTPEPTIDE(UniMod:193)"); TEST_EQUAL(original_sequence.hasNTerminalModification(), true) TEST_EQUAL(original_sequence.hasCTerminalModification(), true) OpenMS::TargetedExperiment::Peptide peptide; OpenMS::TargetedExperiment::Peptide::Modification modification; peptide.sequence = original_sequence.toUnmodifiedString(); // "sulfonation of N-terminus" modification.avg_mass_delta = 136.1265; modification.location = -1; modification.mono_mass_delta = 135.983029; peptide.mods.push_back(modification); //O18 label at both C-terminal oxygens modification.avg_mass_delta = 3.9995; modification.location = peptide.sequence.size(); modification.mono_mass_delta = 4.008491; peptide.mods.push_back(modification); OpenMS::String expected_sequence = "TIDEPEPSTTE"; OpenMS::TargetedExperiment::Peptide shuffled = gen.shufflePeptide(peptide, 0.7, 43); TEST_EQUAL(shuffled.sequence, expected_sequence) TEST_EQUAL(shuffled.mods.size(), 2) TEST_EQUAL(shuffled.mods[0].location, -1) TEST_EQUAL(shuffled.mods[1].location, shuffled.sequence.size()) } END_SECTION START_SECTION([EXTRA] shuffle_peptide_with_KPR) { MRMDecoy gen; OpenMS::TargetedExperiment::Peptide peptide; peptide.sequence = "KPRKPRPK"; OpenMS::String expected_sequence = "KNRKPRPK"; OpenMS::TargetedExperiment::Peptide shuffled = gen.shufflePeptide(peptide, 0.7, 130, 17); TEST_EQUAL(shuffled.sequence, expected_sequence) } END_SECTION START_SECTION(float AASequenceIdentity(const String& sequence, const String& decoy)) { MRMDecoy gen; String AASequenceIdentity_target_sequence = "TESTPEPTIDE"; String AASequenceIdentity_decoy_sequence = "EDITPEPTSET"; float AASequenceIdentity_result = gen.AASequenceIdentity(AASequenceIdentity_target_sequence, AASequenceIdentity_decoy_sequence); float AASequenceIdentity_expected = static_cast<float>(0.454545); TEST_REAL_SIMILAR(AASequenceIdentity_result, AASequenceIdentity_expected) } END_SECTION START_SECTION((OpenMS::TargetedExperiment::Peptide MRMDecoy::reversePeptide( OpenMS::TargetedExperiment::Peptide peptide, const bool keepN, const bool keepC, const String& const_pattern) const)) { MRMDecoy gen; OpenMS::TargetedExperiment::Peptide peptide; peptide.sequence = "TESTPEPTIDE"; OpenMS::TargetedExperiment::Peptide::Modification modification; modification.avg_mass_delta = 79.9799; modification.location = 2; modification.mono_mass_delta = 79.966331; peptide.mods.push_back(modification); { OpenMS::String expected_sequence = "DITPEPTSETE"; OpenMS::Size expected_location = 7; OpenMS::TargetedExperiment::Peptide pseudoreverse = MRMDecoy::reversePeptide(peptide, false, true); TEST_EQUAL(pseudoreverse.sequence, expected_sequence) TEST_EQUAL(pseudoreverse.mods.size(), 1) TEST_EQUAL(pseudoreverse.mods[0].location, expected_location) } { modification.avg_mass_delta = 49.9799; modification.mono_mass_delta = 49.966331; modification.location = 0; peptide.mods.push_back(modification); OpenMS::String expected_sequence = "TDITPEPTSEE"; OpenMS::TargetedExperiment::Peptide pseudoreverse = MRMDecoy::reversePeptide(peptide, true, true); TEST_EQUAL(pseudoreverse.sequence, expected_sequence) TEST_EQUAL(pseudoreverse.mods.size(), 2) TEST_EQUAL(pseudoreverse.mods[0].location, 8) TEST_REAL_SIMILAR(pseudoreverse.mods[0].mono_mass_delta, 79.966331) TEST_EQUAL(pseudoreverse.mods[1].location, 0) TEST_REAL_SIMILAR(pseudoreverse.mods[1].mono_mass_delta, 49.966331) } { String const_pattern = "I"; OpenMS::String expected_sequence = "TDTPEPTSIEE"; // "I" stays in place OpenMS::TargetedExperiment::Peptide pseudoreverse = MRMDecoy::reversePeptide(peptide, true, true, const_pattern); TEST_EQUAL(pseudoreverse.sequence, expected_sequence) TEST_EQUAL(pseudoreverse.mods.size(), 2) TEST_EQUAL(pseudoreverse.mods[0].location, 7) TEST_REAL_SIMILAR(pseudoreverse.mods[0].mono_mass_delta, 79.966331) TEST_EQUAL(pseudoreverse.mods[1].location, 0) TEST_REAL_SIMILAR(pseudoreverse.mods[1].mono_mass_delta, 49.966331) } } END_SECTION START_SECTION(OpenMS::TargetedExperiment::Peptide pseudoreversePeptide(OpenMS::TargetedExperiment::Peptide peptide)) { MRMDecoyHelper gen; OpenMS::TargetedExperiment::Peptide peptide; peptide.sequence = "TESTPEPTIDE"; OpenMS::TargetedExperiment::Peptide::Modification modification; modification.avg_mass_delta = 79.9799; modification.location = 2; modification.mono_mass_delta = 79.966331; peptide.mods.push_back(modification); OpenMS::String expected_sequence = "DITPEPTSETE"; OpenMS::Size expected_location = 7; OpenMS::TargetedExperiment::Peptide pseudoreverse = gen.pseudoreversePeptide_helper(peptide); TEST_EQUAL(pseudoreverse.sequence, expected_sequence) TEST_EQUAL(pseudoreverse.mods.size(), 1) TEST_EQUAL(pseudoreverse.mods[0].location, expected_location) OpenMS::TargetedExperiment::Peptide pseudoreverseAASequence_target_sequence; pseudoreverseAASequence_target_sequence.sequence = "TESTPEPTIDE"; OpenMS::TargetedExperiment::Peptide pseudoreverseAASequence_expected; pseudoreverseAASequence_expected.sequence = "DITPEPTSETE"; OpenMS::TargetedExperiment::Peptide pseudoreverseAASequence_result; pseudoreverseAASequence_result = gen.pseudoreversePeptide_helper(pseudoreverseAASequence_target_sequence); TEST_EQUAL(pseudoreverseAASequence_result.sequence, pseudoreverseAASequence_expected.sequence) } END_SECTION START_SECTION(OpenMS::TargetedExperiment::Peptide reversePeptide(OpenMS::TargetedExperiment::Peptide peptide)) { MRMDecoyHelper gen; OpenMS::TargetedExperiment::Peptide peptide; peptide.sequence = "TESTPEPTIDE"; OpenMS::TargetedExperiment::Peptide::Modification modification; modification.avg_mass_delta = 79.9799; modification.location = 2; modification.mono_mass_delta = 79.966331; peptide.mods.push_back(modification); OpenMS::String expected_sequence = "EDITPEPTSET"; OpenMS::Size expected_location = 8; OpenMS::TargetedExperiment::Peptide reverse = gen.reversePeptide_helper(peptide); TEST_EQUAL(reverse.sequence, expected_sequence) TEST_EQUAL(reverse.mods.size(), 1) TEST_EQUAL(reverse.mods[0].location, expected_location) OpenMS::TargetedExperiment::Peptide reverseAASequence_target_sequence; reverseAASequence_target_sequence.sequence = "TESTPEPTIDE"; OpenMS::TargetedExperiment::Peptide reverseAASequence_expected; reverseAASequence_expected.sequence = "EDITPEPTSET"; OpenMS::TargetedExperiment::Peptide reverseAASequence_result; reverseAASequence_result = gen.reversePeptide_helper(reverseAASequence_target_sequence); TEST_EQUAL(reverseAASequence_result.sequence, reverseAASequence_expected.sequence) } END_SECTION /// Public methods START_SECTION((void generateDecoys(const OpenMS::TargetedExperiment& exp, OpenMS::TargetedExperiment& dec, const String& method, const double aim_decoy_fraction, const bool switchKR, const String& decoy_tag, const int max_attempts, const double identity_threshold, const double precursor_mz_shift, const double product_mz_shift, const double product_mz_threshold, const std::vector<String>& fragment_types, const std::vector<size_t>& fragment_charges, const bool enable_specific_losses, const bool enable_unspecific_losses, const int round_decPow = -4) const)) { String method = "pseudo-reverse"; double identity_threshold = 0.7; Int max_attempts = 5; double product_mz_threshold = 0.8; double precursor_mz_shift = 0.1; double product_mz_shift = 20; String decoy_tag = "DECOY_"; std::vector<String> fragment_types; fragment_types.push_back(String("b")); fragment_types.push_back(String("y")); fragment_types.push_back(String("a")); std::vector<size_t> fragment_charges; fragment_charges.push_back(1); fragment_charges.push_back(2); fragment_charges.push_back(3); fragment_charges.push_back(4); fragment_charges.push_back(5); bool enable_unspecific_losses = false; bool enable_specific_losses = true; String in = "MRMDecoyGenerator_input.TraML"; String out = "MRMDecoyGenerator_output.TraML"; String test; NEW_TMP_FILE(test); TraMLFile traml; TargetedExperiment targeted_exp; TargetedExperiment targeted_decoy; traml.load(OPENMS_GET_TEST_DATA_PATH(in), targeted_exp); MRMDecoy decoys = MRMDecoy(); TEST_EQUAL(targeted_exp.getPeptides().size(), 13) TEST_EQUAL(targeted_exp.getTransitions().size(), 36) decoys.generateDecoys(targeted_exp, targeted_decoy, method, 1.0, false, decoy_tag, max_attempts, identity_threshold, precursor_mz_shift, product_mz_shift, product_mz_threshold, fragment_types, fragment_charges, enable_specific_losses, enable_unspecific_losses); traml.store(test, targeted_decoy); TEST_FILE_SIMILAR(test.c_str(), OPENMS_GET_TEST_DATA_PATH(out)) } END_SECTION ///////////////////////////////////////////////////////////// // Tests comparing Light methods with Heavy methods ///////////////////////////////////////////////////////////// START_SECTION([EXTRA] reversePeptideLight_matches_heavy) { // Test that reversePeptideLight produces the same sequence and modification // positions as the heavy reversePeptide method // Test case 1: Simple peptide with one modification { OpenMS::TargetedExperiment::Peptide peptide; peptide.sequence = "TESTPEPTIDE"; OpenMS::TargetedExperiment::Peptide::Modification modification; modification.avg_mass_delta = 79.9799; modification.location = 2; // S at position 2 modification.mono_mass_delta = 79.966331; modification.unimod_id = 21; // Phospho peptide.mods.push_back(modification); // Create equivalent light modifications std::vector<OpenSwath::LightModification> light_mods; OpenSwath::LightModification light_mod; light_mod.location = 2; light_mod.unimod_id = 21; light_mods.push_back(light_mod); // Test keepN=false, keepC=true (pseudo-reverse style) auto heavy_result = MRMDecoy::reversePeptide(peptide, false, true); auto light_result = MRMDecoy::reversePeptideLight(peptide.sequence, light_mods, false, true); TEST_EQUAL(light_result.first, heavy_result.sequence) TEST_EQUAL(light_result.second.size(), heavy_result.mods.size()) TEST_EQUAL(light_result.second[0].location, heavy_result.mods[0].location) } // Test case 2: Peptide with multiple modifications { OpenMS::TargetedExperiment::Peptide peptide; peptide.sequence = "TESTPEPTIDE"; OpenMS::TargetedExperiment::Peptide::Modification mod1, mod2; mod1.location = 2; // S mod1.unimod_id = 21; mod2.location = 0; // N-term T (kept in place with keepN) mod2.unimod_id = 1; peptide.mods.push_back(mod1); peptide.mods.push_back(mod2); std::vector<OpenSwath::LightModification> light_mods; OpenSwath::LightModification lm1, lm2; lm1.location = 2; lm1.unimod_id = 21; lm2.location = 0; lm2.unimod_id = 1; light_mods.push_back(lm1); light_mods.push_back(lm2); // Test keepN=true, keepC=true auto heavy_result = MRMDecoy::reversePeptide(peptide, true, true); auto light_result = MRMDecoy::reversePeptideLight(peptide.sequence, light_mods, true, true); TEST_EQUAL(light_result.first, heavy_result.sequence) TEST_EQUAL(light_result.second.size(), heavy_result.mods.size()) for (size_t i = 0; i < light_result.second.size(); ++i) { TEST_EQUAL(light_result.second[i].location, heavy_result.mods[i].location) } } // Test case 3: Full reverse (keepN=false, keepC=false) { OpenMS::TargetedExperiment::Peptide peptide; peptide.sequence = "TESTPEPTIDE"; OpenMS::TargetedExperiment::Peptide::Modification mod; mod.location = 2; mod.unimod_id = 21; peptide.mods.push_back(mod); std::vector<OpenSwath::LightModification> light_mods; OpenSwath::LightModification lm; lm.location = 2; lm.unimod_id = 21; light_mods.push_back(lm); auto heavy_result = MRMDecoy::reversePeptide(peptide, false, false); auto light_result = MRMDecoy::reversePeptideLight(peptide.sequence, light_mods, false, false); TEST_EQUAL(light_result.first, heavy_result.sequence) TEST_EQUAL(light_result.second.size(), heavy_result.mods.size()) TEST_EQUAL(light_result.second[0].location, heavy_result.mods[0].location) } // Test case 4: With const_pattern { OpenMS::TargetedExperiment::Peptide peptide; peptide.sequence = "TESTPEPTIDE"; OpenMS::TargetedExperiment::Peptide::Modification mod; mod.location = 2; mod.unimod_id = 21; peptide.mods.push_back(mod); std::vector<OpenSwath::LightModification> light_mods; OpenSwath::LightModification lm; lm.location = 2; lm.unimod_id = 21; light_mods.push_back(lm); String const_pattern = "I"; auto heavy_result = MRMDecoy::reversePeptide(peptide, true, true, const_pattern); auto light_result = MRMDecoy::reversePeptideLight(peptide.sequence, light_mods, true, true, const_pattern); TEST_EQUAL(light_result.first, heavy_result.sequence) TEST_EQUAL(light_result.second.size(), heavy_result.mods.size()) TEST_EQUAL(light_result.second[0].location, heavy_result.mods[0].location) } // Test case 5: Empty modifications { OpenMS::TargetedExperiment::Peptide peptide; peptide.sequence = "TESTPEPTIDE"; std::vector<OpenSwath::LightModification> light_mods; auto heavy_result = MRMDecoy::reversePeptide(peptide, false, true); auto light_result = MRMDecoy::reversePeptideLight(peptide.sequence, light_mods, false, true); TEST_EQUAL(light_result.first, heavy_result.sequence) TEST_EQUAL(light_result.second.size(), 0) } } END_SECTION START_SECTION([EXTRA] pseudoreversePeptideLight_matches_heavy) { MRMDecoyHelper gen; // Test case 1: Simple peptide with modification { OpenMS::TargetedExperiment::Peptide peptide; peptide.sequence = "TESTPEPTIDE"; OpenMS::TargetedExperiment::Peptide::Modification modification; modification.avg_mass_delta = 79.9799; modification.location = 2; modification.mono_mass_delta = 79.966331; modification.unimod_id = 21; peptide.mods.push_back(modification); std::vector<OpenSwath::LightModification> light_mods; OpenSwath::LightModification lm; lm.location = 2; lm.unimod_id = 21; light_mods.push_back(lm); auto heavy_result = gen.pseudoreversePeptide_helper(peptide); auto light_result = gen.pseudoreversePeptideLight_helper(peptide.sequence, light_mods); TEST_EQUAL(light_result.first, heavy_result.sequence) TEST_EQUAL(light_result.second.size(), heavy_result.mods.size()) TEST_EQUAL(light_result.second[0].location, heavy_result.mods[0].location) } // Test case 2: No modifications { OpenMS::TargetedExperiment::Peptide peptide; peptide.sequence = "TESTPEPTIDE"; std::vector<OpenSwath::LightModification> light_mods; auto heavy_result = gen.pseudoreversePeptide_helper(peptide); auto light_result = gen.pseudoreversePeptideLight_helper(peptide.sequence, light_mods); TEST_EQUAL(light_result.first, heavy_result.sequence) TEST_EQUAL(light_result.second.size(), 0) } // Test case 3: Peptide ending with K (tryptic) { OpenMS::TargetedExperiment::Peptide peptide; peptide.sequence = "TESTPEPTIDEK"; OpenMS::TargetedExperiment::Peptide::Modification modification; modification.location = 2; modification.unimod_id = 21; peptide.mods.push_back(modification); std::vector<OpenSwath::LightModification> light_mods; OpenSwath::LightModification lm; lm.location = 2; lm.unimod_id = 21; light_mods.push_back(lm); auto heavy_result = gen.pseudoreversePeptide_helper(peptide); auto light_result = gen.pseudoreversePeptideLight_helper(peptide.sequence, light_mods); TEST_EQUAL(light_result.first, heavy_result.sequence) // C-terminal AA should be preserved TEST_EQUAL(light_result.first[light_result.first.size()-1], 'K') } } END_SECTION START_SECTION([EXTRA] shufflePeptideLight_matches_heavy) { MRMDecoy gen; // Test case 1: Simple shuffle with modification { OpenMS::TargetedExperiment::Peptide peptide; peptide.sequence = "TESTPEPTIDE"; OpenMS::TargetedExperiment::Peptide::Modification modification; modification.avg_mass_delta = 79.9799; modification.location = 2; modification.mono_mass_delta = 79.966331; modification.unimod_id = 21; peptide.mods.push_back(modification); std::vector<OpenSwath::LightModification> light_mods; OpenSwath::LightModification lm; lm.location = 2; lm.unimod_id = 21; light_mods.push_back(lm); // Use same seed for reproducibility int seed = 43; double identity_threshold = 0.7; auto heavy_result = gen.shufflePeptide(peptide, identity_threshold, seed); auto light_result = gen.shufflePeptideLight(peptide.sequence, light_mods, identity_threshold, seed); TEST_EQUAL(light_result.first, heavy_result.sequence) TEST_EQUAL(light_result.second.size(), heavy_result.mods.size()) TEST_EQUAL(light_result.second[0].location, heavy_result.mods[0].location) } // Test case 2: Shuffle with multiple modifications { OpenMS::TargetedExperiment::Peptide peptide; peptide.sequence = "GPPSEDGPGVPPPSPR"; OpenMS::TargetedExperiment::Peptide::Modification mod1, mod2; mod1.avg_mass_delta = 79.9799; mod1.location = 3; // first S mod1.mono_mass_delta = 79.966331; mod1.unimod_id = 21; mod2.avg_mass_delta = 79.9799; mod2.location = 13; // second S mod2.mono_mass_delta = 79.966331; mod2.unimod_id = 21; peptide.mods.push_back(mod1); peptide.mods.push_back(mod2); std::vector<OpenSwath::LightModification> light_mods; OpenSwath::LightModification lm1, lm2; lm1.location = 3; lm1.unimod_id = 21; lm2.location = 13; lm2.unimod_id = 21; light_mods.push_back(lm1); light_mods.push_back(lm2); int seed = 130; double identity_threshold = 0.7; auto heavy_result = gen.shufflePeptide(peptide, identity_threshold, seed); auto light_result = gen.shufflePeptideLight(peptide.sequence, light_mods, identity_threshold, seed); TEST_EQUAL(light_result.first, heavy_result.sequence) TEST_EQUAL(light_result.second.size(), heavy_result.mods.size()) for (size_t i = 0; i < light_result.second.size(); ++i) { TEST_EQUAL(light_result.second[i].location, heavy_result.mods[i].location) } } // Test case 3: Shuffle with terminal K preserved { OpenMS::TargetedExperiment::Peptide peptide; peptide.sequence = "TESTPEPTIDEK"; std::vector<OpenSwath::LightModification> light_mods; int seed = 42; double identity_threshold = 0.7; auto heavy_result = gen.shufflePeptide(peptide, identity_threshold, seed, 20); auto light_result = gen.shufflePeptideLight(peptide.sequence, light_mods, identity_threshold, seed, 20); TEST_EQUAL(light_result.first, heavy_result.sequence) // Terminal K should be preserved TEST_EQUAL(light_result.first[light_result.first.size()-1], 'K') TEST_EQUAL(heavy_result.sequence[heavy_result.sequence.size()-1], 'K') } // Test case 4: Shuffle with terminal R preserved { OpenMS::TargetedExperiment::Peptide peptide; peptide.sequence = "TESTPEPTIDER"; std::vector<OpenSwath::LightModification> light_mods; int seed = 42; double identity_threshold = 0.7; auto heavy_result = gen.shufflePeptide(peptide, identity_threshold, seed, 20); auto light_result = gen.shufflePeptideLight(peptide.sequence, light_mods, identity_threshold, seed, 20); TEST_EQUAL(light_result.first, heavy_result.sequence) // Terminal R should be preserved TEST_EQUAL(light_result.first[light_result.first.size()-1], 'R') } // Test case 5: No modifications { OpenMS::TargetedExperiment::Peptide peptide; peptide.sequence = "TESTPEPTIDE"; std::vector<OpenSwath::LightModification> light_mods; int seed = 42; double identity_threshold = 0.7; auto heavy_result = gen.shufflePeptide(peptide, identity_threshold, seed); auto light_result = gen.shufflePeptideLight(peptide.sequence, light_mods, identity_threshold, seed); TEST_EQUAL(light_result.first, heavy_result.sequence) TEST_EQUAL(light_result.second.size(), 0) } // Test case 6: K/R/P pattern preservation { OpenMS::TargetedExperiment::Peptide peptide; peptide.sequence = "KPRKPRPK"; std::vector<OpenSwath::LightModification> light_mods; int seed = 130; double identity_threshold = 0.7; int max_attempts = 17; auto heavy_result = gen.shufflePeptide(peptide, identity_threshold, seed, max_attempts); auto light_result = gen.shufflePeptideLight(peptide.sequence, light_mods, identity_threshold, seed, max_attempts); TEST_EQUAL(light_result.first, heavy_result.sequence) } } END_SECTION START_SECTION([EXTRA] switchKRLight_matches_heavy) { MRMDecoy gen; // Test case 1: Switch K to R { OpenMS::TargetedExperiment::Peptide heavy_peptide; heavy_peptide.sequence = "TESTPEPTIDEK"; gen.switchKR(heavy_peptide); std::string light_sequence = "TESTPEPTIDEK"; MRMDecoy::switchKRLight(light_sequence); TEST_EQUAL(light_sequence, heavy_peptide.sequence) TEST_EQUAL(light_sequence[light_sequence.size()-1], 'R') } // Test case 2: Switch R to K { OpenMS::TargetedExperiment::Peptide heavy_peptide; heavy_peptide.sequence = "TESTPEPTIDER"; gen.switchKR(heavy_peptide); std::string light_sequence = "TESTPEPTIDER"; MRMDecoy::switchKRLight(light_sequence); TEST_EQUAL(light_sequence, heavy_peptide.sequence) TEST_EQUAL(light_sequence[light_sequence.size()-1], 'K') } // Test case 3: Non-K/R terminal - both should randomize (but may differ due to separate random calls) // We just check that the sequence length is preserved and terminal changed { std::string light_sequence = "TESTPEPTIDEX"; MRMDecoy::switchKRLight(light_sequence); TEST_EQUAL(light_sequence.size(), 12) // Terminal should have changed from X to something else TEST_NOT_EQUAL(light_sequence[light_sequence.size()-1], 'X') } } END_SECTION START_SECTION([EXTRA] hasCNterminalModsLight_matches_behavior) { // Test that hasCNterminalModsLight_ correctly identifies terminal modifications // Test case 1: N-terminal modification (location = -1) { std::vector<OpenSwath::LightModification> mods; OpenSwath::LightModification mod; mod.location = -1; // N-terminal mod.unimod_id = 272; // sulfonation of N-terminus mods.push_back(mod); size_t seq_length = 11; bool has_terminal = MRMDecoyHelper::hasCNterminalModsLight_helper(mods, seq_length, false); TEST_EQUAL(has_terminal, true) } // Test case 2: C-terminal modification (location = sequence length) { std::vector<OpenSwath::LightModification> mods; OpenSwath::LightModification mod; mod.location = 11; // C-terminal for length 11 mod.unimod_id = 193; // O18 label mods.push_back(mod); size_t seq_length = 11; bool has_terminal = MRMDecoyHelper::hasCNterminalModsLight_helper(mods, seq_length, false); TEST_EQUAL(has_terminal, true) } // Test case 3: Modification on C-terminal AA (location = sequence length - 1, checkCterminalAA=true) { std::vector<OpenSwath::LightModification> mods; OpenSwath::LightModification mod; mod.location = 10; // C-terminal AA for length 11 mod.unimod_id = 35; mods.push_back(mod); size_t seq_length = 11; bool has_terminal_with_check = MRMDecoyHelper::hasCNterminalModsLight_helper(mods, seq_length, true); bool has_terminal_without_check = MRMDecoyHelper::hasCNterminalModsLight_helper(mods, seq_length, false); TEST_EQUAL(has_terminal_with_check, true) TEST_EQUAL(has_terminal_without_check, false) } // Test case 4: Internal modification - should return false { std::vector<OpenSwath::LightModification> mods; OpenSwath::LightModification mod; mod.location = 5; // Internal mod.unimod_id = 21; mods.push_back(mod); size_t seq_length = 11; bool has_terminal = MRMDecoyHelper::hasCNterminalModsLight_helper(mods, seq_length, false); TEST_EQUAL(has_terminal, false) } // Test case 5: No modifications - should return false { std::vector<OpenSwath::LightModification> mods; size_t seq_length = 11; bool has_terminal = MRMDecoyHelper::hasCNterminalModsLight_helper(mods, seq_length, false); TEST_EQUAL(has_terminal, false) } // Test case 6: Both N and C terminal modifications { std::vector<OpenSwath::LightModification> mods; OpenSwath::LightModification mod1, mod2; mod1.location = -1; // N-terminal mod1.unimod_id = 272; mod2.location = 11; // C-terminal mod2.unimod_id = 193; mods.push_back(mod1); mods.push_back(mod2); size_t seq_length = 11; bool has_terminal = MRMDecoyHelper::hasCNterminalModsLight_helper(mods, seq_length, false); TEST_EQUAL(has_terminal, true) } } END_SECTION START_SECTION([EXTRA] generateDecoysLight_modified_sequence_duplicate_detection) { // Regression test for the fix where Light path was incorrectly using unmodified sequences // for duplicate detection instead of modified sequences (with UniMod annotations). // This test verifies that peptides with the same unmodified sequence but different // modifications generate separate decoys (not treated as duplicates). MRMDecoy gen; // Create a minimal light experiment with two peptides that have: // - Same unmodified sequence // - Different modifications // These should NOT be treated as duplicates OpenSwath::LightTargetedExperiment exp; // Peptide 1: TESTPEPTIDE with modification at position 2 (UniMod:21, Phospho) OpenSwath::LightCompound compound1; compound1.id = "peptide1"; compound1.sequence = "TESTPEPTIDE"; compound1.charge = 2; OpenSwath::LightModification mod1; mod1.location = 2; mod1.unimod_id = 21; // Phospho compound1.modifications.push_back(mod1); exp.compounds.push_back(compound1); // Peptide 2: TESTPEPTIDE with modification at position 5 (UniMod:35, Oxidation) OpenSwath::LightCompound compound2; compound2.id = "peptide2"; compound2.sequence = "TESTPEPTIDE"; // Same unmodified sequence compound2.charge = 2; // Same charge OpenSwath::LightModification mod2; mod2.location = 5; mod2.unimod_id = 35; // Oxidation compound2.modifications.push_back(mod2); exp.compounds.push_back(compound2); // Add minimal transitions for each peptide so they pass validation OpenSwath::LightTransition transition1; transition1.peptide_ref = "peptide1"; transition1.transition_name = "transition1"; transition1.product_mz = 500.0; transition1.precursor_mz = 600.0; transition1.setDetectingTransition(true); transition1.fragment_charge = 1; // Set fragment type directly using new API (replaces annotations) transition1.setFragmentType("y"); transition1.fragment_nr = 3; exp.transitions.push_back(transition1); OpenSwath::LightTransition transition2; transition2.peptide_ref = "peptide2"; transition2.transition_name = "transition2"; transition2.product_mz = 501.0; transition2.precursor_mz = 601.0; transition2.setDetectingTransition(true); transition2.fragment_charge = 1; // Set fragment type directly using new API (replaces annotations) transition2.setFragmentType("y"); transition2.fragment_nr = 3; exp.transitions.push_back(transition2); // Generate decoys using the Light path OpenSwath::LightTargetedExperiment decoys; std::vector<String> fragment_types; fragment_types.push_back("y"); fragment_types.push_back("b"); std::vector<size_t> fragment_charges; fragment_charges.push_back(1); fragment_charges.push_back(2); gen.generateDecoysLight( exp, decoys, "pseudo-reverse", 1.0, // aim_decoy_fraction - aim for 100% decoys false, // do_switchKR "DECOY_", 10, // max_attempts 0.7, // identity_threshold 0.0, // precursor_mz_shift 20.0, // product_mz_shift 500.0, // product_mz_threshold - high value to match any ion (test focuses on duplicate detection) fragment_types, fragment_charges, true, // enable_specific_losses false, // enable_unspecific_losses -4 // round_decPow ); // Verify that BOTH peptides generated decoys (they should not be treated as duplicates) // Before the fix, the second peptide would be incorrectly excluded as a duplicate // because only the unmodified sequence was used for duplicate detection TEST_EQUAL(decoys.compounds.size(), 2) // Verify that the two decoys have different modified sequences // (i.e., modifications are at different positions) if (decoys.compounds.size() == 2) { const auto& seq1 = decoys.compounds[0].sequence; const auto& seq2 = decoys.compounds[1].sequence; // The sequences should be different because they have different modifications TEST_NOT_EQUAL(seq1, seq2) // Both should contain UniMod annotations TEST_NOT_EQUAL(seq1.find("UniMod:"), std::string::npos) TEST_NOT_EQUAL(seq2.find("UniMod:"), std::string::npos) } // Also verify that we got transitions for both decoys TEST_EQUAL(decoys.transitions.size(), 2) } END_SECTION START_SECTION([EXTRA] generateDecoys_modified_sequence_duplicate_detection) { // Regression test for the fix where Heavy path was incorrectly using unmodified sequences // for duplicate detection instead of modified sequences (with UniMod annotations). // This test verifies that peptides with the same unmodified sequence but different // modifications generate separate decoys (not treated as duplicates). MRMDecoy gen; // Create a minimal TargetedExperiment with two peptides that have: // - Same unmodified sequence // - Different modifications // These should NOT be treated as duplicates TargetedExperiment exp; TargetedExperiment decoy_exp; // Add a dummy protein TargetedExperiment::Protein protein; protein.id = "protein1"; exp.addProtein(protein); // Peptide 1: TESTPEPTIDE with Phospho modification at position 2 TargetedExperiment::Peptide peptide1; peptide1.id = "peptide1"; peptide1.sequence = "TESTPEPTIDE"; peptide1.setChargeState(2); peptide1.protein_refs.push_back("protein1"); TargetedExperiment::Peptide::Modification mod1; mod1.location = 2; mod1.unimod_id = 21; // Phospho mod1.mono_mass_delta = 79.966331; mod1.avg_mass_delta = 79.9799; peptide1.mods.push_back(mod1); exp.addPeptide(peptide1); // Peptide 2: TESTPEPTIDE with Oxidation modification at position 5 TargetedExperiment::Peptide peptide2; peptide2.id = "peptide2"; peptide2.sequence = "TESTPEPTIDE"; // Same unmodified sequence peptide2.setChargeState(2); // Same charge peptide2.protein_refs.push_back("protein1"); TargetedExperiment::Peptide::Modification mod2; mod2.location = 5; mod2.unimod_id = 35; // Oxidation mod2.mono_mass_delta = 15.994915; mod2.avg_mass_delta = 15.9994; peptide2.mods.push_back(mod2); exp.addPeptide(peptide2); // Add minimal transitions for each peptide ReactionMonitoringTransition transition1; transition1.setNativeID("transition1"); transition1.setPeptideRef("peptide1"); transition1.setProductMZ(500.0); transition1.setPrecursorMZ(600.0); transition1.setDetectingTransition(true); CVTerm cv_term1; cv_term1.setCVIdentifierRef("MS"); cv_term1.setAccession("MS:1001220"); cv_term1.setName("frag: y ion"); transition1.addProductCVTerm(cv_term1); ReactionMonitoringTransition::Product product1; product1.setChargeState(1); transition1.setProduct(product1); exp.addTransition(transition1); ReactionMonitoringTransition transition2; transition2.setNativeID("transition2"); transition2.setPeptideRef("peptide2"); transition2.setProductMZ(501.0); transition2.setPrecursorMZ(601.0); transition2.setDetectingTransition(true); CVTerm cv_term2; cv_term2.setCVIdentifierRef("MS"); cv_term2.setAccession("MS:1001220"); cv_term2.setName("frag: y ion"); transition2.addProductCVTerm(cv_term2); ReactionMonitoringTransition::Product product2; product2.setChargeState(1); transition2.setProduct(product2); exp.addTransition(transition2); // Generate decoys using the Heavy path std::vector<String> fragment_types; fragment_types.push_back("y"); fragment_types.push_back("b"); std::vector<size_t> fragment_charges; fragment_charges.push_back(1); fragment_charges.push_back(2); gen.generateDecoys( exp, decoy_exp, "pseudo-reverse", 1.0, // aim_decoy_fraction - aim for 100% decoys false, // do_switchKR "DECOY_", 10, // max_attempts 0.7, // identity_threshold 0.0, // precursor_mz_shift 20.0, // product_mz_shift 500.0, // product_mz_threshold - high value to match any ion fragment_types, fragment_charges, true, // enable_specific_losses false, // enable_unspecific_losses -4 // round_decPow ); // Verify that BOTH peptides generated decoys (they should not be treated as duplicates) // Before the fix, the second peptide would be incorrectly excluded as a duplicate // because only the unmodified sequence was used for duplicate detection TEST_EQUAL(decoy_exp.getPeptides().size(), 2) // Verify that the two decoys have different modified sequences if (decoy_exp.getPeptides().size() == 2) { const auto& pep1 = decoy_exp.getPeptides()[0]; const auto& pep2 = decoy_exp.getPeptides()[1]; // Both should have modifications TEST_EQUAL(pep1.mods.size() >= 1, true) TEST_EQUAL(pep2.mods.size() >= 1, true) // The modifications should be at different positions (since they came from peptides // with modifications at different positions) if (pep1.mods.size() >= 1 && pep2.mods.size() >= 1) { TEST_NOT_EQUAL(pep1.mods[0].location, pep2.mods[0].location) } } // Also verify that we got transitions for both decoys TEST_EQUAL(decoy_exp.getTransitions().size(), 2) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST #ifdef __clang__ #pragma clang diagnostic pop #endif
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/Bzip2Ifstream_test.cpp
.cpp
3,414
111
// 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 $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/DATASTRUCTURES/String.h> #include <OpenMS/FORMAT/Bzip2Ifstream.h> using namespace OpenMS; using namespace std; /////////////////////////// START_TEST(Bzip2Ifstream_test, "$Id$") Bzip2Ifstream* ptr = nullptr; Bzip2Ifstream* nullPointer = nullptr; START_SECTION((Bzip2Ifstream())) ptr = new Bzip2Ifstream; TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((~Bzip2Ifstream())) delete ptr; END_SECTION START_SECTION(Bzip2Ifstream(const char * filename)) TEST_EXCEPTION(Exception::FileNotFound, Bzip2Ifstream bzip2(OPENMS_GET_TEST_DATA_PATH("ThisFileDoesNotExist"))) Bzip2Ifstream bzip(OPENMS_GET_TEST_DATA_PATH("Bzip2IfStream_1.bz2")); TEST_EQUAL(bzip.streamEnd(), false) TEST_EQUAL(bzip.isOpen(),true) char buffer[30]; buffer[29] = '\0'; size_t len = 29; TEST_EQUAL(29, bzip.read(buffer, len)) TEST_EQUAL(String(buffer), String("Was decompression successful?")) END_SECTION START_SECTION(void open(const char *filename)) Bzip2Ifstream bzip; TEST_EXCEPTION(Exception::FileNotFound, bzip.open(OPENMS_GET_TEST_DATA_PATH("ThisFileDoesNotExist"))) bzip.open(OPENMS_GET_TEST_DATA_PATH("Bzip2IfStream_1.bz2")); TEST_EQUAL(bzip.streamEnd(), false) TEST_EQUAL(bzip.isOpen(),true) char buffer[30]; buffer[29] = '\0'; size_t len = 29; TEST_EQUAL(29, bzip.read(buffer, len)) TEST_EQUAL(String(buffer), String("Was decompression successful?")) END_SECTION START_SECTION(size_t read(char *s, size_t n)) //tested in open(const char * filename) Bzip2Ifstream bzip(OPENMS_GET_TEST_DATA_PATH("Bzip2IfStream_1_corrupt.bz2")); char buffer[30]; buffer[29] = '\0'; size_t len = 29; TEST_EXCEPTION(Exception::ParseError, bzip.read(buffer,10)) Bzip2Ifstream bzip2(OPENMS_GET_TEST_DATA_PATH("Bzip2IfStream_1.bz2")); bzip2.read(buffer, len); TEST_EQUAL(1, bzip2.read(buffer,10)); TEST_EQUAL(bzip2.isOpen(), false) TEST_EQUAL(bzip2.streamEnd(),true) bzip2.open(OPENMS_GET_TEST_DATA_PATH("Bzip2IfStream_1_corrupt.bz2")); TEST_EXCEPTION(Exception::ParseError, bzip2.read(buffer,10)) bzip2.close(); TEST_EQUAL(bzip2.isOpen(), false) TEST_EQUAL(bzip2.streamEnd(),true) TEST_EXCEPTION(Exception::IllegalArgument, bzip2.read(buffer,10)) bzip2.close(); TEST_EQUAL(bzip2.isOpen(), false) TEST_EQUAL(bzip2.streamEnd(),true) TEST_EXCEPTION(Exception::IllegalArgument, bzip2.read(buffer,10)) bzip2.open(OPENMS_GET_TEST_DATA_PATH("Bzip2IfStream_1.bz2")); TEST_EQUAL(29, bzip2.read(buffer, len)) TEST_EQUAL(String(buffer), String("Was decompression successful?")) END_SECTION START_SECTION(void close()) //tested in read NOT_TESTABLE END_SECTION START_SECTION(bool streamEnd() const ) //tested in open(const char * filename) and read NOT_TESTABLE END_SECTION START_SECTION(bool isOpen() const ) //tested in open(const char * filename) and read NOT_TESTABLE END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/SequestInfile_test.cpp
.cpp
22,319
575
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: Martin Langwisch $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/DATASTRUCTURES/String.h> #include <OpenMS/FORMAT/SequestInfile.h> #include <iostream> #include <fstream> #include <map> #include <string> #include <sstream> using namespace OpenMS; using namespace std; /////////////////////////// START_TEST(SequestInfile, "$Id$") ///////////////////////////////////////////////////////////// SequestInfile* ptr = nullptr; SequestInfile* nullPointer = nullptr; START_SECTION(SequestInfile()) ptr = new SequestInfile(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION(~SequestInfile()) delete ptr; END_SECTION START_SECTION((SequestInfile& operator=(const SequestInfile &sequest_infile))) SequestInfile sequest_infile1; sequest_infile1.setDatabase("dummy"); SequestInfile sequest_infile2 = sequest_infile1; TEST_EQUAL(( sequest_infile1 == sequest_infile2 ), true) SequestInfile sequest_infile3; TEST_EQUAL(( sequest_infile2 == sequest_infile3 ), false) END_SECTION START_SECTION((SequestInfile(const SequestInfile &sequest_infile))) SequestInfile sequest_infile1; sequest_infile1.setDatabase("dummy"); SequestInfile sequest_infile2(sequest_infile1); TEST_EQUAL(( sequest_infile1 == sequest_infile2 ), true) SequestInfile sequest_infile3; TEST_EQUAL(( sequest_infile2 == sequest_infile3 ), false) END_SECTION START_SECTION((bool operator==(const SequestInfile &sequest_infile) const)) SequestInfile sequest_infile1; sequest_infile1.setDatabase("dummy"); SequestInfile sequest_infile2; sequest_infile2.setDatabase("dummy"); TEST_EQUAL(( sequest_infile1 == sequest_infile2 ), true) SequestInfile sequest_infile3; sequest_infile3.setDatabase("another dummy"); TEST_EQUAL(( sequest_infile1 == sequest_infile3 ), false) END_SECTION SequestInfile file; stringstream ss; ss << "[SEQUEST_ENZYME_INFO]" << endl; ss << "0. AspN 0 D -" << endl; ss << "1. AspN_DE 0 DE -" << endl; ss << "2. Chymotrypsin 1 FWYL -" << endl; ss << "3. Chymotrypsin_WYF 1 FWY -" << endl; ss << "4. Clostripain 1 R -" << endl; ss << "5. Cyanogen_Bromide 1 M -" << endl; ss << "6. Elastase 1 ALIV P" << endl; ss << "7. Elastase/Tryp/Chymo 1 ALIVKRWFY P" << endl; ss << "8. GluC 1 E -" << endl; ss << "9. GluC_ED 1 ED -" << endl; ss << "10. IodosoBenzoate 1 W -" << endl; ss << "11. LysC 1 K -" << endl; ss << "12. No_Enzyme 0 - -" << endl; ss << "13. Proline_Endopept 1 P -" << endl; ss << "14. Trypsin 1 KRLNH -" << endl; ss << "15. Trypsin/Chymo 1 KRLFWYN -" << endl; ss << "16. Trypsin_Strict 1 KR -" << endl; START_SECTION((const String getEnzymeInfoAsString() const)) TEST_STRING_EQUAL(file.getEnzymeInfoAsString(), ss.str()) END_SECTION START_SECTION(void addEnzymeInfo(std::vector< String >& enzyme_info)) std::vector< String > e_info; e_info.push_back("Z_TestEnzyme"); e_info.push_back("1"); e_info.push_back("RMW"); e_info.push_back("-"); file.addEnzymeInfo(e_info); e_info.clear(); ss << "17. Z_TestEnzyme 1 RMW -" << endl; TEST_STRING_EQUAL(file.getEnzymeInfoAsString(), ss.str()) END_SECTION START_SECTION(void handlePTMs(const String& modification_line, const String& modifications_filename, const bool monoisotopic)) // test exceptions String modification_line = "Phosphorylation"; TEST_EXCEPTION_WITH_MESSAGE(Exception::FileNotFound, file.handlePTMs(modification_line, "a", true), "the file 'a' could not be found") // TEST_EXCEPTION_WITH_MESSAGE(Exception::FileNotReadable, file.handlePTMs(modification_line, OPENMS_GET_TEST_DATA_PATH("Sequest_unreadable_unwriteable.txt"), true), "the file `data/Sequest_unreadable_unwriteable.txt' is not readable for the current user") modification_line = "2H20,KRLNH,fix"; TEST_EXCEPTION_WITH_MESSAGE(Exception::ParseError, file.handlePTMs(modification_line, OPENMS_GET_TEST_DATA_PATH("Sequest_PTMs.xml"), true), "There's something wrong with this modification. Aborting! in: 2H20,KRLNH,fix") modification_line = "10.3+"; TEST_EXCEPTION_WITH_MESSAGE(Exception::ParseError, file.handlePTMs(modification_line, OPENMS_GET_TEST_DATA_PATH("Sequest_PTMs.xml"), true), "No residues for modification given. Aborting! in: 10.3+") modification_line = "10.3+,KRLNH,stat,PTM_0"; TEST_EXCEPTION_WITH_MESSAGE(Exception::ParseError, file.handlePTMs(modification_line, OPENMS_GET_TEST_DATA_PATH("Sequest_PTMs.xml"), true), "There's something wrong with the type of this modification. Aborting! in: 10.3+,KRLNH,stat,PTM_0") modification_line = "Phosphorylation:Phosphorylation"; TEST_EXCEPTION_WITH_MESSAGE(Exception::ParseError, file.handlePTMs(modification_line, OPENMS_GET_TEST_DATA_PATH("Sequest_PTMs.xml"), true), "There's already a modification with this name. Aborting! in: Phosphorylation") // test the actual program modification_line = "10.3+,KRLNH,fix:+16,C:16-,cterm,opt:-16,nterm,fix:17-,cterm_prot:-17,nterm_prot,fix"; // "10.3+,KRLNH,fix:Phosphorylation:+16,C:HCNO,nterm,Carbamylation:H2C,CHKNQRILDEST,opt,Methylation:16-,cterm,opt:-16,nterm,fix:17-,cterm_prot:-17,nterm_prot,fix"; // average masses file.handlePTMs(modification_line, OPENMS_GET_TEST_DATA_PATH("Sequest_PTMs.xml"), false); map< String, vector< String > > modifications; modifications["PTM_0"] = vector< String >(3); modifications["PTM_0"][0] = "KRLNH"; modifications["PTM_0"][1] = "10.3"; modifications["PTM_0"][2] = "FIX"; // modifications["Phosphorylation"] = vector< String >(3); // modifications["Phosphorylation"][0] = "STYDHCR"; // modifications["Phosphorylation"][1] = "79.97990"; // modifications["Phosphorylation"][2] = "OPT"; modifications["PTM_1"] = vector< String >(3); modifications["PTM_1"][0] = "C"; modifications["PTM_1"][1] = "16"; modifications["PTM_1"][2] = "OPT"; // modifications["Carbamylation"] = vector< String >(3); // modifications["Carbamylation"][0] = "NTERM"; // modifications["Carbamylation"][1] = "43.02474"; // modifications["Carbamylation"][2] = "OPT"; // modifications["Methylation"] = vector< String >(3); // modifications["Methylation"][0] = "CHKNQRILDEST"; // modifications["Methylation"][1] = "14.02658"; // modifications["Methylation"][2] = "OPT"; // modifications["PTM_5"] = vector< String >(3); // modifications["PTM_5"][0] = "CTERM"; // modifications["PTM_5"][1] = "-16"; // modifications["PTM_5"][2] = "OPT"; // modifications["PTM_6"] = vector< String >(3); // modifications["PTM_6"][0] = "NTERM"; // modifications["PTM_6"][1] = "-16"; // modifications["PTM_6"][2] = "FIX"; // modifications["PTM_7"] = vector< String >(3); // modifications["PTM_7"][0] = "CTERM_PROT"; // modifications["PTM_7"][1] = "-17"; // modifications["PTM_7"][2] = "OPT"; // modifications["PTM_8"] = vector< String >(3); // modifications["PTM_8"][0] = "NTERM_PROT"; // modifications["PTM_8"][1] = "-17"; // modifications["PTM_8"][2] = "FIX"; modifications["PTM_2"] = vector< String >(3); modifications["PTM_2"][0] = "CTERM"; modifications["PTM_2"][1] = "-16"; modifications["PTM_2"][2] = "OPT"; modifications["PTM_3"] = vector< String >(3); modifications["PTM_3"][0] = "NTERM"; modifications["PTM_3"][1] = "-16"; modifications["PTM_3"][2] = "FIX"; modifications["PTM_4"] = vector< String >(3); modifications["PTM_4"][0] = "CTERM_PROT"; modifications["PTM_4"][1] = "-17"; modifications["PTM_4"][2] = "OPT"; modifications["PTM_5"] = vector< String >(3); modifications["PTM_5"][0] = "NTERM_PROT"; modifications["PTM_5"][1] = "-17"; modifications["PTM_5"][2] = "FIX"; map< String, vector< String > >::const_iterator result_mod_i = file.getModifications().begin(); TEST_EQUAL(file.getModifications().size(), modifications.size()) if ( file.getModifications().size() == modifications.size() ) { for ( map< String, vector< String > >::const_iterator mod_i = modifications.begin(); mod_i != modifications.end(); ++mod_i, ++result_mod_i ) { TEST_STRING_EQUAL(result_mod_i->first, mod_i->first) TEST_EQUAL(result_mod_i->second.size(), 3) TEST_EQUAL(result_mod_i->second.size(), mod_i->second.size()) if ( result_mod_i->second.size() == mod_i->second.size() ) { TEST_STRING_EQUAL(result_mod_i->second[0], mod_i->second[0]) TEST_STRING_EQUAL(result_mod_i->second[1], mod_i->second[1]) TEST_STRING_EQUAL(result_mod_i->second[2], mod_i->second[2]) } } } // monoisotopic masses file.handlePTMs(modification_line, OPENMS_GET_TEST_DATA_PATH("Sequest_PTMs.xml"), true); // modifications["Phosphorylation"][1] = "79.96634"; // modifications["Carbamylation"][1] = "43.00582"; // modifications["Methylation"][1] = "14.01565"; result_mod_i = file.getModifications().begin(); TEST_EQUAL(file.getModifications().size(), modifications.size()) if ( file.getModifications().size() == modifications.size() ) { for ( map< String, vector< String > >::const_iterator mod_i = modifications.begin(); mod_i != modifications.end(); ++mod_i, ++result_mod_i ) { TEST_STRING_EQUAL(result_mod_i->first, mod_i->first) TEST_EQUAL(result_mod_i->second.size(), 3) TEST_EQUAL(result_mod_i->second.size(), mod_i->second.size()) if ( result_mod_i->second.size() == mod_i->second.size() ) { TEST_STRING_EQUAL(result_mod_i->second[0], mod_i->second[0]) TEST_STRING_EQUAL(result_mod_i->second[1], mod_i->second[1]) TEST_STRING_EQUAL(result_mod_i->second[2], mod_i->second[2]) } } } END_SECTION START_SECTION((const std::map< String, std::vector< String > >& getModifications() const)) String modification_line = "10.3+,KRLNH,fix:+16,C:16-,cterm,opt:-16,nterm,fix:17-,cterm_prot:-17,nterm_prot,fix"; // "10.3+,KRLNH,fix:Phosphorylation:+16,C:HCNO,nterm,Carbamylation:H2C,CHKNQRILDEST,opt,Methylation:16-,cterm,opt:-16,nterm,fix:17-,cterm_prot:-17,nterm_prot,fix"; // average masses file.handlePTMs(modification_line, OPENMS_GET_TEST_DATA_PATH("Sequest_PTMs.xml"), false); map< String, vector< String > > modifications; modifications["PTM_0"] = vector< String >(3); modifications["PTM_0"][0] = "KRLNH"; modifications["PTM_0"][1] = "10.3"; modifications["PTM_0"][2] = "FIX"; // modifications["Phosphorylation"] = vector< String >(3); // modifications["Phosphorylation"][0] = "STYDHCR"; // modifications["Phosphorylation"][1] = "79.97990"; // modifications["Phosphorylation"][2] = "OPT"; modifications["PTM_1"] = vector< String >(3); modifications["PTM_1"][0] = "C"; modifications["PTM_1"][1] = "16"; modifications["PTM_1"][2] = "OPT"; // modifications["Carbamylation"] = vector< String >(3); // modifications["Carbamylation"][0] = "NTERM"; // modifications["Carbamylation"][1] = "43.02474"; // modifications["Carbamylation"][2] = "OPT"; // modifications["Methylation"] = vector< String >(3); // modifications["Methylation"][0] = "CHKNQRILDEST"; // modifications["Methylation"][1] = "14.02658"; // modifications["Methylation"][2] = "OPT"; // modifications["PTM_5"] = vector< String >(3); // modifications["PTM_5"][0] = "CTERM"; // modifications["PTM_5"][1] = "-16"; // modifications["PTM_5"][2] = "OPT"; // modifications["PTM_6"] = vector< String >(3); // modifications["PTM_6"][0] = "NTERM"; // modifications["PTM_6"][1] = "-16"; // modifications["PTM_6"][2] = "FIX"; // modifications["PTM_7"] = vector< String >(3); // modifications["PTM_7"][0] = "CTERM_PROT"; // modifications["PTM_7"][1] = "-17"; // modifications["PTM_7"][2] = "OPT"; // modifications["PTM_8"] = vector< String >(3); // modifications["PTM_8"][0] = "NTERM_PROT"; // modifications["PTM_8"][1] = "-17"; // modifications["PTM_8"][2] = "FIX"; modifications["PTM_2"] = vector< String >(3); modifications["PTM_2"][0] = "CTERM"; modifications["PTM_2"][1] = "-16"; modifications["PTM_2"][2] = "OPT"; modifications["PTM_3"] = vector< String >(3); modifications["PTM_3"][0] = "NTERM"; modifications["PTM_3"][1] = "-16"; modifications["PTM_3"][2] = "FIX"; modifications["PTM_4"] = vector< String >(3); modifications["PTM_4"][0] = "CTERM_PROT"; modifications["PTM_4"][1] = "-17"; modifications["PTM_4"][2] = "OPT"; modifications["PTM_5"] = vector< String >(3); modifications["PTM_5"][0] = "NTERM_PROT"; modifications["PTM_5"][1] = "-17"; modifications["PTM_5"][2] = "FIX"; map< String, vector< String > >::const_iterator result_mod_i = file.getModifications().begin(); TEST_EQUAL(file.getModifications().size(), modifications.size()) if ( file.getModifications().size() == modifications.size() ) { for ( map< String, vector< String > >::const_iterator mod_i = modifications.begin(); mod_i != modifications.end(); ++mod_i, ++result_mod_i ) { TEST_STRING_EQUAL(result_mod_i->first, mod_i->first) TEST_EQUAL(result_mod_i->second.size(), 3) TEST_EQUAL(result_mod_i->second.size(), mod_i->second.size()) if ( result_mod_i->second.size() == mod_i->second.size() ) { TEST_STRING_EQUAL(result_mod_i->second[0], mod_i->second[0]) TEST_STRING_EQUAL(result_mod_i->second[1], mod_i->second[1]) TEST_STRING_EQUAL(result_mod_i->second[2], mod_i->second[2]) } } } END_SECTION START_SECTION(void setDatabase(const String& database)) file.setDatabase(R"(\\bude\langwisc\sequest_test\Analysis.mzXML.fasta)"); TEST_STRING_EQUAL(file.getDatabase() , "\\\\bude\\langwisc\\sequest_test\\Analysis.mzXML.fasta") END_SECTION START_SECTION((const String& getDatabase() const)) TEST_STRING_EQUAL(file.getDatabase() , "\\\\bude\\langwisc\\sequest_test\\Analysis.mzXML.fasta") END_SECTION START_SECTION(void setNeutralLossesForIons(const String& neutral_losses_for_ions)) file.setNeutralLossesForIons("0 1 1"); TEST_STRING_EQUAL(file.getNeutralLossesForIons() , "0 1 1") END_SECTION START_SECTION((const String& getNeutralLossesForIons() const)) TEST_STRING_EQUAL(file.getNeutralLossesForIons() , "0 1 1") END_SECTION START_SECTION(void setIonSeriesWeights(const String& ion_series_weights)) file.setIonSeriesWeights("0 1.0 0 0 0 0 0 1.0 0"); TEST_STRING_EQUAL(file.getIonSeriesWeights() , "0 1.0 0 0 0 0 0 1.0 0") END_SECTION START_SECTION((const String& getIonSeriesWeights() const)) TEST_STRING_EQUAL(file.getIonSeriesWeights() , "0 1.0 0 0 0 0 0 1.0 0") END_SECTION START_SECTION(void setPartialSequence(const String& partial_sequence)) file.setPartialSequence("SEQVEST TEST"); TEST_STRING_EQUAL(file.getPartialSequence() , "SEQVEST TEST") END_SECTION START_SECTION((const String& getPartialSequence() const)) TEST_STRING_EQUAL(file.getPartialSequence() , "SEQVEST TEST") END_SECTION START_SECTION(void setSequenceHeaderFilter(const String& sequence_header_filter)) file.setSequenceHeaderFilter("homo~sapiens !mus musculus"); TEST_STRING_EQUAL(file.getSequenceHeaderFilter() , "homo~sapiens !mus musculus") END_SECTION START_SECTION((const String& getSequenceHeaderFilter() const)) TEST_STRING_EQUAL(file.getSequenceHeaderFilter() , "homo~sapiens !mus musculus") END_SECTION START_SECTION(void setPrecursorMassTolerance(float precursor_mass_tolerance)) file.setPrecursorMassTolerance(1.3f); TEST_REAL_SIMILAR(file.getPrecursorMassTolerance() , 1.3) END_SECTION START_SECTION((float getPrecursorMassTolerance() const)) TEST_REAL_SIMILAR(file.getPrecursorMassTolerance() , 1.3) END_SECTION START_SECTION(void setPeakMassTolerance(float peak_mass_tolerance)) file.setPeakMassTolerance(0.3f); TEST_REAL_SIMILAR(file.getPeakMassTolerance() , 0.3) END_SECTION START_SECTION((float getPeakMassTolerance() const)) TEST_REAL_SIMILAR(file.getPeakMassTolerance() , 0.3) END_SECTION START_SECTION(void setMatchPeakTolerance(float match_peak_tolerance)) file.setMatchPeakTolerance(1.2f); TEST_REAL_SIMILAR(file.getMatchPeakTolerance() , 1.2) END_SECTION START_SECTION((float getMatchPeakTolerance() const)) TEST_REAL_SIMILAR(file.getMatchPeakTolerance() , 1.2) END_SECTION START_SECTION(void setIonCutoffPercentage(float ion_cutoff_percentage)) file.setIonCutoffPercentage(0.3f); TEST_REAL_SIMILAR(file.getIonCutoffPercentage() , 0.3) END_SECTION START_SECTION((float getIonCutoffPercentage() const)) TEST_REAL_SIMILAR(file.getIonCutoffPercentage() , 0.3) END_SECTION START_SECTION(void setProteinMassFilter(const String& protein_mass_filter)) file.setProteinMassFilter("30.2 0"); TEST_STRING_EQUAL(file.getProteinMassFilter() , "30.2 0") END_SECTION START_SECTION((const String& getProteinMassFilter() const)) TEST_STRING_EQUAL(file.getProteinMassFilter() , "30.2 0") END_SECTION START_SECTION(void setPeptideMassUnit(Size peptide_mass_unit)) file.setPeptideMassUnit(0); TEST_EQUAL(file.getPeptideMassUnit() , 0) END_SECTION START_SECTION((Size getPeptideMassUnit() const)) TEST_EQUAL(file.getPeptideMassUnit() , 0) END_SECTION START_SECTION(void setOutputLines(Size output_lines)) file.setOutputLines(10); TEST_EQUAL(file.getOutputLines() , 10) END_SECTION START_SECTION((Size getOutputLines() const)) TEST_EQUAL(file.getOutputLines() , 10) END_SECTION START_SECTION(Size setEnzyme(String enzyme_name)) TEST_EQUAL(file.setEnzyme("i_dont_exist_enzyme"), 18) TEST_EQUAL(file.setEnzyme("Trypsin"), 0) TEST_EQUAL(file.getEnzymeNumber() , 14) END_SECTION START_SECTION((String getEnzymeName() const)) TEST_STRING_EQUAL(file.getEnzymeName(), "Trypsin") END_SECTION START_SECTION((Size getEnzymeNumber() const)) TEST_EQUAL(file.getEnzymeNumber() , 14) END_SECTION START_SECTION(void setMaxAAPerModPerPeptide(Size max_aa_per_mod_per_peptide)) file.setMaxAAPerModPerPeptide(4); TEST_EQUAL(file.getMaxAAPerModPerPeptide() , 4) END_SECTION START_SECTION((Size getMaxAAPerModPerPeptide() const)) TEST_EQUAL(file.getMaxAAPerModPerPeptide() , 4) END_SECTION START_SECTION(void setMaxModsPerPeptide(Size max_mods_per_peptide)) file.setMaxModsPerPeptide(3); TEST_EQUAL(file.getMaxModsPerPeptide() , 3) END_SECTION START_SECTION((Size getMaxModsPerPeptide() const)) TEST_EQUAL(file.getMaxModsPerPeptide() , 3) END_SECTION START_SECTION(void setNucleotideReadingFrame(Size nucleotide_reading_frame)) file.setNucleotideReadingFrame(0); TEST_EQUAL(file.getNucleotideReadingFrame() , 0) END_SECTION START_SECTION((Size getNucleotideReadingFrame() const)) TEST_EQUAL(file.getNucleotideReadingFrame() , 0) END_SECTION START_SECTION(void setMaxInternalCleavageSites(Size max_internal_cleavage_sites)) file.setMaxInternalCleavageSites(2); TEST_EQUAL(file.getMaxInternalCleavageSites() , 2) END_SECTION START_SECTION((Size getMaxInternalCleavageSites() const)) TEST_EQUAL(file.getMaxInternalCleavageSites() , 2) END_SECTION START_SECTION(void setMatchPeakCount(Size match_peak_count)) file.setMatchPeakCount(5); TEST_EQUAL(file.getMatchPeakCount() , 5) END_SECTION START_SECTION((Size getMatchPeakCount() const)) TEST_EQUAL(file.getMatchPeakCount() , 5) END_SECTION START_SECTION(void setMatchPeakAllowedError(Size match_peak_allowed_error)) file.setMatchPeakAllowedError(4); TEST_EQUAL(file.getMatchPeakAllowedError() , 4) END_SECTION START_SECTION((Size getMatchPeakAllowedError() const)) TEST_EQUAL(file.getMatchPeakAllowedError() , 4) END_SECTION START_SECTION(void setShowFragmentIons(bool show_fragments)) file.setShowFragmentIons(true); TEST_EQUAL(file.getShowFragmentIons() , true) END_SECTION START_SECTION((bool getShowFragmentIons() const)) TEST_EQUAL(file.getShowFragmentIons() , true) END_SECTION START_SECTION(void setPrintDuplicateReferences(bool print_duplicate_references)) file.setPrintDuplicateReferences(true); TEST_EQUAL(file.getPrintDuplicateReferences() , true) END_SECTION START_SECTION((bool getPrintDuplicateReferences() const)) TEST_EQUAL(file.getPrintDuplicateReferences() , true) END_SECTION START_SECTION(void setRemovePrecursorNearPeaks(bool remove_precursor_near_peaks)) file.setRemovePrecursorNearPeaks(true); TEST_EQUAL(file.getRemovePrecursorNearPeaks() , true) END_SECTION START_SECTION((bool getRemovePrecursorNearPeaks() const)) TEST_EQUAL(file.getRemovePrecursorNearPeaks() , true) END_SECTION START_SECTION(void setMassTypeParent(bool mass_type_parent)) file.setMassTypeParent(true); TEST_EQUAL(file.getMassTypeParent() , true) END_SECTION START_SECTION((bool getMassTypeParent() const)) TEST_EQUAL(file.getMassTypeParent() , true) END_SECTION START_SECTION(void setMassTypeFragment(bool mass_type_fragment)) file.setMassTypeFragment(true); TEST_EQUAL(file.getMassTypeFragment() , true) END_SECTION START_SECTION((bool getMassTypeFragment() const)) TEST_EQUAL(file.getMassTypeFragment() , true) END_SECTION START_SECTION(void setNormalizeXcorr(bool normalize_xcorr)) file.setNormalizeXcorr(true); TEST_EQUAL(file.getNormalizeXcorr() , true) END_SECTION START_SECTION((bool getNormalizeXcorr() const)) TEST_EQUAL(file.getNormalizeXcorr() , true) END_SECTION START_SECTION(void setResiduesInUpperCase(bool residues_in_upper_case)) file.setResiduesInUpperCase(true); TEST_EQUAL(file.getResiduesInUpperCase() , true) END_SECTION START_SECTION((bool getResiduesInUpperCase() const)) TEST_EQUAL(file.getResiduesInUpperCase() , true) END_SECTION START_SECTION(void store(const String& filename)) String filename; NEW_TMP_FILE(filename) // test exceptions // TEST_EXCEPTION_WITH_MESSAGE(Exception::UnableToCreateFile, file.store(OPENMS_GET_TEST_DATA_PATH("Sequest_unreadable_unwriteable.txt")), "the file `data/Sequest_unreadable_unwriteable.txt' could not be created") // test actual program file.store(filename); TEST_FILE_EQUAL(filename.c_str(), OPENMS_GET_TEST_DATA_PATH("SequestInfile_test_template1.txt")); END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/AbsoluteQuantitationMethod_test.cpp
.cpp
6,550
221
// 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 $ // -------------------------------------------------------------------------- // #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/ANALYSIS/QUANTITATION/AbsoluteQuantitationMethod.h> using namespace OpenMS; using namespace std; /////////////////////////// START_TEST(AbsoluteQuantitationMethod, "$Id$") ///////////////////////////////////////////////////////////// AbsoluteQuantitationMethod* ptr = nullptr; AbsoluteQuantitationMethod* nullPointer = nullptr; START_SECTION(AbsoluteQuantitationMethod()) { ptr = new AbsoluteQuantitationMethod(); TEST_NOT_EQUAL(ptr, nullPointer); TEST_EQUAL(ptr->getComponentName().size(), 0) TEST_EQUAL(ptr->getFeatureName().size(), 0) TEST_EQUAL(ptr->getISName().size(), 0) TEST_REAL_SIMILAR(ptr->getLLOD(), 0.0) TEST_REAL_SIMILAR(ptr->getULOD(), 0.0) TEST_REAL_SIMILAR(ptr->getLLOQ(), 0.0) TEST_REAL_SIMILAR(ptr->getULOQ(), 0.0) TEST_EQUAL(ptr->getNPoints(), 0) TEST_REAL_SIMILAR(ptr->getCorrelationCoefficient(), 0.0) TEST_EQUAL(ptr->getConcentrationUnits().size(), 0) TEST_EQUAL(ptr->getTransformationModel().size(), 0) TEST_EQUAL(ptr->getTransformationModelParams().size(), 0) } END_SECTION START_SECTION(~AbsoluteQuantitationMethod()) { delete ptr; } END_SECTION START_SECTION(all setters and getters) { AbsoluteQuantitationMethod aqm; aqm.setComponentName("component"); aqm.setFeatureName("feature"); aqm.setISName("IS"); aqm.setLLOD(1.2); aqm.setULOD(3.4); aqm.setLLOQ(5.6); aqm.setULOQ(7.8); aqm.setNPoints(9); aqm.setCorrelationCoefficient(0.44); aqm.setConcentrationUnits("uM"); aqm.setTransformationModel("TransformationModelLinear"); Param params1; params1.setValue("slope", 1); aqm.setTransformationModelParams(params1); TEST_EQUAL(aqm.getComponentName(), "component") TEST_EQUAL(aqm.getFeatureName(), "feature") TEST_EQUAL(aqm.getISName(), "IS") TEST_REAL_SIMILAR(aqm.getLLOD(), 1.2) TEST_REAL_SIMILAR(aqm.getULOD(), 3.4) TEST_REAL_SIMILAR(aqm.getLLOQ(), 5.6) TEST_REAL_SIMILAR(aqm.getULOQ(), 7.8) TEST_EQUAL(aqm.getNPoints(), 9) TEST_REAL_SIMILAR(aqm.getCorrelationCoefficient(), 0.44) TEST_EQUAL(aqm.getConcentrationUnits(), "uM") TEST_EQUAL(aqm.getTransformationModel(), "TransformationModelLinear") Param params2 = aqm.getTransformationModelParams(); TEST_EQUAL(params2.getValue("slope"), 1) } END_SECTION START_SECTION(bool checkLOD(const double value) const) { AbsoluteQuantitationMethod aqm; const double value = 2.0; aqm.setLLOD(0.0); aqm.setULOD(4.0); TEST_EQUAL(aqm.checkLOD(value), true); aqm.setULOD(1.0); TEST_EQUAL(aqm.checkLOD(value), false); aqm.setLLOD(3.0); aqm.setULOD(4.0); TEST_EQUAL(aqm.checkLOD(value), false); } END_SECTION START_SECTION(bool checkLOQ(const double value) const) { AbsoluteQuantitationMethod aqm; const double value = 2.0; aqm.setLLOQ(0.0); aqm.setULOQ(4.0); TEST_EQUAL(aqm.checkLOQ(value), true); aqm.setULOQ(1.0); TEST_EQUAL(aqm.checkLOQ(value), false); aqm.setLLOQ(3.0); aqm.setULOQ(4.0); TEST_EQUAL(aqm.checkLOQ(value), false); } END_SECTION START_SECTION(inline bool operator==(const AbsoluteQuantitationMethod& other) const) { AbsoluteQuantitationMethod aqm1, aqm2; TEST_TRUE(aqm1 == aqm2); aqm1.setLLOD(1.0); aqm2.setLLOD(1.0); TEST_TRUE(aqm1 == aqm2); aqm2.setLLOD(2.0); TEST_EQUAL(aqm1 == aqm2, false); } END_SECTION START_SECTION(inline bool operator!=(const AbsoluteQuantitationMethod& other) const) { AbsoluteQuantitationMethod aqm1, aqm2; TEST_EQUAL(aqm1 != aqm2, false); aqm1.setLLOD(1.0); aqm2.setLLOD(1.0); TEST_EQUAL(aqm1 != aqm2, false); aqm2.setLLOD(2.0); TEST_FALSE(aqm1 == aqm2); } END_SECTION START_SECTION(copyConstructor) { AbsoluteQuantitationMethod aqm; aqm.setComponentName("component"); aqm.setFeatureName("feature"); aqm.setISName("IS"); aqm.setLLOD(1.2); aqm.setULOD(3.4); aqm.setLLOQ(5.6); aqm.setULOQ(7.8); aqm.setNPoints(9); aqm.setCorrelationCoefficient(0.44); aqm.setConcentrationUnits("uM"); aqm.setTransformationModel("TransformationModelLinear"); Param params1; params1.setValue("slope", 1); aqm.setTransformationModelParams(params1); const AbsoluteQuantitationMethod aqm2(aqm); TEST_EQUAL(aqm2.getComponentName(), "component") TEST_EQUAL(aqm2.getFeatureName(), "feature") TEST_EQUAL(aqm2.getISName(), "IS") TEST_REAL_SIMILAR(aqm2.getLLOD(), 1.2) TEST_REAL_SIMILAR(aqm2.getULOD(), 3.4) TEST_REAL_SIMILAR(aqm2.getLLOQ(), 5.6) TEST_REAL_SIMILAR(aqm2.getULOQ(), 7.8) TEST_EQUAL(aqm2.getNPoints(), 9) TEST_REAL_SIMILAR(aqm2.getCorrelationCoefficient(), 0.44) TEST_EQUAL(aqm2.getConcentrationUnits(), "uM") TEST_EQUAL(aqm2.getTransformationModel(), "TransformationModelLinear") Param params2 = aqm2.getTransformationModelParams(); TEST_EQUAL(params2.getValue("slope"), 1) } END_SECTION START_SECTION(copyAssignmentOperator) { AbsoluteQuantitationMethod aqm; aqm.setComponentName("component"); aqm.setFeatureName("feature"); aqm.setISName("IS"); aqm.setLLOD(1.2); aqm.setULOD(3.4); aqm.setLLOQ(5.6); aqm.setULOQ(7.8); aqm.setNPoints(9); aqm.setCorrelationCoefficient(0.44); aqm.setConcentrationUnits("uM"); aqm.setTransformationModel("TransformationModelLinear"); Param params1; params1.setValue("slope", 1); aqm.setTransformationModelParams(params1); const AbsoluteQuantitationMethod aqm2 = aqm; TEST_EQUAL(aqm2.getComponentName(), "component") TEST_EQUAL(aqm2.getFeatureName(), "feature") TEST_EQUAL(aqm2.getISName(), "IS") TEST_REAL_SIMILAR(aqm2.getLLOD(), 1.2) TEST_REAL_SIMILAR(aqm2.getULOD(), 3.4) TEST_REAL_SIMILAR(aqm2.getLLOQ(), 5.6) TEST_REAL_SIMILAR(aqm2.getULOQ(), 7.8) TEST_EQUAL(aqm2.getNPoints(), 9) TEST_REAL_SIMILAR(aqm2.getCorrelationCoefficient(), 0.44) TEST_EQUAL(aqm2.getConcentrationUnits(), "uM") TEST_EQUAL(aqm2.getTransformationModel(), "TransformationModelLinear") Param params2 = aqm2.getTransformationModelParams(); TEST_EQUAL(params2.getValue("slope"), 1) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/OpenSwathSpectrumAccessOpenMS_test.cpp
.cpp
10,080
346
// 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, Witold Wolski $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> #include <OpenMS/FORMAT/TraMLFile.h> #include <boost/assign/std/vector.hpp> #include <boost/assign/list_of.hpp> /////////////////////////// #include <OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/SpectrumAccessOpenMS.h> #include <memory> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(SpectrumAccessOpenMS, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// SpectrumAccessOpenMS* ptr = nullptr; SpectrumAccessOpenMS* nullPointer = nullptr; START_SECTION(SpectrumAccessOpenMS()) { std::shared_ptr< PeakMap > exp ( new PeakMap ); ptr = new SpectrumAccessOpenMS(exp); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(~SpectrumAccessOpenMS()) { delete ptr; } END_SECTION START_SECTION( size_t getNrSpectra() const) { { std::shared_ptr< PeakMap > exp ( new PeakMap ); SpectrumAccessOpenMS spectrum_acc = SpectrumAccessOpenMS(exp); TEST_EQUAL(spectrum_acc.getNrSpectra(), 0); TEST_EQUAL(spectrum_acc.getNrChromatograms(), 0); } { PeakMap* new_exp = new PeakMap; MSSpectrum s; MSChromatogram c; new_exp->addSpectrum(s); new_exp->addSpectrum(s); new_exp->addChromatogram(c); std::shared_ptr< PeakMap > exp (new_exp); SpectrumAccessOpenMS spectrum_acc = SpectrumAccessOpenMS(exp); TEST_EQUAL(spectrum_acc.getNrSpectra(), 2); TEST_EQUAL(spectrum_acc.getNrChromatograms(), 1); } } END_SECTION START_SECTION ( std::shared_ptr<OpenSwath::ISpectrumAccess> lightClone() const) { PeakMap* new_exp = new PeakMap; MSSpectrum s; MSChromatogram c; new_exp->addSpectrum(s); new_exp->addSpectrum(s); new_exp->addChromatogram(c); std::shared_ptr< PeakMap > exp (new_exp); SpectrumAccessOpenMS spectrum_acc = SpectrumAccessOpenMS(exp); TEST_EQUAL(spectrum_acc.getNrSpectra(), 2); TEST_EQUAL(spectrum_acc.getNrChromatograms(), 1); std::shared_ptr<OpenSwath::ISpectrumAccess> sa_clone = spectrum_acc.lightClone(); TEST_EQUAL(sa_clone->getNrSpectra(), 2); TEST_EQUAL(sa_clone->getNrChromatograms(), 1); } END_SECTION START_SECTION ( OpenSwath::SpectrumPtr getSpectrumById(int id);) { { std::shared_ptr< PeakMap > exp ( new PeakMap ); SpectrumAccessOpenMS spectrum_acc = SpectrumAccessOpenMS(exp); TEST_EQUAL(spectrum_acc.getNrSpectra(), 0); // OpenSwath::SpectrumPtr sptr = spectrum_acc.getSpectrumById(0); } { PeakMap* new_exp = new PeakMap; MSSpectrum s; s.setRT(20); Peak1D p; p.setMZ(20.0); s.push_back(p); new_exp->addSpectrum(s); std::shared_ptr< PeakMap > exp (new_exp); SpectrumAccessOpenMS spectrum_acc = SpectrumAccessOpenMS(exp); TEST_EQUAL(spectrum_acc.getNrSpectra(), 1); OpenSwath::SpectrumPtr sptr = spectrum_acc.getSpectrumById(0); TEST_REAL_SIMILAR (sptr->getMZArray()->data[0], 20.0); } { PeakMap* new_exp = new PeakMap; MSSpectrum s; s.setRT(20); Peak1D p; p.setMZ(20.0); p.setIntensity(22.0); s.push_back(p); OpenMS::DataArrays::FloatDataArray fda; fda.push_back(50); fda.setName("testName"); auto fdas = s.getFloatDataArrays(); fdas.push_back(fda); s.setFloatDataArrays(fdas); OpenMS::DataArrays::IntegerDataArray ida; ida.push_back(51); ida.setName("testName_integer"); auto idas = s.getIntegerDataArrays(); idas.push_back(ida); s.setIntegerDataArrays(idas); new_exp->addSpectrum(s); std::shared_ptr< PeakMap > exp (new_exp); SpectrumAccessOpenMS spectrum_acc = SpectrumAccessOpenMS(exp); TEST_EQUAL(spectrum_acc.getNrSpectra(), 1) OpenSwath::SpectrumPtr sptr = spectrum_acc.getSpectrumById(0); TEST_REAL_SIMILAR (sptr->getMZArray()->data[0], 20.0) TEST_REAL_SIMILAR (sptr->getIntensityArray()->data[0], 22.0) TEST_EQUAL (sptr->getDataArrays().size(), 4) TEST_EQUAL (sptr->getDataArrays()[2]->description, "testName") TEST_REAL_SIMILAR (sptr->getDataArrays()[2]->data[0], 50.0) TEST_EQUAL (sptr->getDataArrays()[3]->description, "testName_integer") TEST_REAL_SIMILAR (sptr->getDataArrays()[3]->data[0], 51.0) } } END_SECTION START_SECTION ( OpenSwath::SpectrumMeta getSpectrumMetaById(int id) const) { { PeakMap* new_exp = new PeakMap; MSSpectrum s; s.setRT(20); new_exp->addSpectrum(s); std::shared_ptr< PeakMap > exp (new_exp); SpectrumAccessOpenMS spectrum_acc = SpectrumAccessOpenMS(exp); TEST_EQUAL(spectrum_acc.getNrSpectra(), 1); OpenSwath::SpectrumMeta spmeta = spectrum_acc.getSpectrumMetaById(0); TEST_REAL_SIMILAR(spmeta.RT, 20.0); } } END_SECTION START_SECTION ( SpectrumSettings getSpectraMetaInfo(int id) const) { { PeakMap* new_exp = new PeakMap; MSSpectrum s; s.setComment("remember me"); new_exp->addSpectrum(s); std::shared_ptr< PeakMap > exp (new_exp); SpectrumAccessOpenMS spectrum_acc = SpectrumAccessOpenMS(exp); TEST_EQUAL(spectrum_acc.getNrSpectra(), 1); SpectrumSettings spmeta = spectrum_acc.getSpectraMetaInfo(0); TEST_EQUAL (spmeta.getComment(), "remember me"); } } END_SECTION START_SECTION ( std::vector<std::size_t> SpectrumAccessOpenMS::getSpectraByRT(double RT, double deltaRT) const) { { PeakMap* new_exp = new PeakMap; MSSpectrum s; MSChromatogram c; s.setRT(20); new_exp->addSpectrum(s); s.setRT(40); new_exp->addSpectrum(s); new_exp->addChromatogram(c); std::shared_ptr< PeakMap > exp (new_exp); SpectrumAccessOpenMS spectrum_acc = SpectrumAccessOpenMS(exp); TEST_EQUAL(spectrum_acc.getNrSpectra(), 2); TEST_EQUAL(spectrum_acc.getNrChromatograms(), 1); TEST_EQUAL(spectrum_acc.getSpectraByRT(20, 5.0).size(), 1); TEST_EQUAL(spectrum_acc.getSpectraByRT(20, 25.0).size(), 2); TEST_EQUAL(spectrum_acc.getSpectraByRT(40, 5.0).size(), 1); TEST_EQUAL(spectrum_acc.getSpectraByRT(40, 25.0).size(), 2); TEST_EQUAL(spectrum_acc.getSpectraByRT(50, 5.0).size(), 0); } } END_SECTION START_SECTION( size_t getNrChromatograms() const) { NOT_TESTABLE // see getNrSpectra } END_SECTION START_SECTION(OpenSwath::ChromatogramPtr getChromatogramById(int id)) { { std::shared_ptr< PeakMap > exp ( new PeakMap ); SpectrumAccessOpenMS spectrum_acc = SpectrumAccessOpenMS(exp); TEST_EQUAL(spectrum_acc.getNrSpectra(), 0); TEST_EQUAL(spectrum_acc.getNrChromatograms(), 0); } { PeakMap* new_exp = new PeakMap; MSSpectrum s; MSChromatogram c; c.setName("chrom_nr_1"); c.setNativeID("native_id_nr_1"); ChromatogramPeak p; p.setRT(20.0); c.push_back(p); new_exp->addSpectrum(s); new_exp->addSpectrum(s); new_exp->addChromatogram(c); std::shared_ptr< PeakMap > exp (new_exp); SpectrumAccessOpenMS chrom_acc = SpectrumAccessOpenMS(exp); TEST_EQUAL(chrom_acc.getNrSpectra(), 2); TEST_EQUAL(chrom_acc.getNrChromatograms(), 1); OpenSwath::ChromatogramPtr cptr = chrom_acc.getChromatogramById(0); TEST_REAL_SIMILAR (cptr->getTimeArray()->data[0], 20.0); } { PeakMap* new_exp = new PeakMap; MSChromatogram chrom; ChromatogramPeak p; p.setRT(20.0); p.setIntensity(22.0); chrom.push_back(p); OpenMS::DataArrays::FloatDataArray fda; fda.push_back(50); fda.setName("testName"); auto fdas = chrom.getFloatDataArrays(); fdas.push_back(fda); chrom.setFloatDataArrays(fdas); OpenMS::DataArrays::IntegerDataArray ida; ida.push_back(51); ida.setName("testName_integer"); auto idas = chrom.getIntegerDataArrays(); idas.push_back(ida); chrom.setIntegerDataArrays(idas); new_exp->addChromatogram(chrom); std::shared_ptr< PeakMap > exp (new_exp); SpectrumAccessOpenMS chrom_acc = SpectrumAccessOpenMS(exp); TEST_EQUAL(chrom_acc.getNrChromatograms(), 1) OpenSwath::ChromatogramPtr cptr = chrom_acc.getChromatogramById(0); TEST_REAL_SIMILAR (cptr->getTimeArray()->data[0], 20.0) TEST_REAL_SIMILAR (cptr->getIntensityArray()->data[0], 22.0) TEST_EQUAL (cptr->getDataArrays().size(), 4) TEST_EQUAL (cptr->getDataArrays()[2]->description, "testName") TEST_REAL_SIMILAR (cptr->getDataArrays()[2]->data[0], 50.0) TEST_EQUAL (cptr->getDataArrays()[3]->description, "testName_integer") TEST_REAL_SIMILAR (cptr->getDataArrays()[3]->data[0], 51.0) } } END_SECTION START_SECTION(std::string getChromatogramNativeID(int id) const) { PeakMap* new_exp = new PeakMap; MSSpectrum s; MSChromatogram c; c.setName("chrom_nr_1"); c.setNativeID("native_id_nr_1"); ChromatogramPeak p; p.setRT(20.0); c.push_back(p); new_exp->addSpectrum(s); new_exp->addSpectrum(s); new_exp->addChromatogram(c); std::shared_ptr< PeakMap > exp (new_exp); SpectrumAccessOpenMS spectrum_acc = SpectrumAccessOpenMS(exp); OpenSwath::ChromatogramPtr cptr = spectrum_acc.getChromatogramById(0); TEST_EQUAL (spectrum_acc.getChromatogramNativeID(0), "native_id_nr_1") } END_SECTION START_SECTION (ChromatogramSettings getChromatogramMetaInfo(int id) const) { PeakMap* new_exp = new PeakMap; MSChromatogram c; c.setComment("remember me"); new_exp->addChromatogram(c); std::shared_ptr< PeakMap > exp (new_exp); SpectrumAccessOpenMS spectrum_acc = SpectrumAccessOpenMS(exp); TEST_EQUAL(spectrum_acc.getNrChromatograms(), 1); ChromatogramSettings cpmeta = spectrum_acc.getChromatogramMetaInfo(0); TEST_EQUAL (cpmeta.getComment(), "remember me"); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ModificationsDB_test.cpp
.cpp
12,305
337
// 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 $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/CHEMISTRY/ModificationsDB.h> #include <limits> #include <algorithm> /////////////////////////// using namespace OpenMS; using namespace std; struct ResidueModificationOriginCmp { bool operator() (const ResidueModification* a, const ResidueModification* b) const { return a->getOrigin() < b->getOrigin(); } }; START_TEST(ModificationsDB, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// START_SECTION(bool ModificationsDB::isInstantiated()) { bool instantiated = ModificationsDB::isInstantiated(); TEST_EQUAL(instantiated, false); } END_SECTION ModificationsDB* ptr = nullptr; ModificationsDB* nullPointer = nullptr; START_SECTION(ModificationsDB* getInstance()) { ptr = ModificationsDB::getInstance(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(bool ModificationsDB::isInstantiated()) { bool instantiated = ModificationsDB::isInstantiated(); TEST_EQUAL(instantiated, true); } END_SECTION START_SECTION(Size getNumberOfModifications() const) // range because data may change over time TEST_EQUAL(ptr->getNumberOfModifications() > 100, true); END_SECTION START_SECTION(const ResidueModification& getModification(Size index) const) TEST_EQUAL(!ptr->getModification(0)->getId().empty(), true) END_SECTION START_SECTION((void searchModifications(std::set<const ResidueModification*>& mods, const String& mod_name, const String& residue, ResidueModification::TermSpecificity term_spec) const)) { set<const ResidueModification*> mods; ptr->searchModifications(mods, "Phosphorylation", "T", ResidueModification::ANYWHERE); TEST_EQUAL(mods.size(), 1); TEST_STRING_EQUAL((*mods.begin())->getFullId(), "Phospho (T)"); // terminal mod: ptr->searchModifications(mods, "NIC", "", ResidueModification::N_TERM); TEST_EQUAL(mods.size(), 1); // Phosphorylation Decoy custom mod ptr->searchModifications(mods, "Phosphorylation Decoy", "A", ResidueModification::ANYWHERE); TEST_EQUAL(mods.size(), 1); // Phosphorylation Decoy custom search by title ptr->searchModifications(mods, "PhosphoDecoy"); TEST_EQUAL(mods.size(), 3); ptr->searchModifications(mods, "Label:18O(1)"); TEST_EQUAL(mods.size(), 4); ABORT_IF(mods.size() != 4); // Create a sorted set (sorted by getOrigin) instead of sorted by pointer // value -> this is more robust on different platforms. set<const ResidueModification*, ResidueModificationOriginCmp> mods_sorted; // Copy the mods into our sorted container set<const ResidueModification*>::const_iterator mod_it_ = mods.begin(); for (; mod_it_ != mods.end(); mod_it_++) { mods_sorted.insert((*mod_it_)); } set<const ResidueModification*, ResidueModificationOriginCmp>::const_iterator mod_it = mods_sorted.begin(); TEST_EQUAL((*mod_it)->getOrigin(), 'S') TEST_STRING_EQUAL((*mod_it)->getId(), "Label:18O(1)") TEST_EQUAL((*mod_it)->getTermSpecificity(), ResidueModification::ANYWHERE) ++mod_it; TEST_EQUAL((*mod_it)->getOrigin(), 'T') TEST_STRING_EQUAL((*mod_it)->getId(), "Label:18O(1)") TEST_EQUAL((*mod_it)->getTermSpecificity(), ResidueModification::ANYWHERE) ++mod_it; TEST_EQUAL((*mod_it)->getOrigin(), 'X') TEST_STRING_EQUAL((*mod_it)->getId(), "Label:18O(1)") TEST_EQUAL((*mod_it)->getTermSpecificity(), ResidueModification::C_TERM) ++mod_it; TEST_EQUAL((*mod_it)->getOrigin(), 'Y') TEST_STRING_EQUAL((*mod_it)->getId(), "Label:18O(1)") TEST_EQUAL((*mod_it)->getTermSpecificity(), ResidueModification::ANYWHERE) ptr->searchModifications(mods, "Label:18O(1)", "", ResidueModification::C_TERM); TEST_EQUAL(mods.size(), 1) ABORT_IF(mods.size() != 1) // Copy the mods into our sorted container mods_sorted.clear(); for (mod_it_ = mods.begin(); mod_it_ != mods.end(); mod_it_++) { mods_sorted.insert((*mod_it_)); } mod_it = mods_sorted.begin(); TEST_EQUAL((*mod_it)->getOrigin(), 'X') TEST_STRING_EQUAL((*mod_it)->getId(), "Label:18O(1)") TEST_EQUAL((*mod_it)->getTermSpecificity(), ResidueModification::C_TERM) // no match, thus mods should be empty ptr->searchModifications(mods, "Label:18O(1)", "", ResidueModification::N_TERM); TEST_EQUAL(mods.size(), 0) } END_SECTION START_SECTION((void searchModificationsByDiffMonoMass(std::vector<String>& mods, double mass, double max_error, const String& residue, ResidueModification::TermSpecificity term_spec))) { vector<String> mods; ptr->searchModificationsByDiffMonoMass(mods, 80.0, 0.1, "S"); TEST_EQUAL(find(mods.begin(), mods.end(), "Phospho (S)") != mods.end(), true); TEST_EQUAL(find(mods.begin(), mods.end(), "Sulfo (S)") != mods.end(), true); // something exotic.. mods should return empty (without clearing it before) ptr->searchModificationsByDiffMonoMass(mods, 800000000.0, 0.1, "S"); TEST_EQUAL(mods.size(), 0); // terminal mod: ptr->searchModificationsByDiffMonoMass(mods, 42, 0.1, "", ResidueModification::N_TERM); set<String> uniq_mods; for (vector<String>::const_iterator it = mods.begin(); it != mods.end(); ++it) { uniq_mods.insert(*it); } TEST_EQUAL(mods.size(), 18); TEST_EQUAL(uniq_mods.size(), 18); TEST_EQUAL(uniq_mods.find("Acetyl (N-term)") != uniq_mods.end(), true); // something exotic.. mods should return empty (without clearing it before) ptr->searchModificationsByDiffMonoMass(mods, 4200000, 0.1, "", ResidueModification::N_TERM); TEST_EQUAL(mods.size(), 0); ptr->searchModificationsByDiffMonoMass(mods, 80.0, 0.1); uniq_mods.clear(); for (vector<String>::const_iterator it = mods.begin(); it != mods.end(); ++it) { uniq_mods.insert(*it); } TEST_EQUAL(uniq_mods.find("Phospho (S)") != uniq_mods.end(), true); TEST_EQUAL(uniq_mods.find("Phospho (T)") != uniq_mods.end(), true); TEST_EQUAL(uniq_mods.find("Phospho (Y)") != uniq_mods.end(), true); TEST_EQUAL(uniq_mods.find("Sulfo (S)") != uniq_mods.end(), true); // something exotic.. mods should return empty (without clearing it before) ptr->searchModificationsByDiffMonoMass(mods, 800000000.0, 0.1); TEST_EQUAL(mods.size(), 0); // make sure the common ones are also found for integer masses (this is how // integer mass search is done) mods.clear(); ptr->searchModificationsByDiffMonoMass(mods, 80.0, 1.0, "S"); TEST_EQUAL(mods.empty(), false) TEST_EQUAL(mods[0], "Phospho (S)") mods.clear(); ptr->searchModificationsByDiffMonoMass(mods, 80.0, 1.0, "T"); TEST_EQUAL(mods.empty(), false) TEST_EQUAL(mods[0], "Phospho (T)") mods.clear(); ptr->searchModificationsByDiffMonoMass(mods, 80.0, 1.0, "Y"); TEST_EQUAL(mods.empty(), false) TEST_EQUAL(mods[0], "Phospho (Y)") mods.clear(); ptr->searchModificationsByDiffMonoMass(mods, 16.0, 1.0, "M"); TEST_EQUAL(mods.empty(), false) TEST_EQUAL(mods[0], "Oxidation (M)") ptr->searchModificationsByDiffMonoMass(mods, 0.98, 0.1, "N"); TEST_EQUAL(mods.empty(), false) TEST_EQUAL(mods[0], "Deamidated (N)") ptr->searchModificationsByDiffMonoMass(mods, 0.98, 1.0, "Q"); TEST_EQUAL(mods.empty(), false) TEST_EQUAL(mods[0], "Deamidated (Q)") } END_SECTION START_SECTION((const ResidueModification& getModification(const String& mod_name, const String& residue, ResidueModification::TermSpecificity term_spec) const)) { TEST_EQUAL(ptr->getModification("Carboxymethyl (C)")->getFullId(), "Carboxymethyl (C)"); TEST_EQUAL(ptr->getModification("Carboxymethyl (C)")->getId(), "Carboxymethyl"); TEST_EQUAL(ptr->getModification("Phosphorylation", "S", ResidueModification::ANYWHERE)->getId(), "Phospho"); TEST_EQUAL(ptr->getModification("Phosphorylation", "S", ResidueModification::ANYWHERE)->getFullId(), "Phospho (S)"); // terminal mod: TEST_EQUAL(ptr->getModification("NIC", "", ResidueModification::N_TERM)->getId(), "NIC"); TEST_EQUAL(ptr->getModification("NIC", "", ResidueModification::N_TERM)->getFullId(), "NIC (N-term)"); TEST_EQUAL(ptr->getModification("Acetyl", "", ResidueModification::N_TERM)->getFullId(), "Acetyl (N-term)"); // missing modification (exception) TEST_EXCEPTION(Exception::InvalidValue, ptr->getModification("MISSING")); TEST_EXCEPTION(Exception::InvalidValue, ptr->getModification("MISSING", "", ResidueModification::N_TERM)); TEST_EXCEPTION(Exception::InvalidValue, ptr->getModification("MISSING", "", ResidueModification::C_TERM)); } END_SECTION START_SECTION((Size findModificationIndex(const String& mod_name) const)) { Size index = numeric_limits<Size>::max(); index = ptr->findModificationIndex("Phospho (T)"); TEST_NOT_EQUAL(index, numeric_limits<Size>::max()); } END_SECTION START_SECTION(void readFromOBOFile(const String& filename)) // implicitely tested above NOT_TESTABLE END_SECTION START_SECTION(void readFromUnimodXMLFile(const String& filename)) // just provided for convenience at the moment NOT_TESTABLE END_SECTION START_SECTION((void getAllSearchModifications(std::vector<String>& modifications))) { vector<String> mods; ptr->getAllSearchModifications(mods); TEST_EQUAL(find(mods.begin(), mods.end(), "Phospho (S)") != mods.end(), true); TEST_EQUAL(find(mods.begin(), mods.end(), "Sulfo (S)") != mods.end(), true); TEST_EQUAL(find(mods.begin(), mods.end(), "NIC (N-term)") != mods.end(), true); TEST_EQUAL(find(mods.begin(), mods.end(), "Phospho") != mods.end(), false); TEST_EQUAL(find(mods.begin(), mods.end(), "Dehydrated (N-term C)") != mods.end(), true); // repeat search .. return size should be the same Size old_size=mods.size(); ptr->getAllSearchModifications(mods); TEST_EQUAL(mods.size(), old_size); } END_SECTION START_SECTION((bool addModification(ResidueModification* modification))) { TEST_EQUAL(ptr->has("Phospho (A)"), false); std::unique_ptr<ResidueModification> modification(new ResidueModification()); modification->setFullId("Phospho (A)"); ptr->addModification(std::move(modification)); TEST_EQUAL(ptr->has("Phospho (A)"), true); } END_SECTION START_SECTION([EXTRA] multithreaded example) { // All measurements are best of three (wall time, Linux, 8 threads) // // Serial execution of code: // 1e6 iterations -> 6.36 seconds // Parallel execution of code: // 1e6 iterations -> 9.79 seconds with boost::shared_mutex // 1e6 iterations -> 6.28 seconds with std::mutex // 1e6 iterations -> 4.64 seconds with pragma critical static ModificationsDB* mdb = ModificationsDB::getInstance(); int nr_iterations (1e4), test (0); #pragma omp parallel for reduction (+: test) for (int k = 1; k < nr_iterations + 1; k++) { int mod_id = k; String modname = "mod" + String(mod_id); std::unique_ptr<ResidueModification> new_mod(new ResidueModification()); new_mod->setFullId(modname); new_mod->setMonoMass( 0.11 * mod_id); new_mod->setAverageMass(1.0); new_mod->setDiffMonoMass( 0.05 * mod_id); mdb->addModification(std::move(new_mod)); int tmp = (int)mdb->getModification(modname)->getAverageMass(); test += tmp; } TEST_EQUAL(test, nr_iterations*1.0) // Every modification is the same test = 0; #pragma omp parallel for reduction (+: test) for (int k = 1; k < nr_iterations + 1; k++) { int mod_id = 42; String modname = "mod" + String(mod_id); if (!mdb->has(modname)) { std::unique_ptr<ResidueModification> new_mod(new ResidueModification()); new_mod->setFullId(modname); new_mod->setMonoMass( 0.11 * mod_id); new_mod->setAverageMass(1.0); new_mod->setDiffMonoMass( 0.05 * mod_id); mdb->addModification(std::move(new_mod)); } int tmp = (int)mdb->getModification(modname)->getAverageMass(); test += tmp; } TEST_EQUAL(test, nr_iterations*1.0) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/Deisotoper_test.cpp
.cpp
12,475
348
// 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 $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <iostream> #include <OpenMS/CHEMISTRY/AASequence.h> #include <OpenMS/CHEMISTRY/ISOTOPEDISTRIBUTION/CoarseIsotopePatternGenerator.h> #include <OpenMS/CHEMISTRY/TheoreticalSpectrumGenerator.h> #include <OpenMS/PROCESSING/DEISOTOPING/Deisotoper.h> #include <OpenMS/FORMAT/MzMLFile.h> #include <OpenMS/KERNEL/MSExperiment.h> #include <OpenMS/KERNEL/MSSpectrum.h> #include <OpenMS/SYSTEM/File.h> /////////////////////////// START_TEST(Deisotoper, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; using namespace std; START_SECTION(static void deisotopeAndSingleChargeMSSpectrum(MSSpectrum& in, double fragment_tolerance, bool fragment_unit_ppm, int min_charge = 1, int max_charge = 3, bool keep_only_deisotoped = false, unsigned int min_isopeaks = 3, unsigned int max_isopeaks = 10, bool make_single_charged = true, bool annotate_charge = false)) { MSSpectrum two_patterns; Peak1D p; p.setIntensity(1.0); // one charge one pattern p.setMZ(100.0); two_patterns.push_back(p); p.setMZ(100.0 + Constants::C13C12_MASSDIFF_U); two_patterns.push_back(p); p.setMZ(100.0 + 2.0 * Constants::C13C12_MASSDIFF_U); two_patterns.push_back(p); // one charge two pattern p.setMZ(200.0); two_patterns.push_back(p); p.setMZ(200.0 + 0.5 * Constants::C13C12_MASSDIFF_U); two_patterns.push_back(p); p.setMZ(200.0 + 2.0 * 0.5 * Constants::C13C12_MASSDIFF_U); two_patterns.push_back(p); MSSpectrum theo0 = two_patterns; Deisotoper::deisotopeAndSingleCharge(theo0, 10.0, true, 1, 2, true, 2, 10, false, true); TEST_EQUAL(theo0.size(), 2); // two peaks after deisotoping TEST_REAL_SIMILAR(theo0[0].getMZ(), 100); TEST_REAL_SIMILAR(theo0[1].getMZ(), 200); theo0 = two_patterns; Deisotoper::deisotopeAndSingleCharge(theo0, 10.0, true, 1, 2, true, 2, 10, true, // convert to charge 1 true); TEST_EQUAL(theo0.size(), 2); // two peaks after deisotoping TEST_REAL_SIMILAR(theo0[0].getMZ(), 100); TEST_REAL_SIMILAR(theo0[1].getMZ(), 400.0 - Constants::PROTON_MASS_U); // create a theoretical spectrum generator // and configure to add isotope patterns TheoreticalSpectrumGenerator spec_generator; Param param = spec_generator.getParameters(); param.setValue("isotope_model", "coarse"); param.setValue("max_isotope", 3); param.setValue("add_a_ions", "false"); param.setValue("add_b_ions", "false"); param.setValue("add_losses", "false"); param.setValue("add_precursor_peaks", "false"); spec_generator.setParameters(param); MSSpectrum theo1; AASequence peptide1 = AASequence::fromString("PEPTIDE"); spec_generator.getSpectrum(theo1, peptide1, 1, 2);// charge 1..2 TEST_EQUAL(theo1.size(), 36); theo1.sortByPosition(); Deisotoper::deisotopeAndSingleCharge(theo1, 10.0, true, 1, 2, true, 2, 10, false, true); // create theoretical spectrum without isotopic peaks for comparison to the deisotoped one param.setValue("isotope_model", "none"); // disable additional isotopes spec_generator.setParameters(param); MSSpectrum theo1_noiso; spec_generator.getSpectrum(theo1_noiso, peptide1, 1, 2); // charge 1..2 TEST_EQUAL(theo1.size(), theo1_noiso.size()); // same number of peaks after deisotoping // load data with small intensity satellite peaks (e.g., amidation) MSExperiment input1; MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("Deisotoper_input1.mzML"), input1); Deisotoper::deisotopeAndSingleCharge(input1[0], 0.01, // Da false, 1, 3, false, 2, 10, false, true, false, // no iso peak count annotation true, // decreasing isotope model 2, // enforce only starting from second peak true); String temp_file1 = File::getTempDirectory() + "/" + File::getUniqueName() + "_Deisotoper_output1.mzML"; MzMLFile().store(temp_file1, input1); File::remove(temp_file1); // load data with small intensity satellite peaks (e.g., amidation) MSExperiment input2; String input2_path = OPENMS_GET_TEST_DATA_PATH("Deisotoper_input2.mzML"); if (File::exists(input2_path)) { MzMLFile().load(input2_path, input2); } else { // Fallback: reuse input1 dataset if the second input is not available MzMLFile().load(OPENMS_GET_TEST_DATA_PATH("Deisotoper_input1.mzML"), input2); } Deisotoper::deisotopeAndSingleCharge(input2[0], 0.01, // Da false, 1, 3, false, 2, 10, false, true, false, // no iso peak count annotation true, // decreasing isotope model 2, // enforce only starting from second peak true); String temp_file2 = File::getTempDirectory() + "/" + File::getUniqueName() + "_Deisotoper_output2.mzML"; MzMLFile().store(temp_file2, input2); File::remove(temp_file2); } END_SECTION START_SECTION(static void deisotopeWithAveragineModel(MSSpectrum& spectrum, double fragment_tolerance, bool fragment_unit_ppm)) { // spectrum with one isotopic pattern MSSpectrum spec; CoarseIsotopePatternGenerator gen(5); IsotopeDistribution distr = gen.estimateFromPeptideWeight(700); double base_mz1 = distr[0].getMZ(); for (auto it = distr.begin(); it != distr.end(); ++it) { if (it->getIntensity() != 0) { it->setIntensity(it->getIntensity() * 10); spec.push_back(*it); } } spec.sortByPosition(); MSSpectrum theo(spec); Deisotoper::deisotopeWithAveragineModel(theo, 10.0, true); TEST_EQUAL(theo.size(), 1); TEST_REAL_SIMILAR(theo[0].getMZ(), base_mz1); // Peaks before and after spectrum should not be chosen // Shows a fault of the old algorithm occurring with e.g. deamination double correct_monoiso = theo.getBasePeak()->getMZ(); double deamin_mz = spec.front().getMZ() - OpenMS::Constants::NEUTRON_MASS_U; Peak1D deamin_peak = Peak1D(deamin_mz, 0.06f); spec.push_back(deamin_peak); spec.sortByPosition(); theo = spec; MSSpectrum theo1(spec); Deisotoper::deisotopeWithAveragineModel(theo, 10.0, true, 5000, 1, 3, true);//keep only deisotoped TEST_REAL_SIMILAR(theo.front().getMZ(), correct_monoiso); Deisotoper::deisotopeAndSingleCharge(theo1, 10.0, true, 1, 3, true); TEST_NOT_EQUAL(theo1.front().getMZ(), correct_monoiso);// passes -> not equal // Test a peak with zero intensitiy double add_mz = spec.back().getMZ() + OpenMS::Constants::C13C12_MASSDIFF_U; Peak1D add_peak(add_mz, 0.0); spec.push_back(add_peak); theo = spec; Deisotoper::deisotopeWithAveragineModel(theo, 10.0, true); TEST_NOT_EQUAL(theo.back().getIntensity(), 0.0);// the new peak should be removed // Additional peaks that only fit m/z - wise should not disturb cluster formation spec.back().setIntensity(20);// intensity is a lot too high to fit correct distribution theo = spec; Deisotoper::deisotopeWithAveragineModel(theo, 10.0, true, -1);// do not remove low intensities TEST_EQUAL(theo.size(), 3); TEST_REAL_SIMILAR(theo.back().getMZ(), add_mz);// last peak is still there // spectrum with two isotopic patterns distr = gen.estimateFromPeptideWeight(500); double base_mz2 = distr[0].getMZ(); for (auto it = distr.begin(); it != distr.end(); ++it) { if (it->getIntensity() != 0) { it->setMZ((it->getMZ() + OpenMS::Constants::PROTON_MASS_U) / 2);// set to charge 2 spec.push_back((*it)); } } theo = spec; theo.sortByPosition(); Deisotoper::deisotopeWithAveragineModel(theo, 10.0, true, 5000, 1, 3, true);// keep only deisotoped TEST_EQUAL(theo.size(), 2); TEST_EQUAL(theo[0].getMZ(), base_mz2); TEST_EQUAL(theo[1].getMZ(), base_mz1); // Add unassignable peaks Peak1D peak1(550, 0.8f); spec.push_back(peak1); Peak1D peak2(600, 0.9f); spec.push_back(peak2); spec.sortByPosition(); theo = spec; Deisotoper::deisotopeWithAveragineModel(theo, 10.0, true, -1);// do not remove low intensities TEST_EQUAL(theo.size(), 6); // two spectra, one peak before, one after one spectrum, and two unassignable peaks // keep only deisotoped theo = spec; Deisotoper::deisotopeWithAveragineModel(theo, 10.0, true, 5000, 1, 3, true); // keep only deisotoped TEST_EQUAL(theo.size(), 2); // test with complete theoretical spectrum // create a theoretical spectrum generator // and configure to add isotope patterns TheoreticalSpectrumGenerator spec_generator; Param param = spec_generator.getParameters(); param.setValue("isotope_model", "coarse"); param.setValue("max_isotope", 3); param.setValue("add_a_ions", "false"); param.setValue("add_b_ions", "false"); param.setValue("add_losses", "false"); param.setValue("add_precursor_peaks", "false"); spec_generator.setParameters(param); param.setValue("isotope_model", "coarse"); spec_generator.setParameters(param); AASequence peptide1 = AASequence::fromString("PEPTIDE"); theo.clear(true); spec_generator.getSpectrum(theo, peptide1, 1, 2);// charge 1..2 Deisotoper::deisotopeWithAveragineModel(theo, 10.0, true); // create theoretical spectrum without isotopic peaks for comparison to the deisotoped one param.setValue("isotope_model", "none");// disable additional isotopes spec_generator.setParameters(param); MSSpectrum theo_noiso; spec_generator.getSpectrum(theo_noiso, peptide1, 1, 2);// charge 1..2 TEST_EQUAL(theo.size(), theo_noiso.size()); // same number of peaks after deisotoping // simpler tests with patterns where all isotopic peaks have the same intensity MSSpectrum two_patterns; Peak1D p; two_patterns.clear(true); p.setIntensity(1.0); // first pattern p.setMZ(100.0); two_patterns.push_back(p); p.setMZ(100.0 + Constants::C13C12_MASSDIFF_U); two_patterns.push_back(p); p.setMZ(100.0 + 2.0 * Constants::C13C12_MASSDIFF_U); two_patterns.push_back(p); // second pattern p.setMZ(200.0); two_patterns.push_back(p); p.setMZ(200.0 + 0.5 * Constants::C13C12_MASSDIFF_U); two_patterns.push_back(p); p.setMZ(200.0 + 2.0 * 0.5 * Constants::C13C12_MASSDIFF_U); two_patterns.push_back(p); theo = two_patterns; Deisotoper::deisotopeWithAveragineModel(theo, 10.0, true); TEST_EQUAL(theo.size(), 6);// all six peaks remain, since the patterns should not be similar to averagine model // Test with a section of an actual spectrum MzMLFile file; PeakMap exp; file.load(OPENMS_GET_TEST_DATA_PATH("Deisotoper_test_in.mzML"), exp); theo.clear(true); theo = exp.getSpectrum(0);// copy for readability theo1.clear(true); theo1 = exp.getSpectrum(0);// for next test Size ori_size = theo.size(); Deisotoper::deisotopeWithAveragineModel(theo, 10.0, true, 5000, 1, 3, true);// keep only deisotoped TEST_NOT_EQUAL(theo.size(), ori_size); file.load(OPENMS_GET_TEST_DATA_PATH("Deisotoper_test_out.mzML"), exp); TEST_EQUAL(theo, exp.getSpectrum(0)); // Test if the algorithm also works if we do not remove the low (and zero) intensity peaks Deisotoper::deisotopeWithAveragineModel(theo1, 10.0, true, -1, 1, 3, true);// do not remove low intensity peaks beforehand, but keep only deisotoped TEST_EQUAL(theo1.size(), 104); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/FLASHDeconvFeatureFile_test.cpp
.cpp
8,732
256
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Kyowon Jeong $ // $Authors: Kyowon Jeong $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/FORMAT/FLASHDeconvFeatureFile.h> #include <OpenMS/ANALYSIS/TOPDOWN/DeconvolvedSpectrum.h> #include <OpenMS/ANALYSIS/TOPDOWN/PeakGroup.h> #include <OpenMS/KERNEL/MSSpectrum.h> #include <sstream> /////////////////////////// using namespace OpenMS; using namespace std; ///////////////////////////////////////////////////////////// // Helper function to create a test MassFeature ///////////////////////////////////////////////////////////// FLASHHelperClasses::MassFeature createTestMassFeature(uint index, double mass, int ms_level = 1) { FLASHHelperClasses::MassFeature mf; mf.index = index; mf.avg_mass = mass + 1.0; // average mass slightly higher than mono mf.iso_offset = 0; mf.scan_number = 100; mf.min_scan_number = 95; mf.max_scan_number = 105; mf.rep_charge = 10; mf.min_charge = 5; mf.max_charge = 15; mf.charge_count = 11; mf.isotope_score = 0.95; mf.qscore = 0.85; mf.rep_mz = mass / 10.0 + 1.007276; // approximate m/z mf.is_decoy = false; mf.ms_level = ms_level; // Initialize per charge/isotope intensities mf.per_charge_intensity.resize(20, 0.0f); mf.per_isotope_intensity.resize(10, 0.0f); for (int i = mf.min_charge; i <= mf.max_charge; ++i) { mf.per_charge_intensity[i] = 1000.0f * (i - mf.min_charge + 1); } for (size_t i = 0; i < 5; ++i) { mf.per_isotope_intensity[i] = 500.0f * (i + 1); } // Create a simple mass trace mf.mt = MassTrace(); // Add some peaks to the mass trace Peak2D p1, p2, p3; p1.setRT(100.0); p1.setMZ(mass / 10.0); p1.setIntensity(10000.0f); p2.setRT(101.0); p2.setMZ(mass / 10.0); p2.setIntensity(15000.0f); p3.setRT(102.0); p3.setMZ(mass / 10.0); p3.setIntensity(8000.0f); std::vector<Peak2D> peaks = {p1, p2, p3}; mf.mt = MassTrace(peaks); return mf; } ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// START_TEST(FLASHDeconvFeatureFile, "$Id$") ///////////////////////////////////////////////////////////// // Test writeHeader ///////////////////////////////////////////////////////////// START_SECTION(static void writeHeader(std::ostream& os, bool report_decoy = false)) { // Test header without decoy reporting { ostringstream oss; FLASHDeconvFeatureFile::writeHeader(oss, false); String header = oss.str(); TEST_EQUAL(header.hasSubstring("FeatureIndex"), true) TEST_EQUAL(header.hasSubstring("FileName"), true) TEST_EQUAL(header.hasSubstring("MSLevel"), true) TEST_EQUAL(header.hasSubstring("MonoisotopicMass"), true) TEST_EQUAL(header.hasSubstring("AverageMass"), true) TEST_EQUAL(header.hasSubstring("SumIntensity"), true) TEST_EQUAL(header.hasSubstring("PerChargeIntensity"), true) TEST_EQUAL(header.hasSubstring("PerIsotopeIntensity"), true) TEST_EQUAL(header.hasSubstring("IsDecoy"), false) // Should NOT contain IsDecoy TEST_EQUAL(header.hasSubstring("\n"), true) // Should end with newline } // Test header with decoy reporting { ostringstream oss; FLASHDeconvFeatureFile::writeHeader(oss, true); String header = oss.str(); TEST_EQUAL(header.hasSubstring("IsDecoy"), true) // Should contain IsDecoy TEST_EQUAL(header.hasSubstring("FeatureIndex"), true) } } END_SECTION ///////////////////////////////////////////////////////////// // Test writeTopFDFeatureHeader ///////////////////////////////////////////////////////////// START_SECTION(static void writeTopFDFeatureHeader(std::ostream& os, uint ms_level)) { // Test MS1 header { ostringstream oss; FLASHDeconvFeatureFile::writeTopFDFeatureHeader(oss, 1); String header = oss.str(); TEST_EQUAL(header.hasSubstring("File_name"), true) TEST_EQUAL(header.hasSubstring("Feature_ID"), true) TEST_EQUAL(header.hasSubstring("Mass"), true) TEST_EQUAL(header.hasSubstring("Intensity"), true) TEST_EQUAL(header.hasSubstring("Min_time"), true) TEST_EQUAL(header.hasSubstring("Max_time"), true) TEST_EQUAL(header.hasSubstring("Apex_time"), true) TEST_EQUAL(header.hasSubstring("EC_score"), true) // MS1 header should NOT contain Spectrum_ID TEST_EQUAL(header.hasSubstring("Spectrum_ID"), false) } // Test MS2 header { ostringstream oss; FLASHDeconvFeatureFile::writeTopFDFeatureHeader(oss, 2); String header = oss.str(); TEST_EQUAL(header.hasSubstring("File_name"), true) TEST_EQUAL(header.hasSubstring("Spectrum_ID"), true) // MS2 has Spectrum_ID TEST_EQUAL(header.hasSubstring("Precursor_charge"), true) TEST_EQUAL(header.hasSubstring("Precursor_intensity"), true) TEST_EQUAL(header.hasSubstring("Fraction_feature_ID"), true) } } END_SECTION ///////////////////////////////////////////////////////////// // Test writeFeatures with synthesized data ///////////////////////////////////////////////////////////// START_SECTION(static void writeFeatures(const std::vector<FLASHHelperClasses::MassFeature>& mass_features, const String& file_name, std::ostream& os, bool report_decoy = false)) { // Test with empty features vector { ostringstream oss; std::vector<FLASHHelperClasses::MassFeature> empty_features; FLASHDeconvFeatureFile::writeFeatures(empty_features, "test.mzML", oss, false); TEST_EQUAL(oss.str().empty(), true) } // Test with synthesized features { ostringstream oss; std::vector<FLASHHelperClasses::MassFeature> features; features.push_back(createTestMassFeature(1, 10000.0)); features.push_back(createTestMassFeature(2, 15000.0)); FLASHDeconvFeatureFile::writeFeatures(features, "test_input.mzML", oss, false); String output = oss.str(); // Check that output contains expected data TEST_EQUAL(output.hasSubstring("test_input.mzML"), true) TEST_EQUAL(output.hasSubstring("1\t"), true) // Feature index 1 TEST_EQUAL(output.hasSubstring("2\t"), true) // Feature index 2 // Should contain two lines (one per feature) Size line_count = std::count(output.begin(), output.end(), '\n'); TEST_EQUAL(line_count, 2) } // Test with decoy reporting { ostringstream oss; std::vector<FLASHHelperClasses::MassFeature> features; auto mf = createTestMassFeature(1, 10000.0); mf.is_decoy = true; features.push_back(mf); FLASHDeconvFeatureFile::writeFeatures(features, "test.mzML", oss, true); String output = oss.str(); // Should contain decoy indicator (1 for is_decoy=true) TEST_EQUAL(output.hasSubstring("\t1\t"), true) } } END_SECTION ///////////////////////////////////////////////////////////// // Test writeTopFDFeatures ///////////////////////////////////////////////////////////// START_SECTION(static void writeTopFDFeatures(std::vector<DeconvolvedSpectrum>& deconvolved_spectra, const std::vector<FLASHHelperClasses::MassFeature>& mass_features, const std::map<int, double>& scan_rt_map, const String& file_name, std::ostream& os, uint ms_level)) { // Test with empty inputs { ostringstream oss; std::vector<DeconvolvedSpectrum> empty_spectra; std::vector<FLASHHelperClasses::MassFeature> empty_features; std::map<int, double> empty_rt_map; FLASHDeconvFeatureFile::writeTopFDFeatures(empty_spectra, empty_features, empty_rt_map, "test.mzML", oss, 1); TEST_EQUAL(oss.str().empty(), true) } // Test MS1 features with synthesized data { ostringstream oss; std::vector<DeconvolvedSpectrum> spectra; std::vector<FLASHHelperClasses::MassFeature> features; std::map<int, double> scan_rt_map; // Create test features features.push_back(createTestMassFeature(1, 10000.0, 1)); features.push_back(createTestMassFeature(2, 15000.0, 1)); // Create scan to RT mapping scan_rt_map[100] = 6000.0; // 100 minutes in seconds FLASHDeconvFeatureFile::writeTopFDFeatures(spectra, features, scan_rt_map, "test_input.mzML", oss, 1); String output = oss.str(); // Check output contains expected data for MS1 TEST_EQUAL(output.hasSubstring("test_input.mzML"), true) // Should have feature entries TEST_EQUAL(output.empty(), false) } } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/Peak2D_test.cpp
.cpp
16,689
618
// 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 $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/KERNEL/Peak2D.h> #include <unordered_set> #include <unordered_map> /////////////////////////// START_TEST(Peak2D<D>, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; static_assert(std::is_trivially_destructible<Peak2D> {}); // static_assert(std::is_trivially_default_constructible<Peak2D> {}); static_assert(std::is_trivially_copy_constructible<Peak2D> {}); static_assert(std::is_trivially_copy_assignable<Peak2D> {}); static_assert(std::is_trivially_move_constructible<Peak2D> {}); static_assert(std::is_nothrow_move_constructible<Peak2D> {}); static_assert(std::is_trivially_move_assignable<Peak2D> {}); Peak2D* d10_ptr = nullptr; Peak2D* d10_nullPointer = nullptr; START_SECTION((Peak2D())) { d10_ptr = new Peak2D; TEST_NOT_EQUAL(d10_ptr, d10_nullPointer) } END_SECTION START_SECTION((~Peak2D())) { delete d10_ptr; } END_SECTION START_SECTION((Peak2D(const Peak2D &p))) { Peak2D::PositionType pos; pos[0] = 21.21; pos[1] = 22.22; Peak2D p; p.setIntensity(123.456f); p.setPosition(pos); Peak2D::PositionType pos2; Peak2D::IntensityType i2; Peak2D copy_of_p(p); i2 = copy_of_p.getIntensity(); pos2 = copy_of_p.getPosition(); TEST_REAL_SIMILAR(i2, 123.456) TEST_REAL_SIMILAR(pos2[0], 21.21) TEST_REAL_SIMILAR(pos2[1], 22.22) } END_SECTION START_SECTION((Peak2D(Peak2D &&rhs))) { // Ensure that Peak2D has a no-except move constructor (otherwise // std::vector is inefficient and will copy instead of move). TEST_EQUAL(noexcept(Peak2D(std::declval<Peak2D&&>())), true) Peak2D::PositionType pos; pos[0] = 21.21; pos[1] = 22.22; Peak2D p; p.setIntensity(123.456f); p.setPosition(pos); Peak2D::PositionType pos2; Peak2D::IntensityType i2; Peak2D copy_of_p(std::move(p)); i2 = copy_of_p.getIntensity(); pos2 = copy_of_p.getPosition(); TEST_REAL_SIMILAR(i2, 123.456) TEST_REAL_SIMILAR(pos2[0], 21.21) TEST_REAL_SIMILAR(pos2[1], 22.22) } END_SECTION START_SECTION((explicit Peak2D(const PositionType& pos, const IntensityType in))) { Peak2D p(Peak2D::PositionType(21.21, 22.22), 123.456f); Peak2D copy_of_p(p); TEST_REAL_SIMILAR(copy_of_p.getIntensity(), 123.456) TEST_REAL_SIMILAR(copy_of_p.getPosition()[0], 21.21) TEST_REAL_SIMILAR(copy_of_p.getPosition()[1], 22.22) } END_SECTION START_SECTION((Peak2D& operator=(const Peak2D &rhs))) Peak2D::PositionType pos; pos[0] = 21.21; pos[1] = 22.22; Peak2D p; p.setIntensity(123.456f); p.setPosition(pos); Peak2D::PositionType pos2; Peak2D::IntensityType i2; Peak2D copy_of_p; copy_of_p = p; i2 = copy_of_p.getIntensity(); pos2 = copy_of_p.getPosition(); TEST_REAL_SIMILAR(i2, 123.456) TEST_REAL_SIMILAR(pos2[0], 21.21) TEST_REAL_SIMILAR(pos2[1], 22.22) END_SECTION START_SECTION((IntensityType getIntensity() const)) TEST_REAL_SIMILAR(Peak2D().getIntensity(), 0.0) END_SECTION START_SECTION((PositionType const& getPosition() const)) const Peak2D p; TEST_REAL_SIMILAR(p.getPosition()[0], 0.0) TEST_REAL_SIMILAR(p.getPosition()[1], 0.0) END_SECTION START_SECTION((CoordinateType getRT() const)) TEST_REAL_SIMILAR(Peak2D().getRT(), 0.0) END_SECTION START_SECTION((CoordinateType getMZ() const)) TEST_REAL_SIMILAR(Peak2D().getMZ(), 0.0) END_SECTION START_SECTION((void setRT(CoordinateTypecoordinate))) Peak2D p0; p0.setRT(12345.0); TEST_REAL_SIMILAR(p0.getRT(), 12345.0) END_SECTION START_SECTION((void setMZ(CoordinateTypecoordinate))) Peak2D p0; p0.setMZ(12345.0); TEST_REAL_SIMILAR(p0.getMZ(), 12345.0) END_SECTION START_SECTION((void setPosition(const PositionType &position))) DPosition<2> p; p[0] = 876; p[1] = 12345.0; Peak2D p1; p1.setPosition(p); TEST_REAL_SIMILAR(p1.getPosition()[0], 876) TEST_REAL_SIMILAR(p1.getPosition()[1], 12345.0) END_SECTION START_SECTION((PositionType& getPosition())) DPosition<2> p; p[0] = 876; p[1] = 12345.0; Peak2D p1; p1.getPosition() = p; TEST_REAL_SIMILAR(p1.getPosition()[0], 876) TEST_REAL_SIMILAR(p1.getPosition()[1], 12345.0) END_SECTION START_SECTION((void setIntensity(IntensityType intensity))) Peak2D p; p.setIntensity(17.8f); TEST_REAL_SIMILAR(p.getIntensity(), 17.8) END_SECTION START_SECTION((bool operator == (const Peak2D& rhs) const)) Peak2D p1; Peak2D p2(p1); TEST_TRUE(p1 == p2) p1.setIntensity(5.0f); TEST_EQUAL(p1==p2, false) p2.setIntensity(5.0f); TEST_TRUE(p1 == p2) p1.getPosition()[0]=5; TEST_EQUAL(p1==p2, false) p2.getPosition()[0]=5; TEST_TRUE(p1 == p2) END_SECTION START_SECTION((bool operator != (const Peak2D& rhs) const)) Peak2D p1; Peak2D p2(p1); TEST_EQUAL(p1!=p2, false) p1.setIntensity(5.0f); TEST_FALSE(p1 == p2) p2.setIntensity(5.0f); TEST_EQUAL(p1!=p2, false) p1.getPosition()[0]=5; TEST_FALSE(p1 == p2) p2.getPosition()[0]=5; TEST_EQUAL(p1!=p2, false) END_SECTION START_SECTION(([EXTRA]enum value Peak2D::RT)) { TEST_EQUAL(Peak2D::RT,0); } END_SECTION START_SECTION(([EXTRA]enum value Peak2D::MZ)) { TEST_EQUAL(Peak2D::MZ,1); } END_SECTION START_SECTION(([EXTRA]enum value Peak2D::DIMENSION)) { TEST_EQUAL(Peak2D::DIMENSION,2); } END_SECTION START_SECTION(([EXTRA]enum Peak2D::DimensionId)) { Peak2D::DimensionDescription dim; dim = Peak2D::RT; TEST_EQUAL(dim,Peak2D::RT); dim = Peak2D::MZ; TEST_EQUAL(dim,Peak2D::MZ); dim = Peak2D::DIMENSION; TEST_EQUAL(dim,Peak2D::DIMENSION); } END_SECTION START_SECTION((static char const* shortDimensionName(UInt const dim))) { TEST_STRING_EQUAL(Peak2D::shortDimensionName(Peak2D::RT),"RT"); TEST_STRING_EQUAL(Peak2D::shortDimensionName(Peak2D::MZ),"MZ"); } END_SECTION START_SECTION((static char const* shortDimensionNameRT())) { TEST_STRING_EQUAL(Peak2D::shortDimensionNameRT(),"RT"); } END_SECTION START_SECTION((static char const* shortDimensionNameMZ())) { TEST_STRING_EQUAL(Peak2D::shortDimensionNameMZ(),"MZ"); } END_SECTION START_SECTION((static char const* fullDimensionName(UInt const dim))) { TEST_STRING_EQUAL(Peak2D::fullDimensionName(Peak2D::RT),"retention time"); TEST_STRING_EQUAL(Peak2D::fullDimensionName(Peak2D::MZ),"mass-to-charge"); } END_SECTION START_SECTION((static char const* fullDimensionNameRT())) { TEST_STRING_EQUAL(Peak2D::fullDimensionNameRT(),"retention time"); } END_SECTION START_SECTION((static char const* fullDimensionNameMZ())) { TEST_STRING_EQUAL(Peak2D::fullDimensionNameMZ(),"mass-to-charge"); } END_SECTION START_SECTION((static char const* shortDimensionUnit(UInt const dim))) { TEST_STRING_EQUAL(Peak2D::shortDimensionUnit(Peak2D::RT),"sec"); TEST_STRING_EQUAL(Peak2D::shortDimensionUnit(Peak2D::MZ),"Th"); } END_SECTION START_SECTION((static char const* shortDimensionUnitRT())) { TEST_STRING_EQUAL(Peak2D::shortDimensionUnitRT(),"sec"); } END_SECTION START_SECTION((static char const* shortDimensionUnitMZ())) { TEST_STRING_EQUAL(Peak2D::shortDimensionUnitMZ(),"Th"); } END_SECTION START_SECTION((static char const* fullDimensionUnit(UInt const dim))) { TEST_STRING_EQUAL(Peak2D::fullDimensionUnit(Peak2D::RT),"Seconds"); TEST_STRING_EQUAL(Peak2D::fullDimensionUnit(Peak2D::MZ),"Thomson"); } END_SECTION START_SECTION((static char const* fullDimensionUnitRT())) { TEST_STRING_EQUAL(Peak2D::fullDimensionUnitRT(),"Seconds"); } END_SECTION START_SECTION((static char const* fullDimensionUnitMZ())) { TEST_STRING_EQUAL(Peak2D::fullDimensionUnitMZ(),"Thomson"); } END_SECTION ///////////////////////////////////////////////////////////// // Nested Stuff ///////////////////////////////////////////////////////////// Peak2D p1; p1.setIntensity(10.0); p1.setMZ(10.0); p1.setRT(10.0); Peak2D p2; p2.setIntensity(12.0); p2.setMZ(12.0); p2.setRT(12.0); // IntensityLess START_SECTION(([Peak2D::IntensityLess] bool operator()(const Peak2D &left, const Peak2D &right) const)) std::vector<Peak2D > v; Peak2D p; p.setIntensity(2.5f); v.push_back(p); p.setIntensity(3.5f); v.push_back(p); p.setIntensity(1.5f); v.push_back(p); std::sort(v.begin(), v.end(), Peak2D::IntensityLess()); TEST_REAL_SIMILAR(v[0].getIntensity(), 1.5) TEST_REAL_SIMILAR(v[1].getIntensity(), 2.5) TEST_REAL_SIMILAR(v[2].getIntensity(), 3.5) v[0]=v[2]; v[2]=p; std::sort(v.begin(), v.end(), Peak2D::IntensityLess()); TEST_REAL_SIMILAR(v[0].getIntensity(), 1.5) TEST_REAL_SIMILAR(v[1].getIntensity(), 2.5) TEST_REAL_SIMILAR(v[2].getIntensity(), 3.5) // TEST_EQUAL(Peak2D::IntensityLess()(p1,p2), true) TEST_EQUAL(Peak2D::IntensityLess()(p2,p1), false) TEST_EQUAL(Peak2D::IntensityLess()(p2,p2), false) END_SECTION START_SECTION(([Peak2D::IntensityLess] bool operator()(const Peak2D &left, IntensityType right) const)) TEST_EQUAL(Peak2D::IntensityLess()(p1,p2.getIntensity()), true) TEST_EQUAL(Peak2D::IntensityLess()(p2,p1.getIntensity()), false) TEST_EQUAL(Peak2D::IntensityLess()(p2,p2.getIntensity()), false) END_SECTION START_SECTION(([Peak2D::IntensityLess] bool operator()(IntensityType left, const Peak2D &right) const)) TEST_EQUAL(Peak2D::IntensityLess()(p1.getIntensity(),p2), true) TEST_EQUAL(Peak2D::IntensityLess()(p2.getIntensity(),p1), false) TEST_EQUAL(Peak2D::IntensityLess()(p2.getIntensity(),p2), false) END_SECTION START_SECTION(([Peak2D::IntensityLess] bool operator()(IntensityType left, IntensityType right) const)) TEST_EQUAL(Peak2D::IntensityLess()(p1,p2.getIntensity()), true) TEST_EQUAL(Peak2D::IntensityLess()(p2,p1.getIntensity()), false) TEST_EQUAL(Peak2D::IntensityLess()(p2,p2.getIntensity()), false) END_SECTION // RTLess START_SECTION(([Peak2D::RTLess] bool operator()(const Peak2D &left, const Peak2D &right) const)) std::vector<Peak2D > v; Peak2D p; p.getPosition()[0]=3.0; p.getPosition()[1]=2.5; v.push_back(p); p.getPosition()[0]=2.0; p.getPosition()[1]=3.5; v.push_back(p); p.getPosition()[0]=1.0; p.getPosition()[1]=1.5; v.push_back(p); std::sort(v.begin(), v.end(), Peak2D::RTLess()); TEST_REAL_SIMILAR(v[0].getPosition()[0], 1.0) TEST_REAL_SIMILAR(v[1].getPosition()[0], 2.0) TEST_REAL_SIMILAR(v[2].getPosition()[0], 3.0) TEST_EQUAL(Peak2D::RTLess()(p1,p2), true) TEST_EQUAL(Peak2D::RTLess()(p2,p1), false) TEST_EQUAL(Peak2D::RTLess()(p2,p2), false) END_SECTION START_SECTION(([Peak2D::RTLess] bool operator()(const Peak2D &left, CoordinateType right) const)) TEST_EQUAL(Peak2D::RTLess()(p1,p2.getRT()), true) TEST_EQUAL(Peak2D::RTLess()(p2,p1.getRT()), false) TEST_EQUAL(Peak2D::RTLess()(p2,p2.getRT()), false) END_SECTION START_SECTION(([Peak2D::RTLess] bool operator()(CoordinateType left, const Peak2D &right) const)) TEST_EQUAL(Peak2D::RTLess()(p1.getRT(),p2), true) TEST_EQUAL(Peak2D::RTLess()(p2.getRT(),p1), false) TEST_EQUAL(Peak2D::RTLess()(p2.getRT(),p2), false) END_SECTION START_SECTION(([Peak2D::RTLess] bool operator()(CoordinateType left, CoordinateType right) const)) TEST_EQUAL(Peak2D::RTLess()(p1.getRT(),p2.getRT()), true) TEST_EQUAL(Peak2D::RTLess()(p2.getRT(),p1.getRT()), false) TEST_EQUAL(Peak2D::RTLess()(p2.getRT(),p2.getRT()), false) END_SECTION // PositionLess START_SECTION(([Peak2D::PositionLess] bool operator()(const Peak2D &left, const Peak2D &right) const)) std::vector<Peak2D > v; Peak2D p; p.getPosition()[0]=3.0; p.getPosition()[1]=2.5; v.push_back(p); p.getPosition()[0]=2.0; p.getPosition()[1]=3.5; v.push_back(p); p.getPosition()[0]=1.0; p.getPosition()[1]=1.5; v.push_back(p); std::sort(v.begin(), v.end(), Peak2D::PositionLess()); TEST_REAL_SIMILAR(v[0].getPosition()[0], 1.0) TEST_REAL_SIMILAR(v[1].getPosition()[0], 2.0) TEST_REAL_SIMILAR(v[2].getPosition()[0], 3.0) TEST_REAL_SIMILAR(v[0].getPosition()[1], 1.5) TEST_REAL_SIMILAR(v[1].getPosition()[1], 3.5) TEST_REAL_SIMILAR(v[2].getPosition()[1], 2.5) std::sort(v.begin(), v.end(), Peak2D::MZLess()); TEST_REAL_SIMILAR(v[0].getPosition()[1], 1.5) TEST_REAL_SIMILAR(v[1].getPosition()[1], 2.5) TEST_REAL_SIMILAR(v[2].getPosition()[1], 3.5) TEST_REAL_SIMILAR(v[0].getPosition()[0], 1.0) TEST_REAL_SIMILAR(v[1].getPosition()[0], 3.0) TEST_REAL_SIMILAR(v[2].getPosition()[0], 2.0) // TEST_EQUAL(Peak2D::PositionLess()(p1,p2), true) TEST_EQUAL(Peak2D::PositionLess()(p2,p1), false) TEST_EQUAL(Peak2D::PositionLess()(p2,p2), false) END_SECTION START_SECTION(([Peak2D::PositionLess] bool operator()(const Peak2D &left, const PositionType &right) const)) TEST_EQUAL(Peak2D::PositionLess()(p1,p2.getPosition()), true) TEST_EQUAL(Peak2D::PositionLess()(p2,p1.getPosition()), false) TEST_EQUAL(Peak2D::PositionLess()(p2,p2.getPosition()), false) END_SECTION START_SECTION(([Peak2D::PositionLess] bool operator()(const PositionType &left, const Peak2D &right) const)) TEST_EQUAL(Peak2D::PositionLess()(p1.getPosition(),p2), true) TEST_EQUAL(Peak2D::PositionLess()(p2.getPosition(),p1), false) TEST_EQUAL(Peak2D::PositionLess()(p2.getPosition(),p2), false) END_SECTION START_SECTION(([Peak2D::PositionLess] bool operator()(const PositionType &left, const PositionType &right) const)) TEST_EQUAL(Peak2D::PositionLess()(p1.getPosition(),p2.getPosition()), true) TEST_EQUAL(Peak2D::PositionLess()(p2.getPosition(),p1.getPosition()), false) TEST_EQUAL(Peak2D::PositionLess()(p2.getPosition(),p2.getPosition()), false) END_SECTION // MZLess START_SECTION(([Peak2D::MZLess] bool operator()(const Peak2D &left, const Peak2D &right) const)) std::vector<Peak2D > v; Peak2D p; p.getPosition()[0]=3.0; p.getPosition()[1]=2.5; v.push_back(p); p.getPosition()[0]=2.0; p.getPosition()[1]=3.5; v.push_back(p); p.getPosition()[0]=1.0; p.getPosition()[1]=1.5; v.push_back(p); std::sort(v.begin(), v.end(), Peak2D::MZLess()); TEST_REAL_SIMILAR(v[0].getPosition()[1], 1.5) TEST_REAL_SIMILAR(v[1].getPosition()[1], 2.5) TEST_REAL_SIMILAR(v[2].getPosition()[1], 3.5) TEST_EQUAL(Peak2D::MZLess()(p1,p2), true) TEST_EQUAL(Peak2D::MZLess()(p2,p1), false) TEST_EQUAL(Peak2D::MZLess()(p2,p2), false) END_SECTION START_SECTION(([Peak2D::MZLess] bool operator()(const Peak2D &left, CoordinateType right) const)) TEST_EQUAL(Peak2D::MZLess()(p1,p2.getMZ()), true) TEST_EQUAL(Peak2D::MZLess()(p2,p1.getMZ()), false) TEST_EQUAL(Peak2D::MZLess()(p2,p2.getMZ()), false) END_SECTION START_SECTION(([Peak2D::MZLess] bool operator()(CoordinateType left, const Peak2D &right) const)) TEST_EQUAL(Peak2D::MZLess()(p1.getMZ(),p2), true) TEST_EQUAL(Peak2D::MZLess()(p2.getMZ(),p1), false) TEST_EQUAL(Peak2D::MZLess()(p2.getMZ(),p2), false) END_SECTION START_SECTION(([Peak2D::MZLess] bool operator()(CoordinateType left, CoordinateType right) const)) TEST_EQUAL(Peak2D::MZLess()(p1.getMZ(),p2.getMZ()), true) TEST_EQUAL(Peak2D::MZLess()(p2.getMZ(),p1.getMZ()), false) TEST_EQUAL(Peak2D::MZLess()(p2.getMZ(),p2.getMZ()), false) END_SECTION ///////////////////////////////////////////////////////////// // Hash function tests ///////////////////////////////////////////////////////////// START_SECTION(([EXTRA] std::hash<Peak2D>)) { // Test that equal peaks have equal hashes Peak2D pk1, pk2; pk1.setRT(10.5); pk1.setMZ(100.5); pk1.setIntensity(1000.0f); pk2.setRT(10.5); pk2.setMZ(100.5); pk2.setIntensity(1000.0f); std::hash<Peak2D> hasher; TEST_EQUAL(hasher(pk1), hasher(pk2)) // Test that hash changes when values change Peak2D pk3; pk3.setRT(20.5); pk3.setMZ(100.5); pk3.setIntensity(1000.0f); TEST_NOT_EQUAL(hasher(pk1), hasher(pk3)) // Test use in unordered_set std::unordered_set<Peak2D> peak_set; peak_set.insert(pk1); TEST_EQUAL(peak_set.size(), 1) peak_set.insert(pk2); // same as pk1 TEST_EQUAL(peak_set.size(), 1) // should not increase peak_set.insert(pk3); TEST_EQUAL(peak_set.size(), 2) // Test use in unordered_map std::unordered_map<Peak2D, int> peak_map; peak_map[pk1] = 42; TEST_EQUAL(peak_map[pk1], 42) TEST_EQUAL(peak_map[pk2], 42) // pk2 == pk1, should get same value peak_map[pk3] = 99; TEST_EQUAL(peak_map[pk3], 99) TEST_EQUAL(peak_map.size(), 2) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/PosteriorErrorProbabilityModel_test.cpp
.cpp
11,569
333
// 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$ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/MATH/STATISTICS/PosteriorErrorProbabilityModel.h> #include <OpenMS/FORMAT/IdXMLFile.h> #include <OpenMS/FORMAT/CsvFile.h> #include <OpenMS/DATASTRUCTURES/StringListUtils.h> #include <vector> #include <iostream> /////////////////////////// using namespace OpenMS; using namespace Math; using namespace std; START_TEST(PosteriorErrorProbabilityModel, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// PosteriorErrorProbabilityModel* ptr = nullptr; PosteriorErrorProbabilityModel* nullPointer = nullptr; START_SECTION(PosteriorErrorProbabilityModel()) { ptr = new PosteriorErrorProbabilityModel(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION((virtual ~PosteriorErrorProbabilityModel())) { delete ptr; NOT_TESTABLE } END_SECTION START_SECTION((void fit( std::vector<double>& search_engine_scores))) NOT_TESTABLE //tested below END_SECTION START_SECTION((void fit( std::vector<double>& search_engine_scores, std::vector<double>& probabilities))) ptr = new PosteriorErrorProbabilityModel(); { // ------- This code was used for the test file: ------------ // Use actual Gaussian data to see if fitting works //random_device device_random_; //default_random_engine generator_(device_random_()); // Gaussian mean and SD, mixture of 2. //normal_distribution<> distribution_1_(1.5, 0.5); //normal_distribution<> distribution_2_(3.5, 1.0); // ---------------------------------------------------------- vector<double> rand_score_vector; CsvFile gauss_mix (OPENMS_GET_TEST_DATA_PATH("GaussMix_2_1D.csv"), ';'); StringList gauss_mix_strings; gauss_mix.getRow(0, gauss_mix_strings); // Load mixture of 2 Gaussians (1D) from provided csv for (StringList::const_iterator it = gauss_mix_strings.begin(); it != gauss_mix_strings.end(); ++it) { if(!it->empty()) { rand_score_vector.push_back(it->toDouble()); } } TEST_EQUAL(rand_score_vector.size(),2000) // Class expects sorted scores sort(rand_score_vector.begin(), rand_score_vector.end()); vector<double> probabilities; Param param; param.setValue("number_of_bins", 10); param.setValue("incorrectly_assigned","Gauss"); ptr->setParameters(param); ptr->fit(rand_score_vector, probabilities, "none"); Size i(0),j(1); TOLERANCE_ABSOLUTE(0.5) TEST_REAL_SIMILAR(ptr->getCorrectlyAssignedFitResult().x0 , 3.5) TEST_REAL_SIMILAR(ptr->getCorrectlyAssignedFitResult().sigma, 1.0) TEST_REAL_SIMILAR(ptr->getIncorrectlyAssignedFitResult().x0, 1.5) TEST_REAL_SIMILAR(ptr->getIncorrectlyAssignedFitResult().sigma, 0.5) TEST_REAL_SIMILAR(ptr->getNegativePrior(), 0.5) TOLERANCE_ABSOLUTE(0.001) while(i < rand_score_vector.size() && j < rand_score_vector.size()) { cout<<"i: "<<rand_score_vector[i] << ", j: "<<rand_score_vector[j]<<endl; cout<<"pi:"<<probabilities[i] <<", j: "<<probabilities[j]<<endl; if(rand_score_vector[i] <= rand_score_vector[j]) { TEST_EQUAL(probabilities[i] >= probabilities[j],true) TEST_REAL_SIMILAR(ptr->computeProbability(rand_score_vector[i]), probabilities[i]) TEST_REAL_SIMILAR(ptr->computeProbability(rand_score_vector[j]), probabilities[j]) } else { TEST_EQUAL(probabilities[i] >= probabilities[j],true) TEST_REAL_SIMILAR(ptr->computeProbability(rand_score_vector[i]), probabilities[i]) TEST_REAL_SIMILAR(ptr->computeProbability(rand_score_vector[j]), probabilities[j]) } ++i; ++j; } } { vector<double> score_vector; score_vector.push_back(-0.39); score_vector.push_back(0.06); score_vector.push_back(0.12); score_vector.push_back(0.48); score_vector.push_back(0.94); score_vector.push_back(1.01); score_vector.push_back(1.67); score_vector.push_back(1.68); score_vector.push_back(1.76); score_vector.push_back(1.80); score_vector.push_back(2.44); score_vector.push_back(3.25); score_vector.push_back(3.72); score_vector.push_back(4.12); score_vector.push_back(4.28); score_vector.push_back(4.60); score_vector.push_back(4.92); score_vector.push_back(5.28); score_vector.push_back(5.53); score_vector.push_back(6.22); vector<double> probabilities; Param param; param.setValue("number_of_bins", 10); param.setValue("incorrectly_assigned","Gumbel"); ptr->setParameters(param); ptr->fit(score_vector, probabilities, "none"); Size i(0),j(1); TOLERANCE_ABSOLUTE(0.5) TEST_REAL_SIMILAR(ptr->getCorrectlyAssignedFitResult().x0 , 4.62) TEST_REAL_SIMILAR(ptr->getCorrectlyAssignedFitResult().sigma, 0.87) TEST_REAL_SIMILAR(ptr->getIncorrectlyAssignedFitResult().x0, 1.06) TEST_REAL_SIMILAR(ptr->getIncorrectlyAssignedFitResult().sigma, 0.77) TEST_REAL_SIMILAR(ptr->getNegativePrior(), 0.546) TOLERANCE_ABSOLUTE(0.001) while(i < score_vector.size() && j < score_vector.size()) { cout<<"i: "<<score_vector[i] << ", j: "<<score_vector[j]<<endl; cout<<"pi:"<<probabilities[i] <<", j: "<<probabilities[j]<<endl; if(score_vector[i] <= score_vector[j]) { TEST_EQUAL(probabilities[i] >= probabilities[j],true) TEST_REAL_SIMILAR(ptr->computeProbability(score_vector[i]), probabilities[i]) TEST_REAL_SIMILAR(ptr->computeProbability(score_vector[j]), probabilities[j]) } else { TEST_EQUAL(probabilities[i] >= probabilities[j],true) TEST_REAL_SIMILAR(ptr->computeProbability(score_vector[i]), probabilities[i]) TEST_REAL_SIMILAR(ptr->computeProbability(score_vector[j]), probabilities[j]) } ++i; ++j; } } END_SECTION START_SECTION((void fillLogDensities(std::vector<double>& x_scores,std::vector<double>& incorrect_density,std::vector<double>& correct_density))) NOT_TESTABLE //tested in fit END_SECTION START_SECTION((double computeLogLikelihood(std::vector<double>& incorrect_density, std::vector<double>& correct_density))) NOT_TESTABLE //tested in fit END_SECTION START_SECTION((double getGauss(double x,const GaussFitter::GaussFitResult& params))) NOT_TESTABLE //tested in fit END_SECTION START_SECTION((double getGumbel(double x,const GaussFitter::GaussFitResult& params))) NOT_TESTABLE //tested in fit END_SECTION START_SECTION((GaussFitter::GaussFitResult getCorrectlyAssignedFitResult() const)) //tested in fit NOT_TESTABLE END_SECTION START_SECTION((GaussFitter::GaussFitResult getIncorrectlyAssignedFitResult() const)) //tested in fit NOT_TESTABLE END_SECTION START_SECTION((double getNegativePrior() const)) //tested in fit NOT_TESTABLE END_SECTION START_SECTION((double getSmallestScore() const)) TEST_REAL_SIMILAR(ptr->getSmallestScore(), -0.39) END_SECTION START_SECTION((const String getGumbelGnuplotFormula(const GaussFitter::GaussFitResult& params) const)) String gumbel = ptr->getGumbelGnuplotFormula(ptr->getIncorrectlyAssignedFitResult()); //approx. f(x) = (1/0.907832") * exp(( 1.48185 - x)/0.907832) * exp(-exp(( 1.48185 - x)/0.907832))" cout<<gumbel<<endl; TEST_EQUAL(gumbel.hasSubstring("(1/0.90"), true) TEST_EQUAL(gumbel.hasSubstring("exp(( 1.47"), true) TEST_EQUAL(gumbel.hasSubstring(") * exp(-exp(("), true) END_SECTION START_SECTION((const String getGaussGnuplotFormula(const GaussFitter::GaussFitResult& params) const)) String gauss = ptr->getGaussGnuplotFormula(ptr->getCorrectlyAssignedFitResult()); //g(x)=0.444131 * exp(-(x - 5.05539) ** 2 / 2 / (0.898253) ** 2) TEST_EQUAL(gauss.hasSubstring(" * exp(-(x - "), true) TEST_EQUAL(gauss.hasSubstring(") ** 2 / 2 / ("), true) TEST_EQUAL(gauss.hasSubstring(") ** 2)"), true) END_SECTION START_SECTION(fitWithGumbel) { // ------- This code was used for the test file: ------------ // Use actual Gaussian data to see if fitting works //random_device device_random_; //default_random_engine generator_(device_random_()); // Gaussian mean and SD, mixture of 2. //normal_distribution<> distribution_1_(1.5, 0.5); //normal_distribution<> distribution_2_(3.5, 1.0); // ---------------------------------------------------------- vector<double> rand_score_vector; CsvFile gauss_mix (OPENMS_GET_TEST_DATA_PATH("GumbelGaussMix_2_1D.csv")); StringList gauss_mix_strings; gauss_mix.getRow(0, gauss_mix_strings); // Load mixture of Gumbel and Gaussian (1D) from provided csv for (StringList::const_iterator it = gauss_mix_strings.begin(); it != gauss_mix_strings.end(); ++it) { if(!it->empty()) { rand_score_vector.push_back(it->toDouble()); } } TEST_EQUAL(rand_score_vector.size(),2000) // Class expects sorted scores sort(rand_score_vector.begin(), rand_score_vector.end()); vector<double> probabilities; Param param; param.setValue("number_of_bins", 10); param.setValue("incorrectly_assigned","Gumbel"); ptr->setParameters(param); ptr->fitGumbelGauss(rand_score_vector, "none"); double smallest = ptr->getSmallestScore(); TOLERANCE_ABSOLUTE(0.5) TEST_REAL_SIMILAR(ptr->getCorrectlyAssignedFitResult().x0 , 8.-smallest) TEST_REAL_SIMILAR(ptr->getCorrectlyAssignedFitResult().sigma, 3.5) TEST_REAL_SIMILAR(ptr->getIncorrectlyAssignedGumbelFitResult().a, 2.-smallest) TEST_REAL_SIMILAR(ptr->getIncorrectlyAssignedGumbelFitResult().b, .6) TEST_REAL_SIMILAR(ptr->getNegativePrior(), 0.6) TOLERANCE_ABSOLUTE(0.001) /*while(i < rand_score_vector.size() && j < rand_score_vector.size()) { cout<<"i: "<<rand_score_vector[i] << ", j: "<<rand_score_vector[j]<<endl; cout<<"pi:"<<probabilities[i] <<", j: "<<probabilities[j]<<endl; if(rand_score_vector[i] <= rand_score_vector[j]) { TEST_EQUAL(probabilities[i] >= probabilities[j],true) TEST_REAL_SIMILAR(ptr->computeProbability(rand_score_vector[i]), probabilities[i]) TEST_REAL_SIMILAR(ptr->computeProbability(rand_score_vector[j]), probabilities[j]) } else { TEST_EQUAL(probabilities[i] >= probabilities[j],true) TEST_REAL_SIMILAR(ptr->computeProbability(rand_score_vector[i]), probabilities[i]) TEST_REAL_SIMILAR(ptr->computeProbability(rand_score_vector[j]), probabilities[j]) } ++i; ++j; }*/ } END_SECTION START_SECTION((const String getBothGnuplotFormula(const GaussFitter::GaussFitResult& incorrect, const GaussFitter::GaussFitResult& correct) const)) NOT_TESTABLE delete ptr; END_SECTION START_SECTION((double computeProbability(double score))) NOT_TESTABLE //tested in fit END_SECTION START_SECTION((TextFile* InitPlots(std::vector<double> & x_scores))) NOT_TESTABLE //tested in fit END_SECTION START_SECTION((void plotTargetDecoyEstimation(std::vector<double> &target,std::vector<double> & decoy))) NOT_TESTABLE //not yet tested END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/NASequence_test.cpp
.cpp
26,907
848
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Samuel Wein $ // $Authors: Timo Sachsenberg, Samuel Wein $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/CHEMISTRY/NASequence.h> #include <iostream> #include <OpenMS/SYSTEM/StopWatch.h> #include <OpenMS/CHEMISTRY/Ribonucleotide.h> #include <OpenMS/CHEMISTRY/RibonucleotideDB.h> #include <unordered_set> #include <unordered_map> #include <functional> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(NASequence, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// NASequence* ptr = nullptr; NASequence* null_ptr = nullptr; RibonucleotideDB* db = RibonucleotideDB::getInstance(); START_SECTION((NASequence()=default)) { ptr = new NASequence(); TEST_NOT_EQUAL(ptr, null_ptr) TEST_EQUAL(ptr->getFivePrimeMod(), (void*) nullptr); TEST_EQUAL(ptr->getThreePrimeMod(), (void*) nullptr); TEST_EQUAL(ptr->size(), 0); delete ptr; } END_SECTION START_SECTION((NASequence(const NASequence&) = default)) { // test Copy Constructor NASequence aaa = NASequence::fromString("AAA"); NASequence aaa2(aaa); TEST_EQUAL(aaa.size(), 3); TEST_EQUAL(aaa2.size(), 3); TEST_EQUAL(aaa.operator==(aaa2), true); } END_SECTION START_SECTION((NASequence(NASequence&&) = default)) { // test Move constructor NASequence aaa(NASequence::fromString("AAA")); TEST_EQUAL(aaa.size(), 3); } END_SECTION START_SECTION((NASequence& operator=(const NASequence&)& = default)) { // test Copy Assignment NASequence aaa = NASequence::fromString("AAA"); NASequence c = NASequence::fromString("C"); c = aaa; TEST_EQUAL(aaa.size(), 3); TEST_EQUAL(c.size(), 3); TEST_EQUAL(aaa.operator==(c), true); } END_SECTION START_SECTION((NASequence& operator=(NASequence&&)& = default)) { // test Move Assignment NASequence c = NASequence::fromString("C"); c = NASequence::fromString("AAA"); TEST_EQUAL(c.size(), 3); } END_SECTION START_SECTION((NASequence(std::vector<const Ribonucleotide*> s, const RibonucleotideChainEnd* five_prime, const RibonucleotideChainEnd* three_prime))) { NASequence aaa = NASequence::fromString("AAA"); NASequence aaa2(aaa.getSequence(), nullptr, nullptr); TEST_EQUAL(aaa2.operator==(aaa), true); } END_SECTION START_SECTION((virtual ~NASequence()=default)) { NASequence* n = new NASequence(); delete(n); } END_SECTION START_SECTION((bool operator==(const NASequence& rhs) const)) { NASequence aaa = NASequence::fromString("AAA"); NASequence aaa2(aaa); TEST_EQUAL(aaa.operator==(aaa2), true); } END_SECTION START_SECTION((bool operator<(const NASequence& rhs) const)) { NASequence aaa = NASequence::fromString("AAA"); NASequence aaaa = NASequence::fromString("AAAA"); NASequence cccc = NASequence::fromString("CCCC"); TEST_EQUAL(aaa.operator<(aaaa), true); TEST_EQUAL(aaaa.operator<(aaa), false); TEST_EQUAL(aaaa.operator<(cccc), true); } END_SECTION START_SECTION((void setSequence(const std::vector<const Ribonucleotide*>& s))) { NASequence aaa = NASequence::fromString("AAA"); NASequence cccc = NASequence::fromString("CCCC"); aaa.setSequence(cccc.getSequence()); TEST_EQUAL(aaa.operator==(cccc), true); TEST_EQUAL(aaa.size(), 4); } END_SECTION START_SECTION((const std::vector<const Ribonucleotide*>& getSequence() const )) { // tested via (void setSequence(const std::vector< const Ribonucleotide * > &s)) TEST_EQUAL(true, true); } END_SECTION START_SECTION((std::vector<const Ribonucleotide*>& getSequence())) { // tested via (void setSequence(const std::vector< const Ribonucleotide * > &s)) TEST_EQUAL(true, true); } END_SECTION START_SECTION((void set(size_t index, const Ribonucleotide* r))) { NASequence aaaa = NASequence::fromString("AAAA"); NASequence cccc = NASequence::fromString("CCCC"); aaaa.set(2, cccc.get(2)); TEST_EQUAL(aaaa, NASequence::fromString("AACA")); } END_SECTION START_SECTION((const Ribonucleotide* get(size_t index))) { // tested via ((void set(size_t index, const Ribonucleotide *r))) TEST_EQUAL(true, true); } END_SECTION START_SECTION((const Ribonucleotide*& operator[](size_t index))) { NASequence aaa = NASequence::fromString("AAA"); const NASequence ggg = NASequence::fromString("GGG"); aaa[1] = ggg[2]; TEST_EQUAL(aaa, NASequence::fromString("AGA")); } END_SECTION START_SECTION((const Ribonucleotide*& operator[](size_t index) const )) { NASequence aaa = NASequence::fromString("AAA"); const NASequence ggg = NASequence::fromString("GGG"); aaa[1] = ggg[2]; TEST_EQUAL(aaa[1], ggg[0]); } END_SECTION START_SECTION((bool empty() const )) { NASequence aaa; TEST_EQUAL(aaa.empty(), true); } END_SECTION START_SECTION((size_t size() const )) { NASequence seq; TEST_EQUAL(seq.size(), 0); seq = NASequence::fromString("UGG"); TEST_EQUAL(seq.size(), 3); // don't count terminal phosphate in sequence length: seq = NASequence::fromString("pUGG"); TEST_EQUAL(seq.size(), 3); seq = NASequence::fromString("*UGG"); TEST_EQUAL(seq.size(), 3); seq = NASequence::fromString("UGGp"); TEST_EQUAL(seq.size(), 3); seq = NASequence::fromString("pUGGp"); TEST_EQUAL(seq.size(), 3); } END_SECTION START_SECTION((void clear())) { NASequence aaa = NASequence::fromString("AAA"); aaa.clear(); TEST_EQUAL(aaa.empty(), true); } END_SECTION START_SECTION((bool hasFivePrimeMod() const )) { NASequence aaa = NASequence::fromString("AAA"); TEST_EQUAL(aaa.hasFivePrimeMod(), false); aaa = NASequence::fromString("pAAA"); TEST_EQUAL(aaa.hasFivePrimeMod(), true); aaa = NASequence::fromString("*AAA"); TEST_EQUAL(aaa.hasFivePrimeMod(), true); } END_SECTION START_SECTION((void setFivePrimeMod(const RibonucleotideChainEnd* r))) { NASequence aaa = NASequence::fromString("AAA"); TEST_EQUAL(aaa.hasFivePrimeMod(), false); aaa.setFivePrimeMod(db->getRibonucleotide("pN")); // 5' phosphate TEST_EQUAL(aaa.hasFivePrimeMod(), true); TEST_EQUAL(aaa.getFivePrimeMod()->getCode(), "pN"); TEST_STRING_EQUAL(aaa.toString(), "[pN]AAA"); } END_SECTION START_SECTION((const RibonucleotideChainEnd* getFivePrimeMod() const)) { // tested via (const RibonucleotideChainEnd* getFivePrimeMod() const ) TEST_EQUAL(true, true); } END_SECTION START_SECTION((void setThreePrimeMod(const RibonucleotideChainEnd* r))) { NASequence aaa = NASequence::fromString("AAA"); TEST_EQUAL(aaa.hasThreePrimeMod(), false); aaa.setThreePrimeMod(db->getRibonucleotide("N2'3'cp")); TEST_EQUAL(aaa.hasThreePrimeMod(), true); TEST_EQUAL(aaa.getThreePrimeMod()->getCode(), "N2'3'cp"); TEST_STRING_EQUAL(aaa.toString(), "AAA[N2'3'cp]"); } END_SECTION START_SECTION((const RibonucleotideChainEnd* getThreePrimeMod() const)) { // tested via (void setThreePrimeMod(const RibonucleotideChainEnd* r)) NOT_TESTABLE } END_SECTION START_SECTION((bool hasThreePrimeMod() const)) { // tested via (void setThreePrimeMod(const RibonucleotideChainEnd* r)) NOT_TESTABLE } END_SECTION START_SECTION((EmpiricalFormula getFormula(NASequence::NASFragmentType type = NASequence::Full, Int charge = 0) const)) { NASequence seq = NASequence::fromString("GG"); TEST_EQUAL(seq.getFormula(NASequence::Full, -1), EmpiricalFormula("C10H12N5O7P") + EmpiricalFormula("C10H12N5O5")); TEST_EQUAL(seq.getFormula(NASequence::Full, -2), EmpiricalFormula("C10H12N5O7P") + EmpiricalFormula("C10H11N5O5")); TEST_EQUAL(seq.getFormula(NASequence::WIon, -1), EmpiricalFormula("C20H25N10O15P2")); TEST_EQUAL(seq.getFormula(NASequence::XIon, -1), EmpiricalFormula("C20H23N10O14P2")); TEST_EQUAL(seq.getFormula(NASequence::YIon, -1), EmpiricalFormula("C10H12N5O6P") + EmpiricalFormula("C10H12N5O6")); TEST_EQUAL(seq.getFormula(NASequence::ZIon, -1), EmpiricalFormula("C20H22N10O11P")); TEST_EQUAL(seq.getFormula(NASequence::AIon, -1), EmpiricalFormula("C10H12N5O7P") + EmpiricalFormula("C10H10N5O4")); TEST_EQUAL(seq.getFormula(NASequence::BIon, -1), EmpiricalFormula("C10H12N5O7P") + EmpiricalFormula("C10H12N5O5")); TEST_EQUAL(seq.getFormula(NASequence::CIon, -1), EmpiricalFormula("C10H12N5O7P") + EmpiricalFormula("C10H11N5O7P")); TEST_EQUAL(seq.getFormula(NASequence::DIon, -1), EmpiricalFormula("C10H12N5O7P") + EmpiricalFormula("C10H13N5O8P")); TEST_EQUAL(seq.getFormula(NASequence::AminusB, -1), EmpiricalFormula("C10H12N5O7P") + EmpiricalFormula("C5H5O3")); // Thiol stuff NASequence thiolseq = NASequence::fromString("*[dA*][dA]"); TEST_EQUAL(thiolseq.getFormula(NASequence::WIon, -1), EmpiricalFormula("C20H25N10O9P2S2")); TEST_EQUAL(thiolseq.getFormula(NASequence::YIon, -1), EmpiricalFormula("C20H24N10O7P1S1")); // Test for a-B ions thiolseq = NASequence::fromString("[dA][dA*]"); TEST_EQUAL(thiolseq.getFormula(NASequence::AminusB, 0), EmpiricalFormula("C15H18N5O7P1")); thiolseq = NASequence::fromString("[dA][dA*][dA*]"); TEST_EQUAL(thiolseq.getFormula(NASequence::AminusB, 0), EmpiricalFormula("C25H30N10O11P2S1")); } END_SECTION START_SECTION((double getMonoWeight(NASequence::NASFragmentType type = NASequence::Full, Int charge = 0) const)) { // masses from Mongo-Oligo (http://mods.rna.albany.edu/masspec/Mongo-Oligo): NASequence seq = NASequence::fromString("GGG"); TEST_REAL_SIMILAR(seq.getMonoWeight(NASequence::AminusB, -1), 803.117); TEST_REAL_SIMILAR(seq.getMonoWeight(NASequence::WIon, -1), 1052.143); TEST_REAL_SIMILAR(seq.getMonoWeight(NASequence::YIon, -1), 972.177); // Mongo-Oligo calls this ion "d-H20": TEST_REAL_SIMILAR(seq.getMonoWeight(NASequence::CIon, -1), 1034.133); TEST_REAL_SIMILAR(seq.getMonoWeight(NASequence::AminusB, -2), 802.117); NASequence seq_not_sym = NASequence::fromString("GAU"); TEST_REAL_SIMILAR(seq_not_sym.getMonoWeight(NASequence::AminusB, -1), 787.122); seq = NASequence::fromString("AAUC"); TEST_REAL_SIMILAR(seq.getMonoWeight(NASequence::AminusB, -1), 1077.1548); TEST_REAL_SIMILAR(seq.getMonoWeight(NASequence::CIon, -1), 1268.1644); seq = NASequence::fromString("AUCGp"); TEST_REAL_SIMILAR(seq.getMonoWeight(NASequence::WIon, -1), 1382.1362); TEST_REAL_SIMILAR(seq.getMonoWeight(NASequence::YIon, -1), 1302.1698); seq = NASequence::fromString("[m1A]UCCACA"); TEST_REAL_SIMILAR(seq.getMonoWeight(NASequence::AminusB, -1), 2006.2943); TEST_REAL_SIMILAR(seq.getMonoWeight(NASequence::CIon, -1), 2221.3151); seq = NASequence::fromString("UCCACAGp"); TEST_REAL_SIMILAR(seq.getMonoWeight(NASequence::WIon, -1), 2321.2713); TEST_REAL_SIMILAR(seq.getMonoWeight(NASequence::YIon, -1), 2241.3049); // these masses were checked against external tools: seq = NASequence::fromString("pAAUCCAUGp"); TEST_REAL_SIMILAR(seq.getMonoWeight(NASequence::Full, 0), 2652.312); seq = NASequence::fromString("ACCAAAGp"); TEST_REAL_SIMILAR(seq.getMonoWeight(NASequence::Full, 0), 2289.348); seq = NASequence::fromString("AUUCACCC"); TEST_REAL_SIMILAR(seq.getMonoWeight(NASequence::Full, 0), 2428.362); // with charge (negative!): seq = NASequence::fromString("AAU[m5C]Gp"); TEST_REAL_SIMILAR(seq.getMonoWeight(NASequence::Full, -2), 1644.228); } END_SECTION START_SECTION((double getAverageWeight(NASequence::NASFragmentType type = NASequence::Full, Int charge = 0) const)) { // data from RNAModMapper publication (Yu et al., Anal. Chem. 2017), Fig. 4: NASequence seq = NASequence::fromString("A[ms2i6A]AACCGp"); TEST_REAL_SIMILAR(seq.getAverageWeight(NASequence::Full, -2) / 2, 1201.3); seq = NASequence::fromString("A[ms2i6A]AACC"); TEST_REAL_SIMILAR(seq.getAverageWeight(NASequence::AminusB, -1), 1848.587 + 0.734); TEST_REAL_SIMILAR(seq.getAverageWeight(NASequence::CIon, -2) / 2, 1020.023 - 0.324); seq = NASequence::fromString("[ms2i6A]AACCGp"); TEST_REAL_SIMILAR(seq.getAverageWeight(NASequence::WIon, -2) / 2, 1076.045 + 0.651); TEST_REAL_SIMILAR(seq.getAverageWeight(NASequence::YIon, -2) / 2, 1036.459 + 0.247); } END_SECTION START_SECTION((static NASequence fromString(const String& s))) { NASequence seq = NASequence::fromString(String("CUA")); TEST_STRING_EQUAL(seq.toString(), "CUA"); } END_SECTION START_SECTION((static NASequence fromString(const char* s))) { NASequence seq = NASequence::fromString("GG"); TEST_STRING_EQUAL(seq.toString(), "GG"); } END_SECTION START_SECTION((string toString())) { NASequence seq = NASequence::fromString("GG"); TEST_STRING_EQUAL(seq.toString(), "GG"); // Test that all the entries in the Mod file work can be parsed from strings for(auto it = db->begin(); it != db->end(); ++it) { if ((*it)->getCode() != "c") // handle the phosphates and cyclophosphates separately, we pass on them for now { continue; } else if((*it)->getCode() != "p") { continue; } else { //check that we can get the code from the entry, then convert it to a string and back auto ribocode = NASequence().fromString("[" + (*it)->getCode() + "]"); // get the code, which may or may not have brackets String asString = ribocode.toString(); if (asString.hasPrefix("[")) // if we were multicharacter toString adds brackets { asString = asString.substr(1, asString.size() - 2); } TEST_STRING_EQUAL(asString, (*it)->getCode()); } } } END_SECTION START_SECTION((NASequence getPrefix(Size length) const)) { NASequence seq = NASequence::fromString("A[ms2i6A]AACCGp"); NASequence seq2 = NASequence::fromString("A[ms2i6A]"); NASequence seq3 = NASequence::fromString("AAACCG"); NASequence seq4 = NASequence::fromString("AAA"); TEST_EQUAL(seq.getPrefix(2),seq2); TEST_EQUAL(seq3.getPrefix(3),seq4); TEST_NOT_EQUAL(seq.getPrefix(3),seq2); TEST_NOT_EQUAL(seq.getPrefix(3),seq4); TEST_EXCEPTION(Exception::IndexOverflow, seq.getPrefix(10)); } END_SECTION START_SECTION((NASequence getSuffix(Size length) const)) { NASequence seq = NASequence::fromString("A[ms2i6A]AACAGp"); NASequence seq2 = NASequence::fromString("[ms2i6A]AACAGp"); NASequence seq3 = NASequence::fromString("AAACAG"); NASequence seq4 = NASequence::fromString("CAG"); NASequence seq5 = NASequence::fromString("[C*]AG"); NASequence seq6 = NASequence::fromString("*AG"); TEST_EQUAL(seq.getSuffix(6),seq2); TEST_EQUAL(seq3.getSuffix(3),seq4); TEST_NOT_EQUAL(seq.getSuffix(3),seq2); TEST_NOT_EQUAL(seq.getSuffix(3),seq4); TEST_EXCEPTION(Exception::IndexOverflow, seq.getSuffix(10)); // Check that we handle the weird case of thiol TEST_STRING_EQUAL(seq5.getSuffix(2).toString(), seq6.toString() ); } END_SECTION START_SECTION((NASequence getSubsequence(Size start, Size length) const)) { NASequence seq = NASequence::fromString("pAUCGp"); NASequence seq5 = NASequence::fromString("[C*]AG"); TEST_STRING_EQUAL(seq.getSubsequence().toString(), "pAUCGp"); TEST_STRING_EQUAL(seq.getSubsequence(1).toString(), "UCGp"); TEST_STRING_EQUAL(seq.getSubsequence(0, 2).toString(), "pAU"); TEST_STRING_EQUAL(seq.getSubsequence(2, 1).toString(), "C"); //thiol stuff TEST_STRING_EQUAL(seq5.getSubsequence(1).toString(), "*AG"); } END_SECTION START_SECTION((Iterator begin())) { String result[] = {"A","U","C","G"}; NASequence seq = NASequence::fromString("AUCG"); Size i=0; for (NASequence::Iterator it = seq.begin(); it != seq.end(); ++it, ++i) { TEST_EQUAL((*it).getCode(), result[i]); } } END_SECTION START_SECTION((ConstIterator begin() const)) { String result[] = {"A","U","C","G"}; NASequence seq = NASequence::fromString("AUCG"); Size i=0; for (NASequence::ConstIterator it = seq.begin(); it != seq.end(); ++it, ++i) { TEST_EQUAL((*it).getCode(), result[i]); } } END_SECTION START_SECTION((Iterator end())) { String result[] = {"A","U","C","G"}; NASequence seq = NASequence::fromString("AUCG"); Size i=0; for (NASequence::Iterator it = seq.begin(); it != seq.end(); ++it, ++i) { TEST_EQUAL((*it).getCode(), result[i]); } } END_SECTION START_SECTION((ConstIterator end() const)) { String result[] = {"A","U","C","G"}; NASequence seq = NASequence::fromString("AUCG"); Size i=0; for (NASequence::ConstIterator it = seq.begin(); it != seq.end(); ++it, ++i) { TEST_EQUAL((*it).getCode(), result[i]); } } END_SECTION START_SECTION((ConstIterator cbegin() const)) { String result[] = {"A","U","C","G"}; NASequence seq = NASequence::fromString("AUCG"); Size i=0; for (NASequence::ConstIterator it = seq.cbegin(); it != seq.cend(); ++it, ++i) { TEST_EQUAL((*it).getCode(), result[i]); } } END_SECTION START_SECTION((ConstIterator cend() const)) { String result[] = {"A","U","C","G"}; NASequence seq = NASequence::fromString("AUCG"); Size i=0; for (NASequence::ConstIterator it = seq.cbegin(); it != seq.cend(); ++it, ++i) { TEST_EQUAL((*it).getCode(), result[i]); } } END_SECTION START_SECTION(([NASequence::ConstIterator] ConstIterator() = default)) { NASequence::ConstIterator iter = NASequence::ConstIterator(); // fails if it segfault NOT_TESTABLE } END_SECTION START_SECTION(([NASequence::ConstIterator] ConstIterator(const std::vector<const Ribonucleotide*>* vec_ptr, difference_type position))) { NASequence seq = NASequence::fromString("AUCG"); NASequence::ConstIterator it = seq.cbegin(); TEST_EQUAL((*(it+2)).getCode(), "C"); } END_SECTION START_SECTION(([NASequence::ConstIterator] ConstIterator(const ConstIterator& rhs))) { // TODO } END_SECTION START_SECTION(([NASequence::ConstIterator] ConstIterator(const NASequence::Iterator& rhs))) { NOT_TESTABLE } END_SECTION START_SECTION(([NASequence::ConstIterator] virtual ~ConstIterator())) { NASequence::ConstIterator* ptr = new NASequence::ConstIterator(); delete ptr; } END_SECTION START_SECTION(([NASequence::ConstIterator] const_reference operator*() const)) { String result[] = {"A","U","C","G"}; NASequence seq = NASequence::fromString("AUCG"); Size i=0; for (NASequence::ConstIterator it = seq.cbegin(); it != seq.cend(); ++it, ++i) { TEST_EQUAL((*it).getCode(), result[i]); } } END_SECTION START_SECTION(([NASequence::ConstIterator] const_pointer operator->() const)) { NOT_TESTABLE } END_SECTION START_SECTION(([NASequence::ConstIterator] const ConstIterator operator+(difference_type diff) const)) { NASequence seq = NASequence::fromString("AUCG"); NASequence::ConstIterator it = seq.begin(); TEST_EQUAL((*(it+2)).getCode(), "C"); } END_SECTION START_SECTION(([NASequence::ConstIterator] difference_type operator-(ConstIterator rhs) const)) { // TODO } END_SECTION START_SECTION(([NASequence::ConstIterator] const ConstIterator operator-(difference_type diff) const)) { NASequence seq = NASequence::fromString("AUCG"); NASequence::ConstIterator it = seq.end(); TEST_EQUAL((*(it-2)).getCode(), "C"); } END_SECTION START_SECTION(([NASequence::ConstIterator] bool operator==(const ConstIterator &rhs) const)) { NASequence seq = NASequence::fromString("AUCG"); NASequence::ConstIterator it = seq.end(); TEST_EQUAL((it-4 == seq.begin()), true); } END_SECTION START_SECTION(([NASequence::ConstIterator] bool operator!=(const ConstIterator &rhs) const)) { String result[] = {"A","U","C","G"}; NASequence seq = NASequence::fromString("AUCG"); Size i=0; for (NASequence::ConstIterator it = seq.cbegin(); it != seq.cend(); ++it, ++i) { TEST_EQUAL((*it).getCode(), result[i]); } } END_SECTION START_SECTION(([NASequence::ConstIterator] ConstIterator& operator++())) { String result[] = {"A","U","C","G"}; NASequence seq = NASequence::fromString("AUCG"); Size i=0; for (NASequence::ConstIterator it = seq.cbegin(); it != seq.cend(); ++it, ++i) { TEST_EQUAL((*it).getCode(), result[i]); } } END_SECTION START_SECTION(([NASequence::ConstIterator] ConstIterator& operator--())) { String result[] = {"A","U","C","G"}; NASequence seq = NASequence::fromString("AUCG"); Size i=3; for (NASequence::ConstIterator it = seq.end()-1; it != seq.begin(); --it, --i) { TEST_EQUAL((*it).getCode(), result[i]); } } END_SECTION START_SECTION(([NASequence::ConstIterator] ConstIterator& operator=(const ConstIterator& rhs))) { String result[] = {"A","U","C","G"}; NASequence seq = NASequence::fromString("AUCG"); Size i=0; for (NASequence::ConstIterator it = seq.cbegin(); it != seq.cend(); ++it, ++i) { TEST_EQUAL((*it).getCode(), result[i]); } } END_SECTION START_SECTION(([NASequence::Iterator] Iterator()=default)) { NASequence::Iterator iter= NASequence::Iterator(); NOT_TESTABLE } END_SECTION START_SECTION(([NASequence::Iterator] Iterator(std::vector<const Ribonucleotide*>* vec_ptr, difference_type position))) { NASequence seq = NASequence::fromString("AUCG"); NASequence::Iterator it = seq.begin(); TEST_EQUAL((*(it+2)).getCode(), "C"); } END_SECTION START_SECTION(([NASequence::Iterator] Iterator(const Iterator& rhs))) { NOT_TESTABLE } END_SECTION START_SECTION(([NASequence::Iterator] virtual ~Iterator())) { NASequence::Iterator* ptr = new NASequence::Iterator(); delete ptr; } END_SECTION START_SECTION(([NASequence::Iterator] const_reference operator*() const)) { String result[] = {"A","U","C","G"}; NASequence seq = NASequence::fromString("AUCG"); Size i=0; for (NASequence::Iterator it = seq.begin(); it != seq.end(); ++it, ++i) { TEST_EQUAL((*it).getCode(), result[i]); } } END_SECTION START_SECTION(([NASequence::Iterator] const_pointer operator->() const)) { NOT_TESTABLE } END_SECTION START_SECTION(([NASequence::Iterator] pointer operator->())) { NOT_TESTABLE } END_SECTION START_SECTION(([NASequence::Iterator] const Iterator operator+(difference_type diff) const)) { NASequence seq = NASequence::fromString("AUCG"); NASequence::Iterator it = seq.begin(); TEST_EQUAL((*(it+2)).getCode(), "C"); } END_SECTION START_SECTION(([NASequence::Iterator] difference_type operator-(Iterator rhs) const)) { //TODO } END_SECTION START_SECTION(([NASequence::Iterator] const Iterator operator-(difference_type diff) const)) { NASequence seq = NASequence::fromString("AUCG"); NASequence::Iterator it = seq.end(); TEST_EQUAL((*(it-2)).getCode(), "C"); } END_SECTION START_SECTION(([NASequence::Iterator] bool operator==(const Iterator& rhs) const)) { NASequence seq = NASequence::fromString("AUCG"); NASequence::Iterator it = seq.end(); TEST_EQUAL((it-4 == seq.begin()), true); } END_SECTION START_SECTION(([NASequence::Iterator] bool operator!=(const Iterator& rhs) const)) { String result[] = {"A","U","C","G"}; NASequence seq = NASequence::fromString("AUCG"); Size i=0; for (NASequence::Iterator it = seq.begin(); it != seq.end(); ++it, ++i) { TEST_EQUAL((*it).getCode(), result[i]); } } END_SECTION START_SECTION(([NASequence::Iterator] Iterator& operator++())) { String result[] = {"A","U","C","G"}; NASequence seq = NASequence::fromString("AUCG"); Size i=0; for (NASequence::Iterator it = seq.begin(); it != seq.end(); ++it, ++i) { TEST_EQUAL((*it).getCode(), result[i]); } } END_SECTION START_SECTION(([NASequence::Iterator] Iterator& operator--())) { String result[] = {"A","U","C","G"}; NASequence seq = NASequence::fromString("AUCG"); Size i=3; for (NASequence::Iterator it = seq.end()-1; it != seq.begin(); --it, --i) { TEST_EQUAL((*it).getCode(), result[i]); } } END_SECTION START_SECTION(([NASequence::Iterator] Iterator& operator=(const Iterator& rhs))) { String result[] = {"A","U","C","G"}; NASequence seq = NASequence::fromString("AUCG"); Size i=0; for (NASequence::Iterator it = seq.begin(); it != seq.end(); ++it, ++i) { TEST_EQUAL((*it).getCode(), result[i]); } } END_SECTION START_SECTION(([EXTRA] std::hash<NASequence>)) { // Test that equal sequences have equal hashes NASequence seq1 = NASequence::fromString("AUCG"); NASequence seq2 = NASequence::fromString("AUCG"); std::hash<NASequence> hasher; TEST_EQUAL(hasher(seq1), hasher(seq2)) // Test that different sequences have different hashes NASequence seq3 = NASequence::fromString("AUCGA"); TEST_NOT_EQUAL(hasher(seq1), hasher(seq3)) // Test sequences with modifications NASequence seq4 = NASequence::fromString("A[m1A]UCG"); NASequence seq5 = NASequence::fromString("A[m1A]UCG"); NASequence seq6 = NASequence::fromString("AAUCG"); // Same length, different sequence (no modification) TEST_EQUAL(hasher(seq4), hasher(seq5)) TEST_NOT_EQUAL(hasher(seq4), hasher(seq6)) // Modification matters // Test 5' terminal modifications NASequence seq7 = NASequence::fromString("pAUCG"); NASequence seq8 = NASequence::fromString("pAUCG"); NASequence seq9 = NASequence::fromString("AUCG"); // No 5' mod TEST_EQUAL(hasher(seq7), hasher(seq8)) TEST_NOT_EQUAL(hasher(seq7), hasher(seq9)) // 5' mod matters // Test 3' terminal modifications NASequence seq10 = NASequence::fromString("AUCGp"); NASequence seq11 = NASequence::fromString("AUCGp"); NASequence seq12 = NASequence::fromString("AUCG"); // No 3' mod TEST_EQUAL(hasher(seq10), hasher(seq11)) TEST_NOT_EQUAL(hasher(seq10), hasher(seq12)) // 3' mod matters // Test both terminal modifications NASequence seq13 = NASequence::fromString("pAUCGp"); NASequence seq14 = NASequence::fromString("pAUCGp"); TEST_EQUAL(hasher(seq13), hasher(seq14)) TEST_NOT_EQUAL(hasher(seq13), hasher(seq7)) // Different 3' mod TEST_NOT_EQUAL(hasher(seq13), hasher(seq10)) // Different 5' mod // Test empty sequence NASequence seq_empty1; NASequence seq_empty2; TEST_EQUAL(hasher(seq_empty1), hasher(seq_empty2)) // Test that sequences work in unordered_set std::unordered_set<NASequence> seq_set; seq_set.insert(seq1); seq_set.insert(seq2); // Duplicate, should not increase size seq_set.insert(seq3); // Different sequence seq_set.insert(seq4); // With modification seq_set.insert(seq7); // With 5' mod TEST_EQUAL(seq_set.size(), 4) TEST_EQUAL(seq_set.count(seq1), 1) TEST_EQUAL(seq_set.count(NASequence::fromString("AUCG")), 1) TEST_EQUAL(seq_set.count(seq3), 1) TEST_EQUAL(seq_set.count(seq4), 1) TEST_EQUAL(seq_set.count(seq7), 1) // Test that sequences work in unordered_map std::unordered_map<NASequence, int> seq_map; seq_map[seq1] = 1; seq_map[seq3] = 2; seq_map[seq7] = 3; TEST_EQUAL(seq_map.size(), 3) TEST_EQUAL(seq_map[NASequence::fromString("AUCG")], 1) TEST_EQUAL(seq_map[NASequence::fromString("AUCGA")], 2) TEST_EQUAL(seq_map[NASequence::fromString("pAUCG")], 3) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/MorphologicalFilter_test.cpp
.cpp
22,268
680
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/PROCESSING/BASELINE/MorphologicalFilter.h> #include <OpenMS/KERNEL/MSExperiment.h> #include <OpenMS/KERNEL/Peak2D.h> #include <fstream> /////////////////////////// namespace OpenMS { template < typename ValueT > struct SimpleTopHat { static void erosion( const std::vector<ValueT> & input, std::vector<ValueT> & output, const UInt struc_elem_length ) { const Int size = Int(input.size()); const Int struc_elem_half = struc_elem_length / 2; // yes integer division output.clear(); output.resize(size); for ( Int index = 0; index < size; ++ index ) { Int begin = std::max( 0, index - struc_elem_half ); Int end = std::min( size - 1, index + struc_elem_half ); ValueT value = std::numeric_limits<ValueT>::max(); for ( Int i = begin; i <= end; ++i ) { if ( value > input[i] ) value = input[i]; } output[index] = value; } return; } static void dilation( const std::vector<ValueT> & input, std::vector<ValueT> & output, const UInt struc_elem_length ) { const Int size = Int(input.size()); const Int struc_elem_half = struc_elem_length / 2; // yes integer division output.clear(); output.resize(size); for ( Int index = 0; index < size; ++ index ) { Int begin = std::max( 0, index - struc_elem_half ); Int end = std::min( size - 1, index + struc_elem_half ); ValueT value = - std::numeric_limits<ValueT>::max(); for ( Int i = begin; i <= end; ++i ) { if ( value < input[i] ) value = input[i]; } output[index] = value; } return; } static void gradient( const std::vector<ValueT> & input, std::vector<ValueT> & output, const UInt struc_elem_length ) { const Int size = Int(input.size()); output.clear(); output.resize(size); std::vector<ValueT> dilation; std::vector<ValueT> erosion; SimpleTopHat::erosion(input,erosion,struc_elem_length); SimpleTopHat::dilation(input,dilation,struc_elem_length); for ( Int index = 0; index < size; ++ index ) { output[index] = dilation[index] - erosion[index]; } return; } static void tophat( const std::vector<ValueT> & input, std::vector<ValueT> & output, const UInt struc_elem_length ) { const Int size = Int(input.size()); std::vector<ValueT> opening; erosion(input,output,struc_elem_length); dilation(output,opening,struc_elem_length); for ( Int index = 0; index < size; ++ index ) { output[index] = input[index] - opening[index]; } return; } static void bothat( const std::vector<ValueT> & input, std::vector<ValueT> & output, const UInt struc_elem_length ) { const Int size = Int(input.size()); std::vector<ValueT> closing; dilation(input,output,struc_elem_length); erosion(output,closing,struc_elem_length); for ( Int index = 0; index < size; ++ index ) { output[index] = input[index] - closing[index]; } return; } }; } /////////////////////////// START_TEST(MorphologicalFilter, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using namespace OpenMS; Int data[] = { 1, 2, 3, -2, 0, 1, 0, 0, 0, 1, 1, 1, 4, 5, 6, 4, 3, 2, 2, 5, 5, 6, 6, 1, 0, 0, -1, 0, 0, 3, -2, -3, -1, 1, 1, 1, 1, 4, 6, 2 }; const UInt data_size = sizeof(data)/sizeof(*data); UInt struc_elem_length = 3; typedef SimpleTopHat<Int> STH; std::vector<Int> input; input.reserve(data_size); for ( UInt i = 0; i != data_size; ++i ) input.push_back(data[i]); std::vector<Int> erosion; STH::erosion(input,erosion,struc_elem_length); std::vector<Int> dilation; STH::dilation(input,dilation,struc_elem_length); std::vector<Int> gradient; STH::gradient(input,gradient,struc_elem_length); std::vector<Int> opening; STH::dilation(erosion,opening,struc_elem_length); std::vector<Int> closing; STH::erosion(dilation,closing,struc_elem_length); std::vector<Int> tophat; STH::tophat(input,tophat,struc_elem_length); std::vector<Int> bothat; STH::bothat(input,bothat,struc_elem_length); START_SECTION(([EXTRA] "struct SimpleTopHat, used as reference implementation")) { std::string tmpfn; NEW_TMP_FILE(tmpfn); std::ofstream tmpf(tmpfn.c_str()); // Using a bit of macro magic to ensure that header and numbers are always in sync (gnuplot etc.) #ifdef SIMPLETOPHATTABLE #error "SIMPLETOPHATTABLE already #defined, oops!" #endif #ifdef EnTrY #error "EnTrY already #defined, oops!" #endif #define SIMPLETOPHATTABLE EnTrYfAt(input,1) EnTrY(erosion,2) EnTrY(opening,3) EnTrY(dilation,4) EnTrY(closing,5) EnTrY(gradient,6) EnTrY(tophat,7) EnTrY(bothat,8) #define EnTrY(a,b) " "#a #define EnTrYfAt(a,b) EnTrY(a,b) tmpf << "#" SIMPLETOPHATTABLE << std::endl; #undef EnTrY #undef EnTrYfAt #define EnTrY(a,b) a[i] << " " << #define EnTrYfAt(a,b) EnTrY(a,b) for ( UInt i = 0; i != data_size; ++i ) tmpf << SIMPLETOPHATTABLE std::endl; tmpf.close(); #undef EnTrY #undef EnTrYfAt TEST_FILE_EQUAL(tmpfn.c_str(),OPENMS_GET_TEST_DATA_PATH("MorphologicalFilter_test_1.txt")); // Documentation in MorphologicalFilter uses the following gnuplot script // set terminal png // set key outside reverse Left width 2 #define EnTrY(a,b) ", '" << tmpfn << "' using "#b" w l lw 4 lt " << b << " title '"#a"'" #define EnTrYfAt(a,b) ", '" << tmpfn << "' using "#b" w l lw 10 lt " << b << " title '"#a"'" std::string tmpfn2; NEW_TMP_FILE(tmpfn2); tmpf.open(tmpfn2.c_str()); tmpf << "set title 'morphological filtering operations (width of structuring element: " << struc_elem_length << ")'\n"; tmpf << "set key outside reverse Left width 2\n"; tmpf << "set output '" << tmpfn2 << ".png'\n"; tmpf << "set terminal png size 1000,400\n"; tmpf << "plot [] [-5:10] 0" SIMPLETOPHATTABLE "\n"; tmpf.close(); // Documentation in MorphologicalFilter uses the following gnuplot script #undef SIMPLETOPHATTABLE #define SIMPLETOPHATTABLE EnTrYfAt(input,1) EnTrY(erosion,2) EnTrY(opening,3) /*EnTrY(dilation,4)*/ /*EnTrY(closing,5)*/ /*EnTrY(gradient,6)*/ EnTrY(tophat,7) /*EnTrY(bothat,8)*/ NEW_TMP_FILE(tmpfn2); tmpf.open(tmpfn2.c_str()); tmpf << "set title 'morphological filtering operations (width of structuring element: " << struc_elem_length << ")'\n"; tmpf << "set key outside reverse Left width 2\n"; tmpf << "set output '" << tmpfn2 << ".png'\n"; tmpf << "set terminal png size 1000,400\n"; tmpf << "plot [] [-5:10] 0" SIMPLETOPHATTABLE "\n"; tmpf.close(); #undef EnTrY #undef EnTrYfAt #undef SIMPLETOPHATTABLE } END_SECTION MorphologicalFilter* tophat_ptr = nullptr; MorphologicalFilter* tophat_nullPointer = nullptr; START_SECTION((MorphologicalFilter())) { tophat_ptr = new MorphologicalFilter; TEST_NOT_EQUAL(tophat_ptr, tophat_nullPointer); } END_SECTION START_SECTION((virtual ~MorphologicalFilter())) { delete tophat_ptr; } END_SECTION typedef SimpleTopHat<Peak1D::IntensityType> STHF; std::vector<Peak1D::IntensityType> inputf; inputf.reserve(data_size); for ( UInt i = 0; i != data_size; ++i ) inputf.push_back(data[i]); START_SECTION((template < typename InputIterator, typename OutputIterator > void filterRange( InputIterator input_begin, InputIterator input_end, OutputIterator output_begin))) { // This test uses increasing and decreasing sequences of numbers. This way // we are likely to catch all off-by-one errors. ;-) An [EXTRA] test // follows, which uses more realisic data. using Internal::intensityIteratorWrapper; for ( Int data_size = 0; data_size < 50; ++ data_size ) { Int offset = data_size / 2; std::vector<Peak1D> raw; raw.clear(); Peak1D peak; inputf.clear(); for ( Int i = 0; i != data_size; ++i ) { peak.setIntensity(i-offset); peak.setPos(i); raw.push_back(peak); inputf.push_back(i-offset); } std::vector<Peak1D::IntensityType> filtered; std::vector<Peak1D::IntensityType> simple_filtered_1; MorphologicalFilter mf; for ( Int struc_length = 3; struc_length <= 2 * data_size + 2; struc_length += 2 ) { //STATUS("data_size: " << data_size); //STATUS("struc_elem_length: " << struc_length); { //STATUS("erosion"); filtered.clear(); filtered.resize(data_size); simple_filtered_1.clear(); simple_filtered_1.resize(data_size); Param parameters; parameters.setValue("method","erosion"); parameters.setValue("struc_elem_length",(double)struc_length); mf.setParameters(parameters); mf.filterRange( intensityIteratorWrapper(raw.begin()), intensityIteratorWrapper(raw.end()), filtered.begin() ); STHF::erosion( inputf, simple_filtered_1, struc_length ); for ( Int i = 0; i != data_size; ++i ) { //STATUS(i); TEST_REAL_SIMILAR(filtered[i],simple_filtered_1[i]); } } { //STATUS("dilation"); filtered.clear(); filtered.resize(data_size); simple_filtered_1.clear(); simple_filtered_1.resize(data_size); Param parameters; parameters.setValue("method","dilation"); parameters.setValue("struc_elem_length",(double)struc_length); mf.setParameters(parameters); mf.filterRange( intensityIteratorWrapper(raw.begin()), intensityIteratorWrapper(raw.end()), filtered.begin() ); STHF::dilation( inputf, simple_filtered_1, struc_length ); for ( Int i = 0; i != data_size; ++i ) { //STATUS(i); TEST_REAL_SIMILAR(filtered[i],simple_filtered_1[i]); } } } } for ( Int data_size = 0; data_size < 50; ++ data_size ) { Int offset = data_size / 2; std::vector<Peak1D> raw; raw.clear(); Peak1D peak; inputf.clear(); for ( Int i = 0; i != data_size; ++i ) { peak.setIntensity(offset-i); peak.setPos(i); raw.push_back(peak); inputf.push_back(offset-i); } std::vector<Peak1D::IntensityType> filtered; std::vector<Peak1D::IntensityType> simple_filtered_1; MorphologicalFilter mf; for ( Int struc_length = 3; struc_length <= 2 * data_size + 2; struc_length += 2 ) { //STATUS("data_size: " << data_size); //STATUS("struc_elem_length: " << struc_length); { //STATUS("erosion"); filtered.clear(); filtered.resize(data_size); simple_filtered_1.clear(); simple_filtered_1.resize(data_size); Param parameters; parameters.setValue("method","erosion"); parameters.setValue("struc_elem_length",(double)struc_length); mf.setParameters(parameters); mf.filterRange( intensityIteratorWrapper(raw.begin()), intensityIteratorWrapper(raw.end()), filtered.begin() ); STHF::erosion( inputf, simple_filtered_1, struc_length ); for ( Int i = 0; i != data_size; ++i ) { //STATUS(i); TEST_REAL_SIMILAR(filtered[i],simple_filtered_1[i]); } } { //STATUS("dilation"); filtered.clear(); filtered.resize(data_size); simple_filtered_1.clear(); simple_filtered_1.resize(data_size); Param parameters; parameters.setValue("method","dilation"); parameters.setValue("struc_elem_length",(double)struc_length); mf.setParameters(parameters); mf.filterRange( intensityIteratorWrapper(raw.begin()), intensityIteratorWrapper(raw.end()), filtered.begin() ); STHF::dilation( inputf, simple_filtered_1, struc_length ); for ( Int i = 0; i != data_size; ++i ) { //STATUS(i); TEST_REAL_SIMILAR(filtered[i],simple_filtered_1[i]); } } } } } END_SECTION START_SECTION([EXTRA] (template < typename InputIterator, typename OutputIterator > void filterRange( InputIterator input_begin, InputIterator input_end, OutputIterator output_begin))) { using Internal::intensityIteratorWrapper; std::vector<Peak1D> raw; Peak1D peak; for ( UInt i = 0; i != data_size; ++i ) { peak.setIntensity(data[i]); peak.setPos(i); raw.push_back(peak); } inputf.clear(); for ( UInt i = 0; i != data_size; ++i ) inputf.push_back(data[i]); std::vector<Peak1D::IntensityType> filtered; std::vector<Peak1D::IntensityType> simple_filtered_1; std::vector<Peak1D::IntensityType> simple_filtered_2; std::vector<Peak1D::IntensityType> simple_filtered_3; MorphologicalFilter mf; for ( UInt struc_length = 3; struc_length <= 2 * data_size + 2; struc_length += 2 ) { //STATUS("struc_elem_length: " << struc_length); { //STATUS("erosion"); filtered.clear(); filtered.resize(data_size); simple_filtered_1.clear(); simple_filtered_1.resize(data_size); Param parameters; parameters.setValue("method","erosion"); parameters.setValue("struc_elem_length",(double)struc_length); mf.setParameters(parameters); mf.filterRange( intensityIteratorWrapper(raw.begin()), intensityIteratorWrapper(raw.end()), filtered.begin() ); STHF::erosion(inputf,simple_filtered_1,struc_length); for ( UInt i = 0; i != data_size; ++i ) { //STATUS(i); TEST_REAL_SIMILAR(filtered[i],simple_filtered_1[i]); } //STATUS("erosion_simple"); filtered.clear(); filtered.resize(data_size); simple_filtered_1.clear(); simple_filtered_1.resize(data_size); parameters.setValue("method","erosion_simple"); parameters.setValue("struc_elem_length",(double)struc_length); mf.setParameters(parameters); mf.filterRange( intensityIteratorWrapper(raw.begin()), intensityIteratorWrapper(raw.end()), filtered.begin() ); STHF::erosion(inputf,simple_filtered_1,struc_length); for ( UInt i = 0; i != data_size; ++i ) { TEST_REAL_SIMILAR(filtered[i],simple_filtered_1[i]); } //STATUS("opening"); filtered.clear(); filtered.resize(data_size); simple_filtered_2.clear(); simple_filtered_2.resize(data_size); parameters.setValue("method","opening"); parameters.setValue("struc_elem_length",(double)struc_length); mf.setParameters(parameters); mf.filterRange( intensityIteratorWrapper(raw.begin()), intensityIteratorWrapper(raw.end()), filtered.begin() ); STHF::dilation(simple_filtered_1,simple_filtered_2,struc_length); for ( UInt i = 0; i != data_size; ++i ) { TEST_REAL_SIMILAR(filtered[i],simple_filtered_2[i]); } //STATUS("tophat"); filtered.clear(); filtered.resize(data_size); simple_filtered_3.clear(); simple_filtered_3.resize(data_size); parameters.setValue("method","tophat"); parameters.setValue("struc_elem_length",(double)struc_length); mf.setParameters(parameters); mf.filterRange( intensityIteratorWrapper(raw.begin()), intensityIteratorWrapper(raw.end()), filtered.begin() ); STHF::tophat(inputf,simple_filtered_3,struc_length); for ( UInt i = 0; i != data_size; ++i ) { TEST_REAL_SIMILAR(filtered[i],simple_filtered_3[i]); } } { //STATUS("dilation"); filtered.clear(); filtered.resize(data_size); simple_filtered_1.clear(); simple_filtered_1.resize(data_size); Param parameters; parameters.setValue("method","dilation"); parameters.setValue("struc_elem_length",(double)struc_length); mf.setParameters(parameters); mf.filterRange( intensityIteratorWrapper(raw.begin()), intensityIteratorWrapper(raw.end()), filtered.begin() ); STHF::dilation(inputf,simple_filtered_1,struc_length); for ( UInt i = 0; i != data_size; ++i ) { TEST_REAL_SIMILAR(filtered[i],simple_filtered_1[i]); } //STATUS("dilation_simple"); filtered.clear(); filtered.resize(data_size); simple_filtered_1.clear(); simple_filtered_1.resize(data_size); parameters.setValue("method","dilation_simple"); parameters.setValue("struc_elem_length",(double)struc_length); mf.setParameters(parameters); mf.filterRange( intensityIteratorWrapper(raw.begin()), intensityIteratorWrapper(raw.end()), filtered.begin() ); STHF::dilation(inputf,simple_filtered_1,struc_length); for ( UInt i = 0; i != data_size; ++i ) { TEST_REAL_SIMILAR(filtered[i],simple_filtered_1[i]); } //STATUS("closing"); filtered.clear(); filtered.resize(data_size); simple_filtered_2.clear(); simple_filtered_2.resize(data_size); parameters.setValue("method","closing"); parameters.setValue("struc_elem_length",(double)struc_length); mf.setParameters(parameters); mf.filterRange( intensityIteratorWrapper(raw.begin()), intensityIteratorWrapper(raw.end()), filtered.begin() ); STHF::erosion(simple_filtered_1,simple_filtered_2,struc_length); for ( UInt i = 0; i != data_size; ++i ) { TEST_REAL_SIMILAR(filtered[i],simple_filtered_2[i]); } //STATUS("bothat"); filtered.clear(); filtered.resize(data_size); simple_filtered_3.clear(); simple_filtered_3.resize(data_size); parameters.setValue("method","bothat"); parameters.setValue("struc_elem_length",(double)struc_length); mf.setParameters(parameters); mf.filterRange( intensityIteratorWrapper(raw.begin()), intensityIteratorWrapper(raw.end()), filtered.begin() ); STHF::bothat(inputf,simple_filtered_3,struc_length); for ( UInt i = 0; i != data_size; ++i ) { TEST_REAL_SIMILAR(filtered[i],simple_filtered_3[i]); } } } } END_SECTION START_SECTION((template <typename PeakType> void filter(MSSpectrum& spectrum))) { MSSpectrum raw; Peak1D peak; double spacing = 0.25; for ( UInt i = 0; i < data_size; ++i ) { peak.setIntensity(data[i]); peak.setPos( double(i) * spacing ); raw.push_back(peak); } MorphologicalFilter mf; for ( double struc_size = .5; struc_size <= 2; struc_size += .1 ) { MSSpectrum filtered(raw); Param parameters; parameters.setValue("method","dilation"); parameters.setValue("struc_elem_length",(double)struc_size); parameters.setValue("struc_elem_unit","Thomson"); mf.setParameters(parameters); mf.filter(filtered); UInt struc_size_datapoints = UInt ( ceil ( struc_size / spacing ) ); if ( !Math::isOdd(struc_size_datapoints) ) ++struc_size_datapoints; STH::dilation( input, dilation, struc_size_datapoints ); //STATUS( "struc_size: " << struc_size << " struc_size_datapoints: " << struc_size_datapoints ); for ( UInt i = 0; i != data_size; ++i ) { STATUS("i: " << i); TEST_REAL_SIMILAR(filtered[i].getIntensity(),dilation[i]); } } } END_SECTION START_SECTION((template <typename PeakType > void filterExperiment(MSExperiment< PeakType > &exp))) { MSSpectrum raw; raw.setComment("Let's see if this comment is copied by the filter."); Peak1D peak; double spacing = 0.25; for ( UInt i = 0; i < data_size; ++i ) { peak.setIntensity(data[i]); peak.setPos( double(i) * spacing ); raw.push_back(peak); } MorphologicalFilter mf; for ( double struc_size = .5; struc_size <= 2; struc_size += .1 ) { PeakMap mse_raw; mse_raw.addSpectrum(raw); mse_raw.addSpectrum(raw); mse_raw.addSpectrum(raw); Param parameters; parameters.setValue("method","dilation"); parameters.setValue("struc_elem_length",(double)struc_size); parameters.setValue("struc_elem_unit","Thomson"); mf.setParameters(parameters); mf.filterExperiment( mse_raw ); TEST_EQUAL(mse_raw.size(),3); UInt struc_size_datapoints = UInt ( ceil ( struc_size / spacing ) ); if ( !Math::isOdd(struc_size_datapoints) ) ++struc_size_datapoints; STH::dilation( input, dilation, struc_size_datapoints ); //STATUS( "struc_size: " << struc_size << " struc_size_datapoints: " << struc_size_datapoints ); for ( UInt scan = 0; scan < 3; ++scan ) { TEST_STRING_EQUAL(mse_raw[scan].getComment(),"Let's see if this comment is copied by the filter."); for ( UInt i = 0; i != data_size; ++i ) { //STATUS("i: " << i); TEST_REAL_SIMILAR(mse_raw[scan][i].getIntensity(),dilation[i]); } } } } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/InterpolationModel_test.cpp
.cpp
6,530
270
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/FEATUREFINDER/InterpolationModel.h> #include <OpenMS/CONCEPT/Exception.h> /////////////////////////// using namespace OpenMS; class TestModel : public InterpolationModel { public: TestModel() : InterpolationModel() { setName("TestModel"); check_defaults_ = false; defaultsToParam_(); } TestModel(const TestModel& source) : InterpolationModel(source) { updateMembers_(); } ~TestModel() override { } virtual TestModel& operator = (const TestModel& source) { if (&source == this) return *this; InterpolationModel::operator = (source); updateMembers_(); return *this; } void updateMembers_() override { InterpolationModel::updateMembers_(); } IntensityType getIntensity(const PositionType& pos) const override { return pos[0]*3.0; } IntensityType getIntensity(CoordinateType coord) const { return coord*3.0; } bool isContained(const PositionType& pos) const override { return getIntensity(pos)>cut_off_; } void fillIntensity(PeakType& peak) const { peak.setIntensity(getIntensity(peak.getPosition())); } void getSamples(SamplesType& /*cont*/) const override { } void setSamples() override { } CoordinateType getCenter() const override { return 10.0; } }; START_TEST(InterpolationModel , "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// using std::stringstream; ////////////////////////////////////// // default ctor TestModel* ptr = nullptr; TestModel* nullPointer = nullptr; START_SECTION((InterpolationModel())) ptr = new TestModel(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION // destructor START_SECTION((virtual ~InterpolationModel())) delete ptr; END_SECTION // assignment operator START_SECTION((virtual InterpolationModel& operator=(const InterpolationModel &source))) TestModel tm1; TestModel tm2; tm1.setCutOff(3.3); tm2 = tm1; TEST_REAL_SIMILAR(tm1.getCutOff(),tm2.getCutOff()) TEST_REAL_SIMILAR(tm1.getScalingFactor(),tm2.getScalingFactor()) END_SECTION // copy constructor START_SECTION((InterpolationModel(const InterpolationModel &source))) TestModel fp1; fp1.setCutOff(0.1); TestModel fp2(fp1); TestModel fp3; fp3.setCutOff(0.1); fp1 = TestModel(); TEST_TRUE(fp2 == fp3) END_SECTION START_SECTION(([EXTRA]IntensityType getCutOff() const)) const TestModel s; TEST_REAL_SIMILAR(s.getCutOff(), TestModel::IntensityType(0)) END_SECTION START_SECTION(([EXTRA]void setCutOff(IntensityType cut_off))) TestModel s; s.setCutOff(4.4); TEST_REAL_SIMILAR(s.getCutOff(), 4.4) END_SECTION START_SECTION(([EXTRA]const String& getName() const)) TestModel s; TEST_EQUAL(s.getName(), "TestModel") END_SECTION START_SECTION((IntensityType getIntensity(const PositionType& pos) const)) const TestModel s; TestModel::PositionType pos; pos[0]=0.1; TEST_REAL_SIMILAR(s.getIntensity(pos), 0.3) END_SECTION START_SECTION(([EXTRA]bool isContained(const PositionType& pos) const)) TestModel s; s.setCutOff(0.9); TestModel::PositionType pos; pos[0]=0.1; const TestModel& t = s; TEST_EQUAL(t.isContained(pos), false) END_SECTION START_SECTION(([EXTRA]void fillIntensity(PeakType& peak) const)) const TestModel t; TestModel::PeakType p; p.getPosition()[0]=0.1; p.setIntensity(0.1f); t.fillIntensity(p); TEST_REAL_SIMILAR(p.getIntensity(), 0.3) END_SECTION START_SECTION(([EXTRA]void fillIntensities(PeakIterator beg, PeakIterator end) const)) const TestModel t; std::vector< TestModel::PeakType > vec(4); for (Size i=0; i<4; ++i) { vec[i].setIntensity(-0.5); vec[i].getPosition()[0] = i; } t.fillIntensities(vec.begin()+1, vec.end()-1); TEST_EQUAL(vec[0].getIntensity(), -0.5) TEST_EQUAL(vec[1].getIntensity(), 3.0) TEST_EQUAL(vec[2].getIntensity(), 6.0) TEST_EQUAL(vec[3].getIntensity(), -0.5) END_SECTION START_SECTION( virtual CoordinateType getCenter() const) const TestModel t; TEST_REAL_SIMILAR(t.getCenter(),10.0); END_SECTION START_SECTION([EXTRA] DefaultParmHandler::setParameters(...)) Param p; p.setValue("cutoff",17.0); TestModel m; m.setParameters(p); TEST_REAL_SIMILAR(m.getParameters().getValue("cutoff"), 17.0) END_SECTION START_SECTION( void setScalingFactor(CoordinateType scaling) ) TestModel tm; tm.setScalingFactor(2.0); TEST_REAL_SIMILAR(tm.getParameters().getValue("intensity_scaling"),2.0) TEST_REAL_SIMILAR(tm.getScalingFactor(),2.0) END_SECTION START_SECTION( void setInterpolationStep(CoordinateType interpolation_step) ) TestModel tm; tm.setInterpolationStep( 10.5 ); TEST_REAL_SIMILAR(tm.getParameters().getValue("interpolation_step"), 10.5 ) END_SECTION START_SECTION( virtual void setSamples() ) // not much to be tested here END_SECTION START_SECTION( void getSamples(SamplesType &cont) const ) // not much to be tested here END_SECTION START_SECTION( virtual void setOffset(CoordinateType offset) ) END_SECTION START_SECTION( CoordinateType getScalingFactor() const ) TestModel tm; tm.setScalingFactor(666.0); TEST_REAL_SIMILAR(tm.getParameters().getValue("intensity_scaling"),666.0) TEST_REAL_SIMILAR(tm.getScalingFactor(),666.0) END_SECTION START_SECTION( const LinearInterpolation& getInterpolation() const ) TestModel tm; InterpolationModel::LinearInterpolation interpol1; InterpolationModel::LinearInterpolation interpol2 = tm.getInterpolation(); // compare models TEST_REAL_SIMILAR(interpol1.getScale(), interpol2.getScale()); TEST_REAL_SIMILAR(interpol1.getInsideReferencePoint(), interpol2.getInsideReferencePoint()); TEST_REAL_SIMILAR(interpol1.getOutsideReferencePoint(), interpol2.getOutsideReferencePoint() ); END_SECTION START_SECTION( IntensityType getIntensity(CoordinateType coord) const ) const TestModel s; TestModel::PositionType pos; pos[0]=0.1; TEST_REAL_SIMILAR(s.getIntensity(pos), 0.3) END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/FIAMSDataProcessor_test.cpp
.cpp
6,510
190
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg$ // $Authors: Svetlana Kutuzova, Douglas McCloskey $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/ANALYSIS/ID/FIAMSDataProcessor.h> #include <OpenMS/ANALYSIS/ID/AccurateMassSearchEngine.h> #include <OpenMS/FORMAT/MzTabFile.h> #include <OpenMS/FORMAT/MzMLFile.h> #include <OpenMS/PROCESSING/NOISEESTIMATION/SignalToNoiseEstimatorMedianRapid.h> #include <OpenMS/ANALYSIS/OPENSWATH/SpectrumAddition.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(FIAMSDataProcessor, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// FIAMSDataProcessor* ptr = nullptr; FIAMSDataProcessor* null_ptr = nullptr; START_SECTION(FIAMSDataProcessor()) { ptr = new FIAMSDataProcessor(); TEST_NOT_EQUAL(ptr, null_ptr); } END_SECTION START_SECTION(virtual ~FIAMSDataProcessor()) { delete ptr; } END_SECTION String filename = "SerumTest"; File::TempDir temp_dir; FIAMSDataProcessor fia_processor; Param p; p.setValue("filename", filename); p.setValue("dir_output", temp_dir.getPath()); p.setValue("resolution", 120000.0); p.setValue("polarity", "negative"); p.setValue("max_mz", 1500); p.setValue("bin_step", 20); p.setValue("db:mapping", std::vector<std::string>{OPENMS_GET_TEST_DATA_PATH("reducedHMDBMapping.tsv")}); p.setValue("db:struct", std::vector<std::string>{OPENMS_GET_TEST_DATA_PATH("reducedHMDB2StructMapping.tsv")}); p.setValue("positive_adducts", OPENMS_GET_TEST_DATA_PATH("FIAMS_negative_adducts.tsv")); p.setValue("negative_adducts", OPENMS_GET_TEST_DATA_PATH("FIAMS_positive_adducts.tsv")); fia_processor.setParameters(p); MSExperiment exp; MzMLFile mzml; mzml.load(String(OPENMS_GET_TEST_DATA_PATH("FIAMS_input")) + "/" + filename + ".mzML", exp); MSExperiment exp_merged; MzMLFile mzml_merged; mzml.load(String(OPENMS_GET_TEST_DATA_PATH("FIAMS_input")) + "/" + filename + "_merged.mzML", exp_merged); MSSpectrum spec_merged = exp_merged.getSpectra()[0]; MSExperiment exp_picked; MzMLFile mzml_picked; mzml.load(String(OPENMS_GET_TEST_DATA_PATH("FIAMS_input")) + "/" + filename + "_picked.mzML", exp_picked); MSSpectrum spec_picked = exp_picked.getSpectra()[0]; PeakMap input; Peak1D peak; std::vector<float> ints {100, 120, 130, 140, 150, 100, 60, 50, 30}; std::vector<float> rts {10, 20, 30, 40}; std::vector<MSSpectrum> spectra; for (Size i = 0; i < rts.size(); ++i) { MSSpectrum s; for (Size j = 0; j < ints.size(); ++j) { peak.setIntensity(ints[j]); peak.setMZ(100 + j*2); s.push_back(peak); } s.setRT(rts[i]); input.addSpectrum(s); spectra.push_back(s); } MSSpectrum merged = fia_processor.mergeAlongTime(spectra); START_SECTION((void cutForTime(const MSExperiment & experiment, vector<MSSpectrum> & output, float n_seconds))) { vector<MSSpectrum> output1; fia_processor.cutForTime(input, 0, output1); TEST_EQUAL(output1.size(), 0); vector<MSSpectrum> output2; fia_processor.cutForTime(input, 25, output2); TEST_EQUAL(output2.size(), 2); vector<MSSpectrum> output3; fia_processor.cutForTime(input, 100, output3); TEST_EQUAL(output3.size(), 4); PeakMap empty_input; vector<MSSpectrum> output4; fia_processor.cutForTime(empty_input, 100, output4); TEST_EQUAL(output4.size(), 0); } END_SECTION START_SECTION((mergeAlongTime)) { MSSpectrum output = fia_processor.mergeAlongTime(spectra); TEST_EQUAL(!output.empty(), true); TEST_EQUAL(abs(output.MZBegin(100)->getIntensity() - 400.0) < 1, true); TEST_EQUAL(abs(output.MZBegin(102)->getIntensity() - 480.0) < 1, true); } END_SECTION START_SECTION((extractPeaks)) { MSSpectrum picked = fia_processor.extractPeaks(merged); TEST_EQUAL(abs(picked.MZBegin(108)->getIntensity() - 133) < 1, true); TEST_EQUAL(abs(picked.MZBegin(112)->getIntensity() - 66) < 1, true); } END_SECTION START_SECTION((convertToFeatureMap)) { MSSpectrum picked; for (Size j = 0; j < 10; ++j) { peak.setIntensity(50); peak.setMZ(100 + j*2); picked.push_back(peak); } FeatureMap output_feature = fia_processor.convertToFeatureMap(picked); for (auto it = output_feature.begin(); it != output_feature.end(); ++it) { TEST_EQUAL(it->getIntensity() == 50, true); } } END_SECTION START_SECTION((test_run_cached)) { MzTab mztab_output_30; fia_processor.run(exp, 30, mztab_output_30); String filename_30 = "SerumTest_merged_30.mzML"; TEST_EQUAL(File::exists(temp_dir.getPath() + filename_30), true); bool is_cached_after = fia_processor.run(exp, 30, mztab_output_30); TEST_EQUAL(is_cached_after, true); } END_SECTION START_SECTION((test_run_empty)) { MzTab mztab_output_0; String filename_0 = "SerumTest_picked_0.mzML"; String filename_mztab = "SerumTest_0.mzTab"; fia_processor.run(exp, 0, mztab_output_0); TEST_EQUAL(File::exists(temp_dir.getPath() + filename_0), true); TEST_EQUAL(File::exists(temp_dir.getPath() + filename_mztab), true); TEST_EQUAL(mztab_output_0.getPSMSectionRows().size(), 0); } END_SECTION START_SECTION((test_run_full)) { vector<MSSpectrum> spec_vec; fia_processor.cutForTime(exp, 1000, spec_vec); MSSpectrum merged_result = fia_processor.mergeAlongTime(spec_vec); vector<double> mzs {109.951239, 109.962281, 109.986031, 109.999156}; for (double mz : mzs) { TEST_REAL_SIMILAR(merged_result.MZBegin(mz)->getIntensity(), spec_merged.MZBegin(mz)->getIntensity()); } MSSpectrum picked_result = fia_processor.extractPeaks(merged_result); vector<double> mzs_picked {109.951246, 109.957552, 109.959885, 109.961982, 109.982828}; for (double mz : mzs_picked) { TEST_EQUAL(picked_result.MZBegin(mz)->getIntensity(), spec_picked.MZBegin(mz)->getIntensity()); } TEST_EQUAL(picked_result.size(), spec_picked.size()); MzTab mztab_output; fia_processor.run(exp, 1000, mztab_output); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/OpenSwathDataAccessHelper_test.cpp
.cpp
9,805
312
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Hannes Roest $ // $Authors: Witold Wolski, Hannes Roest, $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> #include <OpenMS/FORMAT/TraMLFile.h> #include <boost/assign/std/vector.hpp> /////////////////////////// #include <OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/DataAccessHelper.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(OpenSwathDataAccessHelper, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// OpenSwathDataAccessHelper* ptr = nullptr; OpenSwathDataAccessHelper* nullPointer = nullptr; START_SECTION(OpenSwathDataAccessHelper()) { ptr = new OpenSwathDataAccessHelper(); TEST_NOT_EQUAL(ptr, nullPointer) } END_SECTION START_SECTION(~OpenSwathDataAccessHelper()) { delete ptr; } END_SECTION START_SECTION(OpenSwathDataAccessHelper::convertToSpectrumPtr(sptr)) { MSSpectrum sptr,omsptr; Peak1D p1; p1.setIntensity(1.0f); p1.setMZ(2.0); Peak1D p2; p2.setIntensity(2.0f); p2.setMZ(10.0); Peak1D p3; p3.setIntensity(3.0f); p3.setMZ(30.0); TEST_STRING_EQUAL(sptr.getName(), "") sptr.setName("my_fancy_name"); sptr.push_back(p1); sptr.push_back(p2); sptr.push_back(p3); OpenSwath::SpectrumPtr p = OpenSwathDataAccessHelper::convertToSpectrumPtr(sptr); OpenSwathDataAccessHelper::convertToOpenMSSpectrum(p,omsptr); TEST_REAL_SIMILAR(p->getMZArray()->data[0],2.0); TEST_REAL_SIMILAR(p->getMZArray()->data[1],10.0); TEST_REAL_SIMILAR(p->getMZArray()->data[2],30.0); TEST_REAL_SIMILAR(p->getIntensityArray()->data[0],1.0f); TEST_REAL_SIMILAR(p->getIntensityArray()->data[1],2.0f); TEST_REAL_SIMILAR(p->getIntensityArray()->data[2],3.0f); } END_SECTION START_SECTION(OpenSwathDataAccessHelper::convertToOpenMSChromatogram(cptr, chromatogram)) { //void OpenSwathDataAccessHelper::convertToOpenMSChromatogram(OpenMS::MSChromatogram & chromatogram, // const OpenSwath::ChromatogramPtr cptr) OpenSwath::ChromatogramPtr cptr(new OpenSwath::Chromatogram()); cptr->getTimeArray()->data.push_back(1.0); cptr->getTimeArray()->data.push_back(2.0); cptr->getTimeArray()->data.push_back(3.0); cptr->getTimeArray()->data.push_back(4.0); cptr->getIntensityArray()->data.push_back(4.0); cptr->getIntensityArray()->data.push_back(3.0); cptr->getIntensityArray()->data.push_back(2.0); cptr->getIntensityArray()->data.push_back(1.0); MSChromatogram chromatogram; OpenSwathDataAccessHelper::convertToOpenMSChromatogram(cptr, chromatogram); TEST_REAL_SIMILAR(chromatogram[0].getRT(),1.); TEST_REAL_SIMILAR(chromatogram[0].getIntensity(),4.); TEST_REAL_SIMILAR(chromatogram[1].getRT(),2.); TEST_REAL_SIMILAR(chromatogram[1].getIntensity(),3.); TEST_REAL_SIMILAR(chromatogram[2].getRT(),3.); TEST_REAL_SIMILAR(chromatogram[2].getIntensity(),2.); } END_SECTION START_SECTION(convertToOpenMSSpectrum(spectrum,sptr)) { OpenSwath::SpectrumPtr cptr(new OpenSwath::Spectrum()); cptr->getMZArray()->data.push_back(1.0); cptr->getMZArray()->data.push_back(2.0); cptr->getMZArray()->data.push_back(3.0); cptr->getMZArray()->data.push_back(4.0); cptr->getIntensityArray()->data.push_back(4.0); cptr->getIntensityArray()->data.push_back(3.0); cptr->getIntensityArray()->data.push_back(2.0); cptr->getIntensityArray()->data.push_back(1.0); MSSpectrum spectrum; OpenSwathDataAccessHelper::convertToOpenMSSpectrum(cptr, spectrum); TEST_REAL_SIMILAR(spectrum[0].getMZ(),1.); TEST_REAL_SIMILAR(spectrum[0].getIntensity(),4.); TEST_REAL_SIMILAR(spectrum[1].getMZ(),2.); TEST_REAL_SIMILAR(spectrum[1].getIntensity(),3.); TEST_REAL_SIMILAR(spectrum[2].getMZ(),3.); TEST_REAL_SIMILAR(spectrum[2].getIntensity(),2.); } END_SECTION START_SECTION((void OpenSwathDataAccessHelper::convertTargetedExp(const OpenMS::TargetedExperiment & transition_exp_, OpenSwath::LightTargetedExperiment & transition_exp))) { OpenMS::TargetedExperiment transition_exp_; OpenSwath::LightTargetedExperiment transition_exp; { TargetedExperiment::Peptide pep; OpenSwath::LightCompound comp; pep.setChargeState(8); pep.setDriftTime(0.6); // add a RT TargetedExperimentHelper::RetentionTime rt; rt.setRT(5.1); rt.retention_time_unit = TargetedExperimentHelper::RetentionTime::RTUnit::SECOND; rt.retention_time_type = TargetedExperimentHelper::RetentionTime::RTType::PREDICTED; pep.rts.push_back(rt); pep.id = "my_id"; pep.setPeptideGroupLabel("group1"); pep.protein_refs.push_back("pr1"); pep.protein_refs.push_back("pr2"); pep.sequence = "PEPTIDE"; // add a modification TargetedExperimentHelper::Peptide::Modification m; m.mono_mass_delta = 123; m.location = 3; m.unimod_id = 5; pep.mods.push_back(m); transition_exp_.addPeptide(pep); ReactionMonitoringTransition transition; transition.setName("tr1"); transition.setNativeID("tr1_nid"); transition.setPeptideRef("my_id"); transition.setLibraryIntensity(400.2); transition.setPrecursorMZ(501.2); transition.setProductMZ(301.2); auto p = transition.getProduct(); p.setChargeState(4); transition.setProduct(p); transition.setDecoyTransitionType( ReactionMonitoringTransition::DecoyTransitionType::DECOY ); transition.setDetectingTransition(false); transition.setQuantifyingTransition(true); transition.setIdentifyingTransition(true); transition_exp_.addTransition(transition); } { TargetedExperiment::Compound pep; OpenSwath::LightCompound comp; pep.setChargeState(8); pep.setDriftTime(0.6); // add a RT TargetedExperimentHelper::RetentionTime rt; rt.setRT(5.3); rt.retention_time_unit = TargetedExperimentHelper::RetentionTime::RTUnit::SECOND; rt.retention_time_type = TargetedExperimentHelper::RetentionTime::RTType::PREDICTED; pep.rts.push_back(rt); pep.id = "my_id"; pep.theoretical_mass = 46.069; pep.molecular_formula = "C2H6O"; pep.smiles_string = "CCO"; pep.setMetaValue("CompoundName", "some_name"); transition_exp_.addCompound(pep); } OpenSwathDataAccessHelper::convertTargetedExp(transition_exp_, transition_exp); TEST_EQUAL( transition_exp.getTransitions().size(), 1) auto tr = transition_exp.getTransitions()[0]; TEST_EQUAL(tr.transition_name, "tr1_nid") TEST_EQUAL(tr.peptide_ref, "my_id") TEST_REAL_SIMILAR(tr.library_intensity, 400.2) TEST_REAL_SIMILAR(tr.precursor_mz, 501.2) TEST_REAL_SIMILAR(tr.product_mz, 301.2) TEST_EQUAL(tr.fragment_charge, 4) TEST_EQUAL(tr.getDecoy(), true) TEST_EQUAL(tr.isDetectingTransition(), false) TEST_EQUAL(tr.isQuantifyingTransition(), true) TEST_EQUAL(tr.isIdentifyingTransition(), true) } END_SECTION START_SECTION((static void convertTargetedCompound(const TargetedExperiment::Peptide& pep, OpenSwath::LightCompound& comp))) { TargetedExperiment::Peptide pep; OpenSwath::LightCompound comp; pep.setChargeState(8); pep.setDriftTime(0.6); // add a RT TargetedExperimentHelper::RetentionTime rt; rt.setRT(5.1); rt.retention_time_unit = TargetedExperimentHelper::RetentionTime::RTUnit::SECOND; rt.retention_time_type = TargetedExperimentHelper::RetentionTime::RTType::PREDICTED; pep.rts.push_back(rt); pep.id = "my_id"; pep.setPeptideGroupLabel("group1"); pep.protein_refs.push_back("pr1"); pep.protein_refs.push_back("pr2"); pep.sequence = "PEPTIDE"; // add a modification TargetedExperimentHelper::Peptide::Modification m; m.mono_mass_delta = 123; m.location = 3; m.unimod_id = 5; pep.mods.push_back(m); OpenSwathDataAccessHelper::convertTargetedCompound(pep, comp); TEST_REAL_SIMILAR(comp.getDriftTime(), 0.6); TEST_EQUAL(comp.getChargeState(), 8); TEST_REAL_SIMILAR(comp.rt, 5.1); TEST_EQUAL(comp.sequence, "PEPTIDE"); TEST_EQUAL(comp.modifications.size(), 1); TEST_EQUAL(comp.protein_refs.size(), 2); TEST_EQUAL(comp.peptide_group_label, "group1"); TEST_EQUAL(comp.id, "my_id"); TEST_EQUAL(comp.modifications[0].location, 3); TEST_EQUAL(comp.modifications[0].unimod_id, 5); } END_SECTION START_SECTION((static void convertTargetedCompound(const TargetedExperiment::Compound& compound, OpenSwath::LightCompound& comp))) { TargetedExperiment::Compound pep; OpenSwath::LightCompound comp; pep.setChargeState(8); pep.setDriftTime(0.6); // add a RT TargetedExperimentHelper::RetentionTime rt; rt.setRT(5.3); rt.retention_time_unit = TargetedExperimentHelper::RetentionTime::RTUnit::SECOND; rt.retention_time_type = TargetedExperimentHelper::RetentionTime::RTType::PREDICTED; pep.rts.push_back(rt); pep.id = "my_id"; pep.theoretical_mass = 46.069; pep.molecular_formula = "C2H6O"; pep.smiles_string = "CCO"; pep.setMetaValue("CompoundName", "some_name"); OpenSwathDataAccessHelper::convertTargetedCompound(pep, comp); TEST_REAL_SIMILAR(comp.getDriftTime(), 0.6); TEST_EQUAL(comp.getChargeState(), 8); TEST_REAL_SIMILAR(comp.rt, 5.3); TEST_EQUAL(comp.sum_formula, "C2H6O"); TEST_EQUAL(comp.compound_name, "some_name"); TEST_EQUAL(comp.id, "my_id"); } END_SECTION START_SECTION((static void convertPeptideToAASequence(const OpenSwath::LightCompound & peptide, AASequence & aa_sequence))) { } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/RealMassDecomposer_test.cpp
.cpp
2,500
102
// 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 $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> #include <map> /////////////////////////// #include <OpenMS/CHEMISTRY/MASSDECOMPOSITION/IMS/RealMassDecomposer.h> /////////////////////////// #include <OpenMS/CHEMISTRY/MASSDECOMPOSITION/IMS/IMSAlphabet.h> #include <OpenMS/CHEMISTRY/ResidueDB.h> #include <OpenMS/CHEMISTRY/Residue.h> using namespace OpenMS; using namespace ims; using namespace std; Weights createWeights() { std::map<char, double> aa_to_weight; set<const Residue*> residues = ResidueDB::getInstance()->getResidues("Natural19WithoutI"); for (set<const Residue*>::const_iterator it = residues.begin(); it != residues.end(); ++it) { aa_to_weight[(*it)->getOneLetterCode()[0]] = (*it)->getMonoWeight(Residue::Internal); } // init mass decomposer IMSAlphabet alphabet; for (std::map<char, double>::const_iterator it = aa_to_weight.begin(); it != aa_to_weight.end(); ++it) { alphabet.push_back(String(it->first), it->second); } // initializes weights Weights weights(alphabet.getMasses(), 0.01); // optimize alphabet by dividing by gcd weights.divideByGCD(); return weights; } START_TEST(RealMassDecomposer, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// RealMassDecomposer* ptr = nullptr; RealMassDecomposer* null_ptr = nullptr; START_SECTION((RealMassDecomposer(const Weights &weights))) { ptr = new RealMassDecomposer(createWeights()); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(~RealMassDecomposer()) { delete ptr; } END_SECTION START_SECTION((decompositions_type getDecompositions(double mass, double error))) { // TODO } END_SECTION START_SECTION((decompositions_type getDecompositions(double mass, double error, const constraints_type &constraints))) { // TODO } END_SECTION START_SECTION((number_of_decompositions_type getNumberOfDecompositions(double mass, double error))) { // TODO } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/SwathFileConsumer_test.cpp
.cpp
19,529
594
// 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 $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> /////////////////////////// #include <OpenMS/FORMAT/DATAACCESS/SwathFileConsumer.h> #include <OpenMS/SYSTEM/File.h> /////////////////////////// #include <OpenMS/KERNEL/MSExperiment.h> #include <OpenMS/FORMAT/MzMLFile.h> #include <OpenMS/OPENSWATHALGO/DATAACCESS/SwathMap.h> using namespace OpenMS; static bool SortSwathMapByLower(const OpenSwath::SwathMap left, const OpenSwath::SwathMap right) { if (left.ms1 && right.ms1) return left.center < right.center; else if (left.ms1) return true; else if (right.ms1) return false; return left.lower < right.lower; } void getSwathFile(PeakMap& exp, int nr_swathes=32, bool ms1=true, bool im=false) { if (ms1) { MSSpectrum s; s.setMSLevel(1); Peak1D p; p.setMZ(100); p.setIntensity(200); // add ion mobility (if needed) if (im) { s.setMetaValue("ion mobility lower offset", 0.6); s.setMetaValue("ion mobility upper offset", 1.5); } s.push_back(p); exp.addSpectrum(s); } // add MS2 (with IM) // if im then add 2*nr_swathes every swath has a corresponding swath with the same m/z isolation but distinct IM if (im) { for (int scheme=0; scheme<2; scheme++) { for (int i = 0; i< nr_swathes; i++) { MSSpectrum s; s.setMSLevel(2); std::vector<Precursor> prec(1); prec[0].setIsolationWindowLowerOffset(12.5); prec[0].setIsolationWindowUpperOffset(12.5); prec[0].setMZ(400 + i*25 + 12.5); s.setPrecursors(prec); Peak1D p; p.setMZ(101 + i); p.setIntensity(201 + i); s.push_back(p); s.setMetaValue("ion mobility lower limit", 0.6 + i *0.05 + scheme*0.1); s.setMetaValue("ion mobility upper limit", 0.6 + i *0.05 + scheme*0.1); exp.addSpectrum(s); } } } else { // add MS2 (without IM) for (int i = 0; i< nr_swathes; i++) { MSSpectrum s; s.setMSLevel(2); std::vector<Precursor> prec(1); prec[0].setIsolationWindowLowerOffset(12.5); prec[0].setIsolationWindowUpperOffset(12.5); prec[0].setMZ(400 + i*25 + 12.5); s.setPrecursors(prec); Peak1D p; p.setMZ(101 + i); p.setIntensity(201 + i); s.push_back(p); exp.addSpectrum(s); } } } START_TEST(SwathFileConsumer, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// // Test "regular" / in memory consumer { RegularSwathFileConsumer* regular_sfc_ptr = nullptr; RegularSwathFileConsumer* regular_sfc_nullPointer = nullptr; START_SECTION(([EXTRA] RegularSwathFileConsumer())) regular_sfc_ptr = new RegularSwathFileConsumer; TEST_NOT_EQUAL(regular_sfc_ptr, regular_sfc_nullPointer) END_SECTION START_SECTION(([EXTRA] virtual ~RegularSwathFileConsumer())) delete regular_sfc_ptr; END_SECTION START_SECTION(([EXTRA] consumeAndRetrieve)) { regular_sfc_ptr = new RegularSwathFileConsumer(); PeakMap exp; getSwathFile(exp); // Consume all the spectra for (Size i = 0; i < exp.getSpectra().size(); i++) { regular_sfc_ptr->consumeSpectrum(exp.getSpectra()[i]); } std::vector< OpenSwath::SwathMap > maps; regular_sfc_ptr->retrieveSwathMaps(maps); TEST_EQUAL(maps.size(), 33) TEST_EQUAL(maps[0].ms1, true) for (Size i = 0; i< 32; i++) { TEST_EQUAL(maps[i+1].ms1, false) TEST_EQUAL(maps[i+1].sptr->getNrSpectra(), 1) TEST_EQUAL(maps[i+1].sptr->getSpectrumById(0)->getMZArray()->data.size(), 1) TEST_REAL_SIMILAR(maps[i+1].sptr->getSpectrumById(0)->getMZArray()->data[0], 101.0+i) TEST_REAL_SIMILAR(maps[i+1].sptr->getSpectrumById(0)->getIntensityArray()->data[0], 201.0+i) TEST_REAL_SIMILAR(maps[i+1].lower, 400+i*25.0) TEST_REAL_SIMILAR(maps[i+1].upper, 425+i*25.0) } delete regular_sfc_ptr; } END_SECTION START_SECTION(([EXTRA] consumeAndRetrieve_known_boundaries)) { // Using the second constructor std::vector< OpenSwath::SwathMap > boundaries; PeakMap exp; getSwathFile(exp); for (int i = 0; i< 32; i++) { OpenSwath::SwathMap m; m.center = 400 + i*25 + 12.5; // enforce slightly different windows than the one in the file m.lower = m.center - 5; m.upper = m.center + 5; boundaries.push_back(m); } regular_sfc_ptr = new RegularSwathFileConsumer(boundaries); // Consume all the spectra for (Size i = 0; i < exp.getSpectra().size(); i++) { regular_sfc_ptr->consumeSpectrum(exp.getSpectra()[i]); } std::vector< OpenSwath::SwathMap > maps; regular_sfc_ptr->retrieveSwathMaps(maps); TEST_EQUAL(maps.size(), 33) TEST_EQUAL(maps[0].ms1, true) for (Size i = 0; i< 32; i++) { TEST_EQUAL(maps[i+1].ms1, false) TEST_EQUAL(maps[i+1].sptr->getNrSpectra(), 1) TEST_EQUAL(maps[i+1].sptr->getSpectrumById(0)->getMZArray()->data.size(), 1) TEST_REAL_SIMILAR(maps[i+1].sptr->getSpectrumById(0)->getMZArray()->data[0], 101.0+i) TEST_REAL_SIMILAR(maps[i+1].sptr->getSpectrumById(0)->getIntensityArray()->data[0], 201.0+i) TEST_REAL_SIMILAR(maps[i+1].lower, 400+i*25.0 + 12.5 - 5.0) TEST_REAL_SIMILAR(maps[i+1].upper, 400+i*25.0 + 12.5 + 5.0) } delete regular_sfc_ptr; } END_SECTION START_SECTION(([EXTRA] consumeAndRetrieve_scrambled)) { // Feed the SWATH maps to the consumer in a scrambled fashion: // Consume an MS2 spectrum, then an MS1 spectrum, then 5 more MS2, then an MS1, skip 5 // of the MS2 spectra and consumer another 5 MS2 spectra. regular_sfc_ptr = new RegularSwathFileConsumer(); PeakMap exp; getSwathFile(exp); regular_sfc_ptr->consumeSpectrum(exp.getSpectra()[6]); // MS2 regular_sfc_ptr->consumeSpectrum(exp.getSpectra()[0]); // MS1 for (Size i = 1; i < 5; i++) { regular_sfc_ptr->consumeSpectrum(exp.getSpectra()[i]); // MS2 } regular_sfc_ptr->consumeSpectrum(exp.getSpectra()[0]); // MS1 for (Size i = 10; i < 15; i++) { regular_sfc_ptr->consumeSpectrum(exp.getSpectra()[i]); // MS2 } // Consume all spectra again to make sure we have "seen" them all (1 MS1 + 32 MS2) for (Size i = 0; i < exp.getSpectra().size(); i++) { regular_sfc_ptr->consumeSpectrum(exp.getSpectra()[i]); } std::vector< OpenSwath::SwathMap > maps; regular_sfc_ptr->retrieveSwathMaps(maps); TEST_EQUAL(maps.size(), 33) std::sort(maps.begin(), maps.end(), SortSwathMapByLower); TEST_EQUAL(maps[0].ms1, true) TEST_EQUAL(maps[0].sptr->getNrSpectra(), 3) for (Size i = 0; i< 32; i++) { TEST_EQUAL(maps[i+1].ms1, false) if (i>15) TEST_EQUAL(maps[i+1].sptr->getNrSpectra(), 1) // some now also have 2 or 3 spectra TEST_EQUAL(maps[i+1].sptr->getSpectrumById(0)->getMZArray()->data.size(), 1) TEST_REAL_SIMILAR(maps[i+1].sptr->getSpectrumById(0)->getMZArray()->data[0], 101.0+i) TEST_REAL_SIMILAR(maps[i+1].sptr->getSpectrumById(0)->getIntensityArray()->data[0], 201.0+i) TEST_REAL_SIMILAR(maps[i+1].lower, 400+i*25.0) TEST_REAL_SIMILAR(maps[i+1].upper, 425+i*25.0) } delete regular_sfc_ptr; } END_SECTION START_SECTION(([EXTRA] consumeAndRetrieve_scrambled_known_boundaries)) { // Using the second constructor std::vector< OpenSwath::SwathMap > boundaries; PeakMap exp; getSwathFile(exp); // add some extra windows for confusion for (int i = 0; i < 2; i++) { OpenSwath::SwathMap m; m.center = 100 + i*25 + 12.5; m.lower = m.center - 5; m.upper = m.center + 5; boundaries.push_back(m); } for (int i = 0; i < 32; i++) { OpenSwath::SwathMap m; m.center = 400 + i*25 + 12.5; // enforce slightly different windows than the one in the file m.lower = m.center - 5; m.upper = m.center + 5; boundaries.push_back(m); } // add some extra windows for confusion for (int i = 0; i < 2; i++) { OpenSwath::SwathMap m; m.center = 5000 + i*25 + 12.5; m.lower = m.center - 5; m.upper = m.center + 5; boundaries.push_back(m); } regular_sfc_ptr = new RegularSwathFileConsumer(boundaries); // Feed the SWATH maps to the consumer in a scrambled fashion: // Consume an MS2 spectrum, then an MS1 spectrum, then 5 more MS2, then an MS1, skip 5 // of the MS2 spectra and consumer another 5 MS2 spectra. regular_sfc_ptr->consumeSpectrum(exp.getSpectra()[6]); // MS2 regular_sfc_ptr->consumeSpectrum(exp.getSpectra()[0]); // MS1 for (Size i = 1; i < 5; i++) { regular_sfc_ptr->consumeSpectrum(exp.getSpectra()[i]); // MS2 } regular_sfc_ptr->consumeSpectrum(exp.getSpectra()[0]); // MS1 for (Size i = 10; i < 15; i++) { regular_sfc_ptr->consumeSpectrum(exp.getSpectra()[i]); // MS2 } // Consume all spectra again to make sure we have "seen" them all (1 MS1 + 32 MS2) for (Size i = 0; i < exp.getSpectra().size(); i++) { regular_sfc_ptr->consumeSpectrum(exp.getSpectra()[i]); } std::vector< OpenSwath::SwathMap > maps; regular_sfc_ptr->retrieveSwathMaps(maps); TEST_EQUAL(maps.size(), 33+2) std::sort(maps.begin(), maps.end(), SortSwathMapByLower); TEST_EQUAL(maps[0].ms1, true) TEST_EQUAL(maps[0].sptr->getNrSpectra(), 3) // two empty ones TEST_EQUAL(maps[1].ms1, false) TEST_EQUAL(maps[1].sptr->getNrSpectra(), 0) TEST_EQUAL(maps[2].ms1, false) TEST_EQUAL(maps[2].sptr->getNrSpectra(), 0) for (Size i = 2; i< 32+2; i++) { TEST_EQUAL(maps[i+1].ms1, false) TEST_EQUAL(maps[i+1].sptr->getNrSpectra() > 0, true) TEST_EQUAL(maps[i+1].sptr->getSpectrumById(0)->getMZArray()->data.size(), 1) TEST_REAL_SIMILAR(maps[i+1].sptr->getSpectrumById(0)->getMZArray()->data[0], 101.0+(i-2)) TEST_REAL_SIMILAR(maps[i+1].sptr->getSpectrumById(0)->getIntensityArray()->data[0], 201.0+(i-2)) TEST_REAL_SIMILAR(maps[i+1].lower, 400+(i-2)*25.0 + 12.5 - 5.0) TEST_REAL_SIMILAR(maps[i+1].upper, 400+(i-2)*25.0 + 12.5 + 5.0) } delete regular_sfc_ptr; } END_SECTION START_SECTION(([EXTRA] consumeAndRetrieve_noMS1)) { regular_sfc_ptr = new RegularSwathFileConsumer(); int nr_swath = 32; PeakMap exp; getSwathFile(exp, nr_swath, false); // Consume all the spectra for (Size i = 0; i < exp.getSpectra().size(); i++) { regular_sfc_ptr->consumeSpectrum(exp.getSpectra()[i]); } std::vector< OpenSwath::SwathMap > maps; regular_sfc_ptr->retrieveSwathMaps(maps); TEST_EQUAL(maps.size(), nr_swath) // Swath number TEST_EQUAL(maps[0].ms1, false) for (int i = 0; i< nr_swath; i++) { TEST_EQUAL(maps[i].ms1, false) TEST_EQUAL(maps[i].sptr->getNrSpectra(), 1) TEST_EQUAL(maps[i].sptr->getSpectrumById(0)->getMZArray()->data.size(), 1) TEST_REAL_SIMILAR(maps[i].sptr->getSpectrumById(0)->getMZArray()->data[0], 101.0+i) TEST_REAL_SIMILAR(maps[i].sptr->getSpectrumById(0)->getIntensityArray()->data[0], 201.0+i) TEST_REAL_SIMILAR(maps[i].lower, 400+i*25.0) TEST_REAL_SIMILAR(maps[i].upper, 425+i*25.0) } delete regular_sfc_ptr; } END_SECTION START_SECTION(([EXTRA] consumeAndRetrieve_noMS2)) { int nr_swath = 0; regular_sfc_ptr = new RegularSwathFileConsumer(); PeakMap exp; getSwathFile(exp, nr_swath, true); // Consume all the spectra for (Size i = 0; i < exp.getSpectra().size(); i++) { regular_sfc_ptr->consumeSpectrum(exp.getSpectra()[i]); } std::vector< OpenSwath::SwathMap > maps; regular_sfc_ptr->retrieveSwathMaps(maps); TEST_EQUAL(maps.size(), 1) // Only MS1 TEST_EQUAL(maps[0].ms1, true) TEST_EQUAL(maps[0].sptr->getNrSpectra(), 1) TEST_EQUAL(maps[0].sptr->getSpectrumById(0)->getMZArray()->data.size(), 1) TEST_REAL_SIMILAR(maps[0].sptr->getSpectrumById(0)->getMZArray()->data[0], 100.0) TEST_REAL_SIMILAR(maps[0].sptr->getSpectrumById(0)->getIntensityArray()->data[0], 200.0) delete regular_sfc_ptr; } END_SECTION START_SECTION(([EXTRA] void retrieveSwathMaps(std::vector< OpenSwath::SwathMap > & maps))) { NOT_TESTABLE // already tested consumeAndRetrieve } END_SECTION START_SECTION(([EXTRA] void consumeChromatogram(MapType::ChromatogramType &) )) { regular_sfc_ptr = new RegularSwathFileConsumer(); MSChromatogram c; regular_sfc_ptr->consumeChromatogram(c); TEST_EQUAL(true, true) delete regular_sfc_ptr; } END_SECTION START_SECTION(([EXTRA] void consumeSpectrum(MapType::SpectrumType & s))) { regular_sfc_ptr = new RegularSwathFileConsumer(); MSSpectrum s; s.setMSLevel(1); regular_sfc_ptr->consumeSpectrum(s); s.setMSLevel(2); TEST_EXCEPTION(Exception::InvalidParameter, regular_sfc_ptr->consumeSpectrum(s)) std::vector<Precursor> prec(1); s.setPrecursors(prec); TEST_EXCEPTION(Exception::InvalidParameter, regular_sfc_ptr->consumeSpectrum(s)) prec[0].setIsolationWindowLowerOffset(12.5); prec[0].setIsolationWindowUpperOffset(12.5); s.setPrecursors(prec); TEST_EXCEPTION(Exception::InvalidParameter, regular_sfc_ptr->consumeSpectrum(s)) prec[0].setMZ(100); s.setPrecursors(prec); regular_sfc_ptr->consumeSpectrum(s); delete regular_sfc_ptr; } END_SECTION } // Test cached consumer // - shared functions in the base class are already tested, only test I/O here { CachedSwathFileConsumer* cached_sfc_ptr = nullptr; CachedSwathFileConsumer* cached_sfc_nullPointer = nullptr; START_SECTION(([EXTRA] CachedSwathFileConsumer())) cached_sfc_ptr = new CachedSwathFileConsumer(File::getTempDirectory() + "/", "tmp_osw_cached", 0, std::vector<int>()); TEST_NOT_EQUAL(cached_sfc_ptr, cached_sfc_nullPointer) END_SECTION START_SECTION(([EXTRA] virtual ~CachedSwathFileConsumer())) delete cached_sfc_ptr; END_SECTION START_SECTION(([EXTRA] consumeAndRetrieve)) { // 2 SWATH should be sufficient for the test //int nr_swath = 1; int nr_swath = 2; std::vector<int> nr_ms2_spectra(nr_swath,1); cached_sfc_ptr = new CachedSwathFileConsumer(File::getTempDirectory() + "/", "tmp_osw_cached", 1, nr_ms2_spectra); PeakMap exp; getSwathFile(exp, nr_swath); // Consume all the spectra for (Size i = 0; i < exp.getSpectra().size(); i++) { cached_sfc_ptr->consumeSpectrum(exp.getSpectra()[i]); } std::vector< OpenSwath::SwathMap > maps; cached_sfc_ptr->retrieveSwathMaps(maps); TEST_EQUAL(maps.size(), nr_swath+1) // Swath number + MS1 TEST_EQUAL(maps[0].ms1, true) TEST_EQUAL(maps[0].sptr->getNrSpectra(), 1) TEST_EQUAL(maps[0].sptr->getSpectrumById(0)->getMZArray()->data.size(), 1) TEST_REAL_SIMILAR(maps[0].sptr->getSpectrumById(0)->getMZArray()->data[0], 100.0) TEST_REAL_SIMILAR(maps[0].sptr->getSpectrumById(0)->getIntensityArray()->data[0], 200.0) for (int i = 0; i< nr_swath; i++) { TEST_EQUAL(maps[i+1].ms1, false) TEST_EQUAL(maps[i+1].sptr->getNrSpectra(), 1) TEST_EQUAL(maps[i+1].sptr->getSpectrumById(0)->getMZArray()->data.size(), 1) TEST_REAL_SIMILAR(maps[i+1].sptr->getSpectrumById(0)->getMZArray()->data[0], 101.0+i) TEST_REAL_SIMILAR(maps[i+1].sptr->getSpectrumById(0)->getIntensityArray()->data[0], 201.0+i) TEST_REAL_SIMILAR(maps[i+1].lower, 400+i*25.0) TEST_REAL_SIMILAR(maps[i+1].upper, 425+i*25.0) } delete cached_sfc_ptr; } END_SECTION START_SECTION(([EXTRA] consumeAndRetrieve_noMS1)) { // 2 SWATH should be sufficient for the test int nr_swath = 2; std::vector<int> nr_ms2_spectra(nr_swath,1); cached_sfc_ptr = new CachedSwathFileConsumer(File::getTempDirectory() + "/", "tmp_osw_cached", 1, nr_ms2_spectra); PeakMap exp; getSwathFile(exp, nr_swath, false); // Consume all the spectra for (Size i = 0; i < exp.getSpectra().size(); i++) { cached_sfc_ptr->consumeSpectrum(exp.getSpectra()[i]); } std::vector< OpenSwath::SwathMap > maps; cached_sfc_ptr->retrieveSwathMaps(maps); TEST_EQUAL(maps.size(), nr_swath) // Swath number TEST_EQUAL(maps[0].ms1, false) for (int i = 0; i< nr_swath; i++) { TEST_EQUAL(maps[i].ms1, false) TEST_EQUAL(maps[i].sptr->getNrSpectra(), 1) TEST_EQUAL(maps[i].sptr->getSpectrumById(0)->getMZArray()->data.size(), 1) TEST_REAL_SIMILAR(maps[i].sptr->getSpectrumById(0)->getMZArray()->data[0], 101.0+i) TEST_REAL_SIMILAR(maps[i].sptr->getSpectrumById(0)->getIntensityArray()->data[0], 201.0+i) TEST_REAL_SIMILAR(maps[i].lower, 400+i*25.0) TEST_REAL_SIMILAR(maps[i].upper, 425+i*25.0) } delete cached_sfc_ptr; } END_SECTION START_SECTION(([EXTRA] consumeAndRetrieve_noMS2)) { int nr_swath = 0; std::vector<int> nr_ms2_spectra(nr_swath,1); cached_sfc_ptr = new CachedSwathFileConsumer(File::getTempDirectory() + "/", "tmp_osw_cached", 1, nr_ms2_spectra); PeakMap exp; getSwathFile(exp, nr_swath, true); // Consume all the spectra for (Size i = 0; i < exp.getSpectra().size(); i++) { cached_sfc_ptr->consumeSpectrum(exp.getSpectra()[i]); } std::vector< OpenSwath::SwathMap > maps; cached_sfc_ptr->retrieveSwathMaps(maps); TEST_EQUAL(maps.size(), 1) // Only MS1 TEST_EQUAL(maps[0].ms1, true) TEST_EQUAL(maps[0].sptr->getNrSpectra(), 1) TEST_EQUAL(maps[0].sptr->getSpectrumById(0)->getMZArray()->data.size(), 1) TEST_REAL_SIMILAR(maps[0].sptr->getSpectrumById(0)->getMZArray()->data[0], 100.0) TEST_REAL_SIMILAR(maps[0].sptr->getSpectrumById(0)->getIntensityArray()->data[0], 200.0) delete cached_sfc_ptr; } END_SECTION START_SECTION(([EXTRA] void retrieveSwathMaps(std::vector< OpenSwath::SwathMap > & maps))) { NOT_TESTABLE // already tested consumeAndRetrieve } END_SECTION START_SECTION(([EXTRA] void consumeChromatogram(MapType::ChromatogramType &) )) { NOT_TESTABLE // already tested consumeAndRetrieve } END_SECTION START_SECTION(([EXTRA] void consumeSpectrum(MapType::SpectrumType & s))) { NOT_TESTABLE // already tested consumeAndRetrieve } END_SECTION } START_SECTION(([EXTRA] consumeAndRetrieve_with_ion_mobility)) { RegularSwathFileConsumer* regular_sfc_ptr = nullptr; regular_sfc_ptr = new RegularSwathFileConsumer(); PeakMap exp; getSwathFile(exp, 32, true, true ); // Consume all the spectra for (Size i = 0; i < exp.getSpectra().size(); i++) { regular_sfc_ptr->consumeSpectrum(exp.getSpectra()[i]); } std::vector< OpenSwath::SwathMap > maps; regular_sfc_ptr->retrieveSwathMaps(maps); TEST_EQUAL(maps.size(), 65) TEST_EQUAL(maps[0].ms1, true) // for a scheme there are 32 swath windows cycling from 400-1200. a new scheme is the same m/z windows however im is shifted for (int scheme =0; scheme<2; scheme++) { for (Size i = 0; i< 32; i++) { TEST_EQUAL(maps[i+1+scheme*32].ms1, false) TEST_EQUAL(maps[i+1+scheme*32].sptr->getNrSpectra(), 1) TEST_EQUAL(maps[i+1+scheme*32].sptr->getSpectrumById(0)->getMZArray()->data.size(), 1) TEST_REAL_SIMILAR(maps[i+1+scheme*32].sptr->getSpectrumById(0)->getMZArray()->data[0], 101.0+i) TEST_REAL_SIMILAR(maps[i+1+scheme*32].sptr->getSpectrumById(0)->getIntensityArray()->data[0], 201.0+i) TEST_REAL_SIMILAR(maps[i+1+scheme*32].lower, 400+i*25.0) TEST_REAL_SIMILAR(maps[i+1+scheme*32].upper, 425+i*25.0) TEST_REAL_SIMILAR(maps[i+1+scheme*32].imLower, 0.6+i*0.05 + scheme *0.1) TEST_REAL_SIMILAR(maps[i+1+scheme*32].imUpper, 0.6 + i*0.05 + scheme*0.1) } } delete regular_sfc_ptr; } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/SpectrumSettings_test.cpp
.cpp
17,189
562
// 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 $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/METADATA/SpectrumSettings.h> #include <OpenMS/METADATA/ProteinIdentification.h> #include <unordered_set> #include <unordered_map> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(SpectrumSettings, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// SpectrumSettings* ptr = nullptr; SpectrumSettings* nullPointer = nullptr; START_SECTION((SpectrumSettings())) ptr = new SpectrumSettings(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((~SpectrumSettings())) delete ptr; END_SECTION START_SECTION((const String& getNativeID() const)) SpectrumSettings tmp; TEST_STRING_EQUAL(tmp.getNativeID(),""); END_SECTION START_SECTION((void setNativeID(const String& native_id))) SpectrumSettings tmp; tmp.setNativeID("nid"); TEST_STRING_EQUAL(tmp.getNativeID(),"nid"); END_SECTION START_SECTION((const std::vector<DataProcessing>& getDataProcessing() const)) SpectrumSettings tmp; TEST_EQUAL(tmp.getDataProcessing().size(),0); END_SECTION START_SECTION((void setDataProcessing(const std::vector< DataProcessing > &data_processing))) SpectrumSettings tmp; std::vector<DataProcessingPtr > dummy; dummy.resize(1); tmp.setDataProcessing(dummy); TEST_EQUAL(tmp.getDataProcessing().size(),1); END_SECTION START_SECTION((std::vector<DataProcessing>& getDataProcessing())) SpectrumSettings tmp; tmp.getDataProcessing().resize(1); TEST_EQUAL(tmp.getDataProcessing().size(),1); END_SECTION START_SECTION((AcquisitionInfo& getAcquisitionInfo())) SpectrumSettings tmp; TEST_EQUAL(tmp.getAcquisitionInfo().empty(), true); END_SECTION START_SECTION((void setAcquisitionInfo(const AcquisitionInfo& acquisition_info))) SpectrumSettings tmp; AcquisitionInfo ai; ai.setMethodOfCombination("test"); tmp.setAcquisitionInfo(ai); TEST_EQUAL(tmp.getAcquisitionInfo() == AcquisitionInfo(), false); END_SECTION START_SECTION((const AcquisitionInfo& getAcquisitionInfo() const)) SpectrumSettings tmp; tmp.getAcquisitionInfo().setMethodOfCombination("test"); TEST_EQUAL(tmp.getAcquisitionInfo() == AcquisitionInfo(), false); END_SECTION START_SECTION((SourceFile& getSourceFile())) SpectrumSettings tmp; TEST_EQUAL(tmp.getSourceFile()==SourceFile(), true); END_SECTION START_SECTION((void setSourceFile(const SourceFile& source_file))) SpectrumSettings tmp; SourceFile sf; sf.setNameOfFile("test"); tmp.setSourceFile(sf); TEST_EQUAL(tmp.getSourceFile()==SourceFile(), false); END_SECTION START_SECTION((const SourceFile& getSourceFile() const)) SpectrumSettings tmp; tmp.getSourceFile().setNameOfFile("test"); TEST_EQUAL(tmp.getSourceFile()==SourceFile(), false); END_SECTION START_SECTION((const InstrumentSettings& getInstrumentSettings() const)) SpectrumSettings tmp; TEST_EQUAL(tmp.getInstrumentSettings()==InstrumentSettings(), true); END_SECTION START_SECTION((void setInstrumentSettings(const InstrumentSettings& instrument_settings))) SpectrumSettings tmp; InstrumentSettings is; is.getScanWindows().resize(1); tmp.setInstrumentSettings(is); TEST_EQUAL(tmp.getInstrumentSettings()==InstrumentSettings(), false); END_SECTION START_SECTION((InstrumentSettings& getInstrumentSettings())) SpectrumSettings tmp; tmp.getInstrumentSettings().getScanWindows().resize(1); TEST_EQUAL(tmp.getInstrumentSettings()==InstrumentSettings(), false); END_SECTION START_SECTION((const std::vector<Precursor>& getPrecursors() const)) SpectrumSettings tmp; TEST_EQUAL(tmp.getPrecursors().size(),0); END_SECTION START_SECTION((void setPrecursors(const std::vector<Precursor>& precursors))) SpectrumSettings tmp; tmp.setPrecursors(vector<Precursor>(2)); TEST_EQUAL(tmp.getPrecursors().size(), 2); END_SECTION START_SECTION((std::vector<Precursor>& getPrecursors())) SpectrumSettings tmp; tmp.getPrecursors().resize(4); TEST_EQUAL(tmp.getPrecursors().size(), 4); END_SECTION START_SECTION((const std::vector<Product>& getProducts() const)) SpectrumSettings tmp; TEST_EQUAL(tmp.getProducts().size(),0); END_SECTION START_SECTION((void setProducts(const std::vector<Product>& products))) SpectrumSettings tmp; tmp.setProducts(vector<Product>(2)); TEST_EQUAL(tmp.getProducts().size(), 2); END_SECTION START_SECTION((std::vector<Product>& getProducts())) SpectrumSettings tmp; tmp.getProducts().resize(4); TEST_EQUAL(tmp.getProducts().size(), 4); END_SECTION START_SECTION((SpectrumType getType() const)) SpectrumSettings tmp; TEST_EQUAL(tmp.getType(), SpectrumSettings::SpectrumType::UNKNOWN); END_SECTION START_SECTION((void setType(SpectrumType type))) SpectrumSettings tmp; tmp.setType(SpectrumSettings::SpectrumType::CENTROID); TEST_EQUAL(tmp.getType(), SpectrumSettings::SpectrumType::CENTROID); END_SECTION START_SECTION((const String& getComment() const)) SpectrumSettings tmp; TEST_EQUAL(tmp.getComment(), ""); END_SECTION START_SECTION((void setComment(const String& comment))) SpectrumSettings tmp; tmp.setComment("bla"); TEST_EQUAL(tmp.getComment(), "bla"); END_SECTION START_SECTION((SpectrumSettings& operator= (const SpectrumSettings& source))) SpectrumSettings tmp; tmp.setMetaValue("bla","bluff"); tmp.getAcquisitionInfo().setMethodOfCombination("test"); tmp.getInstrumentSettings().getScanWindows().resize(1); tmp.getPrecursors().resize(1); tmp.getProducts().resize(1); tmp.setType(SpectrumSettings::SpectrumType::CENTROID); tmp.setComment("bla"); tmp.setNativeID("nid"); tmp.getDataProcessing().resize(1); SpectrumSettings tmp2(tmp); TEST_EQUAL(tmp2.getComment(), "bla"); TEST_EQUAL(tmp2.getType(), SpectrumSettings::SpectrumType::CENTROID); TEST_EQUAL(tmp2.getPrecursors().size(),1); TEST_EQUAL(tmp2.getProducts().size(),1); TEST_EQUAL(tmp2.getInstrumentSettings()==InstrumentSettings(), false); TEST_EQUAL(tmp2.getAcquisitionInfo()==AcquisitionInfo(), false); TEST_EQUAL(tmp2.getAcquisitionInfo().empty(), true); TEST_STRING_EQUAL(tmp2.getNativeID(),"nid"); TEST_EQUAL(tmp2.getDataProcessing().size(),1); TEST_EQUAL(tmp2.getMetaValue("bla")=="bluff",true); END_SECTION START_SECTION((SpectrumSettings(const SpectrumSettings& source))) SpectrumSettings tmp; tmp.getAcquisitionInfo().setMethodOfCombination("test"); tmp.getInstrumentSettings().getScanWindows().resize(1); tmp.getPrecursors().resize(1); tmp.getProducts().resize(1); tmp.setType(SpectrumSettings::SpectrumType::CENTROID); tmp.setComment("bla"); tmp.setNativeID("nid"); tmp.getDataProcessing().resize(1); tmp.setMetaValue("bla","bluff"); SpectrumSettings tmp2; tmp2 = tmp; TEST_EQUAL(tmp2.getComment(), "bla"); TEST_EQUAL(tmp2.getType(), SpectrumSettings::SpectrumType::CENTROID); TEST_EQUAL(tmp2.getPrecursors().size(), 1); TEST_EQUAL(tmp2.getProducts().size(), 1) TEST_EQUAL(tmp2.getInstrumentSettings()==InstrumentSettings(), false); TEST_EQUAL(tmp2.getAcquisitionInfo().empty(), true); TEST_EQUAL(tmp2.getAcquisitionInfo()==AcquisitionInfo(), false); TEST_STRING_EQUAL(tmp2.getNativeID(),"nid"); TEST_EQUAL(tmp2.getDataProcessing().size(),1); TEST_STRING_EQUAL(tmp2.getMetaValue("bla"),"bluff"); tmp2 = SpectrumSettings(); TEST_EQUAL(tmp2.getComment(), ""); TEST_EQUAL(tmp2.getType(), SpectrumSettings::SpectrumType::UNKNOWN); TEST_EQUAL(tmp2.getPrecursors().size(),0); TEST_EQUAL(tmp2.getProducts().size(),0); TEST_EQUAL(tmp2.getInstrumentSettings()==InstrumentSettings(), true); TEST_EQUAL(tmp2.getAcquisitionInfo().empty(), true); TEST_STRING_EQUAL(tmp2.getNativeID(),""); TEST_EQUAL(tmp2.getDataProcessing().size(),0); TEST_EQUAL(tmp2.metaValueExists("bla"),false); END_SECTION START_SECTION((bool operator== (const SpectrumSettings& rhs) const)) SpectrumSettings edit, empty; TEST_TRUE(edit == empty); edit.getAcquisitionInfo().setMethodOfCombination("test"); TEST_EQUAL(edit==empty, false); edit = empty; edit.setNativeID("nid"); TEST_EQUAL(edit==empty, false); edit = empty; edit.getInstrumentSettings().getScanWindows().resize(1); TEST_EQUAL(edit==empty, false); edit = empty; edit.getPrecursors().resize(1); TEST_EQUAL(edit==empty, false); edit = empty; edit.setType(SpectrumSettings::SpectrumType::CENTROID); TEST_EQUAL(edit==empty, false); edit = empty; edit.setComment("bla"); TEST_EQUAL(edit==empty, false); edit = empty; edit.getPrecursors().resize(1); TEST_EQUAL(edit==empty, false); edit = empty; edit.getProducts().resize(1); TEST_EQUAL(edit==empty, false); edit = empty; DataProcessingPtr dp = std::shared_ptr<DataProcessing>(new DataProcessing); edit.getDataProcessing().push_back(dp); TEST_EQUAL(edit==empty, false); edit = empty; edit.setMetaValue("bla","bluff"); TEST_EQUAL(edit==empty, false); END_SECTION START_SECTION((bool operator!= (const SpectrumSettings& rhs) const)) SpectrumSettings edit, empty; TEST_EQUAL(edit!=empty, false); edit.getAcquisitionInfo().setMethodOfCombination("test"); TEST_FALSE(edit == empty); edit = empty; edit.setNativeID("nid"); TEST_FALSE(edit == empty); edit = empty; edit.getInstrumentSettings().getScanWindows().resize(1); TEST_FALSE(edit == empty); edit = empty; edit.getPrecursors().resize(1); TEST_FALSE(edit == empty); edit = empty; edit.setType(SpectrumSettings::SpectrumType::CENTROID); TEST_FALSE(edit == empty); edit = empty; edit.setComment("bla"); TEST_FALSE(edit == empty); edit = empty; edit.getPrecursors().resize(1); TEST_FALSE(edit == empty); edit = empty; edit.getProducts().resize(1); TEST_FALSE(edit == empty); edit = empty; DataProcessingPtr dp = std::shared_ptr<DataProcessing>(new DataProcessing); edit.getDataProcessing().push_back(dp); TEST_FALSE(edit == empty); edit = empty; edit.setMetaValue("bla","bluff"); TEST_FALSE(edit == empty); END_SECTION START_SECTION((void unify(const SpectrumSettings &rhs))) { SpectrumSettings org, appended; // MetaValues org.setMetaValue(1, "will be gone"); org.setMetaValue(2, "will be still present"); appended.setMetaValue(1, "will overwrite org comment"); // Comments org.setComment("Original Comment"); appended.setComment("Appended to org Commment"); // Precursors Precursor org_precursor; org_precursor.setMZ(1.0); org.getPrecursors().push_back(org_precursor); Precursor appended_precursor; appended_precursor.setMZ(2.0); appended.getPrecursors().push_back(appended_precursor); // type org.setType(SpectrumSettings::SpectrumType::PROFILE); appended.setType(SpectrumSettings::SpectrumType::PROFILE); // Products Product org_product; org_product.setMZ(1.0); org.getProducts().push_back(org_product); Product appended_product; appended_product.setMZ(2.0); appended.getProducts().push_back(appended_product); // DataProcessings DataProcessingPtr org_processing = std::shared_ptr<DataProcessing>(new DataProcessing); Software org_software; org_software.setName("org_software"); org_processing->setSoftware(org_software); org.getDataProcessing().push_back(org_processing); DataProcessingPtr appended_processing = std::shared_ptr<DataProcessing>(new DataProcessing); Software appended_software; appended_software.setName("appended_software"); appended_processing->setSoftware(appended_software); appended.getDataProcessing().push_back(appended_processing); org.unify(appended); // MetaValues TEST_EQUAL(org.getMetaValue(1), "will overwrite org comment") TEST_EQUAL(org.getMetaValue(2), "will be still present") // Comments TEST_EQUAL(org.getComment(), "Original CommentAppended to org Commment") // Precursors TEST_EQUAL(org.getPrecursors().size(), 2) ABORT_IF(org.getPrecursors().size()!=2) TEST_EQUAL(org.getPrecursors()[0].getMZ(), 1.0) TEST_EQUAL(org.getPrecursors()[1].getMZ(), 2.0) // type TEST_EQUAL(org.getType(), SpectrumSettings::SpectrumType::PROFILE) // Products TEST_EQUAL(org.getProducts().size(), 2) ABORT_IF(org.getProducts().size()!=2) TEST_EQUAL(org.getProducts()[0].getMZ(), 1.0) TEST_EQUAL(org.getProducts()[1].getMZ(), 2.0) TEST_EQUAL(org.getDataProcessing()[0]->getSoftware().getName(), "org_software") TEST_EQUAL(org.getDataProcessing()[1]->getSoftware().getName(), "appended_software") // unify should set Type to unknown in case of type mismatch SpectrumSettings empty; empty.setType(SpectrumSettings::SpectrumType::CENTROID); org.unify(empty); TEST_EQUAL(org.getType(), SpectrumSettings::SpectrumType::UNKNOWN) } END_SECTION START_SECTION((static StringList getAllNamesOfSpectrumType())) StringList names = SpectrumSettings::getAllNamesOfSpectrumType(); TEST_EQUAL(names.size(), static_cast<size_t>(SpectrumSettings::SpectrumType::SIZE_OF_SPECTRUMTYPE)); TEST_EQUAL(names[static_cast<size_t>(SpectrumSettings::SpectrumType::CENTROID)], "Centroid"); TEST_EQUAL(names[static_cast<size_t>(SpectrumSettings::SpectrumType::PROFILE)], "Profile"); END_SECTION START_SECTION([EXTRA] std::hash<SpectrumSettings>) { // Test 1: Equal objects have equal hashes SpectrumSettings s1, s2; s1.setNativeID("scan=1"); s1.setComment("test comment"); s1.setType(SpectrumSettings::SpectrumType::CENTROID); // Set up instrument settings InstrumentSettings is; is.setScanMode(InstrumentSettings::ScanMode::MSNSPECTRUM); is.setZoomScan(true); ScanWindow sw; sw.begin = 100.0; sw.end = 2000.0; is.getScanWindows().push_back(sw); s1.setInstrumentSettings(is); // Set up acquisition info AcquisitionInfo ai; ai.setMethodOfCombination("sum"); Acquisition acq; acq.setIdentifier("acq_1"); ai.push_back(acq); s1.setAcquisitionInfo(ai); // Set up source file SourceFile sf; sf.setNameOfFile("test.mzML"); sf.setPathToFile("/data/"); sf.setFileType("mzML"); s1.setSourceFile(sf); // Set up precursors Precursor prec; prec.setMZ(500.5); prec.setIntensity(1000.0f); prec.setCharge(2); prec.setActivationEnergy(35.0); prec.setIsolationWindowLowerOffset(1.5); prec.setIsolationWindowUpperOffset(1.5); s1.getPrecursors().push_back(prec); // Set up products Product prod; prod.setMZ(250.25); s1.getProducts().push_back(prod); // Set up data processing DataProcessingPtr dp = std::make_shared<DataProcessing>(); Software soft; soft.setName("TestTool"); soft.setVersion("1.0"); dp->setSoftware(soft); dp->getProcessingActions().insert(DataProcessing::PEAK_PICKING); s1.getDataProcessing().push_back(dp); // Set meta values s1.setMetaValue("key1", "value1"); s1.setMetaValue("key2", 42); // Copy to s2 s2 = s1; // Verify equality TEST_TRUE(s1 == s2); // Test hash equality for equal objects std::hash<SpectrumSettings> hasher; TEST_EQUAL(hasher(s1), hasher(s2)); // Test 2: Default constructed objects have equal hashes SpectrumSettings empty1, empty2; TEST_EQUAL(hasher(empty1), hasher(empty2)); // Test 3: Different objects should (likely) have different hashes SpectrumSettings diff; diff.setNativeID("scan=999"); diff.setComment("different comment"); diff.setType(SpectrumSettings::SpectrumType::PROFILE); // Note: We don't guarantee different hashes for different objects (collisions are allowed) // but we verify the hash function runs without error std::size_t h1 = hasher(s1); std::size_t h2 = hasher(diff); // Just verify they compute (hash collisions are theoretically possible but unlikely here) TEST_NOT_EQUAL(h1, 0); // Basic sanity check (void)h2; // Suppress unused warning // Test 4: Use in unordered_set std::unordered_set<SpectrumSettings> settings_set; settings_set.insert(s1); settings_set.insert(empty1); settings_set.insert(diff); TEST_EQUAL(settings_set.size(), 3); // Insert duplicate settings_set.insert(s2); // s2 == s1 TEST_EQUAL(settings_set.size(), 3); // Should still be 3 // Test 5: Use in unordered_map std::unordered_map<SpectrumSettings, std::string> settings_map; settings_map[s1] = "first"; settings_map[empty1] = "empty"; settings_map[diff] = "different"; TEST_EQUAL(settings_map.size(), 3); TEST_EQUAL(settings_map[s1], "first"); TEST_EQUAL(settings_map[s2], "first"); // s2 == s1, should get same value // Test 6: Modifying a field changes the hash SpectrumSettings modified = s1; modified.setComment("modified comment"); TEST_FALSE(s1 == modified); // Hash should likely differ (not guaranteed, but extremely likely) std::size_t h_orig = hasher(s1); std::size_t h_mod = hasher(modified); // We just verify both compute; collisions are technically possible (void)h_orig; (void)h_mod; } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ConsensusFeature_test.cpp
.cpp
19,049
676
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg $ // $Authors: $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/KERNEL/ConsensusFeature.h> /////////////////////////// #include <OpenMS/CHEMISTRY/ElementDB.h> #include <OpenMS/CHEMISTRY/Element.h> #include <OpenMS/KERNEL/Feature.h> #include <OpenMS/KERNEL/FeatureMap.h> #include <OpenMS/METADATA/PeptideIdentification.h> using namespace OpenMS; using namespace std; START_TEST(ConsensusFeature, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// ConsensusFeature* ptr = nullptr; ConsensusFeature* nullPointer = nullptr; START_SECTION((ConsensusFeature())) ptr = new ConsensusFeature(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((virtual ~ConsensusFeature())) delete ptr; END_SECTION Feature tmp_feature; tmp_feature.setRT(1); tmp_feature.setMZ(2); tmp_feature.setIntensity(200.0f); tmp_feature.setUniqueId(3); Feature tmp_feature2; tmp_feature2.setRT(2); tmp_feature2.setMZ(3); tmp_feature2.setIntensity(300.0f); tmp_feature2.setUniqueId(5); Feature tmp_feature3; tmp_feature3.setRT(3); tmp_feature3.setMZ(4); tmp_feature3.setIntensity(400.0f); tmp_feature3.setUniqueId(7); START_SECTION(([ConsensusFeature::SizeLess] bool operator () ( ConsensusFeature const & left, ConsensusFeature const & right ) const)) ConsensusFeature c1(tmp_feature); c1.insert(1, tmp_feature); c1.insert(2, tmp_feature3); ConsensusFeature c2(tmp_feature2); c2.insert(1,tmp_feature2); ConsensusFeature::SizeLess sl; TEST_EQUAL(sl(c1,c2), 0); TEST_EQUAL(sl(c2,c1), 1); END_SECTION START_SECTION(([ConsensusFeature::SizeLess] bool operator () ( ConsensusFeature const & left, UInt64 const & right ) const)) ConsensusFeature c1(tmp_feature); c1.insert(1, tmp_feature); c1.insert(2, tmp_feature3); ConsensusFeature c2(tmp_feature); c2.insert(1,tmp_feature); c2.insert(2,tmp_feature2); c2.insert(3,tmp_feature3); UInt64 rhs_size = c2.size(); ConsensusFeature::SizeLess sl; TEST_EQUAL(sl(c1,rhs_size), 1); TEST_EQUAL(sl(c2,rhs_size), 0); END_SECTION START_SECTION(([ConsensusFeature::SizeLess] bool operator () ( UInt64 const & left, ConsensusFeature const & right ) const)) ConsensusFeature c1(tmp_feature); c1.insert(1, tmp_feature); c1.insert(2, tmp_feature3); ConsensusFeature c2(tmp_feature); c2.insert(1,tmp_feature); c2.insert(2,tmp_feature2); c2.insert(3,tmp_feature3); UInt64 lhs_size = c1.size(); ConsensusFeature::SizeLess sl; TEST_EQUAL(sl(lhs_size, c1), 0); TEST_EQUAL(sl(lhs_size, c2), 1); END_SECTION START_SECTION(([ConsensusFeature::SizeLess] bool operator () ( const UInt64 & left, const UInt64 & right ) const)) ConsensusFeature c1(tmp_feature); c1.insert(1, tmp_feature); c1.insert(2, tmp_feature3); ConsensusFeature c2(tmp_feature); c2.insert(1,tmp_feature); c2.insert(2,tmp_feature2); c2.insert(3,tmp_feature3); UInt64 lhs_size = c1.size(), rhs_size = c2.size(); ConsensusFeature::SizeLess sl; TEST_EQUAL(sl(lhs_size, rhs_size), 1); TEST_EQUAL(sl(rhs_size, lhs_size), 0); END_SECTION START_SECTION(([ConsensusFeature::MapsLess] bool operator () ( ConsensusFeature const & left, ConsensusFeature const & right ) const)) ConsensusFeature c1(tmp_feature); c1.insert(1, tmp_feature); c1.insert(2, tmp_feature3); ConsensusFeature c2(tmp_feature); c2.insert(3,tmp_feature); c2.insert(4,tmp_feature2); c2.insert(5,tmp_feature3); ConsensusFeature::MapsLess ml; TEST_EQUAL(ml(c1,c1), 0); TEST_EQUAL(ml(c1,c2), 1); TEST_EQUAL(ml(c2,c1), 0); TEST_EQUAL(ml(c2,c2), 0); END_SECTION START_SECTION((ConsensusFeature& operator=(const ConsensusFeature &rhs))) ConsensusFeature cons(tmp_feature); cons.insert(1,tmp_feature); ConsensusFeature cons_copy; cons_copy = cons; TEST_REAL_SIMILAR(cons_copy.getRT(),1.0) TEST_REAL_SIMILAR(cons_copy.getMZ(),2.0) TEST_REAL_SIMILAR(cons_copy.getIntensity(),200.0) TEST_EQUAL((cons_copy.begin())->getMapIndex(),1) TEST_EQUAL((cons_copy.begin())->getUniqueId(),3) TEST_EQUAL((cons_copy.begin())->getIntensity(),200) END_SECTION START_SECTION((ConsensusFeature(const ConsensusFeature &rhs))) { ConsensusFeature cons(tmp_feature); cons.insert(1,tmp_feature); ConsensusFeature cons_copy(cons); TEST_REAL_SIMILAR(cons_copy.getRT(),1.0) TEST_REAL_SIMILAR(cons_copy.getMZ(),2.0) TEST_REAL_SIMILAR(cons_copy.getIntensity(),200.0) TEST_EQUAL((cons_copy.begin())->getMapIndex(),1) TEST_EQUAL((cons_copy.begin())->getUniqueId(),3) TEST_EQUAL((cons_copy.begin())->getIntensity(),200) } END_SECTION START_SECTION((ConsensusFeature(ConsensusFeature &&rhs))) { #ifndef OPENMS_COMPILER_MSVC // Ensure that ConsensusFeature has a no-except move constructor (otherwise // std::vector is inefficient and will copy instead of move). // Note that MSVS does not support noexcept move constructors for STL // constructs such as std::map. TEST_EQUAL(noexcept(ConsensusFeature(std::declval<ConsensusFeature&&>())), true) #endif ConsensusFeature cons(tmp_feature); cons.insert(1,tmp_feature); ConsensusFeature cons_copy(std::move(cons)); TEST_REAL_SIMILAR(cons_copy.getRT(),1.0) TEST_REAL_SIMILAR(cons_copy.getMZ(),2.0) TEST_REAL_SIMILAR(cons_copy.getIntensity(),200.0) TEST_EQUAL((cons_copy.begin())->getMapIndex(),1) TEST_EQUAL((cons_copy.begin())->getUniqueId(),3) TEST_EQUAL((cons_copy.begin())->getIntensity(),200) } END_SECTION START_SECTION((void insert(const HandleSetType &handle_set))) ConsensusFeature::HandleSetType hs; FeatureHandle fh; for ( UInt i = 0; i < 3; ++i ) { fh.setRT(i*77.7); fh.setMapIndex(i+10); fh.setUniqueId(i+1000); hs.insert(fh); } ConsensusFeature cf; cf.insert(hs); TEST_EQUAL(cf.size(),3); TEST_EQUAL(cf.begin()->getMapIndex(),10); TEST_EQUAL(cf.rbegin()->getMapIndex(),12); END_SECTION START_SECTION((void insert(UInt64 map_index, const Peak2D &element, UInt64 element_index))) ConsensusFeature cf; Peak2D el; for ( UInt i = 0; i < 3; ++i ) { el.setRT(i*77.7); cf.insert(10-i,el,i+1000); TEST_EQUAL(cf.size(),i+1); TEST_REAL_SIMILAR(cf.begin()->getRT(),i*77.7); TEST_EQUAL(cf.begin()->getMapIndex(),10-i); TEST_EQUAL(cf.begin()->getUniqueId(),i+1000); } END_SECTION START_SECTION((void insert(UInt64 map_index, const BaseFeature &element))) ConsensusFeature cf; BaseFeature el; for ( UInt i = 0; i < 3; ++i ) { el.setRT(i*77.7); el.setCharge(2*i); el.setUniqueId(i+1000); cf.insert(10-i,el); TEST_EQUAL(cf.size(),i+1); TEST_REAL_SIMILAR(cf.begin()->getRT(),i*77.7); TEST_EQUAL(cf.begin()->getCharge(),2*i); TEST_EQUAL(cf.begin()->getMapIndex(),10-i); TEST_EQUAL(cf.begin()->getUniqueId(),i+1000); } END_SECTION START_SECTION((ConsensusFeature(const BaseFeature &feature))) BaseFeature f; f.setCharge(-17); f.setRT(44324.6); f.setMZ(867.4); f.setUniqueId(23); f.getPeptideIdentifications().resize(1); const BaseFeature& f_cref = f; ConsensusFeature cf(f_cref); TEST_EQUAL(cf.getRT(),44324.6); TEST_EQUAL(cf.getMZ(),867.4); TEST_EQUAL(cf.getCharge(),-17); TEST_EQUAL(cf.getPeptideIdentifications().size(), 1); TEST_EQUAL(cf.empty(), true); END_SECTION START_SECTION((ConsensusFeature(UInt64 map_index, const BaseFeature& element))) { BaseFeature f; f.setCharge(-17); f.setRT(44324.6); f.setMZ(867.4); f.setIntensity(1000); f.setUniqueId(23); f.getPeptideIdentifications().resize(1); ConsensusFeature cf(99, f); TEST_EQUAL(cf.getRT(),44324.6); TEST_EQUAL(cf.getMZ(),867.4); TEST_EQUAL(cf.getCharge(),-17); TEST_EQUAL(cf.getPeptideIdentifications().size(), 1); ConsensusFeature::HandleSetType::const_iterator it = cf.begin(); TEST_EQUAL(it->getMapIndex(), 99) TEST_EQUAL(it->getUniqueId(), 23) TEST_EQUAL(it->getIntensity(), 1000) } END_SECTION START_SECTION([EXTRA](ConsensusFeature(UInt64 map_index, const Feature &element))) ConsensusFeature cons(1,tmp_feature); cons.setUniqueId(3); TEST_REAL_SIMILAR(cons.getRT(),1.0) TEST_REAL_SIMILAR(cons.getMZ(),2.0) TEST_REAL_SIMILAR(cons.getIntensity(),200.0) ConsensusFeature::HandleSetType::const_iterator it = cons.begin(); TEST_EQUAL(it->getMapIndex(),1) TEST_EQUAL(it->getUniqueId(),3) TEST_EQUAL(it->getIntensity(),200) END_SECTION START_SECTION((ConsensusFeature(UInt64 map_index, const Peak2D &element, UInt64 element_index))) Peak2D f; f.setIntensity(-17); const Peak2D& f_cref = f; ConsensusFeature cf(99,f_cref,23); ConsensusFeature::HandleSetType::const_iterator it = cf.begin(); TEST_EQUAL(it->getMapIndex(),99); TEST_EQUAL(it->getUniqueId(),23); TEST_EQUAL(it->getIntensity(),-17); END_SECTION START_SECTION([EXTRA](ConsensusFeature(UInt64 map_index, const ConsensusFeature &element))) ConsensusFeature f; f.setUniqueId(23); f.setIntensity(-17); const ConsensusFeature& f_cref = f; ConsensusFeature cf(99,f_cref); ConsensusFeature::HandleSetType::const_iterator it = cf.begin(); TEST_EQUAL(it->getMapIndex(),99); TEST_EQUAL(it->getUniqueId(),23); TEST_EQUAL(it->getIntensity(),-17); END_SECTION START_SECTION((DRange<1> getIntensityRange() const)) ConsensusFeature cons; Feature f; f.setIntensity(0.0f); f.setUniqueId(0); cons.insert(0,f); f.setUniqueId(1); f.setIntensity(200.0f); cons.insert(0,f); TEST_REAL_SIMILAR(cons.getIntensityRange().minX(),0.0) TEST_REAL_SIMILAR(cons.getIntensityRange().maxX(),200.0) END_SECTION START_SECTION((DRange<2> getPositionRange() const)) ConsensusFeature cons; Feature f; f.setRT(1.0); f.setMZ(500.0); f.setUniqueId(0); cons.insert(0,f); f.setRT(1000.0); f.setMZ(1500.0); f.setUniqueId(1); cons.insert(0,f); TEST_REAL_SIMILAR(cons.getPositionRange().minX(),1.0) TEST_REAL_SIMILAR(cons.getPositionRange().maxX(),1000.0) TEST_REAL_SIMILAR(cons.getPositionRange().minY(),500.0) TEST_REAL_SIMILAR(cons.getPositionRange().maxY(),1500.0) END_SECTION START_SECTION((const HandleSetType& getFeatures() const)) ConsensusFeature cons; cons.insert(2,tmp_feature); const ConsensusFeature cons_copy(cons); ConsensusFeature::HandleSetType group = cons_copy.getFeatures(); ConsensusFeature::HandleSetType::const_iterator it = group.begin(); TEST_EQUAL(it->getMapIndex(),2) TEST_EQUAL(it->getUniqueId(),3) TEST_EQUAL(it->getIntensity(),200) END_SECTION START_SECTION(( std::vector<FeatureHandle> getFeatureList() const)) ConsensusFeature cons; cons.insert(2,tmp_feature); const ConsensusFeature cons_copy(cons); std::vector<FeatureHandle> group = cons_copy.getFeatureList(); TEST_EQUAL(group.size(),1) TEST_EQUAL(group[0].getMapIndex(),2) TEST_EQUAL(group[0].getUniqueId(),3) TEST_EQUAL(group[0].getIntensity(),200) END_SECTION START_SECTION((void insert(const ConsensusFeature& cf))) ConsensusFeature cons, cons_t; FeatureHandle h1(2,tmp_feature); h1.setUniqueId(3); FeatureHandle h2(4,tmp_feature); h2.setUniqueId(5); cons.insert(h1); cons.insert(h2); cons_t.insert(cons); ConsensusFeature::HandleSetType::const_iterator it = cons_t.begin(); TEST_EQUAL(it->getMapIndex(),2) TEST_EQUAL(it->getUniqueId(),3) TEST_EQUAL(it->getIntensity(),200) ++it; TEST_EQUAL(it->getMapIndex(),4) TEST_EQUAL(it->getUniqueId(),5) TEST_EQUAL(it->getIntensity(),200) ++it; TEST_EQUAL(it==cons_t.end(), true) END_SECTION START_SECTION((void insert(const FeatureHandle &handle))) ConsensusFeature cons; FeatureHandle h1(2,tmp_feature); h1.setUniqueId(3); FeatureHandle h2(4,tmp_feature); h2.setUniqueId(5); cons.insert(h1); cons.insert(h2); ConsensusFeature::HandleSetType::const_iterator it = cons.begin(); TEST_EQUAL(it->getMapIndex(),2) TEST_EQUAL(it->getUniqueId(),3) TEST_EQUAL(it->getIntensity(),200) ++it; TEST_EQUAL(it->getMapIndex(),4) TEST_EQUAL(it->getUniqueId(),5) TEST_EQUAL(it->getIntensity(),200) ++it; TEST_EQUAL(it==cons.end(), true) END_SECTION START_SECTION((void insert(UInt64 map_index, const BaseFeature &element))) ConsensusFeature cons; cons.insert(2, tmp_feature); ConsensusFeature::HandleSetType::const_iterator it = cons.begin(); TEST_EQUAL(it->getMapIndex(),2) TEST_EQUAL(it->getUniqueId(),3) TEST_EQUAL(it->getIntensity(),200) ++it; TEST_EQUAL(it==cons.end(),true) END_SECTION START_SECTION((void computeConsensus())) ConsensusFeature cons; //one point cons.insert(2,tmp_feature); cons.computeConsensus(); TEST_REAL_SIMILAR(cons.getIntensity(),200.0) TEST_REAL_SIMILAR(cons.getRT(),1.0) TEST_REAL_SIMILAR(cons.getMZ(),2.0) //two points cons.insert(4,tmp_feature2); cons.computeConsensus(); TEST_REAL_SIMILAR(cons.getIntensity(),250.0) TEST_REAL_SIMILAR(cons.getRT(),1.5) TEST_REAL_SIMILAR(cons.getMZ(),2.5) //three points cons.insert(6,tmp_feature3); cons.computeConsensus(); TEST_REAL_SIMILAR(cons.getIntensity(),300.0) TEST_REAL_SIMILAR(cons.getRT(),2.0) TEST_REAL_SIMILAR(cons.getMZ(),3.0) END_SECTION START_SECTION((void computeMonoisotopicConsensus())) ConsensusFeature cons; //one point cons.insert(2,tmp_feature); cons.computeMonoisotopicConsensus(); TEST_REAL_SIMILAR(cons.getIntensity(),200.0) TEST_REAL_SIMILAR(cons.getRT(),1.0) TEST_REAL_SIMILAR(cons.getMZ(),2.0) //two points cons.insert(4,tmp_feature2); cons.computeMonoisotopicConsensus(); TEST_REAL_SIMILAR(cons.getIntensity(),250.0) TEST_REAL_SIMILAR(cons.getRT(),1.5) TEST_REAL_SIMILAR(cons.getMZ(),2.0) //three points cons.insert(6,tmp_feature3); cons.computeMonoisotopicConsensus(); TEST_REAL_SIMILAR(cons.getIntensity(),300.0) TEST_REAL_SIMILAR(cons.getRT(),2.0) TEST_REAL_SIMILAR(cons.getMZ(),2.0) END_SECTION START_SECTION((void computeDechargeConsensus(const FeatureMap& fm, bool intensity_weighted_averaging=false))) double proton_mass = ElementDB::getInstance()->getElement("H")->getMonoWeight(); double natrium_mass = ElementDB::getInstance()->getElement("Na")->getMonoWeight(); double m = 1000; double m1_add = 0.5; double mz1 = (m+m1_add+3*proton_mass) / 3; double m2_add = 1; double mz2 = (m+m2_add+1*proton_mass + 2*natrium_mass) / 3; double m3_add = -0.5; double mz3 = (m+m3_add+4*proton_mass + natrium_mass) / 5; FeatureMap fm; //one point ConsensusFeature cons; Feature tmp_feature; tmp_feature.setRT(100); tmp_feature.setMZ(mz1); tmp_feature.setIntensity(200.0f); tmp_feature.setCharge(3); tmp_feature.ensureUniqueId(); fm.push_back(tmp_feature); cons.insert(2,tmp_feature); cons.computeDechargeConsensus(fm); TEST_REAL_SIMILAR(cons.getIntensity(),200.0) TEST_REAL_SIMILAR(cons.getRT(),100) TEST_REAL_SIMILAR(cons.getMZ(), m+m1_add); //two points Feature tmp_feature2; tmp_feature2.setRT(102); tmp_feature2.setMZ(mz2); tmp_feature2.setIntensity(400.0f); tmp_feature2.setCharge(3); tmp_feature2.ensureUniqueId(); tmp_feature2.setMetaValue("dc_charge_adduct_mass", 2*natrium_mass + proton_mass); fm.push_back(tmp_feature2); cons.insert(4,tmp_feature2); cons.computeDechargeConsensus(fm, true); TEST_REAL_SIMILAR(cons.getIntensity(),600.0) TEST_REAL_SIMILAR(cons.getRT(),(100.0/3 + 102.0*2/3)) TEST_REAL_SIMILAR(cons.getMZ(),((m+m1_add)/3 + (m+m2_add)*2/3)) cons.computeDechargeConsensus(fm, false); TEST_REAL_SIMILAR(cons.getIntensity(),600.0) TEST_REAL_SIMILAR(cons.getRT(),(100.0/2 + 102.0/2)) TEST_REAL_SIMILAR(cons.getMZ(),((m+m1_add)/2 + (m+m2_add)/2)) //three points Feature tmp_feature3; tmp_feature3.setRT(101); tmp_feature3.setMZ(mz3); tmp_feature3.setIntensity(600.0f); tmp_feature3.setCharge(5); tmp_feature3.ensureUniqueId(); tmp_feature3.setMetaValue("dc_charge_adduct_mass", 1*natrium_mass + 4*proton_mass); fm.push_back(tmp_feature3); cons.insert(4,tmp_feature3); cons.computeDechargeConsensus(fm, true); TEST_REAL_SIMILAR(cons.getIntensity(),1200.0) TEST_REAL_SIMILAR(cons.getRT(),(100.0/6 + 102.0/3 + 101.0/2)) TEST_REAL_SIMILAR(cons.getMZ(),((m+m1_add)/6 + (m+m2_add)/3 + (m+m3_add)/2)) cons.computeDechargeConsensus(fm, false); TEST_REAL_SIMILAR(cons.getIntensity(),1200.0) TEST_REAL_SIMILAR(cons.getRT(),(100.0/3 + 102.0/3 + 101.0/3)) TEST_REAL_SIMILAR(cons.getMZ(),((m+m1_add)/3 + (m+m2_add)/3 + (m+m3_add)/3)) END_SECTION START_SECTION((Size size() const)) { ConsensusFeature c1(tmp_feature); c1.insert(1, tmp_feature); c1.insert(2, tmp_feature3); TEST_EQUAL(c1.size(), 2) ConsensusFeature c2; TEST_EQUAL(c2.size(), 0) c2.insert(1,tmp_feature2); TEST_EQUAL(c2.size(), 1) } END_SECTION START_SECTION((const_iterator begin() const)) { ConsensusFeature c; const ConsensusFeature& c2 = c; TEST_EQUAL(c2.begin()==c2.end(), true) c.insert(1,tmp_feature2); const ConsensusFeature& c3 = c; TEST_EQUAL(c3.begin()->getUniqueId(), 5) } END_SECTION START_SECTION((iterator begin())) { ConsensusFeature c; TEST_EQUAL(c.begin()==c.end(), true) c.insert(1,tmp_feature2); TEST_EQUAL(c.begin()->getUniqueId(), 5) } END_SECTION START_SECTION((const_iterator end() const)) NOT_TESTABLE // tested above END_SECTION START_SECTION((iterator end())) NOT_TESTABLE // tested above END_SECTION START_SECTION((const_reverse_iterator rbegin() const)) { ConsensusFeature c; const ConsensusFeature& c2 = c; TEST_EQUAL(c2.rbegin()==c2.rend(), true) c.insert(1,tmp_feature2); const ConsensusFeature& c3 = c; TEST_EQUAL(c3.rbegin()->getUniqueId(), 5) } END_SECTION START_SECTION((reverse_iterator rbegin())) { ConsensusFeature c; TEST_EQUAL(c.rbegin()==c.rend(), true) c.insert(1,tmp_feature2); TEST_EQUAL(c.rbegin()->getUniqueId(), 5) } END_SECTION START_SECTION((const_reverse_iterator rend() const)) NOT_TESTABLE // tested above END_SECTION START_SECTION((reverse_iterator rend())) NOT_TESTABLE // tested above END_SECTION START_SECTION((void clear())) { ConsensusFeature c1(tmp_feature); c1.insert(1, tmp_feature); c1.insert(2, tmp_feature3); c1.clear(); TEST_EQUAL(c1.size(), 0) ConsensusFeature c2; TEST_EQUAL(c2.size(), 0) c2.insert(1,tmp_feature2); c2.clear(); TEST_EQUAL(c2.size(), 0) } END_SECTION START_SECTION((bool empty() const)) { ConsensusFeature c1(tmp_feature); c1.insert(1, tmp_feature); c1.insert(2, tmp_feature3); TEST_EQUAL(c1.empty(), false) c1.clear(); TEST_EQUAL(c1.empty(), true) ConsensusFeature c2; TEST_EQUAL(c2.size(), 0) c2.insert(1,tmp_feature2); TEST_EQUAL(c2.empty(), false) c2.clear(); TEST_EQUAL(c2.empty(), true) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/NuXLParameterParsing_test.cpp
.cpp
18,335
549
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg$ // $Authors: Timo Sachsenberg$ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> #include <OpenMS/ANALYSIS/NUXL/NuXLFragmentAdductDefinition.h> #include <OpenMS/ANALYSIS/NUXL/NuXLParameterParsing.h> #include <OpenMS/ANALYSIS/NUXL/NuXLPresets.h> #include <OpenMS/CHEMISTRY/ModificationsDB.h> #include <OpenMS/CHEMISTRY/ResidueModification.h> #include <OpenMS/CHEMISTRY/EmpiricalFormula.h> #include <OpenMS/DATASTRUCTURES/String.h> #include <OpenMS/DATASTRUCTURES/ListUtils.h> #include <unordered_set> using namespace std; /////////////////////////// #include <OpenMS/ANALYSIS/NUXL/NuXLParameterParsing.h> #include <OpenMS/CHEMISTRY/ModificationsDB.h> using namespace OpenMS; using namespace std; START_TEST(NuXLParameterParsing, "$Id$") ///////////////////////////////////////////////////////////// NuXLParameterParsing* ptr = nullptr; NuXLParameterParsing* nullPointer = nullptr; START_SECTION(NuXLParameterParsing()) ptr = new NuXLParameterParsing(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION(~NuXLParameterParsing()) delete ptr; END_SECTION START_SECTION((static std::vector<ResidueModification> getModifications(StringList modNames))) { StringList mods; mods.push_back("Phospho (S)"); mods.push_back("Oxidation (M)"); mods.push_back("Acetyl (N-term)"); vector<ResidueModification> result = NuXLParameterParsing::getModifications(mods); TEST_EQUAL(result.size(), 3) TEST_EQUAL(result[0].getId(), "Phospho") TEST_EQUAL(result[1].getId(), "Oxidation") TEST_EQUAL(result[2].getId(), "Acetyl") TEST_EQUAL(result[2].getTermSpecificity(), ResidueModification::N_TERM) } END_SECTION /* START_SECTION((static NucleotideToFragmentAdductMap getTargetNucleotideToFragmentAdducts(StringList fragment_adducts))) { StringList fragment_adducts; fragment_adducts.push_back("U:H-2O-1;U-H2O"); // Format is nucleotide:formula;name fragment_adducts.push_back("U:H-3P-1O-4;U-H3PO4"); NuXLParameterParsing::NucleotideToFragmentAdductMap result = NuXLParameterParsing::getTargetNucleotideToFragmentAdducts(fragment_adducts); TEST_EQUAL(result.size(), 1) // Only U nucleotide TEST_EQUAL(result['U'].size(), 2) // Two adducts for U // Test invalid format StringList invalid_adducts; invalid_adducts.push_back("Invalid format"); NuXLParameterParsing::NucleotideToFragmentAdductMap empty_result = NuXLParameterParsing::getTargetNucleotideToFragmentAdducts(invalid_adducts); TEST_EQUAL(empty_result.empty(), true) } END_SECTION START_SECTION((static MS2AdductsOfSinglePrecursorAdduct getFeasibleFragmentAdducts(const String& exp_pc_adduct, const String& exp_pc_formula, const NucleotideToFragmentAdductMap& nucleotide_to_fragment_adducts, const std::set<char>& can_xl, const bool always_add_default_marker_ions, const bool default_marker_ions_RNA))) { // Create test data StringList fragment_adducts; fragment_adducts.push_back("U:H-2O-1;U-H2O"); NuXLParameterParsing::NucleotideToFragmentAdductMap nuc_to_frag = NuXLParameterParsing::getTargetNucleotideToFragmentAdducts(fragment_adducts); set<char> can_xl = {'U'}; // Test monomer case MS2AdductsOfSinglePrecursorAdduct result = NuXLParameterParsing::getFeasibleFragmentAdducts( "U-H2O", // precursor adduct "C9H11N2O7P", // precursor formula nuc_to_frag, can_xl, true, true); TEST_EQUAL(result.feasible_adducts.size(), 1) // One nucleotide TEST_NOT_EQUAL(result.marker_ions.size(), 0) // Should have marker ions // Test empty precursor formula MS2AdductsOfSinglePrecursorAdduct empty_result = NuXLParameterParsing::getFeasibleFragmentAdducts( "U-H2O", "", nuc_to_frag, can_xl, true, true); TEST_EQUAL(empty_result.feasible_adducts.empty(), true) TEST_EQUAL(empty_result.marker_ions.empty(), true) } END_SECTION START_SECTION((static std::vector<NuXLFragmentAdductDefinition> getMarkerIonsMassSet(const PrecursorsToMS2Adducts& pc2adducts))) { // First create some test data StringList fragment_adducts; fragment_adducts.push_back("U:H-2O-1;U-H2O"); NuXLParameterParsing::NucleotideToFragmentAdductMap nuc_to_frag = NuXLParameterParsing::getTargetNucleotideToFragmentAdducts(fragment_adducts); set<char> can_xl = {'U'}; MS2AdductsOfSinglePrecursorAdduct ms2_adducts = NuXLParameterParsing::getFeasibleFragmentAdducts( "U-H2O", "C9H11N2O7P", nuc_to_frag, can_xl, true, true); NuXLParameterParsing::PrecursorsToMS2Adducts pc2adducts; pc2adducts["U-H2O"] = ms2_adducts; vector<NuXLFragmentAdductDefinition> result = NuXLParameterParsing::getMarkerIonsMassSet(pc2adducts); TEST_NOT_EQUAL(result.size(), 0) // Should have marker ions // Test empty input NuXLParameterParsing::PrecursorsToMS2Adducts empty_pc2adducts; vector<NuXLFragmentAdductDefinition> empty_result = NuXLParameterParsing::getMarkerIonsMassSet(empty_pc2adducts); TEST_EQUAL(empty_result.empty(), true) } END_SECTION */ START_SECTION((static PrecursorsToMS2Adducts getAllFeasibleFragmentAdducts(const NuXLModificationMassesResult& precursor_adducts, const NucleotideToFragmentAdductMap& nucleotide_to_fragment_adducts, const std::set<char>& can_xl, const bool always_add_default_marker_ions, const bool default_marker_ions_RNA))) { // Retrieve preset for RNA-UV (U). // This preset contains all necessary information to generate the precursor adducts and fragment adducts. StringList modifications; // The precursor adducts are then used to generate all feasible fragment adducts. StringList fragment_adducts; // these are responsible for shifted fragment ions. Their fragment adducts thus determine which shifts will be observed on b-,a-,y-ions String can_cross_link; // nucleotides that can directly cross-link // string format: target,formula e.g. "A=C10H14N5O7P", ..., "U=C10H14N5O7P", "X=C9H13N2O8PS" where X represents tU StringList target_nucleotides; // string format: source->target e.g. "A->A", ..., "U->U", "U->X" StringList mappings; NuXLPresets::getPresets("RNA-UV (U)", target_nucleotides, mappings, modifications, fragment_adducts, can_cross_link); // test preset strings TEST_EQUAL(target_nucleotides.size(), 4) StringList expected_target_nucleotides = { "A=C10H14N5O7P", "C=C9H14N3O8P", "G=C10H14N5O8P", "U=C9H13N2O9P" }; TEST_TRUE(target_nucleotides == expected_target_nucleotides); if (target_nucleotides != expected_target_nucleotides) { for (const auto& t : target_nucleotides) { std::cerr << t << endl; } } // list all precursor adducts (including nucleotides that can't cross-link) StringList expected_modifications = { "U:", "U:-H2O", "C:", "C:-H2O", "C:-NH3", "G:", "G:-H2O", "G:-NH3", "A:", "A:-NH3" }; TEST_TRUE(modifications == expected_modifications); if (modifications != expected_modifications) { for (const auto& m : modifications) { std::cerr << m << endl; } } StringList expected_fragment_adducts = { "U:C3O;C3O", "U:C4H4N2O2;U'", "U:C4H2N2O1;U'-H2O", "U:C9H13N2O9P1;U", "U:C9H11N2O8P1;U-H2O", "U:C9H12N2O6;U-HPO3", "U:C9H10N2O5;U-H3PO4", "C:C4H5N3O;C'", "C:C4H3N3;C'-H2O", "C:C4H2N2O;C'-NH3", "C:C9H14N3O8P;C", "C:C9H11N2O8P;C-NH3", "C:C9H12N3O7P;C-H2O", "C:C9H9N2O7P;C-NH3-H2O", "C:C9H13N3O5;C-HPO3", "C:C9H11N3O4;C-H3PO4", "C:C9H10N2O5;C-NH3-HPO3", "C:C9H8N2O4;C-NH3-H3PO4", "G:C5H5N5O;G'", "G:C5H3N5;G'-H2O", "G:C5H2N4O;G'-NH3", "G:C10H14N5O8P;G", "G:C10H12N5O7P;G-H2O", "G:C10H11N4O8P;G-NH3", "G:C10H9N4O7P;G-NH3-H2O", "G:C10H13N5O5;G-HPO3", "G:C10H11N5O4;G-H3PO4", "G:C10H10N4O5;G-NH3-HPO3", "G:C10H8N4O4;G-NH3-H3PO4", "A:C5H5N5;A'", "A:C5H2N4;A'-NH3", "A:C10H14N5O7P;A", "A:C10H12N5O6P;A-H2O", "A:C10H11N4O7P;A-NH3", "A:C10H9N4O6P;A-NH3-H2O", "A:C10H13N5O4;A-HPO3", "A:C10H11N5O3;A-H3PO4", "A:C10H10N5O4;A-NH3-HPO3", "A:C10H8N5O3;A-NH3-H3PO4" }; TEST_TRUE(fragment_adducts == expected_fragment_adducts); TEST_EQUAL(can_cross_link, "U") TEST_EQUAL(mappings.size(), 4) StringList expected_mapping = { "A->A", "C->C", "G->G", "U->U" }; TEST_EQUAL(mappings.size(), 4) TEST_TRUE(mappings == expected_mapping); if (mappings != expected_mapping) { for (const auto& m : mappings) { std::cerr << m << endl; } } // convert string to set set<char> can_xl; for (const auto& c : can_cross_link) { can_xl.insert(c); } // sort and make unique NuXLModificationMassesResult mm = NuXLModificationsGenerator::initModificationMassesNA( target_nucleotides, StringList(), can_xl, mappings, modifications, "", false, 2); mm.formula2mass[""] = 0; // insert "null" modification otherwise peptides without NA will not be searched mm.mod_combinations[""].insert("none"); // check content of formula2mass and ensure order is correct StringList formula = { "", "C18H22N4O16P2", "C18H23N5O15P2", "C18H24N4O17P2", "C18H25N5O16P2", "C19H22N6O15P2", "C19H22N6O16P2", "C19H23N7O14P2", "C19H23N7O15P2", "C19H25N7O15P2", "C19H25N7O16P2", "C9H11N2O8P1", "C9H13N2O9P1" }; DoubleList mass = { 0, 612.051, 611.067, 630.061, 629.077, 636.062, 652.057, 635.078, 651.073, 653.088, 669.083, 306.025, 324.036 }; // compare using approximate double comparison due to floating point precision for (Size i = 0; i != formula.size(); ++i) { TEST_REAL_SIMILAR(mm.formula2mass[formula[i]], mass[i]) } std::vector<std::string> expected_precursor_formula = { "", "C18H22N4O16P2", "C18H23N5O15P2", "C18H24N4O17P2", "C18H25N5O16P2", "C19H22N6O15P2", "C19H22N6O16P2", "C19H23N7O14P2", "C19H23N7O15P2", "C19H25N7O15P2", "C19H25N7O16P2", "C9H11N2O8P1", "C9H13N2O9P1" }; std::vector<std::vector<std::string>> expected_precursors = { {"none"}, {"UC-H3N1", "UU-H2O1"}, {"CU-H2O1"}, {"UU"}, {"CU"}, {"UA-H3N1"}, {"UG-H3N1"}, {"AU-H2O1"}, {"GU-H2O1"}, {"AU"}, {"GU"}, {"U-H2O1"}, {"U"} }; // check content of mod_combinations (order matters) for (Size i = 0; i != expected_precursor_formula.size(); ++i) { TEST_EQUAL(mm.mod_combinations[expected_precursor_formula[i]].size(), expected_precursors[i].size()) for (Size j = 0; j != expected_precursors[i].size(); ++j) { auto it = mm.mod_combinations[expected_precursor_formula[i]].begin(); std::advance(it, j); TEST_EQUAL(*it, expected_precursors[i][j]) } } // first, we determine which fragments adducts can be generated from a single nucleotide (that has no losses) NuXLParameterParsing::NucleotideToFragmentAdductMap nucleotide_to_fragment_adducts = NuXLParameterParsing::getTargetNucleotideToFragmentAdducts(fragment_adducts); // check if all nucleotides are covered by the map (required to generate fragment adducts) std::vector<std::pair<char, std::vector<std::string>>> expected_nucleotides_to_fragments = { {'A', { "A'-NH3", "A'", "A-NH3-H3PO4", "A-H3PO4", "A-NH3-HPO3", "A-HPO3", "A-NH3-H2O", "A-H2O", "A-NH3", "A" }}, {'C', { "C'-H2O", "C'-NH3", "C'", "C-NH3-H3PO4", "C-H3PO4", "C-NH3-HPO3", "C-HPO3", "C-NH3-H2O", "C-H2O", "C-NH3", "C" }}, {'G', { "G'-H2O", "G'-NH3", "G'", "G-NH3-H3PO4", "G-H3PO4", "G-NH3-HPO3", "G-HPO3", "G-NH3-H2O", "G-H2O", "G-NH3", "G" }}, {'U', { "C3O", "U'-H2O", "U'", "U-H3PO4", "U-HPO3", "U-H2O", "U" }} }; TEST_EQUAL(nucleotide_to_fragment_adducts.size(), expected_nucleotides_to_fragments.size()) for (size_t nt = 0; nt != expected_nucleotides_to_fragments.size(); ++nt) { // test target nucleotide formula auto it = nucleotide_to_fragment_adducts.begin(); std::advance(it, nt); TEST_EQUAL(expected_nucleotides_to_fragments[nt].first, it->first); // order should match the expected target nucleotides TEST_EQUAL(expected_nucleotides_to_fragments[nt].second.size(), it->second.size()) if (expected_nucleotides_to_fragments[nt].second.size() != it->second.size()) { for (const auto& f : it->second) { std::cerr << f.name << endl; } } for (size_t f = 0; f != expected_nucleotides_to_fragments[nt].second.size(); ++f) { auto fit = it->second.begin(); std::advance(fit, f); // order should match exactly the expected fragments TEST_TRUE(expected_nucleotides_to_fragments[nt].second[f] == fit->name) } } // calculate all feasible fragment adducts from all possible precursor adducts NuXLParameterParsing::PrecursorsToMS2Adducts all_feasible_fragment_adducts = NuXLParameterParsing::getAllFeasibleFragmentAdducts(mm, nucleotide_to_fragment_adducts, can_xl, true, true); // print all chemically feasible fragment adducts std::vector<std::pair<std::string, std::pair<char, std::vector<std::string>>>> expected_pc2nuc2fragment_adducts = { {"AU", {'U', {"C3O", "U'-H2O", "U'", "U-H3PO4", "U-HPO3", "U-H2O", "U"}}}, {"AU-H2O1", {'U', {"C3O", "U'-H2O", "U'", "U-H3PO4", "U-HPO3", "U-H2O", "U"}}}, {"CU", {'U', {"C3O", "U'-H2O", "U'", "U-H3PO4", "U-HPO3", "U-H2O", "U"}}}, {"CU-H2O1", {'U', {"C3O", "U'-H2O", "U'", "U-H3PO4", "U-HPO3", "U-H2O", "U"}}}, {"GU", {'U', {"C3O", "U'-H2O", "U'", "U-H3PO4", "U-HPO3", "U-H2O", "U"}}}, {"GU-H2O1", {'U', {"C3O", "U'-H2O", "U'", "U-H3PO4", "U-HPO3", "U-H2O", "U"}}}, {"U", {'U', {"C3O", "U'-H2O", "U'", "U-H3PO4", "U-HPO3", "U-H2O", "U"}}}, {"U-H2O1", {'U', {"C3O", "U'-H2O", "U'", "U-H3PO4", "U-H2O"}}}, {"UA-H3N1", {'U', {"C3O", "U'-H2O", "U'", "U-H3PO4", "U-HPO3", "U-H2O", "U"}}}, {"UC-H3N1", {'U', {"C3O", "U'-H2O", "U'", "U-H3PO4", "U-HPO3", "U-H2O", "U"}}}, {"UG-H3N1", {'U', {"C3O", "U'-H2O", "U'", "U-H3PO4", "U-HPO3", "U-H2O", "U"}}}, {"UU", {'U', {"C3O", "U'-H2O", "U'", "U-H3PO4", "U-HPO3", "U-H2O", "U"}}}, {"UU-H2O1", {'U', {"C3O", "U'-H2O", "U'", "U-H3PO4", "U-HPO3", "U-H2O", "U"}}}, {"none", {'U', {}}} }; TEST_EQUAL(all_feasible_fragment_adducts.size(), expected_pc2nuc2fragment_adducts.size()) // Compare each precursor and its associated fragments in order auto it_expected = expected_pc2nuc2fragment_adducts.begin(); auto it_actual = all_feasible_fragment_adducts.begin(); while (it_expected != expected_pc2nuc2fragment_adducts.end() && it_actual != all_feasible_fragment_adducts.end()) { const String& expected_precursor = it_expected->first; const String& actual_precursor = it_actual->first; // Ensure the order of precursors is preserved TEST_EQUAL(expected_precursor, actual_precursor) const auto& expected_adducts = it_expected->second; const MS2AdductsOfSinglePrecursorAdduct& ms2adducts = it_actual->second; const std::vector<NucleotideToFeasibleFragmentAdducts>& nt2feasible = ms2adducts.feasible_adducts; if (!nt2feasible.empty()) { const auto& n2fsa = nt2feasible[0]; // Check nucleotide TEST_EQUAL(n2fsa.first, expected_adducts.first) // Check fragment adducts TEST_EQUAL(n2fsa.second.size(), expected_adducts.second.size()) for (Size i = 0; i < expected_adducts.second.size(); ++i) { if (i < n2fsa.second.size()) { TEST_EQUAL(n2fsa.second[i].name, expected_adducts.second[i]) } } } ++it_expected; ++it_actual; } } END_SECTION START_SECTION(([EXTRA] std::hash<NuXLFragmentAdductDefinition>)) { // Test that equal definitions have equal hashes NuXLFragmentAdductDefinition fad1(EmpiricalFormula("C4H4N2O2"), "U'", 112.027); NuXLFragmentAdductDefinition fad2(EmpiricalFormula("C4H4N2O2"), "U'", 112.027); std::hash<NuXLFragmentAdductDefinition> hasher; TEST_EQUAL(hasher(fad1), hasher(fad2)) // Test that different formulas produce different hashes NuXLFragmentAdductDefinition fad3(EmpiricalFormula("C4H2N2O1"), "U'-H2O", 94.016); TEST_NOT_EQUAL(hasher(fad1), hasher(fad3)) // Test that different names produce different hashes (same formula) NuXLFragmentAdductDefinition fad4(EmpiricalFormula("C4H4N2O2"), "different_name", 112.027); TEST_NOT_EQUAL(hasher(fad1), hasher(fad4)) // Note: mass is not used in operator== so it should not affect the hash NuXLFragmentAdductDefinition fad5(EmpiricalFormula("C4H4N2O2"), "U'", 999.999); TEST_EQUAL(hasher(fad1), hasher(fad5)) // Test empty definitions NuXLFragmentAdductDefinition fad_empty1; NuXLFragmentAdductDefinition fad_empty2; TEST_EQUAL(hasher(fad_empty1), hasher(fad_empty2)) // Test that definitions work in unordered_set std::unordered_set<NuXLFragmentAdductDefinition> fad_set; fad_set.insert(fad1); fad_set.insert(fad2); // Duplicate, should not increase size fad_set.insert(fad3); // Different definition TEST_EQUAL(fad_set.size(), 2) TEST_EQUAL(fad_set.count(fad1), 1) TEST_EQUAL(fad_set.count(fad2), 1) // Same as fad1 TEST_EQUAL(fad_set.count(fad3), 1) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/Precursor_test.cpp
.cpp
16,735
524
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Mathias Walzer $ // $Authors: Marc Sturm $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/METADATA/Precursor.h> /////////////////////////// #include <unordered_set> #include <unordered_map> using namespace OpenMS; using namespace std; START_TEST(Precursor, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// Precursor* ptr = nullptr; Precursor* nullPointer = nullptr; START_SECTION((Precursor())) ptr = new Precursor(); TEST_NOT_EQUAL(ptr, nullPointer) END_SECTION START_SECTION((~Precursor())) delete ptr; END_SECTION START_SECTION((double getActivationEnergy() const)) Precursor tmp; TEST_EQUAL(tmp.getActivationEnergy(),0); END_SECTION START_SECTION((void setActivationEnergy(double activation_energy))) Precursor tmp; tmp.setActivationEnergy(47.11); TEST_REAL_SIMILAR(tmp.getActivationEnergy(),47.11); END_SECTION START_SECTION((double getDriftTime() const)) Precursor tmp; TEST_EQUAL(tmp.getDriftTime(),-1); END_SECTION START_SECTION((void setDriftTime(double dt))) Precursor tmp; tmp.setDriftTime(47.11); TEST_REAL_SIMILAR(tmp.getDriftTime(),47.11); END_SECTION START_SECTION((double getDriftTimeUnit() const )) Precursor tmp; TEST_EQUAL(tmp.getDriftTimeUnit() == DriftTimeUnit::NONE, true); END_SECTION START_SECTION((void setDriftTimeUnit(double dt))) Precursor tmp; tmp.setDriftTimeUnit(DriftTimeUnit::MILLISECOND); TEST_EQUAL(tmp.getDriftTimeUnit() == DriftTimeUnit::MILLISECOND, true); END_SECTION START_SECTION((const set<ActivationMethod>& getActivationMethods() const)) Precursor tmp; TEST_EQUAL(tmp.getActivationMethods().size(),0); END_SECTION START_SECTION((set<ActivationMethod>& getActivationMethods())) Precursor tmp; tmp.getActivationMethods().insert(Precursor::ActivationMethod::CID); TEST_EQUAL(tmp.getActivationMethods().size(),1); END_SECTION START_SECTION((void setActivationMethods(const set<ActivationMethod>& activation_methods))) Precursor tmp; set<Precursor::ActivationMethod> methods; methods.insert(Precursor::ActivationMethod::CID); tmp.setActivationMethods(methods); TEST_EQUAL(tmp.getActivationMethods().size(),1); END_SECTION START_SECTION((StringList getActivationMethodsAsString() const)) Precursor tmp; set<Precursor::ActivationMethod> methods; methods.insert(Precursor::ActivationMethod::CID); tmp.setActivationMethods(methods); StringList result = tmp.getActivationMethodsAsString(); TEST_EQUAL(result.size(), 1); TEST_EQUAL(result[0], "Collision-induced dissociation"); END_SECTION START_SECTION((StringList getActivationMethodsAsShortString() const)) Precursor tmp; set<Precursor::ActivationMethod> methods; methods.insert(Precursor::ActivationMethod::CID); tmp.setActivationMethods(methods); StringList result = tmp.getActivationMethodsAsShortString(); TEST_EQUAL(result.size(), 1); TEST_EQUAL(result[0], "CID"); END_SECTION START_SECTION((static StringList getAllNamesOfActivationMethods())) StringList result = Precursor::getAllNamesOfActivationMethods(); TEST_EQUAL(result.size(), static_cast<size_t>(Precursor::ActivationMethod::SIZE_OF_ACTIVATIONMETHOD)); END_SECTION START_SECTION((static StringList getAllShortNamesOfActivationMethods())) StringList result = Precursor::getAllShortNamesOfActivationMethods(); TEST_EQUAL(result.size(), static_cast<size_t>(Precursor::ActivationMethod::SIZE_OF_ACTIVATIONMETHOD)); END_SECTION START_SECTION((double getIsolationWindowUpperOffset() const)) Precursor tmp; TEST_REAL_SIMILAR(tmp.getIsolationWindowUpperOffset(), 0); END_SECTION START_SECTION((void setIsolationWindowUpperOffset(double bound))) Precursor tmp; tmp.setIsolationWindowUpperOffset(22.7); TEST_REAL_SIMILAR(tmp.getIsolationWindowUpperOffset(), 22.7); END_SECTION START_SECTION((double getIsolationWindowLowerOffset() const)) Precursor tmp; TEST_REAL_SIMILAR(tmp.getIsolationWindowLowerOffset(), 0); END_SECTION START_SECTION((void setIsolationWindowLowerOffset(double bound))) Precursor tmp; tmp.setIsolationWindowLowerOffset(22.8); TEST_REAL_SIMILAR(tmp.getIsolationWindowLowerOffset(), 22.8); END_SECTION START_SECTION((double getDriftTimeWindowUpperOffset() const)) Precursor tmp; TEST_REAL_SIMILAR(tmp.getDriftTimeWindowUpperOffset(), 0); END_SECTION START_SECTION((void setDriftTimeWindowUpperOffset(double bound))) Precursor tmp; tmp.setDriftTimeWindowUpperOffset(22.7); TEST_REAL_SIMILAR(tmp.getDriftTimeWindowUpperOffset(), 22.7); END_SECTION START_SECTION((double getDriftTimeWindowLowerOffset() const)) Precursor tmp; TEST_REAL_SIMILAR(tmp.getDriftTimeWindowLowerOffset(), 0); END_SECTION START_SECTION((void setDriftTimeWindowLowerOffset(double bound))) Precursor tmp; tmp.setDriftTimeWindowLowerOffset(22.8); TEST_REAL_SIMILAR(tmp.getDriftTimeWindowLowerOffset(), 22.8); END_SECTION START_SECTION((Int getCharge() const)) Precursor tmp; TEST_EQUAL(tmp.getCharge(), 0); END_SECTION START_SECTION((void setCharge(Int charge))) Precursor tmp; tmp.setCharge(2); TEST_EQUAL(tmp.getCharge(), 2); END_SECTION START_SECTION((const std::vector<Int>& getPossibleChargeStates() const)) Precursor tmp; TEST_EQUAL(tmp.getPossibleChargeStates().size(), 0); END_SECTION START_SECTION((std::vector<Int>& getPossibleChargeStates())) Precursor tmp; tmp.getPossibleChargeStates().resize(1); TEST_EQUAL(tmp.getPossibleChargeStates().size(), 1); END_SECTION START_SECTION((void setPossibleChargeStates(const std::vector<Int>& possible_charge_states))) Precursor tmp; vector<Int> states(1); tmp.setPossibleChargeStates(states); TEST_EQUAL(tmp.getPossibleChargeStates().size(), 1); END_SECTION START_SECTION((Precursor(const Precursor& source))) { Precursor tmp; tmp.getActivationMethods().insert(Precursor::ActivationMethod::CID); tmp.setActivationEnergy(47.11); tmp.setIsolationWindowUpperOffset(22.7); tmp.setIsolationWindowLowerOffset(22.8); tmp.setDriftTime(7.11); tmp.setDriftTimeWindowUpperOffset(12.8); tmp.setDriftTimeWindowLowerOffset(12.7); tmp.setDriftTimeUnit(DriftTimeUnit::MILLISECOND); tmp.setCharge(2); tmp.getPossibleChargeStates().resize(2); tmp.setMetaValue("label",String("label")); Precursor tmp2(tmp); TEST_EQUAL(tmp2.getActivationMethods().size(),1); TEST_REAL_SIMILAR(tmp2.getActivationEnergy(),47.11); TEST_REAL_SIMILAR(tmp2.getIsolationWindowUpperOffset(), 22.7); TEST_REAL_SIMILAR(tmp2.getIsolationWindowLowerOffset(), 22.8); TEST_REAL_SIMILAR(tmp2.getDriftTime(),7.11); TEST_REAL_SIMILAR(tmp2.getDriftTimeWindowUpperOffset(), 12.8); TEST_REAL_SIMILAR(tmp2.getDriftTimeWindowLowerOffset(), 12.7); TEST_EQUAL(tmp2.getDriftTimeUnit() == DriftTimeUnit::MILLISECOND, true); TEST_EQUAL(tmp2.getCharge(),2); TEST_EQUAL(tmp2.getPossibleChargeStates().size(),2); TEST_EQUAL((String)(tmp2.getMetaValue("label")), "label"); } END_SECTION START_SECTION((Precursor(const Precursor&& source))) { Precursor tmp; tmp.getActivationMethods().insert(Precursor::ActivationMethod::CID); tmp.getActivationMethods().insert(Precursor::ActivationMethod::BIRD); tmp.setActivationEnergy(40.11); tmp.setIsolationWindowUpperOffset(20.7); tmp.setIsolationWindowLowerOffset(20.8); tmp.setDriftTime(0.11); tmp.setDriftTimeWindowUpperOffset(10.8); tmp.setDriftTimeWindowLowerOffset(10.7); tmp.setDriftTimeUnit(DriftTimeUnit::VSSC); tmp.setCharge(8); tmp.getPossibleChargeStates().resize(4); tmp.setMetaValue("label",String("label2")); TEST_EQUAL(tmp.getActivationMethods().size(),2); //copy tmp so we can move one of them Precursor orig = tmp; Precursor tmp2(std::move(tmp)); TEST_EQUAL(tmp2, orig); TEST_EQUAL(tmp2.getActivationMethods().size(),2); TEST_REAL_SIMILAR(tmp2.getActivationEnergy(),40.11); TEST_REAL_SIMILAR(tmp2.getIsolationWindowUpperOffset(), 20.7); TEST_REAL_SIMILAR(tmp2.getIsolationWindowLowerOffset(), 20.8); TEST_REAL_SIMILAR(tmp2.getDriftTime(),0.11); TEST_REAL_SIMILAR(tmp2.getDriftTimeWindowUpperOffset(), 10.8); TEST_REAL_SIMILAR(tmp2.getDriftTimeWindowLowerOffset(), 10.7); TEST_EQUAL(tmp2.getDriftTimeUnit() == DriftTimeUnit::VSSC, true); TEST_EQUAL(tmp2.getCharge(),8); TEST_EQUAL(tmp2.getPossibleChargeStates().size(),4); TEST_EQUAL((String)(tmp2.getMetaValue("label")), "label2"); } END_SECTION START_SECTION((Precursor& operator= (const Precursor& source))) { Precursor tmp; tmp.getActivationMethods().insert(Precursor::ActivationMethod::CID); tmp.setActivationEnergy(47.11); tmp.setIsolationWindowUpperOffset(22.7); tmp.setIsolationWindowLowerOffset(22.8); tmp.setDriftTime(7.11); tmp.setDriftTimeWindowUpperOffset(12.8); tmp.setDriftTimeWindowLowerOffset(12.7); tmp.setDriftTimeUnit(DriftTimeUnit::MILLISECOND); tmp.setCharge(9); tmp.getPossibleChargeStates().resize(5); tmp.setMetaValue("label",String("label")); //normal assignment Precursor tmp2; tmp2 = tmp; TEST_EQUAL(tmp2.getActivationMethods().size(),1); TEST_REAL_SIMILAR(tmp2.getActivationEnergy(),47.11); TEST_REAL_SIMILAR(tmp2.getIsolationWindowUpperOffset(), 22.7); TEST_REAL_SIMILAR(tmp2.getIsolationWindowLowerOffset(), 22.8); TEST_REAL_SIMILAR(tmp2.getDriftTime(),7.11); TEST_REAL_SIMILAR(tmp2.getDriftTimeWindowUpperOffset(), 12.8); TEST_REAL_SIMILAR(tmp2.getDriftTimeWindowLowerOffset(), 12.7); TEST_EQUAL(tmp2.getDriftTimeUnit() == DriftTimeUnit::MILLISECOND, true); TEST_EQUAL(tmp2.getCharge(),9); TEST_EQUAL(tmp2.getPossibleChargeStates().size(),5); TEST_EQUAL((String)(tmp2.getMetaValue("label")), "label"); //assignment of empty object tmp2 = Precursor(); TEST_EQUAL(tmp2.getActivationMethods().size(),0); TEST_REAL_SIMILAR(tmp2.getActivationEnergy(),0.0); TEST_REAL_SIMILAR(tmp2.getIsolationWindowUpperOffset(), 0.0); TEST_REAL_SIMILAR(tmp2.getIsolationWindowLowerOffset(), 0.0); TEST_REAL_SIMILAR(tmp2.getDriftTime(),-1.0); TEST_REAL_SIMILAR(tmp2.getDriftTimeWindowUpperOffset(), 0.0); TEST_REAL_SIMILAR(tmp2.getDriftTimeWindowLowerOffset(), 0.0); TEST_EQUAL(tmp2.getDriftTimeUnit() == DriftTimeUnit::NONE, true); TEST_EQUAL(tmp2.getCharge(),0); TEST_EQUAL(tmp2.getPossibleChargeStates().size(),0); TEST_EQUAL(tmp2.getMetaValue("label").isEmpty(), true); } END_SECTION START_SECTION((Precursor& operator= (const Precursor&& source))) { Precursor tmp; tmp.getActivationMethods().insert(Precursor::ActivationMethod::CID); tmp.getActivationMethods().insert(Precursor::ActivationMethod::BIRD); tmp.setActivationEnergy(40.11); tmp.setIsolationWindowUpperOffset(20.7); tmp.setIsolationWindowLowerOffset(20.8); tmp.setDriftTime(0.11); tmp.setDriftTimeWindowUpperOffset(10.8); tmp.setDriftTimeWindowLowerOffset(10.7); tmp.setDriftTimeUnit(DriftTimeUnit::VSSC); tmp.setCharge(8); tmp.getPossibleChargeStates().resize(4); tmp.setMetaValue("label",String("label2")); //copy tmp so we can move one of them Precursor orig = tmp; //move assignment Precursor tmp2; tmp2 = std::move(tmp); TEST_EQUAL(tmp2, orig); TEST_EQUAL(tmp2.getActivationMethods().size(),2); TEST_REAL_SIMILAR(tmp2.getActivationEnergy(),40.11); TEST_REAL_SIMILAR(tmp2.getIsolationWindowUpperOffset(), 20.7); TEST_REAL_SIMILAR(tmp2.getIsolationWindowLowerOffset(), 20.8); TEST_REAL_SIMILAR(tmp2.getDriftTime(),0.11); TEST_REAL_SIMILAR(tmp2.getDriftTimeWindowUpperOffset(), 10.8); TEST_REAL_SIMILAR(tmp2.getDriftTimeWindowLowerOffset(), 10.7); TEST_EQUAL(tmp2.getDriftTimeUnit() == DriftTimeUnit::VSSC, true); TEST_EQUAL(tmp2.getCharge(),8); TEST_EQUAL(tmp2.getPossibleChargeStates().size(),4); TEST_EQUAL((String)(tmp2.getMetaValue("label")), "label2"); } END_SECTION START_SECTION((bool operator== (const Precursor& rhs) const)) Precursor tmp,tmp2; TEST_TRUE(tmp == tmp2); tmp2.setActivationEnergy(47.11); TEST_EQUAL(tmp==tmp2, false); tmp2 = tmp; tmp.setDriftTime(5.0); TEST_EQUAL(tmp==tmp2, false); tmp2 = tmp; tmp.setDriftTimeUnit(DriftTimeUnit::MILLISECOND); TEST_EQUAL(tmp==tmp2, false); tmp2 = tmp; tmp.getActivationMethods().insert(Precursor::ActivationMethod::CID); TEST_EQUAL(tmp==tmp2, false); tmp2 = tmp; tmp.setIsolationWindowUpperOffset(22.7); TEST_EQUAL(tmp==tmp2, false); tmp2 = tmp; tmp.setIsolationWindowLowerOffset(22.8); TEST_EQUAL(tmp==tmp2, false); tmp2 = tmp; tmp.setDriftTimeWindowUpperOffset(22.7); TEST_EQUAL(tmp==tmp2, false); tmp2 = tmp; tmp.setDriftTimeWindowLowerOffset(22.8); TEST_EQUAL(tmp==tmp2, false); tmp2 = tmp; tmp.setCharge(13); TEST_EQUAL(tmp==tmp2, false); tmp2 = tmp; tmp.getPossibleChargeStates().resize(5); TEST_EQUAL(tmp==tmp2, false); tmp2 = tmp; tmp.setMetaValue("label",String("label")); TEST_EQUAL(tmp==tmp2, false); END_SECTION START_SECTION((bool operator!= (const Precursor& rhs) const)) Precursor tmp,tmp2; TEST_EQUAL(tmp!=tmp2, false); tmp2.setActivationEnergy(47.11); TEST_FALSE(tmp == tmp2); tmp2 = tmp; tmp.setDriftTime(5.0); TEST_FALSE(tmp == tmp2); tmp2 = tmp; tmp.setDriftTimeUnit(DriftTimeUnit::MILLISECOND); TEST_FALSE(tmp == tmp2); tmp2 = tmp; tmp.getActivationMethods().insert(Precursor::ActivationMethod::CID); TEST_FALSE(tmp == tmp2); tmp2 = tmp; tmp2 = tmp; tmp.setIsolationWindowUpperOffset(22.7); TEST_FALSE(tmp == tmp2); tmp2 = tmp; tmp2 = tmp; tmp.setIsolationWindowLowerOffset(22.8); TEST_FALSE(tmp == tmp2); tmp2 = tmp; tmp2 = tmp; tmp.setDriftTimeWindowUpperOffset(22.7); TEST_FALSE(tmp == tmp2); tmp2 = tmp; tmp2 = tmp; tmp.setDriftTimeWindowLowerOffset(22.8); TEST_FALSE(tmp == tmp2); tmp2 = tmp; tmp.setCharge(13); TEST_FALSE(tmp == tmp2); tmp2 = tmp; tmp.getPossibleChargeStates().resize(5); TEST_FALSE(tmp == tmp2); tmp2 = tmp; tmp.setMetaValue("label",String("label")); TEST_FALSE(tmp == tmp2); END_SECTION START_SECTION(double getUnchargedMass() const) Precursor tmp; tmp.setMZ(123); tmp.setCharge(13); TEST_REAL_SIMILAR(tmp.getUnchargedMass(), 1585.90540593198); END_SECTION ///////////////////////////////////////////////////////////// // Hash function tests ///////////////////////////////////////////////////////////// START_SECTION(([EXTRA] std::hash<Precursor>)) { // Test that equal objects produce equal hashes Precursor p1; p1.setMZ(500.5); p1.setIntensity(1000.0); p1.setCharge(2); p1.setActivationEnergy(35.0); p1.setIsolationWindowLowerOffset(1.0); p1.setIsolationWindowUpperOffset(1.0); p1.setDriftTime(10.5); p1.setDriftTimeUnit(DriftTimeUnit::MILLISECOND); p1.setDriftTimeWindowLowerOffset(0.5); p1.setDriftTimeWindowUpperOffset(0.5); p1.getActivationMethods().insert(Precursor::ActivationMethod::CID); p1.getPossibleChargeStates().push_back(2); p1.getPossibleChargeStates().push_back(3); p1.setMetaValue("test_key", "test_value"); Precursor p2(p1); // Copy std::hash<Precursor> hasher; TEST_EQUAL(hasher(p1), hasher(p2)) // Test that different objects can have different hashes Precursor p3; p3.setMZ(600.6); p3.setCharge(3); // Different objects should (likely) have different hashes // Note: This is not guaranteed but highly probable TEST_NOT_EQUAL(hasher(p1), hasher(p3)) // Test use in unordered_set std::unordered_set<Precursor> precursor_set; precursor_set.insert(p1); precursor_set.insert(p2); // Same as p1, should not increase size precursor_set.insert(p3); TEST_EQUAL(precursor_set.size(), 2) TEST_EQUAL(precursor_set.count(p1), 1) TEST_EQUAL(precursor_set.count(p3), 1) // Test use in unordered_map std::unordered_map<Precursor, std::string> precursor_map; precursor_map[p1] = "first"; precursor_map[p3] = "third"; TEST_EQUAL(precursor_map.size(), 2) TEST_EQUAL(precursor_map[p1], "first") TEST_EQUAL(precursor_map[p2], "first") // p2 == p1 TEST_EQUAL(precursor_map[p3], "third") // Test hash consistency - same object should always produce same hash size_t hash1 = hasher(p1); size_t hash2 = hasher(p1); TEST_EQUAL(hash1, hash2) // Test that modifying a field changes the hash Precursor p4(p1); size_t original_hash = hasher(p4); p4.setCharge(5); size_t modified_hash = hasher(p4); TEST_NOT_EQUAL(original_hash, modified_hash) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/ExperimentalDesign_test.cpp
.cpp
23,235
569
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Timo Sachsenberg$ // $Authors: Timo Sachsenberg$ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/METADATA/ExperimentalDesign.h> #include <OpenMS/FORMAT/ExperimentalDesignFile.h> #include <OpenMS/FORMAT/ConsensusXMLFile.h> #include <OpenMS/FORMAT/FeatureXMLFile.h> #include <OpenMS/KERNEL/MSExperiment.h> #include <OpenMS/KERNEL/FeatureMap.h> #include <OpenMS/KERNEL/ConsensusMap.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(ExperimentalDesign, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// ExperimentalDesign* ptr = 0; ExperimentalDesign* null_ptr = 0; ExperimentalDesign labelfree_unfractionated_design = ExperimentalDesignFile::load( OPENMS_GET_TEST_DATA_PATH("ExperimentalDesign_input_1.tsv") , false); ExperimentalDesign fourplex_fractionated_design = ExperimentalDesignFile::load( OPENMS_GET_TEST_DATA_PATH("ExperimentalDesign_input_2.tsv") , false); ExperimentalDesign labelfree_unfractionated_single_table_design = ExperimentalDesignFile::load( OPENMS_GET_TEST_DATA_PATH("ExperimentalDesign_input_1_single_table.tsv") , false); ExperimentalDesign fourplex_fractionated_single_table_design = ExperimentalDesignFile::load( OPENMS_GET_TEST_DATA_PATH("ExperimentalDesign_input_2_single_table.tsv") , false); ExperimentalDesign labelfree_unfractionated_single_table_no_sample_column = ExperimentalDesignFile::load( OPENMS_GET_TEST_DATA_PATH("ExperimentalDesign_input_3_single_table.tsv") , false); START_SECTION(ExperimentalDesign()) { ptr = new ExperimentalDesign(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(~ExperimentalDesign()) { delete ptr; } END_SECTION START_SECTION((ExperimentalDesign(MSFileSection msfile_section, SampleSection sample_section))) { ExperimentalDesign::MSFileSection fs; ExperimentalDesign::SampleSection ss; ExperimentalDesign ed(fs, ss); } END_SECTION START_SECTION((const MSFileSection& getMSFileSection() const )) { ExperimentalDesign::MSFileSection fs = labelfree_unfractionated_design.getMSFileSection(); } END_SECTION START_SECTION((void setMSFileSection(const MSFileSection &msfile_section))) { ExperimentalDesign labelfree_unfractionated_design2 = labelfree_unfractionated_design; ExperimentalDesign::MSFileSection fs; labelfree_unfractionated_design2.setMSFileSection(fs); } END_SECTION START_SECTION((const ExperimentalDesign::SampleSection& getSampleSection() const )) { ExperimentalDesign::SampleSection ss = labelfree_unfractionated_design.getSampleSection(); } END_SECTION START_SECTION((void setSampleSection(const ExperimentalDesign::SampleSection &sample_section))) { ExperimentalDesign labelfree_unfractionated_design2 = labelfree_unfractionated_design; ExperimentalDesign::SampleSection fs; labelfree_unfractionated_design2.setSampleSection(fs); } END_SECTION START_SECTION((std::map<unsigned int, std::vector<String> > getFractionToMSFilesMapping() const )) { const auto lf = labelfree_unfractionated_design.getFractionToMSFilesMapping(); const auto lfst = labelfree_unfractionated_single_table_design.getFractionToMSFilesMapping(); const auto lfstns = labelfree_unfractionated_single_table_no_sample_column.getFractionToMSFilesMapping(); // test both two table as well as single table design for (const auto& f2ms : { lf, lfst, lfstns}) { // unfractionated data so only one fraction TEST_EQUAL(f2ms.size(), 1); // we have unfactionated data so fraction 1 mapps to all 12 files TEST_EQUAL(f2ms.at(1).size(), 12); } const auto fplex = fourplex_fractionated_design.getFractionToMSFilesMapping(); const auto fplexst = fourplex_fractionated_single_table_design.getFractionToMSFilesMapping(); // test both two table as well as single table design for (const auto& f2ms : { fplex, fplexst}) { // tripple fractionated data TEST_EQUAL(f2ms.size(), 3); // three fractions, 24 files, fraction 1..3 map to 8 files each TEST_EQUAL(f2ms.at(1).size(), 8); TEST_EQUAL(f2ms.at(2).size(), 8); TEST_EQUAL(f2ms.at(3).size(), 8); } } END_SECTION START_SECTION((std::map< std::pair< String, unsigned >, unsigned> getPathLabelToSampleMapping(bool) const )) { const auto lf = labelfree_unfractionated_design.getPathLabelToSampleMapping(true); const auto lfst = labelfree_unfractionated_single_table_design.getPathLabelToSampleMapping(true); const auto lfstns = labelfree_unfractionated_single_table_no_sample_column.getPathLabelToSampleMapping(true); const auto fplex = fourplex_fractionated_design.getPathLabelToSampleMapping(true); const auto fplexst = fourplex_fractionated_single_table_design.getPathLabelToSampleMapping(true); // 12 quant. values from label-free, unfractionated files map to 12 samples for (const auto& pl2s : {lf, lfst, lfstns}) { TEST_EQUAL(pl2s.size(), 12); } // 24 quant. values from 4plex, triple fractionated files map to 8 samples for (const auto& pl2s : {fplex, fplexst}) { TEST_EQUAL(pl2s.size(), 24); for (const auto& i : pl2s) { TEST_EQUAL((i.second <=7), true)} } } END_SECTION START_SECTION((std::map< std::pair< String, unsigned >, unsigned> getPathLabelToFractionMapping(bool) const )) { const auto lf = labelfree_unfractionated_design.getPathLabelToFractionMapping(true); const auto lfst = labelfree_unfractionated_single_table_design.getPathLabelToFractionMapping(true); const auto lfstns = labelfree_unfractionated_single_table_no_sample_column.getPathLabelToFractionMapping(true); const auto fplex = fourplex_fractionated_design.getPathLabelToFractionMapping(true); const auto fplexst = fourplex_fractionated_single_table_design.getPathLabelToFractionMapping(true); // 12 quant. values from label-free, unfractionated files map to fraction 1 each for (const auto& pl2f : { lf, lfst, lfstns }) { TEST_EQUAL(pl2f.size(), 12); for (const auto& i : pl2f) { TEST_EQUAL(i.second, 1); } } // 24 quant. values map to fractions 1..3 for (const auto& pl2f : { fplex, fplexst}) { TEST_EQUAL(pl2f.size(), 24); for (const auto& i : pl2f) { TEST_EQUAL((i.second >=1 && i.second <=3), true)} } } END_SECTION START_SECTION((std::map< std::pair< String, unsigned >, unsigned> getPathLabelToFractionGroupMapping(bool) const )) { const auto lf = labelfree_unfractionated_design.getPathLabelToFractionGroupMapping(true); const auto lfst = labelfree_unfractionated_single_table_design.getPathLabelToFractionGroupMapping(true); const auto lfstns = labelfree_unfractionated_single_table_no_sample_column.getPathLabelToFractionGroupMapping(true); const auto fplex = fourplex_fractionated_design.getPathLabelToFractionGroupMapping(true); const auto fplexst = fourplex_fractionated_single_table_design.getPathLabelToFractionGroupMapping(true); // 12 quant. values from label-free, unfractionated files map to different fraction groups for (const auto& pl2fg : { lf, lfst}) { TEST_EQUAL(pl2fg.size(), 12); int count = 1; for (const auto& i : pl2fg) { TEST_EQUAL(i.second, count); ++count; } } for (const auto& pl2fg : { fplex, fplexst}) { TEST_EQUAL(pl2fg.size(), 24); for (const auto& i : pl2fg) { // extract fraction group from file name int file(1); if (i.first.first.hasSubstring("TR2")) { file = 2; } TEST_EQUAL(i.second, file); } } } END_SECTION START_SECTION((std::set< String > ExperimentalDesign::SampleSection::getFactors() const)) const auto lfac = labelfree_unfractionated_design.getSampleSection().getFactors(); const auto lfacst = labelfree_unfractionated_single_table_design.getSampleSection().getFactors(); const auto lfacstns = labelfree_unfractionated_single_table_no_sample_column.getSampleSection().getFactors(); const auto facplex = fourplex_fractionated_design.getSampleSection().getFactors(); const auto facplexst = fourplex_fractionated_single_table_design.getSampleSection().getFactors(); TEST_EQUAL(lfac.size(), 3) TEST_EQUAL(lfacst.size(), 3) TEST_EQUAL(lfacstns.size(), 3) TEST_TRUE(lfac == lfacst) TEST_TRUE(lfac == lfacstns) TEST_TRUE(facplex == facplexst) auto l = lfac.begin(); TEST_EQUAL(*l++, "MSstats_BioReplicate") TEST_EQUAL(*l++, "MSstats_Condition") TEST_EQUAL(*l++, "Sample") l = lfacst.begin(); TEST_EQUAL(*l++, "MSstats_BioReplicate") TEST_EQUAL(*l++, "MSstats_Condition") TEST_EQUAL(*l++, "Sample") l = lfacstns.begin(); TEST_EQUAL(*l++, "MSstats_BioReplicate") TEST_EQUAL(*l++, "MSstats_Condition") TEST_EQUAL(*l++, "Sample") // dummy sample get's automatically added if not present in ED file END_SECTION START_SECTION((unsigned getNumberOfSamples() const )) { const auto lf = labelfree_unfractionated_design.getNumberOfSamples(); const auto lfst = labelfree_unfractionated_single_table_design.getNumberOfSamples(); const auto lfstns = labelfree_unfractionated_single_table_no_sample_column.getNumberOfSamples(); for (const auto& ns : { lf, lfst, lfstns }) { TEST_EQUAL(ns, 12); } const auto fplex = fourplex_fractionated_design.getNumberOfSamples(); const auto fplexst = fourplex_fractionated_single_table_design.getNumberOfSamples(); for (const auto& ns : { fplex, fplexst }) { TEST_EQUAL(ns, 8); } } END_SECTION START_SECTION((String SampleSection::getFactorValue(const unsigned sample, const String &factor) const)) // Note: Number of samples are the same (correctness tested in ExperimentalDesign::SampleSection::getNumberOfSamples()) // Note: Factors are the same (correctness tested in ExperimentalDesign::SampleSection::getFactors()) const auto lns = labelfree_unfractionated_design.getNumberOfSamples(); auto lss_tt = labelfree_unfractionated_design.getSampleSection(); auto lss_st = labelfree_unfractionated_single_table_design.getSampleSection(); auto lss_stns = labelfree_unfractionated_single_table_no_sample_column.getSampleSection(); // 12 samples (see getNumberOfSamples test) for (size_t sample = 0; sample < lns; ++sample) { for (const auto& factor : lss_tt.getFactors()) { // check if single table and two table design agree String f1 = lss_st.getFactorValue(sample, factor); String f2 = lss_tt.getFactorValue(sample, factor); String f3 = lss_stns.getFactorValue(sample, factor); cout << f1 << "\t" << f2 << "\t" << f3 << endl; TEST_EQUAL(f1, f2); TEST_EQUAL(f1, f3); } } const auto fns = fourplex_fractionated_design.getNumberOfSamples(); const auto& fss_tt = fourplex_fractionated_design.getSampleSection(); const auto& fss_st = fourplex_fractionated_single_table_design.getSampleSection(); // 8 samples (see getNumberOfSamples test) for (size_t sample = 0; sample < fns; ++sample) { for (const auto& factor : fss_tt.getFactors()) { // check if single table and two table design agree String f1 = fss_st.getFactorValue(sample, factor); String f2 = fss_tt.getFactorValue(sample, factor); TEST_EQUAL(f1, f2); } } END_SECTION START_SECTION((unsigned getNumberOfFractions() const )) { const auto lf = labelfree_unfractionated_design.getNumberOfFractions(); const auto lfst = labelfree_unfractionated_single_table_design.getNumberOfFractions(); const auto lfstns = labelfree_unfractionated_single_table_no_sample_column.getNumberOfFractions(); const auto fplex = fourplex_fractionated_design.getNumberOfFractions(); const auto fplexst = fourplex_fractionated_single_table_design.getNumberOfFractions(); for (const auto& ns : { lf, lfst, lfstns}) { TEST_EQUAL(ns, 1); } for (const auto& ns : { fplex, fplexst}) { TEST_EQUAL(ns, 3); } } END_SECTION START_SECTION((unsigned getNumberOfLabels() const )) { const auto lf = labelfree_unfractionated_design.getNumberOfLabels(); const auto lfst = labelfree_unfractionated_single_table_design.getNumberOfLabels(); const auto lfstns = labelfree_unfractionated_single_table_no_sample_column.getNumberOfLabels(); const auto fplex = fourplex_fractionated_design.getNumberOfLabels(); const auto fplexst = fourplex_fractionated_single_table_design.getNumberOfLabels(); for (const auto& ns : { lf, lfst, lfstns }) { TEST_EQUAL(ns, 1); } for (const auto& ns : { fplex, fplexst}) { TEST_EQUAL(ns, 4); } } END_SECTION START_SECTION((unsigned getNumberOfMSFiles() const )) { const auto lf = labelfree_unfractionated_design.getNumberOfMSFiles(); const auto lfst = labelfree_unfractionated_single_table_design.getNumberOfMSFiles(); const auto lfstns = labelfree_unfractionated_single_table_no_sample_column.getNumberOfMSFiles(); const auto fplex = fourplex_fractionated_design.getNumberOfMSFiles(); const auto fplexst = fourplex_fractionated_single_table_design.getNumberOfMSFiles(); for (const auto& ns : {lf, lfst, lfstns} ) { TEST_EQUAL(ns, 12); } for (const auto& ns : {fplex, fplexst}) { TEST_EQUAL(ns, 6); } } END_SECTION START_SECTION((unsigned getNumberOfFractionGroups() const )) { const auto lf = labelfree_unfractionated_design.getNumberOfFractionGroups(); const auto lfst = labelfree_unfractionated_single_table_design.getNumberOfFractionGroups(); const auto lfstns = labelfree_unfractionated_single_table_no_sample_column.getNumberOfFractionGroups(); const auto fplex = fourplex_fractionated_design.getNumberOfFractionGroups(); const auto fplexst = fourplex_fractionated_single_table_design.getNumberOfFractionGroups(); for (const auto& ns : {lf, lfst, lfstns} ) { TEST_EQUAL(ns, 12); } for (const auto& ns : {fplex, fplexst}) { TEST_EQUAL(ns, 2); } } END_SECTION START_SECTION((unsigned getSample(unsigned fraction_group, unsigned label=1))) { const auto lf11 = labelfree_unfractionated_design.getSample(1, 1); const auto lfst11 = labelfree_unfractionated_single_table_design.getSample(1, 1); const auto lfstns11 = labelfree_unfractionated_single_table_no_sample_column.getSample(1, 1); const auto fplex11 = fourplex_fractionated_design.getSample(1, 1); const auto fplexst11 = fourplex_fractionated_single_table_design.getSample(1, 1); for (const auto& s : {lf11, lfst11, lfstns11}) { TEST_EQUAL(s, 0); } for (const auto& s : {fplex11, fplexst11}) { TEST_EQUAL(s, 0); } const auto lf12_1 = labelfree_unfractionated_design.getSample(12, 1); const auto lfst12_1 = labelfree_unfractionated_single_table_design.getSample(12, 1); const auto lfstns11_1 = labelfree_unfractionated_single_table_no_sample_column.getSample(12, 1); for (const auto& s : {lf12_1, lfst12_1, lfstns11_1}) { TEST_EQUAL(s, 11); } const auto fplex24 = fourplex_fractionated_design.getSample(2, 4); const auto fplexst24 = fourplex_fractionated_single_table_design.getSample(2, 4); for (const auto& s : {fplex24, fplexst24}) { TEST_EQUAL(s, 7); } } END_SECTION START_SECTION((bool isFractionated() const )) { bool lf = labelfree_unfractionated_design.isFractionated(); bool lfst = labelfree_unfractionated_single_table_design.isFractionated(); bool lfstns = labelfree_unfractionated_single_table_no_sample_column.isFractionated(); bool fplex = fourplex_fractionated_design.isFractionated(); bool fplexst = fourplex_fractionated_single_table_design.isFractionated(); TEST_EQUAL(lf, false); TEST_EQUAL(lfst, false); TEST_EQUAL(lfstns, false); TEST_EQUAL(fplex, true); TEST_EQUAL(fplexst, true); } END_SECTION START_SECTION((bool sameNrOfMSFilesPerFraction() const )) { bool lf = labelfree_unfractionated_design.sameNrOfMSFilesPerFraction(); bool lfst = labelfree_unfractionated_single_table_design.sameNrOfMSFilesPerFraction(); bool lfstns = labelfree_unfractionated_single_table_no_sample_column.sameNrOfMSFilesPerFraction(); bool fplex = fourplex_fractionated_design.sameNrOfMSFilesPerFraction(); bool fplexst = fourplex_fractionated_single_table_design.sameNrOfMSFilesPerFraction(); TEST_EQUAL(lf, true); TEST_EQUAL(lfst, true); TEST_EQUAL(lfstns, true); TEST_EQUAL(fplex, true); TEST_EQUAL(fplexst, true); } END_SECTION START_SECTION((static ExperimentalDesign fromConsensusMap(const ConsensusMap &c))) { ConsensusXMLFile cfile; ConsensusMap cmap; cfile.load(OPENMS_GET_TEST_DATA_PATH("ExperimentalDesign_input_3.consensusXML"), cmap); /* example consensusXML for TMT10Plex <mapList count="10"> <map id="0" name="C:/dev/OpenMS/src/tests/topp/TMTTenPlexMethod_test.mzML" label="tmt10plex_126" size="6"> <UserParam type="string" name="channel_name" value="126"/> <UserParam type="int" name="channel_id" value="0"/> <UserParam type="string" name="channel_description" value=""/> <UserParam type="float" name="channel_center" value="126.127726"/> </map> <map id="1" name="C:/dev/OpenMS/src/tests/topp/TMTTenPlexMethod_test.mzML" label="tmt10plex_127N" size="6"> <UserParam type="string" name="channel_name" value="127N"/> <UserParam type="int" name="channel_id" value="1"/> <UserParam type="string" name="channel_description" value=""/> <UserParam type="float" name="channel_center" value="127.124761"/> </map> ... */ ExperimentalDesign ed_tmt10 = ExperimentalDesign::fromConsensusMap(cmap); TEST_EQUAL(ed_tmt10.getNumberOfLabels(), 10); TEST_EQUAL(ed_tmt10.getNumberOfMSFiles(), 1); TEST_EQUAL(ed_tmt10.getMSFileSection().at(0).label, 1); // "channel_id" + 1 TEST_EQUAL(ed_tmt10.getMSFileSection().at(9).label, 10); // "channel_id" + 1 TEST_EQUAL(ed_tmt10.getMSFileSection().at(0).fraction_group, 1); // only one fraction TEST_EQUAL(ed_tmt10.getMSFileSection().at(9).fraction_group, 1); // only one fraction TEST_EQUAL(ed_tmt10.getMSFileSection().at(0).fraction, 1); TEST_EQUAL(ed_tmt10.getMSFileSection().at(9).fraction, 1); TEST_EQUAL(ed_tmt10.getMSFileSection().at(0).sample, 0); // default: sample from 0..n-1 TEST_EQUAL(ed_tmt10.getMSFileSection().at(9).sample, 9); TEST_EQUAL(ed_tmt10.getMSFileSection().at(0).path, "C:/dev/OpenMS/src/tests/topp/TMTTenPlexMethod_test.mzML"); TEST_EQUAL(ed_tmt10.getMSFileSection().at(1).path, "C:/dev/OpenMS/src/tests/topp/TMTTenPlexMethod_test.mzML"); /* example consensusXML for dimethyl labeling (FeatureFinderMultiplex) <mapList count="2"> <map id="0" name="/home/sachsenb/OpenMS/src/tests/topp/FeatureFinderMultiplex_1_input.mzML" label="Dimethyl0" size="2"> <UserParam type="int" name="channel_id" value="0"/> </map> <map id="1" name="/home/sachsenb/OpenMS/src/tests/topp/FeatureFinderMultiplex_1_input.mzML" label="Dimethyl8" size="2"> <UserParam type="int" name="channel_id" value="1"/> </map> </mapList> */ cmap.clear(); cfile.load(OPENMS_GET_TEST_DATA_PATH("ExperimentalDesign_input_4.consensusXML"), cmap); ExperimentalDesign ed_dimethyl = ExperimentalDesign::fromConsensusMap(cmap); TEST_EQUAL(ed_dimethyl.getNumberOfLabels(), 2); TEST_EQUAL(ed_dimethyl.getNumberOfMSFiles(), 1); TEST_EQUAL(ed_dimethyl.getMSFileSection().at(0).label, 1); // "channel_id" + 1 TEST_EQUAL(ed_dimethyl.getMSFileSection().at(1).label, 2); // "channel_id" + 1 TEST_EQUAL(ed_dimethyl.getMSFileSection().at(0).fraction_group, 1); // only one fraction TEST_EQUAL(ed_dimethyl.getMSFileSection().at(1).fraction_group, 1); // only one fraction TEST_EQUAL(ed_dimethyl.getMSFileSection().at(0).fraction, 1); TEST_EQUAL(ed_dimethyl.getMSFileSection().at(1).fraction, 1); TEST_EQUAL(ed_dimethyl.getMSFileSection().at(0).sample, 0); // default: sample from 0..n-1 TEST_EQUAL(ed_dimethyl.getMSFileSection().at(1).sample, 1); TEST_EQUAL(ed_dimethyl.getMSFileSection().at(0).path, "/home/sachsenb/OpenMS/src/tests/topp/FeatureFinderMultiplex_1_input.mzML"); TEST_EQUAL(ed_dimethyl.getMSFileSection().at(1).path, "/home/sachsenb/OpenMS/src/tests/topp/FeatureFinderMultiplex_1_input.mzML"); /* example consensusXML for label-free (FeatureLinker*) <mapList count="2"> <map id="0" name="raw_file1.mzML" unique_id="8706403922746272921" label="" size="470"> </map> <map id="1" name="raw_file2.mzML" unique_id="10253060449047408476" label="" size="423"> </map> </mapList> */ cmap.clear(); cfile.load(OPENMS_GET_TEST_DATA_PATH("ExperimentalDesign_input_5.consensusXML"), cmap); ExperimentalDesign ed_labelfree = ExperimentalDesign::fromConsensusMap(cmap); TEST_EQUAL(ed_labelfree.getNumberOfLabels(), 1); TEST_EQUAL(ed_labelfree.getNumberOfMSFiles(), 2); TEST_EQUAL(ed_labelfree.getMSFileSection().at(0).label, 1); // "channel_id" + 1 TEST_EQUAL(ed_labelfree.getMSFileSection().at(1).label, 1); // "channel_id" + 1 TEST_EQUAL(ed_labelfree.getMSFileSection().at(0).fraction, 1); // only one fraction TEST_EQUAL(ed_labelfree.getMSFileSection().at(1).fraction, 1); TEST_EQUAL(ed_labelfree.getMSFileSection().at(0).fraction_group, 1); // each form a different group TEST_EQUAL(ed_labelfree.getMSFileSection().at(1).fraction_group, 2); TEST_EQUAL(ed_labelfree.getMSFileSection().at(0).sample, 0); // default: sample from 0..n-1 TEST_EQUAL(ed_labelfree.getMSFileSection().at(1).sample, 1); TEST_EQUAL(ed_labelfree.getMSFileSection().at(0).path, "raw_file1.mzML"); TEST_EQUAL(ed_labelfree.getMSFileSection().at(1).path, "raw_file2.mzML"); } END_SECTION START_SECTION((static ExperimentalDesign fromFeatureMap(const FeatureMap &f))) { FeatureXMLFile ffile; FeatureMap fmap; ffile.load(OPENMS_GET_TEST_DATA_PATH("ExperimentalDesign_input_6.featureXML"), fmap); ExperimentalDesign ed_labelfree = ExperimentalDesign::fromFeatureMap(fmap); TEST_EQUAL(ed_labelfree.getNumberOfLabels(), 1); TEST_EQUAL(ed_labelfree.getNumberOfMSFiles(), 1); TEST_EQUAL(ed_labelfree.getMSFileSection().at(0).label, 1); // "channel_id" + 1 TEST_EQUAL(ed_labelfree.getMSFileSection().at(0).fraction_group, 1); // only one fraction TEST_EQUAL(ed_labelfree.getMSFileSection().at(0).fraction, 1); TEST_EQUAL(ed_labelfree.getMSFileSection().at(0).sample, 0); // default: sample indices from 0..n-1 TEST_EQUAL(ed_labelfree.getMSFileSection().at(0).path, "file://C:/raw_file1.mzML"); } END_SECTION START_SECTION((isValid_())) { // missing fractions and wrong orders should work now String foo = OPENMS_GET_TEST_DATA_PATH("ExperimentalDesign_input_2_wrong.tsv"); ExperimentalDesignFile::load(foo,false); String baz = OPENMS_GET_TEST_DATA_PATH("ExperimentalDesign_input_2_wrong_3.tsv"); ExperimentalDesignFile::load(baz,false); // fraction groups still need to be consecutive String bar = OPENMS_GET_TEST_DATA_PATH("ExperimentalDesign_input_2_wrong_2.tsv"); TEST_EXCEPTION(Exception::InvalidValue, ExperimentalDesignFile::load(bar,false)); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/PeptideEvidence_test.cpp
.cpp
2,235
135
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: $ // $Authors: $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> /////////////////////////// #include <OpenMS/METADATA/PeptideEvidence.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(PeptideEvidence, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// PeptideEvidence* ptr = nullptr; PeptideEvidence* null_ptr = nullptr; START_SECTION(PeptideEvidence()) { ptr = new PeptideEvidence(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(~PeptideEvidence()) { delete ptr; } END_SECTION START_SECTION((PeptideEvidence(const PeptideEvidence &source))) { // TODO } END_SECTION START_SECTION((~PeptideEvidence())) { // TODO } END_SECTION START_SECTION((PeptideEvidence& operator=(const PeptideEvidence &source))) { // TODO } END_SECTION START_SECTION((bool operator==(const PeptideEvidence &rhs) const )) { // TODO } END_SECTION START_SECTION((bool operator!=(const PeptideEvidence &rhs) const )) { // TODO } END_SECTION START_SECTION((const String& getProteinAccession() const )) { // TODO } END_SECTION START_SECTION((void setProteinAccession(const String &s))) { // TODO } END_SECTION START_SECTION((void setStart(const Int a))) { // TODO } END_SECTION START_SECTION((Int getStart() const )) { // TODO } END_SECTION START_SECTION((void setEnd(const Int a))) { // TODO } END_SECTION START_SECTION((Int getEnd() const )) { // TODO } END_SECTION START_SECTION((void setAABefore(const char acid))) { // TODO } END_SECTION START_SECTION((char getAABefore() const )) { // TODO } END_SECTION START_SECTION((void setAAAfter(const char acid))) { // TODO } END_SECTION START_SECTION((char getAAAfter() const )) { // TODO } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/INIUpdater_test.cpp
.cpp
2,619
102
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow $ // $Authors: Chris Bielow $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/APPLICATIONS/INIUpdater.h> /////////////////////////// #include <OpenMS/DATASTRUCTURES/ListUtils.h> using namespace OpenMS; using namespace std; START_TEST(INIUpdater, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// INIUpdater* ptr = nullptr; INIUpdater* null_ptr = nullptr; START_SECTION(INIUpdater()) { ptr = new INIUpdater(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(~INIUpdater()) { delete ptr; } END_SECTION START_SECTION((StringList getToolNamesFromINI(const Param &ini) const)) { Param p; INIUpdater i; StringList names = i.getToolNamesFromINI(p); TEST_EQUAL(names.size(), 0) p.setValue("FeatureFinder:version","1.9"); p.setValue("SomeTool:version","whatever"); names = i.getToolNamesFromINI(p); TEST_EQUAL(names.size(), 2) p.setValue("BrokenTool:version2","1.9"); names = i.getToolNamesFromINI(p); TEST_EQUAL(names.size(), 2) } END_SECTION START_SECTION((const ToolMapping& getNameMapping())) { INIUpdater i; ToolMapping m = i.getNameMapping(); TEST_NOT_EQUAL(m.size(), 0) TEST_EQUAL(m[Internal::ToolDescriptionInternal("FeatureFinder",ListUtils::create<String>("centroided"))] == Internal::ToolDescriptionInternal("FeatureFinderCentroided",ListUtils::create<String>("")), true) } END_SECTION START_SECTION((bool getNewToolName(const String &old_name, const String &tools_type, String &new_name))) { INIUpdater i; String new_name; i.getNewToolName("FeatureFinder", "centroided", new_name); TEST_EQUAL(new_name, "FeatureFinderCentroided"); i.getNewToolName("PeakPicker", "wavelet", new_name); TEST_EQUAL(new_name, "PeakPickerWavelet"); i.getNewToolName("FileInfo", "", new_name); TEST_EQUAL(new_name, "FileInfo"); i.getNewToolName("FileInfo", "bogus type", new_name); // type will be ignored - ok TEST_EQUAL(new_name, "FileInfo"); TEST_EQUAL(i.getNewToolName("UNKNOWNTOOL", "bogus type", new_name), false); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/PeakPickerIterative_test.cpp
.cpp
1,525
69
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: $ // $Authors: $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> /////////////////////////// #include <OpenMS/PROCESSING/CENTROIDING/PeakPickerIterative.h> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(PeakPickerIterative, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// PeakPickerIterative* ptr = nullptr; PeakPickerIterative* null_ptr = nullptr; START_SECTION(PeakPickerIterative()) { ptr = new PeakPickerIterative(); TEST_NOT_EQUAL(ptr, null_ptr) } END_SECTION START_SECTION(~PeakPickerIterative()) { delete ptr; } END_SECTION START_SECTION((void updateMembers_())) { // TODO } END_SECTION START_SECTION((~PeakPickerIterative())) { // TODO } END_SECTION START_SECTION((template < typename PeakType > void pick(const MSSpectrum &input, MSSpectrum &output))) { // TODO } END_SECTION START_SECTION((template < typename PeakType > void pickExperiment(const MSExperiment< PeakType > &input, MSExperiment< PeakType > &output))) { // TODO } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/SiriusFragmentAnnotation_test.cpp
.cpp
5,222
110
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Oliver Alka $ // $Authors: Oliver Alka $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/FORMAT/DATAACCESS/SiriusFragmentAnnotation.h> #include <OpenMS/CONCEPT/LogStream.h> #include <fstream> #include <QtCore/QDir> #include <QtCore/QString> /////////////////////////// using namespace OpenMS; using namespace std; START_TEST(SiriusFragmentAnnotation, "$Id$") ///////////////////////////////////////////////////////////// SiriusFragmentAnnotation* fa_ptr = nullptr; SiriusFragmentAnnotation* fa_null = nullptr; START_SECTION(SiriusFragmentAnnotation()) { fa_ptr = new SiriusFragmentAnnotation; TEST_NOT_EQUAL(fa_ptr, fa_null); } END_SECTION START_SECTION(~SiriusFragmentAnnotation()) { delete fa_ptr; } END_SECTION // mz intensity rel.intensity exactmass explanation // 123.000363 65857.38 3.36 122.999604 C7H3Cl // test function START_SECTION(static void extractSiriusFragmentAnnotationMapping(const String& path_to_sirius_workspace, MSSpectrum& msspectrum_to_fill, bool use_exact_mass)) { String test_path = OPENMS_GET_TEST_DATA_PATH("SiriusFragmentAnnotation_test"); MSSpectrum annotated_msspectrum = SiriusFragmentAnnotation::extractAnnotationsFromSiriusFile(test_path, 1, false, false)[0]; TEST_STRING_SIMILAR(annotated_msspectrum.getNativeID(), "sample=1 period=1 cycle=676 experiment=4|sample=1 period=1 cycle=677 experiment=5|sample=1 period=1 cycle=678 experiment=3"); TEST_EQUAL(annotated_msspectrum.getMSLevel(), 2); TEST_EQUAL(annotated_msspectrum.empty(), false); TEST_REAL_SIMILAR(annotated_msspectrum[0].getMZ(), 70.040098); TEST_STRING_SIMILAR(annotated_msspectrum.getMetaValue("peak_mz"), "mz"); TEST_STRING_SIMILAR(annotated_msspectrum.getFloatDataArrays()[0].getName(), "exact_mass"); TEST_REAL_SIMILAR(annotated_msspectrum.getFloatDataArrays()[0][0], 70.040098); TEST_STRING_SIMILAR(annotated_msspectrum.getStringDataArrays()[0][0], "C2H3N3"); TEST_STRING_SIMILAR(annotated_msspectrum.getMetaValue("annotated_sumformula"), "C15H17ClN4"); TEST_STRING_SIMILAR(annotated_msspectrum.getMetaValue("annotated_adduct"), "[M+H]+"); TEST_REAL_SIMILAR(annotated_msspectrum.getMetaValue("decoy"), 0); } END_SECTION // test exact mass output START_SECTION(static void extractSiriusFragmentAnnotationMapping(const String& path_to_sirius_workspace, MSSpectrum& msspectrum_to_fill, bool use_exact_mass)) { String test_path = OPENMS_GET_TEST_DATA_PATH("SiriusFragmentAnnotation_test"); MSSpectrum annotated_msspectrum = SiriusFragmentAnnotation::extractAnnotationsFromSiriusFile(test_path, 1, false, true)[0]; TEST_STRING_SIMILAR(annotated_msspectrum.getNativeID(), "sample=1 period=1 cycle=676 experiment=4|sample=1 period=1 cycle=677 experiment=5|sample=1 period=1 cycle=678 experiment=3"); TEST_EQUAL(annotated_msspectrum.getMSLevel(), 2); TEST_EQUAL(annotated_msspectrum.empty(), false); TEST_REAL_SIMILAR(annotated_msspectrum[0].getMZ(), 70.040098) TEST_STRING_SIMILAR(annotated_msspectrum.getMetaValue("peak_mz"), "exact_mass"); TEST_STRING_SIMILAR(annotated_msspectrum.getFloatDataArrays()[0].getName(), "mz"); TEST_REAL_SIMILAR(annotated_msspectrum.getFloatDataArrays()[0][0], 70.040098); TEST_STRING_SIMILAR(annotated_msspectrum.getStringDataArrays()[0][0], "C2H3N3"); TEST_STRING_SIMILAR(annotated_msspectrum.getMetaValue("annotated_sumformula"), "C15H17ClN4"); TEST_STRING_SIMILAR(annotated_msspectrum.getMetaValue("annotated_adduct"), "[M+H]+"); TEST_REAL_SIMILAR(annotated_msspectrum.getMetaValue("decoy"), 0); } END_SECTION // test decoy extraction START_SECTION(static void extractSiriusDecoyAnnotationMapping(const String& path_to_sirius_workspace, MSSpectrum& msspectrum_to_fill)) { String test_path = OPENMS_GET_TEST_DATA_PATH("SiriusFragmentAnnotation_test"); MSSpectrum decoy_msspectrum = SiriusFragmentAnnotation::extractAnnotationsFromSiriusFile(test_path, 1, true, false)[0]; TEST_STRING_SIMILAR(decoy_msspectrum.getNativeID(), "sample=1 period=1 cycle=676 experiment=4|sample=1 period=1 cycle=677 experiment=5|sample=1 period=1 cycle=678 experiment=3"); TEST_EQUAL(decoy_msspectrum.getMSLevel(), 2); TEST_EQUAL(decoy_msspectrum.empty(), false); TEST_REAL_SIMILAR(decoy_msspectrum[0].getMZ(), 53.013424); TEST_STRING_SIMILAR(decoy_msspectrum.getMetaValue("peak_mz"), "mz"); TEST_STRING_SIMILAR(decoy_msspectrum.getStringDataArrays()[0][0], "C2N2"); TEST_STRING_SIMILAR(decoy_msspectrum.getMetaValue("annotated_sumformula"), "C15H17ClN4"); TEST_STRING_SIMILAR(decoy_msspectrum.getMetaValue("annotated_adduct"), "[M+H]+"); TEST_REAL_SIMILAR(decoy_msspectrum.getMetaValue("decoy"), 1); } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/IMDataConverter_test.cpp
.cpp
8,797
268
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Eugen Netz $ // $Authors: Eugen Netz, Chris Bielow $ // -------------------------------------------------------------------------- // #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/IONMOBILITY/IMDataConverter.h> #include <OpenMS/KERNEL/MSExperiment.h> #include <OpenMS/FORMAT/MzMLFile.h> using namespace OpenMS; using namespace std; /////////////////////////// START_TEST(IMDataConverter, "$Id$") ///////////////////////////////////////////////////////////// IMDataConverter* e_ptr = nullptr; IMDataConverter* e_nullPointer = nullptr; START_SECTION((IMDataConverter())) e_ptr = new IMDataConverter; TEST_NOT_EQUAL(e_ptr, e_nullPointer) END_SECTION START_SECTION((~IMDataConverter())) delete e_ptr; END_SECTION START_SECTION((std::vector<std::pair<double, MSExperiment>> splitByFAIMSCV(PeakMap& exp))) MzMLFile IM_file; PeakMap exp; IM_file.load(OPENMS_GET_TEST_DATA_PATH("IM_FAIMS_test.mzML"), exp); TEST_EQUAL(exp.getSpectra().size(), 19) auto splitPeakMap = IMDataConverter::splitByFAIMSCV(std::move(exp)); TEST_EQUAL(exp.empty(), true) // moved out TEST_EQUAL(splitPeakMap.size(), 3) // expect keys -65, -55, -45 in ascending order TEST_EQUAL(splitPeakMap[0].first, -65.0) TEST_EQUAL(splitPeakMap[1].first, -55.0) TEST_EQUAL(splitPeakMap[2].first, -45.0) TEST_EQUAL(splitPeakMap[0].second.size(), 4) TEST_EQUAL(splitPeakMap[1].second.size(), 9) TEST_EQUAL(splitPeakMap[2].second.size(), 6) for (const auto& spec : splitPeakMap[0].second) { TEST_EQUAL(spec.getDriftTime(), -65.0) } for (const auto& spec : splitPeakMap[1].second) { TEST_EQUAL(spec.getDriftTime(), -55.0) } for (const auto& spec : splitPeakMap[2].second) { TEST_EQUAL(spec.getDriftTime(), -45.0) } TEST_EQUAL(splitPeakMap[1].second.getExperimentalSettings().getDateTime().toString(), "2019-09-07T09:40:04") END_SECTION START_SECTION(static void setIMUnit(DataArrays::FloatDataArray& fda, const DriftTimeUnit unit)) MSSpectrum::FloatDataArray fda; TEST_EXCEPTION(Exception::InvalidValue, IMDataConverter::setIMUnit(fda, DriftTimeUnit::FAIMS_COMPENSATION_VOLTAGE)) TEST_EXCEPTION(Exception::InvalidValue, IMDataConverter::setIMUnit(fda, DriftTimeUnit::NONE)) DriftTimeUnit unit; IMDataConverter::setIMUnit(fda, DriftTimeUnit::MILLISECOND); TEST_EQUAL(IMDataConverter::getIMUnit(fda, unit), true) TEST_EQUAL(DriftTimeUnit::MILLISECOND == unit, true) IMDataConverter::setIMUnit(fda, DriftTimeUnit::VSSC); TEST_EQUAL(IMDataConverter::getIMUnit(fda, unit), true) TEST_EQUAL(DriftTimeUnit::VSSC == unit, true) END_SECTION START_SECTION(static bool getIMUnit(const DataArrays::FloatDataArray& fda, DriftTimeUnit& unit)) NOT_TESTABLE // tested above END_SECTION MSSpectrum frame; frame.push_back({1.0, 11.0f}); frame.push_back({1.0 + Math::ppmToMass(4.0, 1.0), 12.0f}); // should merge with the one above frame.push_back({1.2, 13.0f}); frame.push_back({2.0, 20.0f}); frame.push_back({3.0 - Math::ppmToMass(3.0, 3.0), 32.0f}); // should merge with the one below frame.push_back({3.0, 31.0f}); frame.push_back({4.0, 40.0f}); frame.push_back({5.0, 50.0f}); frame.push_back({6.0, 60.0f}); frame.push_back({7.0, 70.0f}); frame.setRT(1); MSSpectrum::FloatDataArray& afa = frame.getFloatDataArrays().emplace_back(); // <---------- bin 1 -----------> < bin 2 > < -- bin 3 ---> afa.assign({1.1, 1.11, 1.11, 2.2, 3.2, 3.22, 4.4, 5.6, 6.6, 7.7}); IMDataConverter::setIMUnit(afa, DriftTimeUnit::MILLISECOND); MSSpectrum spec; spec.push_back({111.0, -1.0f}); spec.push_back({222.0, -2.0f}); spec.push_back({333.0, -3.0f}); spec.setRT(2); // just a spectrum with RT = 2 START_SECTION(static MSExperiment reshapeIMFrameToMany(MSSpectrum im_frame)) { // not am IM frame: TEST_EXCEPTION(Exception::MissingInformation, IMDataConverter::reshapeIMFrameToMany(spec)) { auto exp = IMDataConverter::reshapeIMFrameToMany(frame); TEST_EQUAL(exp.size(), 9); // nine different IM-values TEST_EQUAL(exp[0].size(), 1); TEST_EQUAL(exp[1].size(), 2); TEST_EQUAL(exp[1][0].getIntensity(), 12.0f); TEST_EQUAL(exp[1][1].getIntensity(), 13.0f); TEST_EQUAL(exp[0].getDriftTime(), 1.1f); TEST_TRUE(exp[0].getDriftTimeUnit() == DriftTimeUnit::MILLISECOND); TEST_EQUAL(exp[0].getRT(), 1); TEST_EQUAL(exp[1].getDriftTime(), 1.11f); TEST_EQUAL(exp[8].getDriftTime(), 7.7f); TEST_TRUE(exp.isIMFrame()); auto frame_reconstruct = IMDataConverter::reshapeIMFrameToSingle(exp); TEST_EQUAL(frame_reconstruct.size(), 1) TEST_EQUAL(frame_reconstruct[0], frame); } } END_SECTION START_SECTION((static std::tuple<std::vector<MSExperiment>, Math::BinContainer> splitExperimentByIonMobility(MSExperiment&& in, UInt number_of_IM_bins, double bin_extension_abs, double mz_binning_width, MZ_UNITS mz_binning_width_unit))) { MSExperiment e_in; e_in.addSpectrum(frame); auto frame2 = frame; // a second frame so we can test if two RT's show up in the result frame2.setRT(3); e_in.addSpectrum(frame2); // IM-range is 7.7-1.1 = 6.6 // --> each bin is 2.2 wide const auto [exp_slices, bin_values] = IMDataConverter::splitExperimentByIonMobility(std::move(e_in), 3, 0.0, 5.0, MZ_UNITS::PPM); const auto ranges = Math::BinContainer { {1.1, 3.3}, {3.3, 5.5}, {5.5, 7.7}}; for (int i = 0; i < 3; ++i) { TEST_REAL_SIMILAR(bin_values[i].getMin(), ranges[i].getMin()); TEST_REAL_SIMILAR(bin_values[i].getMax(), ranges[i].getMax()); } TEST_EQUAL(exp_slices.size(), 3); const auto& exp11 = exp_slices[0]; const auto& exp33 = exp_slices[1]; const auto& exp55 = exp_slices[2]; TEST_EQUAL(exp11[0].size(), 4); TEST_EQUAL(exp33[0].size(), 1); TEST_EQUAL(exp55[0].size(), 3); TEST_EQUAL(exp11[1].size(), 4); // second frame. Identical to first frame TEST_EQUAL(exp33[1].size(), 1); TEST_EQUAL(exp55[1].size(), 3); TEST_EQUAL(exp11[0][0].getIntensity(), 11+12); TEST_REAL_SIMILAR(exp11[0].getDriftTime(), 2.2f); // center of bin 1.1-3.3 TEST_TRUE(exp11[0].getDriftTimeUnit() == DriftTimeUnit::MILLISECOND); TEST_EQUAL(exp11[0].getRT(), 1); TEST_EQUAL(exp11[1].getRT(), 3); TEST_EQUAL(exp33[0].getRT(), 1); TEST_EQUAL(exp33[1].getRT(), 3); TEST_EQUAL(exp55[0].getRT(), 1); TEST_EQUAL(exp55[1].getRT(), 3); } END_SECTION START_SECTION(static MSExperiment reshapeIMFrameToSingle(const MSExperiment& in)) NOT_TESTABLE // tested_above END_SECTION START_SECTION((std::vector<std::pair<double, MSExperiment>> splitByFAIMSCV assigns MS2 without explicit CV to last seen FAIMS CV)) { PeakMap exp_synth; MSSpectrum ms1a; ms1a.setMSLevel(1); ms1a.setDriftTimeUnit(DriftTimeUnit::FAIMS_COMPENSATION_VOLTAGE); ms1a.setDriftTime(-55.0); MSSpectrum ms2a; ms2a.setMSLevel(2); ms2a.setDriftTimeUnit(DriftTimeUnit::NONE); MSSpectrum ms2b; ms2b.setMSLevel(2); ms2b.setDriftTimeUnit(DriftTimeUnit::NONE); MSSpectrum ms1b; ms1b.setMSLevel(1); ms1b.setDriftTimeUnit(DriftTimeUnit::FAIMS_COMPENSATION_VOLTAGE); ms1b.setDriftTime(-45.0); MSSpectrum ms2c; ms2c.setMSLevel(2); ms2c.setDriftTimeUnit(DriftTimeUnit::NONE); exp_synth.addSpectrum(ms1a); exp_synth.addSpectrum(ms2a); exp_synth.addSpectrum(ms2b); exp_synth.addSpectrum(ms1b); exp_synth.addSpectrum(ms2c); auto bins = IMDataConverter::splitByFAIMSCV(std::move(exp_synth)); TEST_EQUAL(bins.size(), 2) // bins ordered by ascending CV: -55 first, -45 second TEST_EQUAL(bins[0].first, -55.0) TEST_EQUAL(bins[1].first, -45.0) const auto& bin_minus55 = bins[0].second; const auto& bin_minus45 = bins[1].second; TEST_EQUAL(bin_minus55.size(), 3) // ms1a + ms2a + ms2b TEST_EQUAL(bin_minus45.size(), 2) // ms1b + ms2c Size ms2_bin0 = 0; for (const auto& s : bin_minus55) if (s.getMSLevel() > 1) ++ms2_bin0; TEST_EQUAL(ms2_bin0, 2) Size ms2_bin1 = 0; for (const auto& s : bin_minus45) if (s.getMSLevel() > 1) ++ms2_bin1; TEST_EQUAL(ms2_bin1, 1) } END_SECTION START_SECTION((std::vector<std::pair<double, MSExperiment>> splitByFAIMSCV returns single-element group for non-FAIMS dataset)) { PeakMap exp_nonfaims; MSSpectrum s; s.setMSLevel(1); s.setDriftTimeUnit(DriftTimeUnit::MILLISECOND); s.setDriftTime(10.0); exp_nonfaims.addSpectrum(s); auto bins = IMDataConverter::splitByFAIMSCV(std::move(exp_nonfaims)); TEST_EQUAL(bins.size(), 1) TEST_EQUAL(bins[0].second.size(), 1) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/Ms2IdentificationRate_test.cpp
.cpp
9,031
269
// Copyright (c) 2002-present, OpenMS Inc. -- EKU Tuebingen, ETH Zurich, and FU Berlin // SPDX-License-Identifier: BSD-3-Clause // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow $ // $Authors: Swenja Wagner, Patricia Scheil $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/KERNEL/FeatureMap.h> #include <OpenMS/KERNEL/MSExperiment.h> #include <OpenMS/METADATA/MetaInfoInterface.h> #include <OpenMS/METADATA/PeptideHit.h> #include <OpenMS/QC/Ms2IdentificationRate.h> #include <vector> ////////////////////////// using namespace OpenMS; START_TEST(Ms2IdentificationRate, "$Id$") ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// // construct PeptideHits PeptideHit pep_hit1_t1; pep_hit1_t1.setMetaValue("target_decoy", "target"); PeptideHit pep_hit1_t2; pep_hit1_t2.setMetaValue("target_decoy", "target"); PeptideHit pep_hit2_d; pep_hit2_d.setMetaValue("target_decoy", "decoy"); PeptideHit pep_hit_fdr; // construct vectors of PeptideHits std::vector<PeptideHit> pep_hits_target = {pep_hit1_t1, pep_hit1_t2}; std::vector<PeptideHit> pep_hits_decoy = {pep_hit2_d}; std::vector<PeptideHit> pep_hits_empty = {}; std::vector<PeptideHit> pep_hits_fdr = {pep_hit_fdr}; // construct Peptideidentification with PeptideHits PeptideIdentification pep_id_target; pep_id_target.setHits(pep_hits_target); PeptideIdentification pep_id_decoy; pep_id_decoy.setHits(pep_hits_decoy); PeptideIdentification pep_id_empty; pep_id_empty.setHits(pep_hits_empty); PeptideIdentification pep_id_fdr; pep_id_fdr.setHits(pep_hits_fdr); PeptideIdentificationList pep_ids = {pep_id_target, pep_id_decoy, pep_id_empty}; PeptideIdentificationList pep_ids_empty {}; PeptideIdentificationList pep_ids_fdr = {pep_id_fdr}; PeptideIdentificationList two_target_ids = {pep_id_target, pep_id_target, pep_id_decoy, pep_id_empty}; // construct features with peptideIdentifications Feature feat_empty_pi; feat_empty_pi.setPeptideIdentifications(pep_ids_empty); Feature feat_target; feat_target.setPeptideIdentifications(pep_ids); Feature feat_empty; Feature feat_fdr; feat_fdr.setPeptideIdentifications(pep_ids_fdr); // construct FeatureMap FeatureMap fmap; fmap.push_back(feat_empty_pi); fmap.push_back(feat_target); fmap.push_back(feat_empty); FeatureMap fmap_fdr; fmap_fdr.push_back(feat_fdr); FeatureMap fmap_empty; fmap.setUnassignedPeptideIdentifications(pep_ids); // construct MSSpectrum MSSpectrum ms2; ms2.setMSLevel(2); MSSpectrum ms1; ms1.setMSLevel(1); std::vector<MSSpectrum> ms_spectra = {ms2, ms2, ms2, ms2, ms2, ms2, ms1}; std::vector<MSSpectrum> ms1_spectra = {ms1}; std::vector<MSSpectrum> ms2_2_spectra = {ms2}; // construct MSExperiment MSExperiment ms_exp; ms_exp.setSpectra(ms_spectra); // construct MSExperiment without MS2 spectra MSExperiment ms1_exp; ms1_exp.setSpectra(ms1_spectra); // construct MSExperiment with two MS2 spectra MSExperiment ms2_2_exp; ms2_2_exp.setSpectra(ms2_2_spectra); // construct empty MSExperiment MSExperiment ms_empty_exp; ////////////////////////////////////////////////////////////////// // start Section ///////////////////////////////////////////////////////////////// Ms2IdentificationRate* ptr = nullptr; Ms2IdentificationRate* nulpt = nullptr; START_SECTION(Ms2IdentificationRate()) { ptr = new Ms2IdentificationRate(); TEST_NOT_EQUAL(ptr, nulpt) } END_SECTION START_SECTION(~Ms2IdentificationRate()) { delete ptr; } END_SECTION Ms2IdentificationRate ms2ir; Ms2IdentificationRate ms2ir_fdr; Ms2IdentificationRate ms2ir_force_fdr; Ms2IdentificationRate ms2ir_ms1; Ms2IdentificationRate ms2ir_ms2_2; Ms2IdentificationRate ms2ir_empty_msexp; Ms2IdentificationRate ms2ir_empty_fmap; // tests compute function with FeatureMap START_SECTION(void compute(FeatureMap const& feature_map, MSExperiment const& exp, bool force_index = false)) { // test with valid input ms2ir.compute(fmap, ms_exp); std::vector<Ms2IdentificationRate::IdentificationRateData> result; result = ms2ir.getResults(); for (const auto& idrd : result) { TEST_EQUAL(idrd.num_peptide_identification, 2) TEST_EQUAL(idrd.num_ms2_spectra, 6) TEST_REAL_SIMILAR(idrd.identification_rate, 1. / 3) } // less ms2 spectra than identifictions TEST_EXCEPTION_WITH_MESSAGE(Exception::Precondition, ms2ir_ms2_2.compute(fmap, ms2_2_exp), "There are more Identifications than MS2 spectra. Please check your data.") // empty ms experiment TEST_EXCEPTION_WITH_MESSAGE(Exception::MissingInformation, ms2ir_empty_msexp.compute(fmap, ms_empty_exp), "MSExperiment is empty") // empty feature map ms2ir_empty_fmap.compute(fmap_empty, ms_exp); std::vector<Ms2IdentificationRate::IdentificationRateData> result_empty_fmap; result_empty_fmap = ms2ir_empty_fmap.getResults(); for (const auto& idrd_empty_fmap : result_empty_fmap) { TEST_EQUAL(idrd_empty_fmap.num_peptide_identification, 0) TEST_EQUAL(idrd_empty_fmap.num_ms2_spectra, 6) TEST_REAL_SIMILAR(idrd_empty_fmap.identification_rate, 0) } // no fdr TEST_EXCEPTION_WITH_MESSAGE(Exception::Precondition, ms2ir_fdr.compute(fmap_fdr, ms_exp), "No target/decoy annotation found. If you want to continue regardless use -MS2_id_rate:assume_all_target") // force no fdr ms2ir_force_fdr.compute(fmap_fdr, ms_exp, true); std::vector<Ms2IdentificationRate::IdentificationRateData> result_force_fdr; result_force_fdr = ms2ir_force_fdr.getResults(); for (const auto& idrd_force_fdr : result_force_fdr) { TEST_EQUAL(idrd_force_fdr.num_peptide_identification, 1) TEST_EQUAL(idrd_force_fdr.num_ms2_spectra, 6) TEST_REAL_SIMILAR(idrd_force_fdr.identification_rate, 1. / 6) } // no ms2 spectra TEST_EXCEPTION_WITH_MESSAGE(Exception::MissingInformation, ms2ir_ms1.compute(fmap, ms1_exp), "No MS2 spectra found") } END_SECTION Ms2IdentificationRate id_rate; Ms2IdentificationRate id_rate_one_ms2; Ms2IdentificationRate id_rate_empty_exp; Ms2IdentificationRate id_rate_no_ids; Ms2IdentificationRate id_rate_no_index; Ms2IdentificationRate id_rate_force_no_index; Ms2IdentificationRate id_rate_ms1; // tests compute function with PeptideIdentifications START_SECTION(void compute(const PeptideIdentificationList& pep_ids, const MSExperiment& exp, bool force_index = false)) { // test with valid input id_rate.compute(pep_ids, ms_exp); std::vector<Ms2IdentificationRate::IdentificationRateData> result; result = id_rate.getResults(); for (const auto& idrd : result) { TEST_EQUAL(idrd.num_peptide_identification, 1) TEST_EQUAL(idrd.num_ms2_spectra, 6) TEST_REAL_SIMILAR(idrd.identification_rate, 1. / 6) } // less ms2 spectra than identifictions TEST_EXCEPTION_WITH_MESSAGE(Exception::Precondition, id_rate_one_ms2.compute(two_target_ids, ms2_2_exp), "There are more Identifications than MS2 spectra. Please check your data.") // empty ms experiment TEST_EXCEPTION_WITH_MESSAGE(Exception::MissingInformation, id_rate_empty_exp.compute(pep_ids, ms_empty_exp), "MSExperiment is empty") // empty feature map id_rate_no_ids.compute(pep_ids_empty, ms_exp); std::vector<Ms2IdentificationRate::IdentificationRateData> result_no_pep_ids; result_no_pep_ids = id_rate_no_ids.getResults(); for (const auto& idrd_empty_fmap : result_no_pep_ids) { TEST_EQUAL(idrd_empty_fmap.num_peptide_identification, 0) TEST_EQUAL(idrd_empty_fmap.num_ms2_spectra, 6) TEST_REAL_SIMILAR(idrd_empty_fmap.identification_rate, 0) } // no fdr TEST_EXCEPTION_WITH_MESSAGE(Exception::Precondition, id_rate_no_index.compute(pep_ids_fdr, ms_exp), "No target/decoy annotation found. If you want to continue regardless use -MS2_id_rate:assume_all_target") // force no fdr id_rate_force_no_index.compute(pep_ids_fdr, ms_exp, true); std::vector<Ms2IdentificationRate::IdentificationRateData> result_force_fdr; result_force_fdr = id_rate_force_no_index.getResults(); for (const auto& idrd_force_fdr : result_force_fdr) { TEST_EQUAL(idrd_force_fdr.num_peptide_identification, 1) TEST_EQUAL(idrd_force_fdr.num_ms2_spectra, 6) TEST_REAL_SIMILAR(idrd_force_fdr.identification_rate, 1. / 6) } // no ms2 spectra TEST_EXCEPTION_WITH_MESSAGE(Exception::MissingInformation, id_rate_ms1.compute(pep_ids, ms1_exp), "No MS2 spectra found") } END_SECTION START_SECTION(const String& getName() const override) {TEST_EQUAL(ms2ir.getName(), "Ms2IdentificationRate")} END_SECTION START_SECTION(QCBase::Status requirements() const override) { QCBase::Status stat = QCBase::Status() | QCBase::Requires::RAWMZML | QCBase::Requires::POSTFDRFEAT; TEST_EQUAL(stat == ms2ir.requirements(), true) } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++
3D
OpenMS/OpenMS
src/tests/class_tests/openms/source/RANSACModelLinear_test.cpp
.cpp
19,784
429
// 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 $ // -------------------------------------------------------------------------- #include <OpenMS/CONCEPT/ClassTest.h> #include <OpenMS/test_config.h> /////////////////////////// #include <OpenMS/ML/RANSAC/RANSAC.h> #include <OpenMS/ML/RANSAC/RANSACModelLinear.h> /////////////////////////// using namespace std; using namespace OpenMS; using namespace Math; /////////////////////////// // random number generator using srand (used in std::random_shuffle()) int myRNG(int n) { return std::rand() / (1.0 + RAND_MAX) * n; } START_TEST(RANSACModelLinear, "$Id$") // fixed seed across all platforms srand(123); ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// RansacModelLinear mod; START_SECTION((static ModelParameters rm_fit_impl(const DVecIt& begin, const DVecIt& end))) { std::vector<std::pair<double, double> > test_pairs; test_pairs.push_back(std::make_pair(7.66217066e+00, 3.32871078e+02)); test_pairs.push_back(std::make_pair(1.88986378e+01, 8.41782838e+02)); test_pairs.push_back(std::make_pair(1.43387751e+01, 6.48336013e+02)); test_pairs.push_back(std::make_pair(1.04946477e+01, 5.30115032e+02)); test_pairs.push_back(std::make_pair(2.40052860e+00, 1.36793947e+02)); test_pairs.push_back(std::make_pair(2.65925164e+00, 1.38532208e+02)); test_pairs.push_back(std::make_pair(7.00156815e+00, 3.03487855e+01)); test_pairs.push_back(std::make_pair(1.76671412e+01, 7.67575677e+02)); test_pairs.push_back(std::make_pair(1.02592601e+01, 5.32449429e+02)); test_pairs.push_back(std::make_pair(1.29020672e+01,-1.74450591e+01)); test_pairs.push_back(std::make_pair(2.66076055e-02, 1.78205080e+01)); test_pairs.push_back(std::make_pair(1.87212750e+01, 8.59152499e+02)); test_pairs.push_back(std::make_pair(1.81219758e+01,-5.79165989e-01)); test_pairs.push_back(std::make_pair(5.27778174e+00, 1.88005119e+02)); test_pairs.push_back(std::make_pair(4.56777946e+00, 1.61530045e+02)); test_pairs.push_back(std::make_pair(2.82887267e+00, 1.64411907e+02)); test_pairs.push_back(std::make_pair(5.77563248e+00, 2.69781852e+02)); test_pairs.push_back(std::make_pair(1.08263921e+01, 4.65275655e+02)); test_pairs.push_back(std::make_pair(9.61444550e+00, 3.82697907e+02)); test_pairs.push_back(std::make_pair(5.34540857e+00, 2.56156813e+02)); RansacModel<>::ModelParameters coeff = mod.rm_fit_impl(test_pairs.begin(), test_pairs.end()); TEST_REAL_SIMILAR( coeff[0], 46.03865245); TEST_REAL_SIMILAR( coeff[1], 31.20358812); double rss = mod.rm_rss_impl(test_pairs.begin(), test_pairs.end(), coeff); TEST_REAL_SIMILAR( rss, 864089.67832345); std::vector<std::pair<double, double> > new_test_pairs; new_test_pairs.push_back(std::make_pair(1.20513989e+01, 5.42172984e+02)); new_test_pairs.push_back(std::make_pair(1.68354224e+00, 1.23674095e+02)); new_test_pairs.push_back(std::make_pair(4.64668635e+00, 2.61350113e+02)); new_test_pairs.push_back(std::make_pair(8.13976269e+00, 3.24462812e+02)); new_test_pairs.push_back(std::make_pair(1.04776397e+01, 4.04452477e+02)); new_test_pairs.push_back(std::make_pair(1.56315091e+01, 6.95756737e+02)); new_test_pairs.push_back(std::make_pair(1.27266524e+01, 6.53571377e+01)); new_test_pairs.push_back(std::make_pair(1.33784812e+01, 3.03064682e+01)); new_test_pairs.push_back(std::make_pair(9.73484306e+00,-1.55933991e+00)); new_test_pairs.push_back(std::make_pair(1.29040386e+00, 4.19535249e+01)); new_test_pairs.push_back(std::make_pair(1.36889336e+01, 5.37472495e+02)); new_test_pairs.push_back(std::make_pair(3.37465643e+00, 1.52514434e+02)); new_test_pairs.push_back(std::make_pair(2.86567552e+00, 5.62442618e+01)); new_test_pairs.push_back(std::make_pair(1.63579656e+01, 8.41451166e+02)); new_test_pairs.push_back(std::make_pair(2.01345432e+01, 8.57894838e+02)); new_test_pairs.push_back(std::make_pair(1.62549940e+01, 7.15378774e+02)); new_test_pairs.push_back(std::make_pair(5.79326803e+00, 2.69370208e+02)); new_test_pairs.push_back(std::make_pair(2.04520306e+00, 8.66527618e+01)); new_test_pairs.push_back(std::make_pair(1.16970916e+01, 6.05836392e+02)); new_test_pairs.push_back(std::make_pair(8.68788731e+00, 9.52993526e+00)); new_test_pairs.push_back(std::make_pair(2.79787727e+00, 1.08213952e+02)); new_test_pairs.push_back(std::make_pair(1.95778572e+01, 1.39196902e+02)); new_test_pairs.push_back(std::make_pair(1.69500204e-01, 3.09473207e+01)); new_test_pairs.push_back(std::make_pair(1.17974170e+01, 2.51798532e+01)); new_test_pairs.push_back(std::make_pair(4.67384259e+00, 2.30870376e+02)); new_test_pairs.push_back(std::make_pair(1.41658478e+01, 5.86317425e+02)); new_test_pairs.push_back(std::make_pair(5.00923637e+00,-1.86559595e+01)); new_test_pairs.push_back(std::make_pair(9.87160022e+00, 4.61676941e+02)); new_test_pairs.push_back(std::make_pair(1.14474730e+01, 4.83241860e+02)); new_test_pairs.push_back(std::make_pair(3.79416666e+00, 1.64038065e+02)); RansacModel<>::DVec inliers = mod.rm_inliers(new_test_pairs.begin(), new_test_pairs.end(), coeff, 7e3); TEST_REAL_SIMILAR( inliers[0].first, 1.68354224e+00); TEST_REAL_SIMILAR( inliers[1].first, 4.64668635e+00); TEST_REAL_SIMILAR( inliers[2].first, 8.13976269e+00); TEST_REAL_SIMILAR( inliers[3].first, 1.04776397e+01); TEST_REAL_SIMILAR( inliers[4].first, 1.29040386e+00); TEST_REAL_SIMILAR( inliers[5].first, 1.36889336e+01); TEST_REAL_SIMILAR( inliers[6].first, 3.37465643e+00); TEST_REAL_SIMILAR( inliers[7].first, 2.86567552e+00); TEST_REAL_SIMILAR( inliers[8].first, 5.79326803e+00); TEST_REAL_SIMILAR( inliers[9].first, 2.04520306e+00); TEST_REAL_SIMILAR( inliers[10].first, 2.79787727e+00); TEST_REAL_SIMILAR( inliers[11].first, 1.69500204e-01); TEST_REAL_SIMILAR( inliers[12].first, 4.67384259e+00); TEST_REAL_SIMILAR( inliers[13].first, 1.14474730e+01); TEST_REAL_SIMILAR( inliers[14].first, 3.79416666e+00); TEST_EQUAL( inliers.size(), 15); } END_SECTION START_SECTION((static double rm_rsq_impl(const DVecIt& begin, const DVecIt& end))) NOT_TESTABLE // tested above in rm_fit_impl END_SECTION START_SECTION((static double rm_rss_impl(const DVecIt& begin, const DVecIt& end, const ModelParameters& coefficients))) NOT_TESTABLE // tested above in rm_fit_impl END_SECTION START_SECTION((static DVec rm_inliers_impl(const DVecIt& begin, const DVecIt& end, const ModelParameters& coefficients, double max_threshold))) NOT_TESTABLE // tested above in rm_fit_impl END_SECTION START_SECTION([EXTRA](static Math::RANSAC<Math::RansacModelLinear>::ransac(const std::vector<std::pair<double, double> >& pairs, size_t n, size_t k, double t, size_t d, bool relative_d = false, int (*rng)(int) = NULL))) { /* // Python reference implementation that was used to generate the test data: http://wiki.scipy.org/Cookbook/RANSAC import numpy import scipy # use numpy if scipy unavailable import scipy.linalg # use numpy if scipy unavailable ## Copyright (c) 2004-2007, Andrew D. Straw. All rights reserved. ## Redistribution and use in source and binary forms, with or without ## modification, are permitted provided that the following conditions are ## met: ## * Redistributions of source code must retain the above copyright ## notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above ## copyright notice, this list of conditions and the following ## disclaimer in the documentation and/or other materials provided ## with the distribution. ## * Neither the name of the Andrew D. Straw nor the names of its ## contributors may be used to endorse or promote products derived ## from this software without specific prior written permission. ## THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ## "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ## LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ## A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ## OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ## SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ## LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ## OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. def ransac(data,model,n,k,t,d,debug=False,return_all=False): """fit model parameters to data using the RANSAC algorithm This implementation written from pseudocode found at http://en.wikipedia.org/w/index.php?title=RANSAC&oldid=116358182 {{{ Given: data - a set of observed data points model - a model that can be fitted to data points n - the minimum number of data values required to fit the model k - the maximum number of iterations allowed in the algorithm t - a threshold value for determining when a data point fits a model d - the number of close data values required to assert that a model fits well to data Return: bestfit - model parameters which best fit the data (or nil if no good model is found) iterations = 0 bestfit = nil besterr = something really large while iterations < k { maybeinliers = n randomly selected values from data maybemodel = model parameters fitted to maybeinliers alsoinliers = empty set for every point in data not in maybeinliers { if point fits maybemodel with an error smaller than t add point to alsoinliers } if the number of elements in alsoinliers is > d { % this implies that we may have found a good model % now test how good it is bettermodel = model parameters fitted to all points in maybeinliers and alsoinliers thiserr = a measure of how well model fits these points if thiserr < besterr { bestfit = bettermodel besterr = thiserr } } increment iterations } return bestfit }}} """ iterations = 0 bestfit = None besterr = numpy.inf best_inlier_idxs = None while iterations < k: maybe_idxs, test_idxs = random_partition(n,data.shape[0]) maybeinliers = data[maybe_idxs,:] # OPENMS_TEST: print all maybeinliers # print "maybeinliers" # print maybeinliers # print "end maybeinliers" test_points = data[test_idxs] maybemodel = model.fit(maybeinliers) test_err = model.get_error( test_points, maybemodel) also_idxs = test_idxs[test_err < t] # select indices of rows with accepted points alsoinliers = data[also_idxs,:] # OPENMS_TEST: print alsoinliers # print alsoin if debug: print 'test_err.min()',test_err.min() print 'test_err.max()',test_err.max() print 'numpy.mean(test_err)',numpy.mean(test_err) print 'iteration %d:len(alsoinliers) = %d'%( iterations,len(alsoinliers)) if len(alsoinliers) > d: betterdata = numpy.concatenate( (maybeinliers, alsoinliers) ) bettermodel = model.fit(betterdata) better_errs = model.get_error( betterdata, bettermodel) thiserr = numpy.mean( better_errs ) if thiserr < besterr: bestfit = bettermodel besterr = thiserr best_inlier_idxs = numpy.concatenate( (maybe_idxs, also_idxs) ) iterations+=1 if bestfit is None: raise ValueError("did not meet fit acceptance criteria") if return_all: return bestfit, {'inliers':best_inlier_idxs} else: return bestfit def random_partition(n,n_data): """return n random rows of data (and also the other len(data)-n rows)""" all_idxs = numpy.arange( n_data ) # OPENMS_TEST: exclude random component #numpy.random.shuffle(all_idxs) idxs1 = all_idxs[:n] idxs2 = all_idxs[n:] return idxs1, idxs2 class LinearLeastSquaresModel: """linear system solved using linear least squares This class serves as an example that fulfills the model interface needed by the ransac() function. """ def __init__(self,input_columns,output_columns,debug=False): self.input_columns = input_columns self.output_columns = output_columns self.debug = debug def fit(self, data): A = numpy.vstack([data[:,i] for i in self.input_columns]).T B = numpy.vstack([data[:,i] for i in self.output_columns]).T # OPENMS_TEST: make linear regression compatible # lstsq needs correct weights! W = numpy.vstack(numpy.ones(len(A))) A = numpy.hstack((A,W)) x,resids,rank,s = scipy.linalg.lstsq(A,B) # OPENMS_TEST: print coefficients & rss #print x #print resids return x def get_error( self, data, model): A = numpy.vstack([data[:,i] for i in self.input_columns]).T B = numpy.vstack([data[:,i] for i in self.output_columns]).T # OPENMS_TEST: make linear regression compatible # lstsq needs correct weights! W = numpy.vstack(numpy.ones(len(A))) A = numpy.hstack((A,W)) B_fit = scipy.dot(A,model) err_per_point = numpy.sum((B-B_fit)**2,axis=1) # sum squared error per row return err_per_point def test(): # generate perfect input data # Fix seed numpy.random.seed(42) n_samples = 50 n_inputs = 1 n_outputs = 1 A_exact = 20*numpy.random.random((n_samples,n_inputs) ) perfect_fit = 60*numpy.random.normal(size=(n_inputs,n_outputs) ) # the model B_exact = scipy.dot(A_exact,perfect_fit) assert B_exact.shape == (n_samples,n_outputs) # add a little gaussian noise (linear least squares alone should handle this well) A_noisy = A_exact + numpy.random.normal(size=A_exact.shape ) B_noisy = B_exact + numpy.random.normal(size=B_exact.shape ) if 1: # add some outliers n_outliers = 10 all_idxs = numpy.arange( A_noisy.shape[0] ) numpy.random.shuffle(all_idxs) outlier_idxs = all_idxs[:n_outliers] non_outlier_idxs = all_idxs[n_outliers:] A_noisy[outlier_idxs] = 20*numpy.random.random((n_outliers,n_inputs) ) B_noisy[outlier_idxs] = 50*numpy.random.normal(size=(n_outliers,n_outputs) ) # setup model all_data = numpy.hstack( (A_noisy,B_noisy) ) input_columns = range(n_inputs) # the first columns of the array output_columns = [n_inputs+i for i in range(n_outputs)] # the last columns of the array debug = False model = LinearLeastSquaresModel(input_columns,output_columns,debug=debug) linear_fit,resids,rank,s = scipy.linalg.lstsq(all_data[:,input_columns], all_data[:,output_columns]) # OPENMS_TEST: print input data #print all_data # run RANSAC algorithm ransac_fit, ransac_data = ransac(all_data,model, 20, 1, 7e3, 10, # misc. parameters debug=debug,return_all=True) # OPENMS_TEST: print result data #print all_data[ransac_data['inliers']] if 0: import pylab sort_idxs = numpy.argsort(A_exact[:,0]) A_col0_sorted = A_exact[sort_idxs] # maintain as rank-2 array if 1: pylab.plot( A_noisy[:,0], B_noisy[:,0], 'k.', label='data' ) pylab.plot( A_noisy[ransac_data['inliers'],0], B_noisy[ransac_data['inliers'],0], 'bx', label='RANSAC data' ) else: pylab.plot( A_noisy[non_outlier_idxs,0], B_noisy[non_outlier_idxs,0], 'k.', label='noisy data' ) pylab.plot( A_noisy[outlier_idxs,0], B_noisy[outlier_idxs,0], 'r.', label='outlier data' ) pylab.plot( A_col0_sorted[:,0], numpy.dot(A_col0_sorted,ransac_fit)[:,0], label='RANSAC fit' ) pylab.plot( A_col0_sorted[:,0], numpy.dot(A_col0_sorted,perfect_fit)[:,0], label='exact system' ) pylab.plot( A_col0_sorted[:,0], numpy.dot(A_col0_sorted,linear_fit)[:,0], label='linear fit' ) pylab.legend() pylab.show() if __name__=='__main__': test() */ std::vector<std::pair<double, double> > test_pairs, test_pairs_out; // 50 points... double tx[] = {7.66217066, 18.8986378, 14.3387751, 10.4946477, 2.4005286, 2.65925164, 7.00156815, 17.6671412, 10.2592601, 12.9020672, 0.0266076055, 18.721275, 18.1219758, 5.27778174, 4.56777946, 2.82887267, 5.77563248, 10.8263921, 9.6144455, 5.34540857, 12.0513989, 1.68354224, 4.64668635, 8.13976269, 10.4776397, 15.6315091, 12.7266524, 13.3784812, 9.73484306, 1.29040386, 13.6889336, 3.37465643, 2.86567552, 16.3579656, 20.1345432, 16.254994, 5.79326803, 2.04520306, 11.6970916, 8.68788731, 2.79787727, 19.5778572, 0.169500204, 11.797417, 4.67384259, 14.1658478, 5.00923637, 9.87160022, 11.447473, 3.79416666}; double ty[] = {332.871078, 841.782838, 648.336013, 530.115032, 136.793947, 138.532208, 30.3487855, 767.575677, 532.449429, 17.4450591, 17.820508, 859.152499, 0.579165989, 188.005119, 161.530045, 164.411907, 269.781852, 465.275655, 382.697907, 256.156813, 542.172984, 123.674095, 261.350113, 324.462812, 404.452477, 695.756737, 65.3571377, 30.3064682, 1.55933991, 41.9535249, 537.472495, 152.514434, 56.2442618, 841.451166, 857.894838, 715.378774, 269.370208, 86.6527618, 605.836392, 9.52993526, 108.213952, 139.196902, 30.9473207, 25.1798532, 230.870376, 586.317425, 18.6559595, 461.676941, 483.24186, 164.038065}; for (int i = 0; i < 50; ++i) { test_pairs.push_back(make_pair(tx[i], ty[i])); } std::sort(test_pairs.begin(), test_pairs.end()); Math::RANSAC<Math::RansacModelLinear> r; //TODO set seed test_pairs_out = r.ransac(test_pairs, 2, 1200, 100*100, 10, false); std::sort(test_pairs_out.begin(), test_pairs_out.end()); for (Size i = 0; i < test_pairs_out.size(); ++i) { cerr << test_pairs_out[i].first << " " << test_pairs_out[i].second << "\n"; } TEST_EQUAL( test_pairs_out.size(), 40); ABORT_IF(test_pairs_out.size() != 40); double ty_out[] = {17.8205, 30.9473, 41.9535, 123.674, 86.6528, 136.794, 138.532, 108.214, 164.412, 56.2443, 152.514, 164.038, 161.53, 261.35, 230.87, 188.005, 256.157, 269.782, 269.37, 332.871, 324.463, 382.698, 461.677, 532.449, 404.452, 530.115, 465.276, 483.242, 605.836, 542.173, 537.472, 586.317, 648.336, 695.757, 715.379, 841.451, 767.576, 859.152, 841.783, 857.895}; for (Size i = 0; i < test_pairs_out.size(); ++i) { TEST_REAL_SIMILAR( test_pairs_out[i].second, ty_out[i]); } } END_SECTION ///////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// END_TEST
C++